text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix "moveFeature" tool initialization errors | (function () {
"use strict";
if (window.ol && ol.source && !ol.source.VectorEventType) {
// HACK: monkey patch event types not present in current OL6 repackage build
// @see https://github.com/openlayers/openlayers/blob/main/src/ol/source/VectorEventType.js
ol.source.VectorEventType = {
ADDFEATURE: 'addfeature',
CHANGEFEATURE: 'changefeature',
CLEAR: 'clear',
REMOVEFEATURE: 'removefeature'
};
}
if (window.ol && !ol.ObjectEventType) {
// HACK: monkey patch event types not present in current OL6 repackage build
// @see https://github.com/openlayers/openlayers/blob/main/src/ol/ObjectEventType.js
ol.ObjectEventType = {
PROPERTYCHANGE: 'propertychange'
};
}
if (window.ol && ol.interaction && !ol.interaction.ModifyEventType) {
// HACK: monkey patch event types not present in current OL6 repackage build
// @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Modify.js#L64
ol.interaction.ModifyEventType = {
MODIFYSTART: 'modifystart',
MODIFYEND: 'modifyend'
};
}
if (window.ol && ol.interaction && !ol.interaction.TranslateEventType) {
// HACK: monkey patch event types not present in current OL6 repackage build
// @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Translate.js#L12
ol.interaction.TranslateEventType = {
TRANSLATESTART: 'translatestart',
TRANSLATING: 'translating',
TRANSLATEEND: 'translateend'
};
}
})();
| (function () {
"use strict";
if (window.ol && ol.source && !ol.source.VectorEventType) {
// HACK: monkey patch event types not present in current OL6 repackage build
// @see https://github.com/openlayers/openlayers/blob/main/src/ol/source/VectorEventType.js
ol.source.VectorEventType = {
ADDFEATURE: 'addfeature',
CHANGEFEATURE: 'changefeature',
CLEAR: 'clear',
REMOVEFEATURE: 'removefeature'
};
}
if (window.ol && !ol.ObjectEventType) {
// HACK: monkey patch event types not present in current OL6 repackage build
// @see https://github.com/openlayers/openlayers/blob/main/src/ol/ObjectEventType.js
ol.ObjectEventType = {
PROPERTYCHANGE: 'propertychange'
};
}
if (window.ol && ol.interaction && !ol.interaction.ModifyEventType) {
// HACK: monkey patch event types not present in current OL6 repackage build
// @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Modify.js#L64
ol.interaction.ModifyEventType = {
MODIFYSTART: 'modifystart',
MODIFYEND: 'modifyend'
};
}
})();
|
Resolve getter e setter para isObrigatorio | package br.fameg.edu.domain.model;
import java.math.BigDecimal;
import java.sql.Date;
import javax.persistence.*;
@Entity
public class Trabalho {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String descricao;
@OneToOne
private Professor professor;
@Column(nullable = true)
private BigDecimal nota;
@Column(nullable = true)
private Date dataEntrega;
@Column
private boolean isObrigatorio;
public Trabalho() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public Date getDataEntrega() {
return dataEntrega;
}
public void setDataEntrega(Date dataEntrega) {
this.dataEntrega = dataEntrega;
}
public BigDecimal getNota() {
return nota;
}
public void setNota(BigDecimal nota) {
this.nota = nota;
}
public boolean isObrigatorio() {
return isObrigatorio;
}
public void setObrigatorio(boolean isObrigatorio) {
this.isObrigatorio = isObrigatorio;
}
}
| package br.fameg.edu.domain.model;
import java.math.BigDecimal;
import java.sql.Date;
import javax.persistence.*;
@Entity
public class Trabalho {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String descricao;
@OneToOne
private Professor professor;
@Column(nullable = true)
private BigDecimal nota;
@Column(nullable = true)
private Date dataEntrega;
@Column
private boolean isObrigatorio;
public Trabalho() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public Date getDataEntrega() {
return dataEntrega;
}
public void setDataEntrega(Date dataEntrega) {
this.dataEntrega = dataEntrega;
}
public BigDecimal getNota() {
return nota;
}
public void setNota(BigDecimal nota) {
this.nota = nota;
}
}
|
Fix warnings in php7.2 by initialising the operands array | <?php
/*
* This file is part of the Ruler package, an OpenSky project.
*
* (c) 2011 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Ruler;
/**
* @author Jordan Raub <[email protected]>
*/
abstract class Operator
{
const UNARY = 'UNARY';
const BINARY = 'BINARY';
const MULTIPLE = 'MULTIPLE';
protected $operands = [];
/**
* @param array $operands
*/
public function __construct()
{
foreach (func_get_args() as $operand) {
$this->addOperand($operand);
}
}
public function getOperands()
{
switch ($this->getOperandCardinality()) {
case self::UNARY:
if (1 != count($this->operands)) {
throw new \LogicException(get_class($this) . ' takes only 1 operand');
}
break;
case self::BINARY:
if (2 != count($this->operands)) {
throw new \LogicException(get_class($this) . ' takes 2 operands');
}
break;
case self::MULTIPLE:
if (0 == count($this->operands)) {
throw new \LogicException(get_class($this) . ' takes at least 1 operand');
}
break;
}
return $this->operands;
}
abstract public function addOperand($operand);
abstract protected function getOperandCardinality();
}
| <?php
/*
* This file is part of the Ruler package, an OpenSky project.
*
* (c) 2011 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Ruler;
/**
* @author Jordan Raub <[email protected]>
*/
abstract class Operator
{
const UNARY = 'UNARY';
const BINARY = 'BINARY';
const MULTIPLE = 'MULTIPLE';
protected $operands;
/**
* @param array $operands
*/
public function __construct()
{
foreach (func_get_args() as $operand) {
$this->addOperand($operand);
}
}
public function getOperands()
{
switch ($this->getOperandCardinality()) {
case self::UNARY:
if (1 != count($this->operands)) {
throw new \LogicException(get_class($this) . ' takes only 1 operand');
}
break;
case self::BINARY:
if (2 != count($this->operands)) {
throw new \LogicException(get_class($this) . ' takes 2 operands');
}
break;
case self::MULTIPLE:
if (0 == count($this->operands)) {
throw new \LogicException(get_class($this) . ' takes at least 1 operand');
}
break;
}
return $this->operands;
}
abstract public function addOperand($operand);
abstract protected function getOperandCardinality();
}
|
Allow themes to overload BoomCMS views (e.g. for customising login page / user generation email | <?php
namespace BoomCMS\ServiceProviders;
use BoomCMS\Core\Template\Manager as TemplateManager;
use BoomCMS\Support\Helpers\Config;
use Illuminate\Support\ServiceProvider;
class TemplateServiceProvider extends ServiceProvider
{
protected $themes = [];
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$manager = new TemplateManager($this->app['files'], $this->app['boomcms.repositories.template'], $this->app['cache.store']);
$this->app->singleton('boomcms.template.manager', function () use ($manager) {
return $manager;
});
$this->themes = $manager->getInstalledThemes();
foreach ($this->themes as $theme) {
Config::merge($theme->getConfigDirectory().DIRECTORY_SEPARATOR.'boomcms.php');
}
foreach ($this->themes as $theme) {
$views = $theme->getViewDirectory();
$init = $theme->getDirectory().DIRECTORY_SEPARATOR.'init.php';
$this->loadViewsFrom($views, $theme->getName());
$this->loadViewsFrom($views.'/boomcms', 'boomcms');
$this->loadViewsFrom($views.'/chunks', 'boomcms.chunks');
if (file_exists($init)) {
include $init;
}
}
}
public function register()
{
}
}
| <?php
namespace BoomCMS\ServiceProviders;
use BoomCMS\Core\Template\Manager as TemplateManager;
use BoomCMS\Support\Helpers\Config;
use Illuminate\Support\ServiceProvider;
class TemplateServiceProvider extends ServiceProvider
{
protected $themes = [];
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$manager = new TemplateManager($this->app['files'], $this->app['boomcms.repositories.template'], $this->app['cache.store']);
$this->app->singleton('boomcms.template.manager', function () use ($manager) {
return $manager;
});
$this->themes = $manager->getInstalledThemes();
foreach ($this->themes as $theme) {
Config::merge($theme->getConfigDirectory().DIRECTORY_SEPARATOR.'boomcms.php');
}
foreach ($this->themes as $theme) {
$views = $theme->getViewDirectory();
$init = $theme->getDirectory().DIRECTORY_SEPARATOR.'init.php';
$this->loadViewsFrom($views, $theme->getName());
$this->loadViewsFrom($views.'/chunks', 'boomcms.chunks');
if (file_exists($init)) {
include $init;
}
}
}
public function register()
{
}
}
|
Fix error after login: V1 is not a function | (function () {
angular
.module('auth')
.controller('LoginController', LoginController);
LoginController.$inject = [
'AuthService',
'Notification',
'$scope',
'$location'
];
function LoginController(AuthService, Notification, $scope, $location) {
var vm = this;
vm.STATUS_WAITING = 0;
vm.STATUS_LOADING = 1;
vm.user = {
username: "",
password: ""
};
vm.submit = submit;
activate();
function activate() {
vm.status = vm.STATUS_WAITING;
}
function submit() {
vm.status = vm.STATUS_LOADING;
AuthService.login(vm.user)
.catch(function (res) {
Notification.warning('Login failed');
vm.user.password = "";
vm.status = vm.STATUS_WAITING;
vm.user.error = res.data.error;
});
}
}
})();
| (function () {
angular
.module('auth')
.controller('LoginController', LoginController);
LoginController.$inject = [
'AuthService',
'Notification',
'$scope',
'$location'
];
function LoginController(AuthService, Notification, $scope, $location) {
var vm = this;
vm.STATUS_WAITING = 0;
vm.STATUS_LOADING = 1;
vm.user = {
username: "",
password: ""
};
vm.submit = submit;
activate();
function activate() {
vm.status = vm.STATUS_WAITING;
}
function submit() {
vm.status = vm.STATUS_LOADING;
return AuthService.login(vm.user)
.catch(function (res) {
Notification.warning('Login failed');
vm.user.password = "";
vm.status = vm.STATUS_WAITING;
vm.user.error = res.data.error;
});
}
}
})();
|
Support default exports with babel-jsm-plugin | var exportIds = [];
function exportEnterHandler(node, parent) {
// For variable declarations since exports will have multiple id names in one
if (node.declaration.declarations) {
node.declaration.declarations.forEach(function(declaration) {
exportIds.push(declaration.id.name);
}.bind(this));
return node.declaration;
}
exportIds.push(node.declaration.id.name);
// Replace with declarations, which removes the export
return node.declaration;
}
module.exports = function (babel) {
var t = babel.types;
return new babel.Transformer("babel-jsm-plugin", {
ExportNamedDeclaration: {
enter: exportEnterHandler.bind(this),
},
ExportDefaultDeclaration: {
enter: exportEnterHandler.bind(this),
},
Program: {
exit: function(node, parent) {
var arrayOfSymbols = t.arrayExpression([]);
exportIds.forEach(function(exportedId) {
// Create an array of strings with the export identifier names
arrayOfSymbols.elements.push(t.literal(exportedId));
// Add in this.identifier = identifier for each export and add it to the end
var assignmentStatement = t.expressionStatement(
t.assignmentExpression('=', t.identifier('this.' + exportedId), t.identifier(exportedId)));
this.pushContainer('body', assignmentStatement);
}.bind(this));
// Create an assignment for this.EXPORTED_SYMBOLS = ['export1', 'export2', ...]
var exportsVar = t.expressionStatement(
t.assignmentExpression('=', t.identifier('this.EXPORTED_SYMBOLS'), arrayOfSymbols));
this.unshiftContainer('body', exportsVar);
},
},
});
};
| module.exports = function (babel) {
var exportIds = [];
var t = babel.types;
return new babel.Transformer("babel-jsm-plugin", {
ExportNamedDeclaration: {
enter: function(node, parent) {
// For variable declarations since exports will have multiple id names in one
if (node.declaration.declarations) {
node.declaration.declarations.forEach(function(declaration) {
exportIds.push(declaration.id.name);
}.bind(this));
return node.declaration;
}
exportIds.push(node.declaration.id.name);
// Replace with declarations, which removes the export
return node.declaration;
},
},
Program: {
exit: function(node, parent) {
var arrayOfSymbols = t.arrayExpression([]);
exportIds.forEach(function(exportedId) {
// Create an array of strings with the export identifier names
arrayOfSymbols.elements.push(t.literal(exportedId));
// Add in this.identifier = identifier for each export and add it to the end
var assignmentStatement = t.expressionStatement(
t.assignmentExpression('=', t.identifier('this.' + exportedId), t.identifier(exportedId)));
this.pushContainer('body', assignmentStatement);
}.bind(this));
// Create an assignment for this.EXPORTED_SYMBOLS = ['export1', 'export2', ...]
var exportsVar = t.expressionStatement(
t.assignmentExpression('=', t.identifier('this.EXPORTED_SYMBOLS'), arrayOfSymbols));
this.unshiftContainer('body', exportsVar);
},
},
});
};
|
Use Blade's helper to check for the first row | <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<style>
body {margin: 20px}
</style>
</head>
<body>
<table class="table table-bordered table-condensed table-striped">
@foreach($data as $row)
@if ($loop->first)
<tr>
@foreach($row as $key => $value)
<th>{!! $key !!}</th>
@endforeach
</tr>
@endif
<tr>
@foreach($row as $key => $value)
@if(is_string($value) || is_numeric($value))
<td>{!! $value !!}</td>
@else
<td></td>
@endif
@endforeach
</tr>
@endforeach
</table>
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<style>
body {margin: 20px}
</style>
</head>
<body>
<table class="table table-bordered table-condensed table-striped">
@foreach($data as $row)
@if ($row == reset($data))
<tr>
@foreach($row as $key => $value)
<th>{!! $key !!}</th>
@endforeach
</tr>
@endif
<tr>
@foreach($row as $key => $value)
@if(is_string($value) || is_numeric($value))
<td>{!! $value !!}</td>
@else
<td></td>
@endif
@endforeach
</tr>
@endforeach
</table>
</body>
</html>
|
Reorder function in importer base class. | OV.ImporterBase = class
{
constructor ()
{
this.extension = null;
this.callbacks = null;
this.model = null;
this.error = null;
this.message = null;
}
Import (content, extension, callbacks)
{
this.extension = extension;
this.callbacks = callbacks;
this.model = new OV.Model ();
this.error = false;
this.message = null;
this.ResetState ();
this.ImportContent (content);
if (this.error) {
return;
}
if (OV.IsModelEmpty (this.model)) {
this.error = true;
return;
}
OV.FinalizeModel (this.model, this.callbacks.getDefaultMaterial);
}
ResetState ()
{
}
CanImportExtension (extension)
{
return false;
}
GetKnownFileFormats ()
{
return {};
}
GetUpDirection ()
{
return OV.Direction.Z;
}
ImportContent (content)
{
}
GetModel ()
{
return this.model;
}
SetError ()
{
this.error = true;
}
IsError ()
{
return this.error;
}
SetMessage (message)
{
this.message = message;
}
GetMessage ()
{
return this.message;
}
};
| OV.ImporterBase = class
{
constructor ()
{
this.extension = null;
this.callbacks = null;
this.model = null;
this.error = null;
this.message = null;
}
Import (content, extension, callbacks)
{
this.extension = extension;
this.callbacks = callbacks;
this.model = new OV.Model ();
this.error = false;
this.message = null;
this.ResetState ();
this.ImportContent (content);
if (this.error) {
return;
}
if (OV.IsModelEmpty (this.model)) {
this.error = true;
return;
}
OV.FinalizeModel (this.model, this.callbacks.getDefaultMaterial);
}
ResetState ()
{
}
ImportContent (content)
{
}
CanImportExtension (extension)
{
return false;
}
GetKnownFileFormats ()
{
return {};
}
GetUpDirection ()
{
return OV.Direction.Z;
}
GetModel ()
{
return this.model;
}
SetError ()
{
this.error = true;
}
IsError ()
{
return this.error;
}
SetMessage (message)
{
this.message = message;
}
GetMessage ()
{
return this.message;
}
};
|
Fix version to include 2.0 for now (3.0 appears unfindable) | import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
url='http://github.com/django/asgiref/',
author='Django Software Foundation',
author_email='[email protected]',
description='ASGI specs, helper code, and adapters',
long_description=open(readme_path).read(),
license='BSD',
zip_safe=False,
packages=find_packages(exclude=['tests']),
include_package_data=True,
extras_require={
"tests": [
"pytest~=3.3",
"pytest-asyncio~=0.8",
],
},
install_requires=[
'async_timeout>=2.0,<4.0',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
],
)
| import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
url='http://github.com/django/asgiref/',
author='Django Software Foundation',
author_email='[email protected]',
description='ASGI specs, helper code, and adapters',
long_description=open(readme_path).read(),
license='BSD',
zip_safe=False,
packages=find_packages(exclude=['tests']),
include_package_data=True,
extras_require={
"tests": [
"pytest~=3.3",
"pytest-asyncio~=0.8",
],
},
install_requires=[
'async_timeout~=3.0',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Fix endless execution of integration tests | var injection = require('../services/injection.js');
var Q = require('q');
var mongoose = require('mongoose');
module.exports = function (test, fixtureName, testFn) {
var dbUrl = 'mongodb://localhost:27017/' + fixtureName;
var cleanUp = function () {
return Q.nbind(mongoose.connect, mongoose)(dbUrl).then(function () {
var db = mongoose.connection.db;
return Q.nbind(db.dropDatabase, db)().then(function () {
db.close();
});
});
};
cleanUp().then(function () {
var allcountServer = require('../allcount-server.js');
injection.resetInjection();
injection.bindFactory('port', 9080);
injection.bindFactory('dbUrl', dbUrl);
injection.bindFactory('gitRepoUrl', 'test-fixtures/' + fixtureName);
allcountServer.reconfigureAllcount();
return allcountServer.inject('allcountServerStartup');
}).then(function (server) {
return Q.nbind(server.startup, server)().then(function (errors) {
if (errors) {
throw new Error(errors.join('\n'));
}
return Q(testFn()).then(function () {
return server.stop().then(function () {
injection.resetInjection();
});
});
});
}).finally(cleanUp).finally(function () {
test.done();
}).done();
}; | var injection = require('../services/injection.js');
var Q = require('q');
var mongoose = require('mongoose');
module.exports = function (test, fixtureName, testFn) {
var dbUrl = 'mongodb://localhost:27017/' + fixtureName;
var cleanUp = function () {
return Q.nbind(mongoose.connect, mongoose)(dbUrl).then(function () {
var db = mongoose.connection.db;
return Q.nbind(db.dropDatabase, db)().then(function () {
db.close();
});
});
};
cleanUp().then(function () {
var allcountServer = require('../allcount-server.js');
injection.resetInjection();
injection.bindFactory('port', 9080);
injection.bindFactory('dbUrl', dbUrl);
injection.bindFactory('gitRepoUrl', 'test-fixtures/' + fixtureName);
allcountServer.reconfigureAllcount();
return allcountServer.inject('allcountServerStartup');
}).then(function (server) {
return Q.nbind(server.startup, server)().then(function (errors) {
if (errors) {
throw new Error(errors.join('\n'));
}
return Q(testFn()).then(function () {
return server.stop().then(function () {
injection.resetInjection();
});
});
});
}).finally(cleanUp).done(function () {
test.done();
});
}; |
Add DHCP lease binding to the protocol | // Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';
var di = require('di');
module.exports = eventsProtocolFactory;
di.annotate(eventsProtocolFactory, new di.Provide('Protocol.Events'));
di.annotate(eventsProtocolFactory,
new di.Inject(
'Services.Messenger',
'Protocol.Exchanges.Events',
'Assert'
)
);
function eventsProtocolFactory (messenger, eventsExchange, assert) {
function EventsProtocol () {
}
EventsProtocol.prototype.publishTftpSuccess = function (nodeId, data) {
assert.ok(nodeId);
assert.object(data);
messenger.publish(
eventsExchange.exchange,
'tftp.success' + '.' + nodeId,
data
);
};
EventsProtocol.prototype.publishTftpFailure = function (nodeId, data) {
assert.ok(nodeId);
assert.object(data);
messenger.publish(
eventsExchange.exchange,
'tftp.failure' + '.' + nodeId,
data
);
};
EventsProtocol.prototype.publishHttpResponse = function (nodeId, data) {
assert.ok(nodeId);
assert.object(data);
messenger.publish(
eventsExchange.exchange,
'http.response' + '.' + nodeId,
data
);
};
EventsProtocol.prototype.publishDhcpBoundLease = function(nodeId, data) {
assert.ok(nodeId);
assert.ok(data);
messenger.publish(
eventsExchange.exchange,
'dhcp.bind.success' + '.' + nodeId,
data
);
};
return new EventsProtocol();
}
| // Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';
var di = require('di');
module.exports = eventsProtocolFactory;
di.annotate(eventsProtocolFactory, new di.Provide('Protocol.Events'));
di.annotate(eventsProtocolFactory,
new di.Inject(
'Services.Messenger',
'Protocol.Exchanges.Events',
'Assert'
)
);
function eventsProtocolFactory (messenger, eventsExchange, assert) {
function EventsProtocol () {
}
EventsProtocol.prototype.publishTftpSuccess = function (nodeId, data) {
assert.ok(nodeId);
assert.object(data);
messenger.publish(
eventsExchange.exchange,
'tftp.success' + '.' + nodeId,
data
);
};
EventsProtocol.prototype.publishTftpFailure = function (nodeId, data) {
assert.ok(nodeId);
assert.object(data);
messenger.publish(
eventsExchange.exchange,
'tftp.failure' + '.' + nodeId,
data
);
};
EventsProtocol.prototype.publishHttpResponse = function (nodeId, data) {
assert.ok(nodeId);
assert.object(data);
messenger.publish(
eventsExchange.exchange,
'http.response' + '.' + nodeId,
data
);
};
return new EventsProtocol();
}
|
Fix samples comparison after upgrading to MSON Zoo 3.0. | import React from 'react';
import ReactDomServer from 'react-dom/server';
import msonZoo from 'mson-zoo';
import jsBeautify from 'js-beautify';
import fs from 'fs';
import path from 'path';
import assert from 'assert';
import dedent from 'dedent';
import parseMson from '../playground/parseMson';
import { Attributes } from '../dist/attributes-kit-server';
describe('Comparision with reference fixtures', () => {
msonZoo.samples.forEach((sample) => {
let renderedElement = null;
let htmlString = null;
describe(`If I render ${sample.fileName} on the server`, (done) => {
let header = '# Data Structures';
parseMson(`${header}\n${sample.fileContent}`, (err, dataStructureElements) => {
if (err) {
return done(err);
}
renderedElement = React.createElement(Attributes, {
element: dataStructureElements[0],
dataStructures: dataStructureElements,
collapseByDefault: false,
maxInheritanceDepth: undefined,
includedProperties: 'show',
inheritedProperties: 'show',
});
htmlString = jsBeautify.html(ReactDomServer.renderToStaticMarkup(renderedElement));
});
describe('And I compare that with the reference fixture', () => {
const reference = fs.readFileSync(
path.join('./fixtures', `${sample.fileName}`),
'utf8'
);
it('They should be equal', () => {
assert.equal(htmlString, reference);
});
});
});
});
});
| import React from 'react';
import ReactDomServer from 'react-dom/server';
import msonZoo from 'mson-zoo';
import jsBeautify from 'js-beautify';
import fs from 'fs';
import path from 'path';
import assert from 'assert';
import dedent from 'dedent';
import parseMson from '../playground/parseMson';
import { Attributes } from '../dist/attributes-kit-server';
describe('Comparision with reference fixtures', () => {
msonZoo.samples.forEach((sample) => {
let renderedElement = null;
let htmlString = null;
describe(`If I render ${sample.name} on the server`, (done) => {
let header = '# Data Structures';
parseMson(`${header}\n${sample.fileContent}`, (err, dataStructureElements) => {
if (err) {
return done(err);
}
renderedElement = React.createElement(Attributes, {
element: dataStructureElements[0],
collapseByDefault: false,
maxInheritanceDepth: undefined,
includedProperties: 'show',
inheritedProperties: 'show',
});
htmlString = jsBeautify.html(ReactDomServer.renderToStaticMarkup(renderedElement));
});
describe('And I compare that with the reference fixture', () => {
const reference = fs.readFileSync(path.join('./fixtures', `${sample.name}`));
it('They should be equal', () => {
assert.equal(htmlString, reference);
});
});
});
});
});
|
Add dirname to resolve.root to fix import linting in Atom | var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BundleTracker = require('webpack-bundle-tracker');
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
context: __dirname,
devtool: 'eval-source-map',
entry: {
// Used to extract common libraries
vendor: [
'classnames', 'es6-promise', 'isomorphic-fetch',
'moment', 'react', 'react-bootstrap', 'react-dom'
],
frontpageEvents: [
'./assets/js/frontpage/events/index'
],
frontpageArticles: [
'./assets/js/frontpage/articles/index'
]
},
resolve: {
root: path.resolve(__dirname, './assets/js/'),
},
output: {
path: path.resolve('./assets/webpack_bundles/'),
filename: '[name]-[hash].js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract('style', 'css!less'),
}
]
},
lessLoader: {
includePath: [path.resolve(__dirname, './styles')]
},
plugins: [
new CommonsChunkPlugin({
names: ['vendor'],
minChunks: Infinity
}),
new BundleTracker({filename: './webpack-stats.json'})
]
};
| var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BundleTracker = require('webpack-bundle-tracker');
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
context: __dirname,
devtool: 'eval-source-map',
entry: {
// Used to extract common libraries
vendor: [
'classnames', 'es6-promise', 'isomorphic-fetch',
'moment', 'react', 'react-bootstrap', 'react-dom'
],
frontpageEvents: [
'./assets/js/frontpage/events/index'
],
frontpageArticles: [
'./assets/js/frontpage/articles/index'
]
},
resolve: {
root: path.resolve('./assets/js/'),
},
output: {
path: path.resolve('./assets/webpack_bundles/'),
filename: '[name]-[hash].js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract('style', 'css!less'),
}
]
},
lessLoader: {
includePath: [path.resolve(__dirname, './styles')]
},
plugins: [
new CommonsChunkPlugin({
names: ['vendor'],
minChunks: Infinity
}),
new BundleTracker({filename: './webpack-stats.json'})
]
};
|
Add a watch for html changes and launch htmlmin | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
build: ['Gruntfile.js', 'src/**/*.js']
},
watch: {
scripts: {
files: 'src/**/*.js',
tasks: ['jshint']
},
html: {
files: 'src/**/*.html',
tasks: ['htmlmin']
}
},
copy: {
build: {
files: [
{
expand: true,
src: 'node_modules/knockout/build/output/knockout-latest.js',
dest: 'dist/js/',
flatten: true,
rename: function (dest, src) {
return dest + 'knockout.js';
}
}
]
}
},
htmlmin: {
build: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
'dist/index.html': 'src/index.html'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
// Default task(s).
grunt.registerTask('default', ['jshint']);
};
| module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
build: ['Gruntfile.js', 'src/**/*.js']
},
watch: {
scripts: {
files: 'src/**/*.js',
tasks: ['jshint']
}
},
copy: {
build: {
files: [
{
expand: true,
src: 'node_modules/knockout/build/output/knockout-latest.js',
dest: 'dist/js/',
flatten: true,
rename: function (dest, src) {
return dest + 'knockout.js';
}
}
]
}
},
htmlmin: {
build: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
'dist/index.html': 'src/index.html'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
// Default task(s).
grunt.registerTask('default', ['jshint']);
};
|
Make input type = "number"
This should help display the correct keyboard on mobile devices | import React from 'react';
import RIEStatefulBase from './RIEStatefulBase';
export default class RIENumber extends RIEStatefulBase {
constructor(props) {
super(props);
}
static propTypes = {
format: React.PropTypes.func
};
validate = (value) => {
return !isNaN(value) && isFinite(value) && value.length > 0;
};
renderNormalComponent = () => {
return <span
tabIndex="0"
className={this.makeClassString()}
onFocus={this.startEditing}
onClick={this.startEditing}>{this.props.format ? this.props.format(this.state.newValue || this.props.value) : (this.state.newValue || this.props.value)}</span>;
};
renderEditingComponent = () => {
return <input disabled={(this.props.shouldBlockWhileLoading && this.state.loading)}
type="number"
className={this.makeClassString()}
defaultValue={this.props.value}
onInput={this.textChanged}
onBlur={this.finishEditing}
ref="input"
onKeyDown={this.keyDown} />;
};
}
| import React from 'react';
import RIEStatefulBase from './RIEStatefulBase';
export default class RIENumber extends RIEStatefulBase {
constructor(props) {
super(props);
}
static propTypes = {
format: React.PropTypes.func
};
validate = (value) => {
return !isNaN(value) && isFinite(value) && value.length > 0;
};
renderNormalComponent = () => {
return <span
tabIndex="0"
className={this.makeClassString()}
onFocus={this.startEditing}
onClick={this.startEditing}>{this.props.format ? this.props.format(this.state.newValue || this.props.value) : (this.state.newValue || this.props.value)}</span>;
};
renderEditingComponent = () => {
return <input disabled={(this.props.shouldBlockWhileLoading && this.state.loading)}
className={this.makeClassString()}
defaultValue={this.props.value}
onInput={this.textChanged}
onBlur={this.finishEditing}
ref="input"
onKeyDown={this.keyDown} />;
};
}
|
Fix router behaviour for manually changed URLs | class RcdHistoryRouter {
constructor() {
this.routes = {};
this.defaultRoute;
window.onpopstate = (event) => {
this.refreshState();
};
}
init() {
return this;
}
addDefaultRoute(callback) {
this.defaultRoute = callback;
return this;
}
addRoute(route, callback) {
this.routes[route] = callback;
return this;
}
setState(state) {
if (state) {
history.pushState(state, null, '#' + state);
var parametersIndex = state.indexOf("?");
var route = parametersIndex == -1 ? state : state.substring(0, parametersIndex);
this.routes[route]();
} else {
this.defaultRoute();
history.pushState(state, null, '#');
}
return this;
}
getCurrentState() {
return location.hash && location.hash.substring(1);
}
refreshState() {
this.setState(this.getCurrentState());
}
getParameters() {
var currentState = this.getCurrentState();
var parametersIndex = currentState.indexOf("?");
var parameters = {};
if (parametersIndex !== -1) {
var parametersString = currentState.substring(parametersIndex + 1);
parametersString.split('&').forEach((parameterEntry) => {
var parameterEntryValue = parameterEntry.split('=');
parameters[parameterEntryValue[0]] = parameterEntryValue[1];
});
}
return parameters;
}
} | class RcdHistoryRouter {
constructor() {
this.routes = {};
this.defaultRoute;
window.onpopstate = (event) => this.setState(event.state);
}
init() {
return this;
}
addDefaultRoute(callback) {
this.defaultRoute = callback;
return this;
}
addRoute(route, callback) {
this.routes[route] = callback;
return this;
}
setState(state) {
if (state) {
history.pushState(state, null, '#' + state);
var parametersIndex = state.indexOf("?");
var route = parametersIndex == -1 ? state : state.substring(0, parametersIndex);
this.routes[route]();
} else {
this.defaultRoute();
history.pushState(state, null, '#');
}
return this;
}
getCurrentState() {
return location.hash && location.hash.substring(1);
}
refreshState() {
this.setState(this.getCurrentState());
}
getParameters() {
var currentState = this.getCurrentState();
var parametersIndex = currentState.indexOf("?");
var parameters = {};
if (parametersIndex !== -1) {
var parametersString = currentState.substring(parametersIndex + 1);
parametersString.split('&').forEach((parameterEntry) => {
var parameterEntryValue = parameterEntry.split('=');
parameters[parameterEntryValue[0]] = parameterEntryValue[1];
});
}
return parameters;
}
} |
Make plugin name bold in /help | import Plugin from "./Plugin";
export default class MasterPlugin extends Plugin {
static get plugin() {
return {
name: "MasterPlugin",
description: "",
help: "This plugin has access to PluginManager and will perform all the 'meta'/'super' actions.",
type: Plugin.Type.SPECIAL,
visibility: Plugin.Visibility.HIDDEN,
needs: {
database: true,
utils: true
}
};
}
constructor(listener, pluginManager) {
super(listener);
this.pluginManager = pluginManager;
}
onCommand({message, command, args}, reply) {
if (command !== "help") return;
const data = this.pluginManager.plugins
.map(pl => pl.plugin)
.filter(pl => pl.visibility !== Plugin.Visibility.HIDDEN);
if (args.length === 0) {
reply({
type: "text",
text: data
.map(pl => `*${pl.name}*: ${pl.description}`)
.join("\n"),
options: {
parse_mode: "markdown",
disable_web_page_preview: true
}
});
} else {
const pluginName = args[0].toLowerCase();
const plugin = data
.filter(pl => pl.name.toLowerCase() === pluginName)[0];
reply({
type: "text",
text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`,
options: {
parse_mode: "markdown",
disable_web_page_preview: true
}
});
}
}
} | import Plugin from "./Plugin";
export default class MasterPlugin extends Plugin {
static get plugin() {
return {
name: "MasterPlugin",
description: "",
help: "This plugin has access to PluginManager and will perform all the 'meta'/'super' actions.",
type: Plugin.Type.SPECIAL,
visibility: Plugin.Visibility.HIDDEN,
needs: {
database: true,
utils: true
}
};
}
constructor(listener, pluginManager) {
super(listener);
this.pluginManager = pluginManager;
}
onCommand({message, command, args}, reply) {
if (command !== "help") return;
const data = this.pluginManager.plugins
.map(pl => pl.plugin)
.filter(pl => pl.visibility !== Plugin.Visibility.HIDDEN);
if (args.length === 0) {
reply({
type: "text",
text: data
.map(pl => `${pl.name}: ${pl.description}`)
.join("\n"),
options: {
parse_mode: "markdown",
disable_web_page_preview: true
}
});
} else {
const pluginName = args[0].toLowerCase();
const plugin = data
.filter(pl => pl.name.toLowerCase() === pluginName)[0];
reply({
type: "text",
text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`,
options: {
parse_mode: "markdown",
disable_web_page_preview: true
}
});
}
}
} |
Write a specific message to the queue | async function activemq_service(args) {
/*
description("ActiveMQ Service")
base_component_id("activemq_service")
load_once_from_file(true)
only_run_on_server(true)
*/
var promise = new Promise(async function(returnfn) {
//
// test_connection
//
try {
const stompit = require('stompit');
console.log(1)
const connectOptions = {
'host': args.host,
'port': args.port,
'connectHeaders':{
'host': '/',
'login': args.username,
'passcode': args.password
}
};
stompit.connect(connectOptions, function(error, client) {
console.log(2)
if (error) {
console.log('connect error ' + error.message);
return;
}
const sendHeaders = {
'destination':args.destination,
'content-type': 'text/plain'
};
console.log(3)
const frame = client.send(sendHeaders);
frame.write(args.message);
frame.end();
console.log(4)
returnfn({success: args})
});
} catch (err) {
console.log(6)
returnfn({error: err})
}
})
var ret = await promise
return ret
}
| async function activemq_service(args) {
/*
description("ActiveMQ Service")
base_component_id("activemq_service")
load_once_from_file(true)
only_run_on_server(true)
*/
var promise = new Promise(async function(returnfn) {
//
// test_connection
//
try {
const stompit = require('stompit');
console.log(1)
const connectOptions = {
'host': args.host,
'port': args.port,
'connectHeaders':{
'host': '/',
'login': args.username,
'passcode': args.password
}
};
stompit.connect(connectOptions, function(error, client) {
console.log(2)
if (error) {
console.log('connect error ' + error.message);
return;
}
const sendHeaders = {
'destination':args.destination,
'content-type': 'text/plain'
};
console.log(3)
const frame = client.send(sendHeaders);
frame.write('hello');
frame.end();
console.log(4)
returnfn({success: args})
});
} catch (err) {
console.log(6)
returnfn({error: err})
}
})
var ret = await promise
return ret
}
|
Fix issues with loading from dict | # Copyright (c) 2010 John Reese
# Licensed under the MIT license
import yaml
from combine import CombineError
MANIFEST_FORMAT = 1
class Manifest:
def __init__(self):
self.properties = {"manifest-format": MANIFEST_FORMAT}
self.actions = []
def add_property(self, name, value):
self.properties[name] = value
def add_action(self, action):
self.actions.append(action)
def to_dict(self):
"""
Generate a dictionary representation of the Manifest object.
"""
return dict(self.properties, actions=self.actions)
@classmethod
def from_dict(cls, data):
"""
Given a dictionary object, generate a new Manifest object.
"""
format = data["manifest-format"]
if (format > MANIFEST_FORMAT or format < 0):
raise CombineError("Unsupported manifest format")
mft = Manifest()
for key, value in data.items():
if key == "actions":
for action in value:
mft.add_action(dict(action))
else:
mft.add_property(key, value)
return mft
def to_yaml(self):
"""
Generate a YAML data string representing the Manifest object.
"""
str = yaml.safe_dump(self.to_dict(), default_flow_style=False)
return str
@classmethod
def from_yaml(cls, str):
"""
Given a string of YAML data, generate a new Manifest object.
"""
data = yaml.safe_load(str)
return cls.from_dict(data)
| # Copyright (c) 2010 John Reese
# Licensed under the MIT license
import yaml
from combine import CombineError
MANIFEST_FORMAT = 1
class Manifest:
def __init__(self):
self.properties = {"manifest-format": MANIFEST_FORMAT}
self.actions = []
def add_property(self, name, value):
self.properties[name] = value
def add_action(self, action):
self.actions.append(action)
def to_dict(self):
"""
Generate a dictionary representation of the Manifest object.
"""
return dict(self.properties, actions=self.actions)
@classmethod
def from_dict(cls, data):
"""
Given a dictionary object, generate a new Manifest object.
"""
format = data["manifest-format"]
if (format > MANIFEST_FORMAT or format < 0):
raise CombineError("Unsupported manifest format")
mft = Manifest()
for key, value in data.items():
if key == "actions":
for action in value:
mft.add_action(action)
else:
mft.add_property(key, value)
for action in data["actions"]:
mft.add_action(action)
return mft
def to_yaml(self):
"""
Generate a YAML data string representing the Manifest object.
"""
str = yaml.safe_dump(self.to_dict(), default_flow_style=False)
return str
@classmethod
def from_yaml(cls, str):
"""
Given a string of YAML data, generate a new Manifest object.
"""
data = yaml.safe_load(str)
return cls.from_dict(data)
|
Replace "type" form option with "entry_type". | <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\UserBundle\Configuration;
use Darvin\ConfigBundle\Configuration\AbstractConfiguration;
use Darvin\ConfigBundle\Parameter\ParameterModel;
/**
* Configuration
*
* @method array getNotificationEmails()
*/
class Configuration extends AbstractConfiguration
{
/**
* {@inheritdoc}
*/
public function getModel()
{
return array(
new ParameterModel('notification_emails', ParameterModel::TYPE_ARRAY, array(), array(
'form' => array(
'options' => array(
'entry_type' => 'Symfony\Component\Form\Extension\Core\Type\EmailType',
'allow_add' => true,
'allow_delete' => true,
),
),
)),
);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'darvin_user';
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\UserBundle\Configuration;
use Darvin\ConfigBundle\Configuration\AbstractConfiguration;
use Darvin\ConfigBundle\Parameter\ParameterModel;
/**
* Configuration
*
* @method array getNotificationEmails()
*/
class Configuration extends AbstractConfiguration
{
/**
* {@inheritdoc}
*/
public function getModel()
{
return array(
new ParameterModel('notification_emails', ParameterModel::TYPE_ARRAY, array(), array(
'form' => array(
'options' => array(
'type' => 'Symfony\Component\Form\Extension\Core\Type\EmailType',
'allow_add' => true,
'allow_delete' => true,
),
),
)),
);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'darvin_user';
}
}
|
Add extension to DI configuration | <?php
namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('dms_twig_extension');
$rootNode->children()
->arrayNode('fabpot')
->addDefaultsIfNotSet()
->children()
->booleanNode('i18n')->defaultFalse()->end()
->booleanNode('debug')->defaultFalse()->end()
->booleanNode('text')->defaultTrue()->end()
->booleanNode('intl')->defaultTrue()->end()
->end()
->end();
$rootNode->children()
->arrayNode('dms')
->addDefaultsIfNotSet()
->children()
->booleanNode('textual_date')->defaultTrue()->end()
->booleanNode('pad_string')->defaultTrue()->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('dms_twig_extension');
$rootNode->children()
->arrayNode('fabpot')
->addDefaultsIfNotSet()
->children()
->booleanNode('i18n')->defaultFalse()->end()
->booleanNode('debug')->defaultFalse()->end()
->booleanNode('text')->defaultTrue()->end()
->booleanNode('intl')->defaultTrue()->end()
->end()
->end();
$rootNode->children()
->arrayNode('dms')
->addDefaultsIfNotSet()
->children()
->booleanNode('textual_date')->defaultTrue()->end()
->end()
->end();
return $treeBuilder;
}
}
|
Fix bug for numpy's irfftn
address #232
Fix bug for numpy's irfftn. The size of the returned array must be
passed because the returned size is potentially not unique. Without
this change only the return kernel would possibly have the wrong shape. | from .abstract import _AbstractMicrostructureBasis
import numpy as np
class _RealFFTBasis(_AbstractMicrostructureBasis):
def __init__(self, *args, **kwargs):
super(_RealFFTBasis, self).__init__(*args, **kwargs)
def _fftn(self, X, threads=1, avoid_copy=True):
if self._pyfftw:
return self._fftmodule.rfftn(np.ascontiguousarray(X),
axes=self._axes,
threads=threads,
planner_effort='FFTW_ESTIMATE',
overwrite_input=True,
avoid_copy=avoid_copy)()
else:
return self._fftmodule.rfftn(X, axes=self._axes)
def _ifftn(self, X, s=None, threads=1, avoid_copy=True):
if self._pyfftw:
return self._fftmodule.irfftn(np.ascontiguousarray(X), s=s,
axes=self._axes,
threads=threads,
planner_effort='FFTW_ESTIMATE',
avoid_copy=avoid_copy)().real
else:
return self._fftmodule.irfftn(X, axes=self._axes, s=s).real
def discretize(self, X):
raise NotImplementedError
| from .abstract import _AbstractMicrostructureBasis
import numpy as np
class _RealFFTBasis(_AbstractMicrostructureBasis):
def __init__(self, *args, **kwargs):
super(_RealFFTBasis, self).__init__(*args, **kwargs)
def _fftn(self, X, threads=1, avoid_copy=True):
if self._pyfftw:
return self._fftmodule.rfftn(np.ascontiguousarray(X),
axes=self._axes,
threads=threads,
planner_effort='FFTW_ESTIMATE',
overwrite_input=True,
avoid_copy=avoid_copy)()
else:
return self._fftmodule.rfftn(X, axes=self._axes)
def _ifftn(self, X, s=None, threads=1, avoid_copy=True):
if self._pyfftw:
return self._fftmodule.irfftn(np.ascontiguousarray(X), s=s,
axes=self._axes,
threads=threads,
planner_effort='FFTW_ESTIMATE',
avoid_copy=avoid_copy)().real
else:
return self._fftmodule.irfftn(X, axes=self._axes).real
def discretize(self, X):
raise NotImplementedError
|
Handle empty response form /suggest | /**
* Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017.
*/
import html from '../../templates/helpers';
const template = (context) => {
return new Promise((resolve) => {
context.api.getSuggestedSymptoms(context.data).then((suggestedSymptoms) => {
if (!suggestedSymptoms.length) {
resolve('<p><i class="fa fa-circle-o-notch fa-spin fa-fw"></i> I am thinking...</p>');
document.getElementById('next-step').click();
}
resolve(html`
<h5 class="card-title">Do you have any of the following symptoms?</h5>
<div class="card-text">
<form>
${suggestedSymptoms.map(symptom => {
return html`
<div class="form-group">
<label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0">
<input id="${symptom.id}" type="checkbox" class="input-symptom custom-control-input">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">${symptom.name}</span>
</label>
</div>
`;
})}
</form>
<p class="text-muted small"><i class="fa fa-info-circle"></i> This is a list of symptoms suggested by our AI, basing on the information gathered so far during the interview.</p>
</div>
`);
});
});
};
export default template;
| /**
* Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017.
*/
import html from '../../templates/helpers';
const template = (context) => {
return new Promise((resolve) => {
context.api.getSuggestedSymptoms(context.data).then((suggestedSymptoms) => {
resolve(html`
<h5 class="card-title">Do you have any of the following symptoms?</h5>
<div class="card-text">
<form>
${suggestedSymptoms.map(symptom => {
return html`
<div class="form-group">
<label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0">
<input id="${symptom.id}" type="checkbox" class="input-symptom custom-control-input">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">${symptom.name}</span>
</label>
</div>
`;
})}
</form>
<p class="text-muted small"><i class="fa fa-info-circle"></i> This is a list of symptoms suggested by our AI, basing on the information gathered so far during the interview.</p>
</div>
`);
});
});
};
export default template;
|
Use 'end' instead of 'exit' to guarantee that streams are flushed. | var cp = require('child_process');
var Q = require('q');
var createError = require('./createError');
// Executes a shell command
// Buffers the stdout and stderr
// If an error occurs, a meaningfull error is generated
function cmd(command, args, options) {
var process,
stderr = '',
stdout = '',
deferred = Q.defer();
process = cp.spawn(command, args, options);
process.stdout.on('data', function (data) { stdout += data.toString(); });
process.stderr.on('data', function (data) { stderr += data.toString(); });
process.on('close', function (code) {
var fullCommand,
error;
process.removeAllListeners();
if (code) {
// Generate the full command to be presented in the error message
if (!Array.isArray(args)) {
args = [];
}
fullCommand = command;
fullCommand += args.length ? ' ' + args.join(' ') : '';
// Build the error instance
error = createError('Failed to execute "' + fullCommand + '", exit code of #' + code, 'ECMDERR', {
details: stderr,
exitCode: code
});
return deferred.reject(error);
}
return deferred.resolve(stdout);
});
return deferred.promise;
}
module.exports = cmd; | var cp = require('child_process');
var Q = require('q');
var createError = require('./createError');
// Executes a shell command
// Buffers the stdout and stderr
// If an error occurs, a meaningfull error is generated
function cmd(command, args, options) {
var process,
stderr = '',
stdout = '',
deferred = Q.defer();
process = cp.spawn(command, args, options);
process.stdout.on('data', function (data) { stdout += data.toString(); });
process.stderr.on('data', function (data) { stderr += data.toString(); });
process.on('exit', function (code) {
var fullCommand,
error;
process.removeAllListeners();
if (code) {
// Generate the full command to be presented in the error message
if (!Array.isArray(args)) {
args = [];
}
fullCommand = command;
fullCommand += args.length ? ' ' + args.join(' ') : '';
// Build the error instance
error = createError('Failed to execute "' + fullCommand + '", exit code of #' + code, 'ECMDERR', {
details: stderr,
exitCode: code
});
return deferred.reject(error);
}
return deferred.resolve(stdout);
});
return deferred.promise;
}
module.exports = cmd; |
Fix misplaced colon in test suite | #! usr/bin/env python3
import unittest
from sqlviz import Schema
# Tests will go here...eventually
class InventorySchemaSpec (unittest.TestCase):
def setUp (self):
self.schema = Schema(
"""DROP TABLE Inventory;
CREATE TABLE Inventory
(
id INT PRIMARY KEY,
product VARCHAR(50) UNIQUE,
quantity INT,
price DECIMAL(18,2)
);""")
def test_n_tables(self):
self.assertEqual(self.schema.n_tables(), 1,
"The Inventory schema should contain 1 table.")
def test_n_keys(self):
self.assertEqual(self.schema.n_keys(), {"PRIMARY KEY": 1, "FOREIGN KEY": 0},
"The Inventory schema should contain 1 primary key and 0 foreign keys.")
def test_n_datatypes(self):
self.assertEqual(self.schema.n_datatypes(), {"INT": 2, "VARCHAR": 1, "DECIMAL": 1},
"The Inventory schema should contain two INTs, one VARCHAR, and one DECIMAL")
def lengths(self):
self.assertEqual(self.schema.lengths(), {"VARCHAR": [50], "DECIMAL": [(18,2)]},
"The Inventory schema should contain one VARCHAR(50) and one DECIMAL(18,2)")
if __name__ == '__main__':
unittest.main()
| #! usr/bin/env python3
import unittest
from sqlviz import Schema
# Tests will go here...eventually
class InventorySchemaSpec (unittest.TestCase):
def setUp (self):
self.schema = Schema(
"""DROP TABLE Inventory;
CREATE TABLE Inventory
(
id INT PRIMARY KEY,
product VARCHAR(50) UNIQUE,
quantity INT,
price DECIMAL(18,2)
);""")
def test_n_tables(self):
self.assertEqual(self.schema.n_tables(), 1,
"The Inventory schema should contain 1 table.")
def test_n_keys(self):
self.assertEqual(self.schema.n_keys(), {"PRIMARY KEY": 1, "FOREIGN KEY:" 0},
"The Inventory schema should contain 1 primary key and 0 foreign keys.")
def test_n_datatypes(self):
self.assertEqual(self.schema.n_datatypes(), {"INT": 2, "VARCHAR": 1, "DECIMAL": 1},
"The Inventory schema should contain two INTs, one VARCHAR, and one DECIMAL")
def lengths(self):
self.assertEqual(self.schema.lengths(), {"VARCHAR": [50], "DECIMAL": [(18,2)]},
"The Inventory schema should contain one VARCHAR(50) and one DECIMAL(18,2)")
if __name__ == '__main__':
unittest.main()
|
Set a timer to detect when the mouse stops moving | buttonCodeToChar = {1: "Left", 2: "Middle", 3: "Right"};
buttonCharToCode = {"Left": 1, "Middle": 2, "Right": 3};
function Mouse() {
// It'd be good to get this info on construction
this.x = -1;
this.y = -1;
this.dx = 0;
this.dy = 0;
this.events = [];
this.timeout = null;
this.UpdatePosition = function(nx, ny) {
clearTimeout(this.timeout);
// It's impossible to know where the mouse is when it's first created,
// before a mousemove event is fired. If we do nothing the initial
// dx and dy are incorrect, so we hack this to not update the dx and dy
// till we've gotten one mousemove
if (this.x == -1 && this.y == -1) {
this.x = nx;
this.y = ny;
} else {
this.dx = nx - this.x;
this.dy = ny - this.y;
this.x = nx;
this.y = ny;
}
this.timeout = setTimeout(this.StoppedMoving.bind(this), 100);
}
this.ButtonDown = function(button) {
if (button instanceof Number) {
button = buttonCodeToChar(button);
}
if (this[button] == false || this[button] == null) {
return false;
}
return true;
}
this.StoppedMoving = function() {
this.dx = 0;
this.dy = 0;
}
}
function MouseEvent(button, action) {
this.button = button;
this.action = action;
}
| buttonCodeToChar = {1: "Left", 2: "Middle", 3: "Right"};
buttonCharToCode = {"Left": 1, "Middle": 2, "Right": 3};
function Mouse() {
// It'd be good to get this info on construction
this.x = -1;
this.y = -1;
this.dx = 0;
this.dy = 0;
this.events = [];
this.UpdatePosition = function(nx, ny) {
// It's impossible to know where the mouse is when it's first created,
// before a mousemove event is fired. If we do nothing the initial
// dx and dy are incorrect, so we hack this to not update the dx and dy
// till we've gotten one mousemove
if (this.x == -1 && this.y == -1) {
this.x = nx;
this.y = ny;
} else {
this.dx = nx - this.x;
this.dy = ny - this.y;
this.x = nx;
this.y = ny;
}
}
this.ButtonDown = function(button) {
if (button instanceof Number) {
button = buttonCodeToChar(button);
}
if (this[button] == false || this[button] == null) {
return false;
}
return true;
}
}
function MouseEvent(button, action) {
this.button = button;
this.action = action;
}
|
Add Evil Martians link to footer | import React, { Component } from "react"
import styles from "./index.css"
import logo from "./evilmartians.svg"
export default class Footer extends Component {
render() {
return (
<footer className={ styles.root } role="contentinfo">
<div className={ styles.inner }>
<div className={ styles.info }>
<p className={ styles.license }>
{ "Distributed under the MIT License." }
</p>
<p className={ styles.issue }>{ "Found an issue?" }
<a
className={ styles.report }
href="https://github.com/postcss/postcss.org/issues"
>
{ "Report it!" }
</a>
</p>
</div>
<div className={ styles.logo }>
<a
className={ styles.logoLink }
href="https://evilmartians.com/"
>
<img
alt="Evil Martians"
className={ styles.logoInner }
src={ logo }
/>
</a>
</div>
</div>
</footer>
)
}
}
| import React, { Component } from "react"
import styles from "./index.css"
import logo from "./evilmartians.svg"
export default class Footer extends Component {
render() {
return (
<footer className={ styles.root } role="contentinfo">
<div className={ styles.inner }>
<div className={ styles.info }>
<p className={ styles.license }>
{ "Distributed under the MIT License." }
</p>
<p className={ styles.issue }>{ "Found an issue?" }
<a
className={ styles.report }
href="https://github.com/postcss/postcss.org/issues"
>
{ "Report it!" }
</a>
</p>
</div>
<div className={ styles.logo }>
<img
alt="Evil Martians Logo"
className={ styles.logoInner }
src={ logo }
/>
</div>
</div>
</footer>
)
}
}
|
Print table if no file format provided | import csv
import json
import os
from tabulate import tabulate
def write_data(d, u, f=None):
if f is not None:
directory = './data/'
if not os.path.exists(directory):
os.makedirs(directory)
file = open(directory + u + '.' + f, 'w')
if f == 'json':
file.write(json.dumps(d, indent=4))
elif f == 'csv':
keys = d[0].keys()
dw = csv.DictWriter(file, fieldnames=keys)
dw.writeheader()
dw.writerows(d)
elif f == 'md':
file.write('## %s - GitHub repositories\n' % u)
for row in d:
file.write(
'#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'],
row['desc'],
row['lang'],
row['stars']))
elif f == 'txt':
file.write('%s - GitHub repositories\n\n' % u)
for row in d:
file.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'],
row['desc'],
row['lang'],
row['stars']))
file.close()
else:
print(tabulate(d, headers="keys"))
| import colour
import csv
import json
import os
import pprint
# write to file as json, csv, markdown, plaintext or print table
def write_data(data, user, format=None):
if format is not None:
directory = './data/'
if not os.path.exists(directory):
os.makedirs(directory)
f = open(directory + user + '.' + format, 'w')
if format == 'json':
f.write(json.dumps(data, indent=4))
elif format == 'csv':
keys = data[0].keys()
dw = csv.DictWriter(f, fieldnames=keys)
dw.writeheader()
dw.writerows(data)
elif format == 'md':
f.write('## %s - GitHub repositories\n' % user)
for row in data:
f.write(
'#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'],
row['desc'],
row['lang'],
row['stars']))
elif format == 'txt':
f.write('%s - GitHub repositories\n\n' % user)
for row in data:
f.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'],
row['desc'],
row['lang'],
row['stars']))
f.close()
|
Add the new tags at the end | <?php
namespace PMT\WebBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\JsonResponse;
class AjaxController extends Controller
{
/**
* @Route("/ajax/tags.json", name="pmtweb_ajax_tags")
* @Method("post")
*/
public function tagsAction()
{
$term = trim($this->getRequest()->request->get('q'));
$tags = $this->getDoctrine()->getRepository('PMT\CoreBundle\Entity\Tag')
->findByName($term);
$tagObjects = array_map(
function ($tag) {
return array(
'id' => $tag->getName(),
'text' => $tag->getName(),
);
},
$tags
);
if ($this->getRequest()->request->get('add_new') && !in_array($term, $tags)) {
$tagObjects[] =
array(
'id' => $term,
'text' => 'new: ' . $term,
);
}
$response = new JsonResponse();
$response->setData(
array(
'tags' => $tagObjects,
)
);
return $response;
}
}
| <?php
namespace PMT\WebBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\JsonResponse;
class AjaxController extends Controller
{
/**
* @Route("/ajax/tags.json", name="pmtweb_ajax_tags")
* @Method("post")
*/
public function tagsAction()
{
$term = trim($this->getRequest()->request->get('q'));
$tags = $this->getDoctrine()->getRepository('PMT\CoreBundle\Entity\Tag')
->findByName($term);
$tagObjects = array_map(
function ($tag) {
return array(
'id' => $tag->getName(),
'text' => $tag->getName(),
);
},
$tags
);
if ($this->getRequest()->request->get('add_new') && !in_array($term, $tags)) {
array_unshift(
$tagObjects,
array(
'id' => $term,
'text' => 'new: ' . $term,
)
);
}
$response = new JsonResponse();
$response->setData(
array(
'tags' => $tagObjects,
)
);
return $response;
}
}
|
Use ExecutorService instead of Executor | package de.haw.vs.nameservice.connectionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server implements IServer {
private ServerSocket serverSocket;
private volatile boolean stopping;
private final Logger log = LoggerFactory.getLogger(Server.class);
private final int maxConcurrentConnections = 30;
private final ExecutorService threadPool = Executors.newFixedThreadPool(maxConcurrentConnections);
@Override
public void initServer(int port) {
try {
serverSocket = new ServerSocket(port);
this.stopping = false;
} catch (IOException e) {
this.stopping = true;
log.error("Could not start server at port: " + String.valueOf(port), e);
}
}
@Override
public void run() {
log.info("Started server");
while (!stopping) {
try {
Socket clientSocket = serverSocket.accept();
IClientRequestHandler clientRequest = new ClientRequestHandler(clientSocket);
threadPool.submit(clientRequest);
} catch (IOException e) {
log.warn("Error while client tried to connect", e);
}
}
try {
serverSocket.close();
} catch (IOException e) {
log.warn("Could not close server socket");
}
log.info("Stopped server");
}
public boolean isStopping() {
return stopping;
}
public void stop() {
this.stopping = true;
}
}
| package de.haw.vs.nameservice.connectionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Server implements IServer {
private ServerSocket serverSocket;
private volatile boolean stopping;
private final Logger log = LoggerFactory.getLogger(Server.class);
private final int maxConcurrentConnections = 30;
private final Executor threadPool = Executors.newFixedThreadPool(maxConcurrentConnections);
@Override
public void initServer(int port) {
try {
serverSocket = new ServerSocket(port);
this.stopping = false;
} catch (IOException e) {
this.stopping = true;
log.error("Could not start server at port: " + String.valueOf(port), e);
}
}
@Override
public void run() {
log.info("Started server");
while (!stopping) {
try {
Socket clientSocket = serverSocket.accept();
IClientRequestHandler clientRequest = new ClientRequestHandler(clientSocket);
threadPool.execute(clientRequest);
} catch (IOException e) {
log.warn("Error while client tried to connect", e);
}
}
try {
serverSocket.close();
} catch (IOException e) {
log.warn("Could not close server socket");
}
log.info("Stopped server");
}
public boolean isStopping() {
return stopping;
}
public void stop() {
this.stopping = true;
}
}
|
Fix broken reference to YouTube metadata | <?php
require_once __DIR__ . '/../bootstrap.php';
$client = new Madcoda\Youtube(['key' => $config->youtube->key]);
$mostRecentVideoDateTime = $db->getRead()->fetchValue(
"SELECT `datetime` FROM `jpemeric_stream`.`youtube` ORDER BY `datetime` DESC LIMIT 1"
);
$mostRecentVideoDateTime = new DateTime($mostRecentVideoDateTime);
$playlist = $client->getPlaylistItemsByPlaylistId($config->youtube->favorites_playlist, 10);
foreach ($playlist as $playlistItem) {
$datetime = new DateTime($playlistItem->snippet->publishedAt);
if ($datetime <= $mostRecentVideoDateTime) {
break;
}
$uniqueVideoCheck = $db->getRead()->fetchValue(
"SELECT 1 FROM `jpemeric_stream`.`youtube` WHERE `video_id` = :video_id LIMIT 1",
['video_id' => $playlistItem->contentDetails->videoId]
);
if ($uniqueVideoCheck !== false) {
continue;
}
$datetime->setTimezone(new DateTimeZone('America/Phoenix'));
$db->getWrite()->perform(
"INSERT INTO `jpemeric_stream`.`youtube` (`video_id`, `datetime`, `metadata`) " .
"VALUES (:video_id, :datetime, :metadata)",
[
'video_id' => $playlistItem->contentDetails->videoId,
'datetime' => $datetime->format('Y-m-d H:i:s'),
'metadata' => json_encode($playlistItem),
]
);
}
| <?php
require_once __DIR__ . '/../bootstrap.php';
$client = new Madcoda\Youtube(['key' => $config->youtube->key]);
$mostRecentVideoDateTime = $db->getRead()->fetchValue(
"SELECT `datetime` FROM `jpemeric_stream`.`youtube` ORDER BY `datetime` DESC LIMIT 1"
);
$mostRecentVideoDateTime = new DateTime($mostRecentVideoDateTime);
$playlist = $client->getPlaylistItemsByPlaylistId($config->youtube->favorites_playlist, 10);
foreach ($playlist as $playlistItem) {
$datetime = new DateTime($playlistItem->snippet->publishedAt);
if ($datetime <= $mostRecentVideoDateTime) {
break;
}
$uniqueVideoCheck = $db->getRead()->fetchValue(
"SELECT 1 FROM `jpemeric_stream`.`youtube` WHERE `video_id` = :video_id LIMIT 1",
['video_id' => $playlistItem->contentDetails->videoId]
);
if ($uniqueVideoCheck !== false) {
continue;
}
$datetime->setTimezone(new DateTimeZone('America/Phoenix'));
$db->getWrite()->perform(
"INSERT INTO `jpemeric_stream`.`youtube` (`video_id`, `datetime`, `metadata`) " .
"VALUES (:video_id, :datetime, :metadata)",
[
'video_id' => $playlistItem->contentDetails->videoId,
'datetime' => $datetime->format('Y-m-d H:i:s'),
'metadata' => json_encode($metadata),
]
);
}
|
Add falsey arguments check to loop condition | (function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define('stack-generator', ['stackframe'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('stackframe'));
} else {
root.StackGenerator = factory(root.StackFrame);
}
}(this, function(StackFrame) {
return {
backtrace: function StackGenerator$$backtrace(opts) {
var stack = [];
var maxStackSize = 10;
if (typeof opts === 'object' && typeof opts.maxStackSize === 'number') {
maxStackSize = opts.maxStackSize;
}
var curr = arguments.callee;
while (curr && stack.length < maxStackSize && curr['arguments']) {
// Allow V8 optimizations
var args = new Array(curr['arguments'].length);
for (var i = 0; i < args.length; ++i) {
args[i] = curr['arguments'][i];
}
if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
stack.push(new StackFrame({functionName: RegExp.$1 || undefined, args: args}));
} else {
stack.push(new StackFrame({args: args}));
}
try {
curr = curr.caller;
} catch (e) {
break;
}
}
return stack;
}
};
}));
| (function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define('stack-generator', ['stackframe'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('stackframe'));
} else {
root.StackGenerator = factory(root.StackFrame);
}
}(this, function(StackFrame) {
return {
backtrace: function StackGenerator$$backtrace(opts) {
var stack = [];
var maxStackSize = 10;
if (typeof opts === 'object' && typeof opts.maxStackSize === 'number') {
maxStackSize = opts.maxStackSize;
}
var curr = arguments.callee;
while (curr && stack.length < maxStackSize) {
if (!curr['arguments']) {
break;
}
// Allow V8 optimizations
var args = new Array(curr['arguments'].length);
for (var i = 0; i < args.length; ++i) {
args[i] = curr['arguments'][i];
}
if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
stack.push(new StackFrame({functionName: RegExp.$1 || undefined, args: args}));
} else {
stack.push(new StackFrame({args: args}));
}
try {
curr = curr.caller;
} catch (e) {
break;
}
}
return stack;
}
};
}));
|
Insert custom commands through the getCommands() function. | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Languages
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Templates Toolbar Class
*
* @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya>
* @category Nooku
* @package Nooku_Server
* @subpackage Languages
*/
class ComTemplatesControllerToolbarTemplate extends ComDefaultControllerToolbarDefault
{
public function getCommands()
{
$this->addSeperator()
->addPreview();
return parent::getCommands();
}
protected function _commandPreview(KControllerToolbarCommand $command)
{
$state = $this->getController()->getModel()->getState();
$template = $state->name;
$base = $state->application == 'site' ? JURI::root() : JURI::base();
$command->append(array(
'width' => '640',
'height' => '480',
))->append(array(
'attribs' => array(
'href' => $base.'index.php?tp=1&template='.$template,
'target' => 'preview'
)
));
}
} | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Languages
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Templates Toolbar Class
*
* @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya>
* @category Nooku
* @package Nooku_Server
* @subpackage Languages
*/
class ComTemplatesControllerToolbarTemplate extends ComDefaultControllerToolbarDefault
{
public function __construct(KConfig $config)
{
parent::__construct($config);
$this->addSeperator()
->addPreview();
}
protected function _commandPreview(KControllerToolbarCommand $command)
{
$state = $this->getController()->getModel()->getState();
$template = $state->name;
$base = $state->application == 'site' ? JURI::root() : JURI::base();
$command->append(array(
'width' => '640',
'height' => '480',
))->append(array(
'attribs' => array(
'href' => $base.'index.php?tp=1&template='.$template,
'target' => 'preview'
)
));
}
} |
Check if error available on output | """Test mixins."""
import os
import sys
import six
from django.core.management import call_command
from django.utils.six import StringIO
class CallCommandMixin(object):
"""A mixin to provide command execution shortcuts."""
def setUp(self):
"""Replace stdin"""
super(CallCommandMixin, self).setUp()
self.stdin = sys.stdin
def tearDown(self):
sys.stdin = self.stdin
def import_report(self, path):
"""Import test report from file."""
with open(path) as fp:
buf = six.StringIO(fp.read())
sys.stdin = buf
out = StringIO()
call_command("import_aggregated_report", "--pipe", stdout=out)
return out.getvalue()
def import_reports(self, folder="reports"):
"""Import reports from folder."""
path = os.path.join(os.path.dirname(__file__), folder)
for f in os.listdir(path):
fpath = os.path.join(path, f)
if f.startswith(".") or not os.path.isfile(fpath):
continue
self.import_report(fpath)
def import_fail_reports(self, folder="fail-reports"):
"""Import failed reports from folder."""
path = os.path.join(os.path.dirname(__file__), folder)
for f in os.listdir(path):
fpath = os.path.join(path, f)
if f.startswith(".") or not os.path.isfile(fpath):
continue
ret = self.import_report(fpath)
self.assertNotIn('ERROR-PARSING', ret)
| """Test mixins."""
import os
import sys
import six
from django.core.management import call_command
class CallCommandMixin(object):
"""A mixin to provide command execution shortcuts."""
def setUp(self):
"""Replace stdin"""
super(CallCommandMixin, self).setUp()
self.stdin = sys.stdin
def tearDown(self):
sys.stdin = self.stdin
def import_report(self, path):
"""Import test report from file."""
with open(path) as fp:
buf = six.StringIO(fp.read())
sys.stdin = buf
call_command("import_aggregated_report", "--pipe")
def import_reports(self, folder="reports"):
"""Import reports from folder."""
path = os.path.join(os.path.dirname(__file__), folder)
for f in os.listdir(path):
fpath = os.path.join(path, f)
if f.startswith(".") or not os.path.isfile(fpath):
continue
self.import_report(fpath)
def import_fail_reports(self, folder="fail-reports"):
"""Import failed reports from folder."""
path = os.path.join(os.path.dirname(__file__), folder)
for f in os.listdir(path):
fpath = os.path.join(path, f)
if f.startswith(".") or not os.path.isfile(fpath):
continue
self.import_report(fpath)
# TODO check return code different from 0
|
Sort elements according to newEntityIds order. | import { without } from 'substance'
export default function updateEntityChildArray(editorSession, nodeId, tagName, attribute, oldEntityIds, newEntityIds) {
editorSession.transaction(tx => {
let node = tx.get(nodeId)
let addedEntityIds = without(newEntityIds, ...oldEntityIds)
let removedEntityIds = without(oldEntityIds, ...newEntityIds)
// Remove old entities
removedEntityIds.forEach(entityId => {
let entityRefNode = node.find(`${tagName}[${attribute}=${entityId}]`)
node.removeChild(entityRefNode)
// Remove it completely
tx.delete(entityRefNode.id)
})
// Create new entities
addedEntityIds.forEach(entityId => {
let entityRefNode = node.find(`${tagName}[${attribute}=${entityId}]`)
if (!entityRefNode) {
let opts = {}
if (attribute === 'id') {
opts = { id: entityId }
}
entityRefNode = tx.createElement(tagName, opts)
if (attribute !== 'id') {
entityRefNode.setAttribute(attribute, entityId)
}
}
node.appendChild(entityRefNode)
})
let map = {}
let refs = tx.findAll(`${tagName}`)
refs.forEach(ref => {
const rid = ref.getAttribute('rid')
map[rid] = ref
})
node.children.forEach(child => {
node.removeChild(child)
})
newEntityIds.forEach(entityId => {
node.appendChild(map[entityId])
})
tx.setSelection(null)
})
}
| import { without } from 'substance'
export default function updateEntityChildArray(editorSession, nodeId, tagName, attribute, oldEntityIds, newEntityIds) {
editorSession.transaction(tx => {
let node = tx.get(nodeId)
let addedEntityIds = without(newEntityIds, ...oldEntityIds)
let removedEntityIds = without(oldEntityIds, ...newEntityIds)
// Remove old entities
removedEntityIds.forEach(entityId => {
let entityRefNode = node.find(`${tagName}[${attribute}=${entityId}]`)
node.removeChild(entityRefNode)
// Remove it completely
tx.delete(entityRefNode.id)
})
// Create new entities
addedEntityIds.forEach(entityId => {
let entityRefNode = node.find(`${tagName}[${attribute}=${entityId}]`)
if (!entityRefNode) {
let opts = {}
if (attribute === 'id') {
opts = { id: entityId }
}
entityRefNode = tx.createElement(tagName, opts)
if (attribute !== 'id') {
entityRefNode.setAttribute(attribute, entityId)
}
}
node.appendChild(entityRefNode)
})
// TODO: Now, sort elements according to newEntityIds order
// 1) create mapping table for all ref-nodes entityId -> refNode
// map = {'entity-12': <ref id="r1" rid="entity-12"/>}
// 2) node.empty()
// 3) iterate through newEntityIds and do node.append(map[entityId])
console.warn('TODO: implement sorting')
tx.setSelection(null)
})
}
|
Remove backslash escaping where it is not needed. | <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;
/**
* Anti-spam form type
*/
class AntiSpamType extends AbstractType
{
const ANTI_SPAM_TYPE_CLASS = __CLASS__;
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'label' => false,
'attr' => array(
'class' => 'title_field',
),
'constraints' => new Blank(),
'mapped' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'Symfony\Component\Form\Extension\Core\Type\TextType';
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'darvin_utils_anti_spam';
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;
/**
* Anti-spam form type
*/
class AntiSpamType extends AbstractType
{
const ANTI_SPAM_TYPE_CLASS = __CLASS__;
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'label' => false,
'attr' => array(
'class' => 'title_field',
),
'constraints' => new Blank(),
'mapped' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType';
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'darvin_utils_anti_spam';
}
}
|
Check observer callback functionhood at registration | /*
* debugger.io: An interactive web scripting sandbox
*
* observers.js: mutation observers
*/
define([
'config', 'utils', 'jquery', 'underscore',
'bus'
],
function(
config, utils, $, _, bus
) {
'use strict';
var observers = utils.module('observers');
var listeners = {};
var last_lid = 0;
var MutationObserver =
window.MutationObserver || window.WebKitMutationObserver;
bus.init(function(av) {
utils.log('init observers module');
var observer = new MutationObserver(function(mutations) {
// pass each mutation
_.each(mutations, function(mutation) {
// to each listener function
_.each(listeners, function(listener) { listener(mutation); });
});
});
observer.observe(document, { childList: true, subtree: true });
});
/**
* Register a new observer listener function
*
* @param {Function} callback - listener function, passed MutationRecord
* @return {Integer} unique listener id
*/
observers.register_listener = function(callback) {
if (!_.isFunction(callback) { return; });
var lid = last_lid++;
utils.log('registering observer listener', lid);
listeners[lid] = callback;
return lid;
};
/**
* Unregister an observer listener by id
*
* @param {Integer} lid - listener id
*/
observers.unregister_listener = function(lid) {
if (_.has(listeners, lid)) {
utils.log('unregistering observer listener', lid);
delete listeners[lid];
}
};
return observers;
});
| /*
* debugger.io: An interactive web scripting sandbox
*
* observers.js: mutation observers
*/
define([
'config', 'utils', 'jquery', 'underscore',
'bus'
],
function(
config, utils, $, _, bus
) {
'use strict';
var observers = utils.module('observers');
var listeners = {};
var last_lid = 0;
var MutationObserver =
window.MutationObserver || window.WebKitMutationObserver;
bus.init(function(av) {
utils.log('init observers module');
var observer = new MutationObserver(function(mutations) {
// pass each mutation
_.each(mutations, function(mutation) {
// to each listener function
_.each(listeners, function(listener) {
if (_.isFunction(listener)) { listener(mutation); }
});
});
});
observer.observe(document, { childList: true, subtree: true });
});
/**
* Register a new observer listener function
*
* @param {Function} callback - listener function, passed MutationRecord
* @return {Integer} unique listener id
*/
observers.register_listener = function(callback) {
var lid = last_lid++;
utils.log('registering observer listener', lid);
listeners[lid] = callback;
return lid;
};
/**
* Unregister an observer listener by id
*
* @param {Integer} lid - listener id
*/
observers.unregister_listener = function(lid) {
if (_.has(listeners, lid)) {
utils.log('unregistering observer listener', lid);
delete listeners[lid];
}
};
return observers;
});
|
Allow modification of the prohibited keys array, via class methods | <?php
namespace Silktide\LazyBoy\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* RestControllerTrait
*/
trait RestControllerTrait
{
private $prohibitedKeys = [
"password" => true,
"salt" => true
];
protected function success($data = null, $code = 200)
{
if ($data === null) {
$data = ["success" => true];
} else {
$data = $this->normaliseData($data);
}
return new JsonResponse($data, $code);
}
protected function error($message, $data = [], $code = 400)
{
$payload = [
"success" => false,
"error" => $message
];
if (!empty($data)) {
$payload["context"] = $this->normaliseData($data);
}
return new JsonResponse($payload, $code);
}
protected function normaliseData($data)
{
if (is_array($data)) {
foreach ($data as $key => $value) {
if (isset($this->prohibitedKeys[$key])) {
unset ($data[$key]);
} else {
$data[$key] = $this->normaliseData($value);
}
}
}
return $data;
}
protected function addProhibitedKeys(array $keys)
{
foreach ($keys as $key) {
if (is_string($key)) {
$this->prohibitedKeys[$key] = true;
}
}
}
protected function removeProhibitedKeys(array $keys)
{
foreach ($keys as $key) {
unset($this->prohibitedKeys[$key]);
}
}
} | <?php
namespace Silktide\LazyBoy\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* RestControllerTrait
*/
trait RestControllerTrait
{
private $prohibitedKeys = [
"password" => true,
"salt" => true
];
protected function success($data = null, $code = 200)
{
if ($data === null) {
$data = ["success" => true];
} else {
$data = $this->normaliseData($data);
}
return new JsonResponse($data, $code);
}
protected function error($message, $data = [], $code = 400)
{
$payload = [
"success" => false,
"error" => $message
];
if (!empty($data)) {
$payload["context"] = $this->normaliseData($data);
}
return new JsonResponse($payload, $code);
}
protected function normaliseData($data)
{
if (is_array($data)) {
foreach ($data as $key => $value) {
if (isset($this->prohibitedKeys[$key])) {
unset ($data[$key]);
} else {
$data[$key] = $this->normaliseData($value);
}
}
}
return $data;
}
} |
Fix: Enable Config instantiation from kwargs only | # -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
from ConfigParser import ConfigParser
from utils.snippets import items_to_dict
class Config(dict):
"""
Unix shells like environment class. Implements add,
get, load, flush methods. Handles lists of values too.
Basically Acts like a basic key/value store.
"""
def __init__(self, f=None, *args, **kwargs):
if f:
self.update_with_file(f) # Has to be called last!
self.update(kwargs)
dict.__init__(self, *args, **kwargs)
def update_with_file(self, f):
"""
Updates the environment using an ini file containing
key/value descriptions.
"""
config = ConfigParser()
with open(f, 'r') as f:
config.readfp(f)
for section in config.sections():
self.update(items_to_dict(config.items(section)))
def reload_from_file(self, f=''):
self.flush(f)
self.load(f)
def update_with_args(self, args):
"""Loads argparse kwargs into environment, as `section`"""
for (arg, value) in args:
if value is not None:
self[arg] = value
def flush(self):
"""
Flushes the environment from it's manually
set attributes.
"""
for attr in self.attributes:
delattr(self, attr)
| # -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
from ConfigParser import ConfigParser
from utils.snippets import items_to_dict
class Config(dict):
"""
Unix shells like environment class. Implements add,
get, load, flush methods. Handles lists of values too.
Basically Acts like a basic key/value store.
"""
def __init__(self, f, *args, **kwargs):
if f:
self.update_with_file(f) # Has to be called last!
self.update(kwargs)
dict.__init__(self, *args, **kwargs)
def update_with_file(self, f):
"""
Updates the environment using an ini file containing
key/value descriptions.
"""
config = ConfigParser()
with open(f, 'r') as f:
config.readfp(f)
for section in config.sections():
self.update(items_to_dict(config.items(section)))
def reload_from_file(self, f=''):
self.flush(f)
self.load(f)
def update_with_args(self, args):
"""Loads argparse kwargs into environment, as `section`"""
for (arg, value) in args:
if value is not None:
self[arg] = value
def flush(self):
"""
Flushes the environment from it's manually
set attributes.
"""
for attr in self.attributes:
delattr(self, attr)
|
Set cov-core dependency to 1.11 | import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long_description=open('README.rst').read().strip(),
author='Marc Schlaich',
author_email='[email protected]',
url='https://github.com/schlamar/pytest-cov',
py_modules=['pytest_cov'],
install_requires=['pytest>=2.5.2',
'cov-core>=1.11'],
entry_points={'pytest11': ['pytest_cov = pytest_cov']},
license='MIT License',
zip_safe=False,
keywords='py.test pytest cover coverage distributed parallel',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Topic :: Software Development :: Testing'])
| import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long_description=open('README.rst').read().strip(),
author='Marc Schlaich',
author_email='[email protected]',
url='https://github.com/schlamar/pytest-cov',
py_modules=['pytest_cov'],
install_requires=['pytest>=2.5.2',
'cov-core>=1.10'],
entry_points={'pytest11': ['pytest_cov = pytest_cov']},
license='MIT License',
zip_safe=False,
keywords='py.test pytest cover coverage distributed parallel',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Topic :: Software Development :: Testing'])
|
Change return type hinting to reference the Proxy class | <?php
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\Exception\InvalidArgumentException;
use function array_map;
use function implode;
/**
* The `staticProxyConstructor` implementation for null object proxies
*
*/
class StaticProxyConstructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass Reflection of the class to proxy
*
* @throws InvalidArgumentException
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);
$nullableProperties = array_map(
function (ReflectionProperty $publicProperty) : string {
return '$instance->' . $publicProperty->getName() . ' = null;';
},
Properties::fromReflectionClass($originalClass)->getPublicProperties()
);
$this->setReturnType($this->getName());
$this->setDocBlock('Constructor for null object initialization');
$this->setBody(
'static $reflection;' . "\n\n"
. '$reflection = $reflection ?? $reflection = new \ReflectionClass(__CLASS__);' . "\n"
. '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n"
. ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '')
. 'return $instance;'
);
}
}
| <?php
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\Exception\InvalidArgumentException;
use function array_map;
use function implode;
/**
* The `staticProxyConstructor` implementation for null object proxies
*
*/
class StaticProxyConstructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass Reflection of the class to proxy
*
* @throws InvalidArgumentException
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);
$nullableProperties = array_map(
function (ReflectionProperty $publicProperty) : string {
return '$instance->' . $publicProperty->getName() . ' = null;';
},
Properties::fromReflectionClass($originalClass)->getPublicProperties()
);
$this->setReturnType($originalClass->getName());
$this->setDocBlock('Constructor for null object initialization');
$this->setBody(
'static $reflection;' . "\n\n"
. '$reflection = $reflection ?? $reflection = new \ReflectionClass(__CLASS__);' . "\n"
. '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n"
. ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '')
. 'return $instance;'
);
}
}
|
Fix centering of provider list | var m = require('mithril');
var utils = require('./utils');
var MESSAGES = JSON.parse(require('raw!./messages.json'));
var Footer = {};
Footer.view = function(ctrl) {
return m('', [
m(
'ul.provider-footer.col-xs-12.col-lg-10.col-lg-offset-1',
{
style: {
'list-style-type': 'none'
}
},
ctrl.renderProviders()
),
m('.row', m('.col-md-12', {style: 'padding-top: 30px;'}, m('span', m.trust(MESSAGES.ABOUTSHARE))))
]);
};
Footer.controller = function(vm) {
var self = this;
self.vm = vm;
self.renderProvider = function(result, index) {
return m('li.provider-filter', {
onclick: function(cb){
self.vm.query(self.vm.query() === '' ? '*' : self.vm.query());
self.vm.showFooter = false;
utils.updateFilter(self.vm, 'source:' + result.short_name);
}
},
m('', [
m('img', {
src: result.favicon,
style: {
width: '16px',
height: '16px'
}
}), ' ',
result.long_name]
)
);
};
self.renderProviders = function() {
return self.vm.showFooter ? $.map(self.vm.sortProviders(), self.renderProvider) : null;
};
};
module.exports = Footer;
| var m = require('mithril');
var utils = require('./utils');
var MESSAGES = JSON.parse(require('raw!./messages.json'));
var Footer = {};
Footer.view = function(ctrl) {
return m('', [
m(
'ul.provider-footer.col-xs-12.col-lg-10.col-lg-offset-2',
{
style: {
'list-style-type': 'none'
}
},
ctrl.renderProviders()
),
m('.row', m('.col-md-12', {style: 'padding-top: 30px;'}, m('span', m.trust(MESSAGES.ABOUTSHARE))))
]);
};
Footer.controller = function(vm) {
var self = this;
self.vm = vm;
self.renderProvider = function(result, index) {
return m('li.provider-filter', {
onclick: function(cb){
self.vm.query(self.vm.query() === '' ? '*' : self.vm.query());
self.vm.showFooter = false;
utils.updateFilter(self.vm, 'source:' + result.short_name);
}
},
m('', [
m('img', {
src: result.favicon,
style: {
width: '16px',
height: '16px'
}
}), ' ',
result.long_name]
)
);
};
self.renderProviders = function() {
return self.vm.showFooter ? $.map(self.vm.sortProviders(), self.renderProvider) : null;
};
};
module.exports = Footer;
|
Apply new symfony preset fixer "phpdoc_types_null_last" | <?php
namespace Kunstmaan\VotingBundle\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use Kunstmaan\VotingBundle\Entity\AbstractVote;
use Kunstmaan\VotingBundle\Event\EventInterface;
abstract class AbstractVoteListener
{
/**
* @var EntityManagerInterface
*/
protected $em;
/**
* @var array
*/
protected $actions;
/**
* @param EntityManagerInterface $em
* @param array $actions
*/
public function __construct(EntityManagerInterface $em, array $actions = array())
{
$this->em = $em;
$this->actions = $actions;
}
/**
* @return array
*/
public function getActions()
{
return $this->actions;
}
/**
* @param AbstractVote $vote
* @param EventInterface $event
* @param int|null $defaultValue
*/
protected function createVote(AbstractVote $vote, EventInterface $event, $defaultValue = null)
{
$vote->setReference($event->getReference());
if ($event->getRequest() !== null) {
$vote->setIp($event->getRequest()->getClientIp());
}
if ($event->getValue() !== null) {
$vote->setValue($event->getValue());
} elseif ($defaultValue !== null) {
$vote->setValue($defaultValue);
}
$this->em->persist($vote);
$this->em->flush();
}
}
| <?php
namespace Kunstmaan\VotingBundle\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use Kunstmaan\VotingBundle\Entity\AbstractVote;
use Kunstmaan\VotingBundle\Event\EventInterface;
abstract class AbstractVoteListener
{
/**
* @var EntityManagerInterface
*/
protected $em;
/**
* @var array
*/
protected $actions;
/**
* @param EntityManagerInterface $em
* @param array $actions
*/
public function __construct(EntityManagerInterface $em, array $actions = array())
{
$this->em = $em;
$this->actions = $actions;
}
/**
* @return array
*/
public function getActions()
{
return $this->actions;
}
/**
* @param AbstractVote $vote
* @param EventInterface $event
* @param null|int $defaultValue
*/
protected function createVote(AbstractVote $vote, EventInterface $event, $defaultValue = null)
{
$vote->setReference($event->getReference());
if ($event->getRequest() !== null) {
$vote->setIp($event->getRequest()->getClientIp());
}
if ($event->getValue() !== null) {
$vote->setValue($event->getValue());
} elseif ($defaultValue !== null) {
$vote->setValue($defaultValue);
}
$this->em->persist($vote);
$this->em->flush();
}
}
|
Set CURLOPT_RETURNTRANSFER to true so that the string value of the transfer is returned rather than outputting it directly. | <?php
namespace Zipkin\Reporters\Http;
use BadFunctionCallException;
use RuntimeException;
final class CurlFactory implements ClientFactory
{
private function __construct()
{
}
/**
* @return CurlFactory
* @throws \BadFunctionCallException if the curl extension is not installed.
*/
public static function create()
{
if (!function_exists('curl_init')) {
throw new BadFunctionCallException('cURL is not enabled');
}
return new self();
}
/**
* {@inheritdoc}
*/
public function build(array $options = [])
{
/**
* @param string $payload
* @throws RuntimeException
* @return void
*/
return function ($payload) use ($options) {
$handle = curl_init($options['endpoint_url']);
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS, $payload);
curl_setopt($handle, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($payload),
]);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
if (curl_exec($handle) === true) {
$statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if ($statusCode !== 202) {
throw new RuntimeException(
sprintf('Reporting of spans failed, status code %d', $statusCode)
);
}
} else {
throw new RuntimeException(sprintf(
'Reporting of spans failed: %s, error code %s',
curl_error($handle),
curl_errno($handle)
));
}
};
}
}
| <?php
namespace Zipkin\Reporters\Http;
use BadFunctionCallException;
use RuntimeException;
final class CurlFactory implements ClientFactory
{
private function __construct()
{
}
/**
* @return CurlFactory
* @throws \BadFunctionCallException if the curl extension is not installed.
*/
public static function create()
{
if (!function_exists('curl_init')) {
throw new BadFunctionCallException('cURL is not enabled');
}
return new self();
}
/**
* {@inheritdoc}
*/
public function build(array $options = [])
{
/**
* @param string $payload
* @throws RuntimeException
* @return void
*/
return function ($payload) use ($options) {
$handle = curl_init($options['endpoint_url']);
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS, $payload);
curl_setopt($handle, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($payload),
]);
if (curl_exec($handle) === true) {
$statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if ($statusCode !== 202) {
throw new RuntimeException(
sprintf('Reporting of spans failed, status code %d', $statusCode)
);
}
} else {
throw new RuntimeException(sprintf(
'Reporting of spans failed: %s, error code %s',
curl_error($handle),
curl_errno($handle)
));
}
};
}
}
|
Revert "Temporarily disable rpc authorization on configserver"
This reverts commit 0ce64af793fe21b6047af2be1b973b525b008c3a. | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.rpc.security;
import com.google.inject.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.config.provision.security.NodeIdentifier;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.security.tls.TransportSecurityUtils;
import com.yahoo.vespa.config.server.host.HostRegistries;
import com.yahoo.vespa.config.server.rpc.RequestHandlerProvider;
/**
* A provider for {@link RpcAuthorizer}. The instance provided is dependent on the configuration of the configserver.
*
* @author bjorncs
*/
public class DefaultRpcAuthorizerProvider implements Provider<RpcAuthorizer> {
private final RpcAuthorizer rpcAuthorizer;
@Inject
public DefaultRpcAuthorizerProvider(ConfigserverConfig config,
NodeIdentifier nodeIdentifier,
HostRegistries hostRegistries,
RequestHandlerProvider handlerProvider) {
this.rpcAuthorizer =
TransportSecurityUtils.isTransportSecurityEnabled() && config.multitenant() && config.hostedVespa()
? new MultiTenantRpcAuthorizer(nodeIdentifier, hostRegistries, handlerProvider)
: new NoopRpcAuthorizer();
}
@Override
public RpcAuthorizer get() {
return rpcAuthorizer;
}
@Override
public void deconstruct() {}
}
| // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.rpc.security;
import com.google.inject.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.config.provision.security.NodeIdentifier;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.security.tls.TransportSecurityUtils;
import com.yahoo.vespa.config.server.host.HostRegistries;
import com.yahoo.vespa.config.server.rpc.RequestHandlerProvider;
/**
* A provider for {@link RpcAuthorizer}. The instance provided is dependent on the configuration of the configserver.
*
* @author bjorncs
*/
public class DefaultRpcAuthorizerProvider implements Provider<RpcAuthorizer> {
private final RpcAuthorizer rpcAuthorizer;
@Inject
public DefaultRpcAuthorizerProvider(ConfigserverConfig config,
NodeIdentifier nodeIdentifier,
HostRegistries hostRegistries,
RequestHandlerProvider handlerProvider) {
// TODO Re-enable once performance/stability issues with MultiTenantRpcAuthorizer are fixed
this.rpcAuthorizer =
TransportSecurityUtils.isTransportSecurityEnabled() && config.multitenant() && config.hostedVespa() && false
? new MultiTenantRpcAuthorizer(nodeIdentifier, hostRegistries, handlerProvider)
: new NoopRpcAuthorizer();
}
@Override
public RpcAuthorizer get() {
return rpcAuthorizer;
}
@Override
public void deconstruct() {}
}
|
Upgrade dependencies a wee bit | import sys
from setuptools import setup, find_packages
import mut
REQUIRES = [
'boto>=2.39,<2.40',
'certifi',
'docopt>=0.6,<0.7',
'docutils',
'dominate>=2.1,<2.2',
'libgiza>=0.2.13,<0.3',
'PyYAML',
'requests>2.9,<2.10',
'rstcloth>=0.2.6',
'sphinx>=1.5',
]
# Need a fallback for the typing module
if sys.version < '3.5':
REQUIRES.append('mypy-lang')
setup(
name='mut',
description='',
version=mut.__version__,
author='Andrew Aldridge',
author_email='[email protected]',
license='Apache',
packages=find_packages(),
install_requires=REQUIRES,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Build Tools',
'Topic :: Documentation',
'Topic :: Text Processing',
],
entry_points={
'console_scripts': [
'mut = mut.helper:main',
'mut-build = mut.main:main',
'mut-images = mut.build_images:main',
'mut-intersphinx = mut.intersphinx:main',
'mut-lint = mut.lint:main',
'mut-publish = mut.stage:main',
],
}
)
| import sys
from setuptools import setup, find_packages
import mut
REQUIRES = [
'boto>=2.39,<2.40',
'certifi',
'docopt>=0.6,<0.7',
'docutils',
'dominate>=2.1,<2.2',
'libgiza>=0.2.13,<0.3',
'PyYAML',
'requests>2.9,<2.10',
'rstcloth>0.2.5',
'sphinx>1.4',
]
# Need a fallback for the typing module
if sys.version < '3.5':
REQUIRES.append('mypy-lang')
setup(
name='mut',
description='',
version=mut.__version__,
author='Andrew Aldridge',
author_email='[email protected]',
license='Apache',
packages=find_packages(),
install_requires=REQUIRES,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Build Tools',
'Topic :: Documentation',
'Topic :: Text Processing',
],
entry_points={
'console_scripts': [
'mut = mut.helper:main',
'mut-build = mut.main:main',
'mut-images = mut.build_images:main',
'mut-intersphinx = mut.intersphinx:main',
'mut-lint = mut.lint:main',
'mut-publish = mut.stage:main',
],
}
)
|
Fix invalid typehint for subject in is_granted Twig function | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* SecurityExtension exposes security context features.
*
* @author Fabien Potencier <[email protected]>
*/
final class SecurityExtension extends AbstractExtension
{
private $securityChecker;
public function __construct(AuthorizationCheckerInterface $securityChecker = null)
{
$this->securityChecker = $securityChecker;
}
/**
* @param mixed $object
*/
public function isGranted($role, $object = null, string $field = null): bool
{
if (null === $this->securityChecker) {
return false;
}
if (null !== $field) {
$object = new FieldVote($object, $field);
}
try {
return $this->securityChecker->isGranted($role, $object);
} catch (AuthenticationCredentialsNotFoundException $e) {
return false;
}
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
new TwigFunction('is_granted', [$this, 'isGranted']),
];
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* SecurityExtension exposes security context features.
*
* @author Fabien Potencier <[email protected]>
*/
final class SecurityExtension extends AbstractExtension
{
private $securityChecker;
public function __construct(AuthorizationCheckerInterface $securityChecker = null)
{
$this->securityChecker = $securityChecker;
}
public function isGranted($role, object $object = null, string $field = null): bool
{
if (null === $this->securityChecker) {
return false;
}
if (null !== $field) {
$object = new FieldVote($object, $field);
}
try {
return $this->securityChecker->isGranted($role, $object);
} catch (AuthenticationCredentialsNotFoundException $e) {
return false;
}
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
new TwigFunction('is_granted', [$this, 'isGranted']),
];
}
}
|
Add ability to set hashing function in SimpleHash | package gash
// A simple chained hash.
type SimpleHash struct {
items [][]*KvPair
capacity int
fn HashFn
}
func CreateSimpleHash(capacity int, fn HashFn) SimpleHash {
table := SimpleHash{}
table.capacity = capacity
table.items = make([][]*KvPair, capacity)
for index := range table.items {
table.items[index] = []*KvPair{}
}
table.fn = fn
return table
}
func (table SimpleHash) Insert(k string, v interface{}) {
index := table.fn(k) % table.capacity
item := KvPair{k, v}
isSet := false
for searchIndex, pair := range table.items[index] {
if pair.Key == k {
table.items[index][searchIndex].Value = v
isSet = true
break
}
}
if (!isSet) {
table.items[index] = append(table.items[index], &item)
}
}
func (table SimpleHash) Find(k string) interface{} {
index := table.fn(k) % table.capacity
for _, pair := range table.items[index] {
if pair.Key == k {
return pair.Value
}
}
return nil
}
func (table SimpleHash) Remove(k string) {
index := table.fn(k) % table.capacity
for searchIndex, pair := range table.items[index] {
if pair.Key == k {
table.items[index] = append(table.items[index][:searchIndex],
table.items[index][searchIndex+1:]...)
break
}
}
}
| package gash
// A simple chained hash.
type SimpleHash struct {
items [][]*KvPair
capacity int
}
func CreateSimpleHash(capacity int) SimpleHash {
table := SimpleHash{}
table.capacity = capacity
table.items = make([][]*KvPair, capacity)
for index := range table.items {
table.items[index] = []*KvPair{}
}
return table
}
func (table SimpleHash) Insert(k string, v interface{}) {
index := Djb2(k) % table.capacity
item := KvPair{k, v}
isSet := false
for searchIndex, pair := range table.items[index] {
if pair.Key == k {
table.items[index][searchIndex].Value = v
isSet = true
break
}
}
if (!isSet) {
table.items[index] = append(table.items[index], &item)
}
}
func (table SimpleHash) Find(k string) interface{} {
index := Djb2(k) % table.capacity
for _, pair := range table.items[index] {
if pair.Key == k {
return pair.Value
}
}
return nil
}
func (table SimpleHash) Remove(k string) {
index := Djb2(k) % table.capacity
for searchIndex, pair := range table.items[index] {
if pair.Key == k {
table.items[index] = append(table.items[index][:searchIndex],
table.items[index][searchIndex+1:]...)
break
}
}
}
|
Mark saturation as an epic ability | package org.cyclops.everlastingabilities.ability.config;
import net.minecraft.init.MobEffects;
import net.minecraft.item.EnumRarity;
import org.cyclops.cyclopscore.helper.MinecraftHelpers;
import org.cyclops.everlastingabilities.ability.AbilityTypePotionEffectSelf;
import org.cyclops.everlastingabilities.core.config.extendedconfig.AbilityConfig;
/**
* Config for an ability.
* @author rubensworks
*
*/
public class AbilitySaturationConfig extends AbilityConfig {
/**
* The unique instance.
*/
public static AbilityConfig _instance;
/**
* Make a new instance.
*/
public AbilitySaturationConfig() {
super(
true,
"saturation",
"Reduce hunger",
new AbilityTypePotionEffectSelf("saturation", EnumRarity.EPIC, 3, 30, MobEffects.SATURATION) {
@Override
protected int getDuration(int tickModulus) {
return 1;
}
@Override
protected int getTickModulus() {
return MinecraftHelpers.SECOND_IN_TICKS * 5;
}
}
);
}
}
| package org.cyclops.everlastingabilities.ability.config;
import net.minecraft.init.MobEffects;
import net.minecraft.item.EnumRarity;
import org.cyclops.cyclopscore.helper.MinecraftHelpers;
import org.cyclops.everlastingabilities.ability.AbilityTypePotionEffectSelf;
import org.cyclops.everlastingabilities.core.config.extendedconfig.AbilityConfig;
/**
* Config for an ability.
* @author rubensworks
*
*/
public class AbilitySaturationConfig extends AbilityConfig {
/**
* The unique instance.
*/
public static AbilityConfig _instance;
/**
* Make a new instance.
*/
public AbilitySaturationConfig() {
super(
true,
"saturation",
"Reduce hunger",
new AbilityTypePotionEffectSelf("saturation", EnumRarity.RARE, 3, 30, MobEffects.SATURATION) {
@Override
protected int getDuration(int tickModulus) {
return 1;
}
@Override
protected int getTickModulus() {
return MinecraftHelpers.SECOND_IN_TICKS * 5;
}
}
);
}
}
|
Update calculator request for new CRONUS versions | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
define('CRONUS_BASE', 'http://hess.ess.washington.edu/');
define('CRONUS_URI', CRONUS_BASE . 'cgi-bin/matweb');
class Calculator
{
public static function send($submitText, $calcType)
{
// prepare for a curl call
if ($calcType == 'erosion') {
$mlmfile = 'al_be_erosion_many_v23';
} else {
// Assume age
$mlmfile = 'age_input_v3';
}
$fields = array(
'mlmfile' => $mlmfile,
'reportType' => 'HTML',
'resultType' => 'long',
'plotFlag' => 'yes',
'requesting_ip' => getRealIp(),
'summary' => 'yes', // Assume data from 1 landform, currently true.
'text_block' => $submitText,
);
$options = array(
CURLOPT_POST => count($fields),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => http_build_query($fields),
CURLOPT_CONNECTTIMEOUT => 90,
CURLOPT_TIMEOUT => 200,
);
// send the request with curl
$ch = curl_init(CRONUS_URI);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (!$result) {
die('Error retrieving calculator result:<br>' . curl_error($ch));
}
curl_close($ch);
return $result;
}
}
| <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
define('CRONUS_BASE', 'http://hess.ess.washington.edu/');
define('CRONUS_URI', CRONUS_BASE . 'cgi-bin/matweb');
class Calculator {
function send($submitText, $calcType) {
// prepare for a curl call
$fields = array(
'requesting_ip' => getRealIp(),
'mlmfile' => 'al_be_' . $calcType . '_many_v22',
'text_block' => $submitText,
);
$options = array(
CURLOPT_POST => count($fields),
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($fields),
CURLOPT_CONNECTTIMEOUT => 90,
CURLOPT_TIMEOUT => 200,
);
// send the request with curl
$ch = curl_init(CRONUS_URI);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (!$result) {
die('Error retrieving calculator result:<br>' . curl_error($ch));
}
curl_close($ch);
$rep = '<head><base href="' . CRONUS_BASE . '" />';
$html = str_replace('<head>', $rep, $result);
return $html;
}
} |
Add log if worker is down | <?php
namespace APIBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;
class InjectTypeController extends Controller
{
/**
* @ApiDoc(
* description="List inject types"
* )
* @Rest\Get("/inject_types")
*/
public function getInjectTypesAction(Request $request)
{
$logger = $this->get('logger');
$contracts = array();
try {
$url = $this->getParameter('worker_url') . '/cxf/contracts';
$contracts = json_decode(@file_get_contents($url), true);
} catch (\Exception $e) {
$logger->info('Contracts can not be retrieved from worker');
}
$other = array();
$other['type'] = 'openex_manual';
$other['fields'] = array();
$other['fields'][] = array(
'name' => 'content',
'type' => 'textarea',
'cardinality' => '1',
'mandatory' => true,
);
$contracts[] = $other;
$output = json_encode($contracts);
return new Response($output);
}
} | <?php
namespace APIBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;
class InjectTypeController extends Controller
{
/**
* @ApiDoc(
* description="List inject types"
* )
* @Rest\Get("/inject_types")
*/
public function getInjectTypesAction(Request $request)
{
$url = $this->getParameter('worker_url') . '/cxf/contracts';
try {
$contracts = json_decode(@file_get_contents($url), true);
} catch(\Exception $e) {}
$other = array();
$other['type'] = 'openex_manual';
$other['fields'] = array();
$other['fields'][] = array(
'name' => 'content',
'type' => 'textarea',
'cardinality' => '1',
'mandatory' => true,
);
$contracts[] = $other;
$output = json_encode($contracts);
return new Response($output);
}
} |
Set default values for command and args | import json
from collections import OrderedDict
from .command import ShellCommand
from .settings import FormatterSettings
class Formatter():
def __init__(self, name, command='', args='', formatter=None):
self.__name = name
self.__settings = FormatterSettings(name.lower())
if formatter:
self.__format = formatter
else:
command = command.split(' ')
options = self.__settings.options
args = args.split(' ')
self.__format = ShellCommand(command + options + args).run
@property
def name(self):
return self.__name
@property
def sources(self):
return self.__settings.sources
@property
def format_on_save(self):
return self.__settings.format_on_save
@format_on_save.setter
def format_on_save(self, value):
self.__settings.format_on_save = value
def format(self, input):
return self.__format(input)
class JsonFormatter(Formatter):
def __init__(self):
def format_json(input):
try:
data = json.loads(input, object_pairs_hook=OrderedDict)
return json.dumps(data, indent=4), None
except ValueError:
return None, 'Invalid JSON'
super().__init__(name='JSON', formatter=format_json)
| import json
from collections import OrderedDict
from .command import ShellCommand
from .settings import FormatterSettings
class Formatter():
def __init__(self, name, command=None, args=None, formatter=None):
self.__name = name
self.__format = formatter
self.__settings = FormatterSettings(name.lower())
if not formatter:
command = command.split(' ') if command else []
options = self.__settings.options
args = args.split(' ') if args else []
self.__format = ShellCommand(command + options + args).run
@property
def name(self):
return self.__name
@property
def sources(self):
return self.__settings.sources
@property
def format_on_save(self):
return self.__settings.format_on_save
@format_on_save.setter
def format_on_save(self, value):
self.__settings.format_on_save = value
def format(self, input):
return self.__format(input)
class JsonFormatter(Formatter):
def __init__(self):
def format_json(input):
try:
data = json.loads(input, object_pairs_hook=OrderedDict)
return json.dumps(data, indent=4), None
except ValueError:
return None, 'Invalid JSON'
super().__init__(name='JSON', formatter=format_json)
|
Rename folers, convert to lowercase | /*Config*/
var concat = require( 'gulp-concat' );
var gulp = require( 'gulp' );
var rename = require( 'gulp-rename' );
var runSequence = require( 'run-sequence' );
var sourceMaps = require( 'gulp-sourcemaps' );
/*SASS/CSS*/
var autoPrefixer = require( 'gulp-autoprefixer' );
var cssMin = require( 'gulp-cssnano' );
var sass = require( 'gulp-sass' );
/*Config*/
var vendorCssFiles = [
'node_modules/normalize.css/normalize.css'
];
gulp.task( 'watch', function() {
gulp.watch( 'sass/**/*.scss', [ 'css' ] );
} );
gulp.task( 'build', function( callback ) {
return runSequence(
'vendorStyles',
'css'
);
} );
gulp.task( 'vendorStyles', function() {
return gulp.src( vendorCssFiles )
.pipe( concat( '_vendor.scss' ) )
.pipe( gulp.dest( 'sass/base/' ) );
} );
gulp.task( 'css', function() {
return gulp.src( 'sass/main.scss' )
.pipe( sass()
.on( 'error', sass.logError ) )
.pipe( sourceMaps.init() )
.pipe( autoPrefixer( {
browsers: [ 'last 2 versions' ],
cascade: false
} ) )
.pipe( sourceMaps.write( '.' ) )
.pipe( gulp.dest( 'stylesheets' ) );
} ); | /*Config*/
var concat = require( 'gulp-concat' );
var gulp = require( 'gulp' );
var rename = require( 'gulp-rename' );
var runSequence = require( 'run-sequence' );
var sourceMaps = require( 'gulp-sourcemaps' );
/*SASS/CSS*/
var autoPrefixer = require( 'gulp-autoprefixer' );
var cssMin = require( 'gulp-cssnano' );
var sass = require( 'gulp-sass' );
/*Config*/
var vendorCssFiles = [
'node_modules/normalize.css/normalize.css'
];
gulp.task( 'watch', function() {
gulp.watch( 'sass/**/*.scss', [ 'css' ] );
} );
gulp.task( 'build', function( callback ) {
return runSequence(
'vendorStyles',
'css'
);
} );
gulp.task( 'vendorStyles', function() {
return gulp.src( vendorCssFiles )
.pipe( concat( '_vendor.scss' ) )
.pipe( gulp.dest( 'sass/base/' ) );
} );
gulp.task( 'css', function() {
return gulp.src( 'sass/main.scss' )
.pipe( sass()
.on( 'error', sass.logError ) )
.pipe( sourceMaps.init() )
.pipe( autoPrefixer( {
browsers: [ 'last 2 versions' ],
cascade: false
} ) )
.pipe( sourceMaps.write( '.' ) )
.pipe( gulp.dest( 'Stylesheets' ) );
} ); |
Fix help text and debug. | <?php namespace FireflyIII\Http\Controllers;
use FireflyIII\Helpers\Help\HelpInterface;
use Log;
use Preferences;
use Response;
/**
* Class HelpController
*
* @package FireflyIII\Http\Controllers
*/
class HelpController extends Controller
{
/**
* HelpController constructor.
*/
public function __construct()
{
parent::__construct();
}
/**
* @param HelpInterface $help
* @param $route
*
* @return \Illuminate\Http\JsonResponse
*/
public function show(HelpInterface $help, string $route)
{
$content = [
'text' => '<p>' . strval(trans('firefly.route_has_no_help')) . '</p>',
'title' => 'Help',
];
if (!$help->hasRoute($route)) {
Log::error('No such route: ' . $route);
return Response::json($content);
}
if ($help->inCache($route)) {
$content = [
'text' => $help->getFromCache('help.' . $route . '.text'),
'title' => $help->getFromCache('help.' . $route . '.title'),
];
return Response::json($content);
}
$language = Preferences::get('language', env('DEFAULT_LANGUAGE', 'en_US'))->data;
Log::debug('Will get help from Github for language "' . $language . '" and route "' . $route . '".');
$content = $help->getFromGithub($language, $route);
$help->putInCache($route, $content);
return Response::json($content);
}
}
| <?php namespace FireflyIII\Http\Controllers;
use FireflyIII\Helpers\Help\HelpInterface;
use Log;
use Preferences;
use Response;
/**
* Class HelpController
*
* @package FireflyIII\Http\Controllers
*/
class HelpController extends Controller
{
/**
* HelpController constructor.
*/
public function __construct()
{
parent::__construct();
}
/**
* @param HelpInterface $help
* @param $route
*
* @return \Illuminate\Http\JsonResponse
*/
public function show(HelpInterface $help, string $route)
{
$content = [
'text' => '<p>There is no help for this route!</p>',
'title' => 'Help',
];
if (!$help->hasRoute($route)) {
Log::error('No such route: ' . $route);
return Response::json($content);
}
if ($help->inCache($route)) {
$content = [
'text' => $help->getFromCache('help.' . $route . '.text'),
'title' => $help->getFromCache('help.' . $route . '.title'),
];
return Response::json($content);
}
$language = Preferences::get('language', env('DEFAULT_LANGUAGE', 'en_US'))->data;
$content = $help->getFromGithub($language, $route);
$help->putInCache($route, $content);
return Response::json($content);
}
}
|
Use app.extensions to get perm reference. | # -*- coding: utf-8 -*-
from flask import Blueprint, render_template, current_app, url_for, redirect, request, flash
bp = Blueprint('perm-admin', __name__, template_folder='templates', static_folder='static')
@bp.route('/')
def index():
if not current_app.extensions['perm'].has_perm_admin_logined():
return redirect(url_for('perm-admin.login'))
render_data = {
'base_api_url': current_app.config.get('PERM_ADMIN_API_PREFIX'),
'base_web_url': current_app.config.get('PERM_ADMIN_PREFIX'),
'debug': current_app.config.get('DEBUG'),
}
return render_template('/perm-admin/index.html', **render_data)
@bp.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
admin_id = current_app.extensions['perm'].get_perm_admin_id_by_auth(username, password)
if admin_id:
current_app.extensions['perm'].login_perm_admin(admin_id)
return redirect(url_for('perm-admin.index'))
else:
flash(u'Invalid Password', 'error')
return redirect(url_for('perm-admin.login'))
return render_template('/perm-admin/login.html')
@bp.route('/logout')
def logout():
current_app.extensions['perm'].logout_perm_admin()
return redirect(url_for('perm-admin.login'))
| # -*- coding: utf-8 -*-
from flask import Blueprint, render_template, current_app, url_for, redirect, request, flash
bp = Blueprint('perm-admin', __name__, template_folder='templates', static_folder='static')
@bp.route('/')
def index():
if not bp.perm.has_perm_admin_logined():
return redirect(url_for('perm-admin.login'))
render_data = {
'base_api_url': current_app.config.get('PERM_ADMIN_API_PREFIX'),
'base_web_url': current_app.config.get('PERM_ADMIN_PREFIX'),
'debug': current_app.config.get('DEBUG'),
}
return render_template('/perm-admin/index.html', **render_data)
@bp.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if bp.perm.check_perm_admin_auth(username, password):
bp.perm.login_perm_admin()
return redirect(url_for('perm-admin.index'))
else:
flash(u'Invalid Password', 'error')
return redirect(url_for('perm-admin.login'))
return render_template('/perm-admin/login.html')
@bp.route('/logout')
def logout():
bp.perm.logout_perm_admin()
return redirect(url_for('perm-admin.login'))
|
Fix planning page on Safari
new Date("…") cannot parse ISO8601 with a timezone on certain non-fully
ES5 compliant browsers | App.Views.PlanningView = Backbone.View.extend({
className: 'planning',
initialize: function() {
this.lessons = this.collection;
this.lessons.on('add change remove reset', this.render, this);
},
render: function() {
var lessons = this.lessons.toArray();
// Build day views and keep DOM elements for insertion
var elements = [];
this.groupByDay(lessons, function(date, lessons) {
var view = new App.Views.PlanningDayView({
date: date,
lessons: lessons
});
view.render();
elements.push(view.el);
});
this.$el.append(elements);
return this;
},
groupByDay: function(lessons, iterator) {
// Lessons are expected in date sorted order
var lastDate, // The day we are working on
lessonDate, // The date of of currently evaluated lesson
lessonBag = []; // Temporary array holding holding lessons between each iterator call
_.each(lessons, function(lesson) {
lessonDate = moment(lesson.get('start')).toDate();
lessonDate.setHours(0,0,0,0); // We strip time components to compare date reliablely
if (lessonDate > lastDate) {
// We changed of day: call iterator and reset lesson bag
iterator(lastDate, lessonBag);
lessonBag = [];
}
lessonBag.push(lesson);
lastDate = lessonDate;
});
}
}); | App.Views.PlanningView = Backbone.View.extend({
className: 'planning',
initialize: function() {
this.lessons = this.collection;
this.lessons.on('add change remove reset', this.render, this);
},
render: function() {
var lessons = this.lessons.toArray();
// Build day views and keep DOM elements for insertion
var elements = [];
this.groupByDay(lessons, function(date, lessons) {
var view = new App.Views.PlanningDayView({
date: date,
lessons: lessons
});
view.render();
elements.push(view.el);
});
this.$el.append(elements);
return this;
},
groupByDay: function(lessons, iterator) {
// Lessons are expected in date sorted order
var lastDate, // The day we are working on
lessonDate, // The date of of currently evaluated lesson
lessonBag = []; // Temporary array holding holding lessons between each iterator call
_.each(lessons, function(lesson) {
lessonDate = new Date(lesson.get('start'));
lessonDate.setHours(0,0,0,0); // We strip time components to compare date reliablely
if (lessonDate > lastDate) {
// We changed of day: call iterator and reset lesson bag
iterator(lastDate, lessonBag);
lessonBag = [];
}
lessonBag.push(lesson);
lastDate = lessonDate;
});
}
}); |
Add deferVisibleCompile option (default: false)
This defers compilation of visible elements too. Will be useful for incrementally showing long lists. | (function () {
'use strict';
angular.module('ngDeferredShow', [])
.directive('ngDeferredShow', function ($parse, $timeout, $animate) {
var timeoutBatches = {};
return {
restrict: 'A',
transclude: 'element',
multiElement: true,
priority: 600,
terminal: true,
link: function (scope, element, attrs, $ctrl, $transclude) {
var visible, deferVisibleCompile, compiled, timeout;
visible = $parse(attrs.ngDeferredShow)(scope);
deferVisibleCompile = $parse(attrs.deferVisibleCompile)(scope);
compiled = false;
if (visible && !deferVisibleCompile) {
compile();
}
else {
timeout = $parse(attrs.compileTimeout)(scope);
batchTimeout(compile, timeout);
}
scope.$watch(attrs.ngDeferredShow, function (value) {
visible = value;
if (compiled) {
updateVisibility();
}
});
function compile() {
$transclude(function (clone) {
$animate.enter(clone, element.parent(), element);
element = clone;
compiled = true;
updateVisibility();
});
}
function updateVisibility() {
$animate[visible ? 'removeClass' : 'addClass'](element, 'ng-hide');
}
}
};
function batchTimeout(callback, timeout) {
var batch = timeoutBatches[timeout];
if (!batch) {
batch = timeoutBatches[timeout] = [];
$timeout(function () {
delete timeoutBatches[timeout];
angular.forEach(batch, function (callback) {
callback();
});
}, timeout);
}
batch.push(callback);
}
});
}());
| (function () {
'use strict';
angular.module('ngDeferredShow', [])
.directive('ngDeferredShow', function ($parse, $timeout, $animate) {
var timeoutBatches = {};
return {
restrict: 'A',
transclude: 'element',
multiElement: true,
priority: 600,
terminal: true,
link: function (scope, element, attrs, $ctrl, $transclude) {
var visible, compiled, timeout;
visible = $parse(attrs.ngDeferredShow)(scope);
compiled = false;
if (visible) {
compile();
}
else {
timeout = $parse(attrs.compileTimeout)(scope);
batchTimeout(compile, timeout);
}
scope.$watch(attrs.ngDeferredShow, function (value) {
visible = value;
if (compiled) {
updateVisibility();
}
});
function compile() {
$transclude(function (clone) {
$animate.enter(clone, element.parent(), element);
element = clone;
compiled = true;
updateVisibility();
});
}
function updateVisibility() {
$animate[visible ? 'removeClass' : 'addClass'](element, 'ng-hide');
}
}
};
function batchTimeout(callback, timeout) {
var batch = timeoutBatches[timeout];
if (!batch) {
batch = timeoutBatches[timeout] = [];
$timeout(function () {
delete timeoutBatches[timeout];
angular.forEach(batch, function (callback) {
callback();
});
}, timeout);
}
batch.push(callback);
}
});
}()); |
Add a note about caching | # Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.
import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings
class TowerConfiguration(object):
# TODO: Caching so we don't have to hit the database every time for settings
def __getattr__(self, key):
ts = TowerSettings.objects.filter(key=key)
if not ts.exists():
return getattr(django_settings, key)
return ts[0].value_converted
def create(key, value):
settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
if key not in settings_manifest:
raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
settings_entry = settings_manifest[key]
setting_actual = TowerSettings.objects.filter(key=key)
if not settings_actual.exists():
settings_actual = TowerSettings(key=key,
description=settings_entry['description'],
category=settings_entry['category'],
value=value,
value_type=settings_entry['type'])
else:
settings_actual['value'] = value
settings_actual.save()
tower_settings = TowerConfiguration()
| # Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.
import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings
class TowerConfiguration(object):
def __getattr__(self, key):
ts = TowerSettings.objects.filter(key=key)
if not ts.exists():
return getattr(django_settings, key)
return ts[0].value_converted
def create(key, value):
settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
if key not in settings_manifest:
raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
settings_entry = settings_manifest[key]
setting_actual = TowerSettings.objects.filter(key=key)
if not settings_actual.exists():
settings_actual = TowerSettings(key=key,
description=settings_entry['description'],
category=settings_entry['category'],
value=value,
value_type=settings_entry['type'])
else:
settings_actual['value'] = value
settings_actual.save()
tower_settings = TowerConfiguration()
|
Move error catch outside of the returned promise | import Promise from 'bluebird';
import {EventEmitter} from 'events';
import lodash from 'lodash';
export class Store extends EventEmitter {
constructor(dispatcher) {
super();
this.dispatcher = dispatcher;
this._callbackId = dispatcher.register(dispatchHandler.bind(this));
this._triggers = [];
}
bind(actionType, method) {
if (actionType == null) {
throw new TypeError('Action type passed to Store#bind() is undefined');
}
if (typeof actionType !== 'function') {
throw new TypeError('Action type passed to Store#bind() is not a function/constructor');
}
if (method == null) {
throw new TypeError('Method passed to Store#bind() is undefined');
}
if (typeof method !== 'function') {
throw new TypeError('Method passed to Store#bind() is not a function');
}
this._triggers.push({actionType, method});
}
waitFor(controller) {
this.dispatcher.waitFor(controller._callbackId);
}
}
function dispatchHandler(action) {
return Promise.all(lodash.map(this._triggers, ({actionType, method}) => {
if (action instanceof actionType) {
const promise = Promise.try(() => {
return method.call(this, action);
});
promise.catch(err => {
this.emit('error', err);
});
return promise;
}
}));
}
| import Promise from 'bluebird';
import {EventEmitter} from 'events';
import lodash from 'lodash';
export class Store extends EventEmitter {
constructor(dispatcher) {
super();
this.dispatcher = dispatcher;
this._callbackId = dispatcher.register(dispatchHandler.bind(this));
this._triggers = [];
}
bind(actionType, method) {
if (actionType == null) {
throw new TypeError('Action type passed to Store#bind() is undefined');
}
if (typeof actionType !== 'function') {
throw new TypeError('Action type passed to Store#bind() is not a function/constructor');
}
if (method == null) {
throw new TypeError('Method passed to Store#bind() is undefined');
}
if (typeof method !== 'function') {
throw new TypeError('Method passed to Store#bind() is not a function');
}
this._triggers.push({actionType, method});
}
waitFor(controller) {
this.dispatcher.waitFor(controller._callbackId);
}
}
function dispatchHandler(action) {
return Promise.all(lodash.map(this._triggers, ({actionType, method}) => {
if (action instanceof actionType) {
return Promise.try(() => {
return method.call(this, action);
}).catch(err => {
this.emit('error', err);
throw err;
});
}
}));
}
|
Message.Note: Fix isNote prop for rendering
This resolve the React warning for `isNote` rendering for `Message.Action`. | // @flow
import React from 'react'
import Text from '../Text'
import ChatBlock from './ChatBlock'
import classNames from '../../utilities/classNames'
import { providerContextTypes } from './propTypes'
import type { MessageChat, MessageThemeContext } from './types'
type Props = MessageChat & {
className?: string,
icon?: string,
}
type Context = MessageThemeContext
const Action = (props: Props, context: Context) => {
const {
children,
className,
from,
icon,
isNote,
ltr,
rtl,
to,
read,
timestamp,
type,
...rest
} = props
const { theme } = context
const componentClassName = classNames(
'c-MessageAction',
theme && `is-theme-${theme}`,
className
)
const isThemeEmbed = theme === 'embed'
const textSize = '11'
const textShade = isThemeEmbed ? 'faint' : 'muted'
return (
<ChatBlock
from={from}
ltr={ltr}
read={read}
rtl={rtl}
timestamp={timestamp}
to={to}
type="action"
>
<div className={componentClassName} {...rest}>
<Text
className="c-MessageAction__text"
shade={textShade}
size={textSize}
>
{children}
</Text>
</div>
</ChatBlock>
)
}
Action.contextTypes = providerContextTypes
Action.displayName = 'Message.Action'
export default Action
| // @flow
import React from 'react'
import Text from '../Text'
import ChatBlock from './ChatBlock'
import classNames from '../../utilities/classNames'
import { providerContextTypes } from './propTypes'
import type { MessageChat, MessageThemeContext } from './types'
type Props = MessageChat & {
className?: string,
icon?: string,
}
type Context = MessageThemeContext
const Action = (props: Props, context: Context) => {
const {
children,
className,
from,
icon,
ltr,
rtl,
to,
read,
timestamp,
type,
...rest
} = props
const { theme } = context
const componentClassName = classNames(
'c-MessageAction',
theme && `is-theme-${theme}`,
className
)
const isThemeEmbed = theme === 'embed'
const textSize = '11'
const textShade = isThemeEmbed ? 'faint' : 'muted'
return (
<ChatBlock
from={from}
ltr={ltr}
read={read}
rtl={rtl}
timestamp={timestamp}
to={to}
type="action"
>
<div className={componentClassName} {...rest}>
<Text
className="c-MessageAction__text"
shade={textShade}
size={textSize}
>
{children}
</Text>
</div>
</ChatBlock>
)
}
Action.contextTypes = providerContextTypes
Action.displayName = 'Message.Action'
export default Action
|
BUG: Fix a failing test due to refactor | """
Testing the MlabSceneModel
"""
import unittest
import numpy as np
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
test_object = TestObject()
x, y, z = np.random.random((3, 10))
plt = mlab.plot3d(x, y, z,
figure=test_object.scene1.mayavi_scene)
pts = mlab.points3d(x, y, z,
figure=test_object.scene2.mayavi_scene)
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
if __name__ == '__main__':
unittest.main()
| """
Testing the MlabSceneModel
"""
import unittest
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
f = mlab.figure()
test_object = TestObject()
plt = test_object.scene1.mlab.test_plot3d()
pts = test_object.scene2.mlab.test_points3d()
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
# Check that the current figure was not upset by plotting to the
# object
self.assertEqual(mlab.gcf(), f)
if __name__ == '__main__':
unittest.main()
|
Fix ThreadListItem prop type checking | var ChatThreadActionCreators = require('../actions/ChatThreadActionCreators');
var React = require('react');
var cx = require('react/lib/cx');
var TimeAgo = require('./TimeAgo.react');
var Avatar = require('./Avatar.react');
var Status = require('./Status.react');
var ChatMessageUtils = require('../utils/ChatMessageUtils');
var LeftRightAlign = require('../../../js/components/LeftRightAlign.jsx');
var ReactPropTypes = React.PropTypes;
var Router = require('react-router');
var Link = Router.Link;
var Navigation = Router.Navigation;
var ThreadListItem = React.createClass({
propTypes: {
thread: ReactPropTypes.object,
currentThreadID: ReactPropTypes.string,
threadType: ReactPropTypes.string.isRequired
},
render: function() {
var thread = this.props.thread;
var lastMessage = thread.lastMessage;
var contact = ChatMessageUtils.getMessageOther(this.props.thread.id);
return (
<Link className={cx({
'list-group-item': true,
'active': thread.id === this.props.currentThreadID
})} to={this.props.threadType} params={{id: thread.id}}>
<p>{this.props.thread.name}</p>
<LeftRightAlign>
<p><b>{contact}</b> <em>[<Status user={contact} />]</em></p>
<p className="messageTimestamp"><TimeAgo when={lastMessage ? lastMessage.date : new Date()} /></p>
</LeftRightAlign>
{lastMessage && lastMessage.text}
</Link>
);
},
});
module.exports = ThreadListItem;
| var ChatThreadActionCreators = require('../actions/ChatThreadActionCreators');
var React = require('react');
var cx = require('react/lib/cx');
var TimeAgo = require('./TimeAgo.react');
var Avatar = require('./Avatar.react');
var Status = require('./Status.react');
var ChatMessageUtils = require('../utils/ChatMessageUtils');
var LeftRightAlign = require('../../../js/components/LeftRightAlign.jsx');
var ReactPropTypes = React.PropTypes;
var Router = require('react-router');
var Link = Router.Link;
var Navigation = Router.Navigation;
var ThreadListItem = React.createClass({
propTypes: {
thread: ReactPropTypes.object,
currentThreadID: ReactPropTypes.string,
threadType: ReactPropTypes.string.required
},
render: function() {
var thread = this.props.thread;
var lastMessage = thread.lastMessage;
var contact = ChatMessageUtils.getMessageOther(this.props.thread.id);
return (
<Link className={cx({
'list-group-item': true,
'active': thread.id === this.props.currentThreadID
})} to={this.props.threadType} params={{id: thread.id}}>
<p>{this.props.thread.name}</p>
<LeftRightAlign>
<p><b>{contact}</b> <em>[<Status user={contact} />]</em></p>
<p className="messageTimestamp"><TimeAgo when={lastMessage ? lastMessage.date : new Date()} /></p>
</LeftRightAlign>
{lastMessage && lastMessage.text}
</Link>
);
},
});
module.exports = ThreadListItem;
|
Test case to verify creation of api documentation web page | /////////////////////
// gulp-node-slate //
/////////////////////
// Run:
// $ cd gulp-node-slate
// $ npm update
// $ npm run mocha
var assert = require('assert');
var es = require('event-stream');
var fs = require('fs');
var File = require('vinyl');
var gulpNodeSlate = require('../index.js');
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('The gulp-node-slate plugin', () => {
it('is exported as a function', () => {
var actual = typeof gulpNodeSlate;
var expected = 'function';
assert.equal(actual, expected);
});
});
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Running the gulp-node-slate plugin', () => {
it('passes through a file in the stream', (done) => {
var mockFile = new File({ contents: es.readArray(['[A]', '[B]', '[C]']) });
function handleFileFromStream(file) {
assert(file.isStream());
function handleDataFromFile(err, data) {
assert.equal(data, '[A][B][C]');
done();
}
file.contents.pipe(es.wait(handleDataFromFile));
}
var pluginStream = gulpNodeSlate();
pluginStream.on('data', handleFileFromStream);
pluginStream.write(mockFile);
pluginStream.end();
}).timeout(60000); //in case node-slate needs to be downloaded
it('creates the API documentation web page', () => {
var webPage = 'build/index.html';
assert(fs.existsSync(webPage));
});
});
| /////////////////////
// gulp-node-slate //
/////////////////////
// Run:
// $ cd gulp-node-slate
// $ npm update
// $ npm run mocha
var assert = require('assert');
var es = require('event-stream');
var File = require('vinyl');
var gulpNodeSlate = require('../index.js');
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('The gulp-node-slate plugin', () => {
it('is exported as a function', () => {
var actual = typeof gulpNodeSlate;
var expected = 'function';
assert.equal(actual, expected);
});
});
////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Running the gulp-node-slate plugin', () => {
it('passes through a file in the stream', (done) => {
var mockFile = new File({ contents: es.readArray(['[A]', '[B]', '[C]']) });
function handleFileFromStream(file) {
assert(file.isStream());
function handleDataFromFile(err, data) {
assert.equal(data, '[A][B][C]');
done();
}
file.contents.pipe(es.wait(handleDataFromFile));
}
var pluginStream = gulpNodeSlate();
pluginStream.on('data', handleFileFromStream);
pluginStream.write(mockFile);
pluginStream.end();
}).timeout(60000); //in case node-slate needs to be downloaded
});
|
Bump version: 0.0.20 -> 0.0.21
[ci skip] | # /setup.py
#
# Installation and setup script for parse-shebang
#
# See /LICENCE.md for Copyright information
"""Installation and setup script for parse-shebang."""
from setuptools import find_packages, setup
setup(name="parse-shebang",
version="0.0.21",
description="""Parse shebangs and return their components.""",
long_description_markdown_filename="README.md",
author="Sam Spilsbury",
author_email="[email protected]",
classifiers=["Development Status :: 3 - Alpha",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Intended Audience :: Developers",
"Topic :: System :: Shells",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License"],
url="http://github.com/polysquare/python-parse-shebang",
license="MIT",
keywords="development",
packages=find_packages(exclude=["test"]),
install_requires=["six"],
extras_require={
"upload": ["setuptools-markdown"]
},
test_suite="nose.collector",
zip_safe=True,
include_package_data=True)
| # /setup.py
#
# Installation and setup script for parse-shebang
#
# See /LICENCE.md for Copyright information
"""Installation and setup script for parse-shebang."""
from setuptools import find_packages, setup
setup(name="parse-shebang",
version="0.0.20",
description="""Parse shebangs and return their components.""",
long_description_markdown_filename="README.md",
author="Sam Spilsbury",
author_email="[email protected]",
classifiers=["Development Status :: 3 - Alpha",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Intended Audience :: Developers",
"Topic :: System :: Shells",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License"],
url="http://github.com/polysquare/python-parse-shebang",
license="MIT",
keywords="development",
packages=find_packages(exclude=["test"]),
install_requires=["six"],
extras_require={
"upload": ["setuptools-markdown"]
},
test_suite="nose.collector",
zip_safe=True,
include_package_data=True)
|
Add old browser compat routine for loading pictures | import Loader from 'src/modules/lazy-loader';
let observer;
let galleryContainer;
const loader = new Loader({
url: '/api/gallery',
page: 2,
limit: 1,
});
function lastPost() {
const posts = document.querySelectorAll('.gallery-post');
return posts[posts.length - 1];
}
function observeLastPost() {
if (!observer) return false;
observer.observe(lastPost());
return lastPost;
}
export default (options) => {
galleryContainer = document.querySelector('.gallery-posts');
const next = () => {
loader.nextPage()
.then(({ data: html }) => {
galleryContainer.insertAdjacentHTML('beforeend', html);
if (observer) observeLastPost();
if (options.afterInsert && typeof options.afterInsert === 'function') {
options.afterInsert(lastPost());
}
})
.catch(() => {
// No more posts
});
}
const observerHandler = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
if (observer) observer.unobserve(entry.target);
next();
}
});
};
if (!('IntersectionObserver' in window)) {
// Alternative routine
document.body.classList.add('no-intersection-observer');
document
.querySelector('button.compat-int-obs')
.addEventListener('click', next);
} else {
// Modern browser
observer = new IntersectionObserver(observerHandler, {
threshold: 0,
});
observeLastPost();
}
}
| import axios from 'axios';
function Loader(options = {}) {
this.page = options.page || 0;
this.limit = options.limit || 1;
this.url = options.url || '';
this.nextPage = () => {
this.page += 1;
return axios.get(this.url, {
params: {
page: this.page,
limit: this.limit,
},
responseType: 'text',
});
};
}
function observeLastPost(observer) {
const posts = document.querySelectorAll('.gallery-post');
const lastPost = posts[posts.length - 1];
observer.observe(lastPost);
return lastPost;
}
export default (options) => {
let observer;
const galleryContainer = document.querySelector('.gallery-posts');
const loader = new Loader({
url: '/api/gallery',
page: 2,
limit: 1,
});
const handler = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
loader.nextPage()
.then(({ data: postHtml }) => {
galleryContainer.insertAdjacentHTML('beforeend', postHtml);
const lastPost = observeLastPost(observer);
if (options.afterInsert && typeof options.afterInsert === 'function') {
options.afterInsert(lastPost);
}
}).catch(() => {
// No more posts
});
}
});
};
observer = new IntersectionObserver(handler, {
threshold: 0,
});
observeLastPost(observer);
}
|
Use the updated pymongo syntax for mongo snapshot cursor | #!/usr/bin/env python
import datetime
import logging
import api
def get_now_str():
format = '%d.%h-%H:%M:%S'
now = datetime.datetime.now()
now_str = datetime.datetime.strftime(now, format)
return now_str
if __name__ == '__main__':
collections = api.SEARCHABLE_COLLECTIONS
api.logger.setLevel(logging.INFO)
db = api.data_db
for collection in collections:
started = datetime.datetime.now()
count = db[collection].count()
print 'Starting to work on {} at {}'.format(collection, get_now_str())
print 'Collection {} has {} documents.'.format(collection, count)
for doc in db[collection].find({}, modifiers={"$snapshot": "true"}):
key = '{}.{}'.format(collection, doc['_id'])
related = api.get_bhp_related(doc)
if not related:
print 'No related items found for {}'.format(key)
doc['related'] = []
db[collection].save(doc)
continue
else:
doc['related'] = related
db[collection].save(doc)
finished = datetime.datetime.now()
per_doc_time = (finished - started).total_seconds()/count
print '''Finished working on {} at {}.
Related took {:.2f} seconds per document.'''.format(
collection, get_now_str(), per_doc_time)
| #!/usr/bin/env python
import datetime
import logging
import api
def get_now_str():
format = '%d.%h-%H:%M:%S'
now = datetime.datetime.now()
now_str = datetime.datetime.strftime(now, format)
return now_str
if __name__ == '__main__':
collections = api.SEARCHABLE_COLLECTIONS
api.logger.setLevel(logging.INFO)
db = api.data_db
for collection in collections:
#if collection != 'movies':
# continue
started = datetime.datetime.now()
count = db[collection].count()
print 'Starting to work on {} at {}'.format(collection, get_now_str())
print 'Collection {} has {} documents.'.format(collection, count)
for doc in db[collection].find({}, snapshot=True):
key = '{}.{}'.format(collection, doc['_id'])
related = api.get_bhp_related(doc)
if not related:
print 'No related items found for {}'.format(key)
doc['related'] = []
db[collection].save(doc)
continue
else:
doc['related'] = related
db[collection].save(doc)
finished = datetime.datetime.now()
per_doc_time = (finished - started).total_seconds()/count
print '''Finished working on {} at {}.
Related took {:.2f} seconds per document.'''.format(
collection, get_now_str(), per_doc_time)
|
Watch files, but consider example working on plunkr | const browserSync = require('browser-sync');
const path = require('path');
const url = require('url');
const server = browserSync.create();
server.init({
port: 3000,
files: [
'**/*.js', '**/*.html', '**/*.css'
],
server: {
baseDir: __dirname,
routes: {
"/node_modules": "node_modules",
"/src": "src"
}
},
reloadDebounce: 100,
localOnly: true,
middleware: [
function (req, res, next) {
// Log request
console.info('[BS] ' + req.method + ' ' + req.url);
next();
},
{
route: "/api",
handle: handleApi
}
]
});
function handleApi(req, res) {
if (req.url === '/') {
// Redirect from root
res.writeHead(303, {
'Location': req.originalUrl + '/json'
});
res.end();
}
else if (req.url === '/json') {
// Unspecified content
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
meaning: 42
}));
} else {
// Not found
res.writeHead(404);
res.end();
}
}
| const browserSync = require('browser-sync');
const path = require('path');
const url = require('url');
const server = browserSync.create();
server.init({
port: 3000,
server: {
baseDir: __dirname,
routes: {
"/node_modules": "node_modules",
"/src": "src"
}
},
reloadDebounce: 500,
localOnly: true,
middleware: [
function (req, res, next) {
// Log request
console.info('[BS] ' + req.method + ' ' + req.url);
next();
},
{
route: "/api",
handle: handleApi
}
]
});
function handleApi(req, res) {
if (req.url === '/') {
// Redirect from root
res.writeHead(303, {
'Location': req.originalUrl + '/json'
});
res.end();
}
else if (req.url === '/json') {
// Unspecified content
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
meaning: 42
}));
} else {
// Not found
res.writeHead(404);
res.end();
}
}
|
Make is so we run performance against merged patches | import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if isinstance(event, events.CommentAddedEvent):
if event.change.project == 'openstack/keystone':
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
if event.change.project == 'openstack/keystone':
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
| import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if event.change.project == 'openstack/keystone':
if isinstance(event, events.CommentAddedEvent):
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
|
Use in, because has_key seems to be deprecated
Signed-off-by: Stefan Marr <[email protected]> | import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("Double" ,),
("Empty" ,),
("Hash" ,),
("Integer" ,),
("ObjectSize" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("Super" ,),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
| import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("Double" ,),
("Empty" ,),
("Hash" ,),
("Integer" ,),
("ObjectSize" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("Super" ,),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if sys.modules.has_key('pytest'):
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
|
Make cleverbot module behave like a typing human | /**
* Created by Julian/Wolke on 27.11.2016.
*/
let Manager = require('../../structures/manager');
let Cleverbot = require('cleverbot');
let re = /<@[0-9].*>/g;
let cleverbotKey = remConfig.cleverbot_api_key;
class CleverBotManager extends Manager {
constructor() {
super();
this.cleverbot = new Cleverbot({'key': cleverbotKey});
this.continuationStrings = {};
}
talk(msg) {
var message = msg.content.replace(re, '');
var continuationString = this.continuationStrings[msg.channel.id];
if (continuationString && continuationString.length > 2000) {
msg.channel.createMessage("I am having trouble remembering this conversation... Let's start over!");
this.continuationStrings[msg.channel.id] = undefined;
return;
}
this.cleverbot
.query(message, {'cs': continuationString})
.then(response => {
setTimeout(() => {
msg.channel.sendTyping();
setTimeout(() => {
msg.channel.createMessage(response.output);
}, response.output.length * 65);
}, message.length * 25);
this.continuationStrings[msg.channel.id] = response.cs;
})
.catch(error => {
console.error(error);
return msg.channel.createMessage(':x: An error with cleverbot occured!');
});
}
}
module.exports = {class: CleverBotManager, deps: [], async: false, shortcode: 'cm'}; | /**
* Created by Julian/Wolke on 27.11.2016.
*/
let Manager = require('../../structures/manager');
let Cleverbot = require('cleverbot');
let re = /<@[0-9].*>/g;
let cleverbotKey = remConfig.cleverbot_api_key;
class CleverBotManager extends Manager {
constructor() {
super();
this.cleverbot = new Cleverbot({'key': cleverbotKey});
this.continuationStrings = {};
}
talk(msg) {
var message = msg.content.replace(re, '');
var continuationString = this.continuationStrings[msg.channel.id];
if (continuationString && continuationString.length > 2000) {
msg.channel.createMessage("I am having trouble remembering this conversation... Let's start over!");
this.continuationStrings[msg.channel.id] = undefined;
return;
}
this.cleverbot
.query(message, {'cs': continuationString})
.then(response => {
msg.channel.createMessage(':pencil: ' + response.output);
this.continuationStrings[msg.channel.id] = response.cs;
})
.catch(error => {
console.error(error);
return msg.channel.createMessage(':x: An error with cleverbot occured!');
});
}
}
module.exports = {class: CleverBotManager, deps: [], async: false, shortcode: 'cm'}; |
Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@326640 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit cb9b1a2163f960e34721f74bad30622fda71e43b) | """Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
import platform
import shutil
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCModulesTestCase(TestBase):
NO_DEBUG_INFO_TESTCASE = True
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
TestBase.setUp(self)
@skipUnlessDarwin
def test_expr(self):
self.build()
self.main_source_file = lldb.SBFileSpec("main.m")
self.runCmd("settings set target.auto-import-clang-modules true")
mod_cache = self.getBuildArtifact("my-clang-modules-cache")
if os.path.isdir(mod_cache):
shutil.rmtree(mod_cache)
self.assertFalse(os.path.isdir(mod_cache),
"module cache should not exist")
self.runCmd('settings set symbols.clang-modules-cache-path "%s"' % mod_cache)
self.runCmd('settings set target.clang-module-search-paths "%s"'
% self.getSourceDir())
(target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(
self, "Set breakpoint here", self.main_source_file)
self.runCmd("expr @import Foo")
self.assertTrue(os.path.isdir(mod_cache), "module cache exists")
| """Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
import platform
import shutil
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCModulesTestCase(TestBase):
NO_DEBUG_INFO_TESTCASE = True
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
TestBase.setUp(self)
def test_expr(self):
self.build()
self.main_source_file = lldb.SBFileSpec("main.m")
self.runCmd("settings set target.auto-import-clang-modules true")
mod_cache = self.getBuildArtifact("my-clang-modules-cache")
if os.path.isdir(mod_cache):
shutil.rmtree(mod_cache)
self.assertFalse(os.path.isdir(mod_cache),
"module cache should not exist")
self.runCmd('settings set symbols.clang-modules-cache-path "%s"' % mod_cache)
self.runCmd('settings set target.clang-module-search-paths "%s"'
% self.getSourceDir())
(target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(
self, "Set breakpoint here", self.main_source_file)
self.runCmd("expr @import Darwin")
self.assertTrue(os.path.isdir(mod_cache), "module cache exists")
|
Include migrations in package and bump version to v0.3 | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).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-trello-webhooks",
version="0.3",
packages=[
'trello_webhooks',
'trello_webhooks.management',
'trello_webhooks.management.commands',
'trello_webhooks.migrations',
'trello_webhooks.templatetags',
'trello_webhooks.tests',
],
install_requires=['django>=1.7.1'],
include_package_data=True,
description='Django Trello Webhooks - Trello callback integration for Django.',
long_description=README,
url='https://github.com/yunojuno/django-trello-webhooks',
author='Hugo Rodger-Brown',
author_email='[email protected]',
maintainer='Hugo Rodger-Brown',
maintainer_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).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-trello-webhooks",
version="0.2",
packages=[
'trello_webhooks',
'trello_webhooks.management',
'trello_webhooks.management.commands',
'trello_webhooks.templatetags',
'trello_webhooks.tests',
],
install_requires=['django>=1.7.1'],
include_package_data=True,
description='Django Trello Webhooks - Trello callback integration for Django.',
long_description=README,
url='https://github.com/yunojuno/django-trello-webhooks',
author='Hugo Rodger-Brown',
author_email='[email protected]',
maintainer='Hugo Rodger-Brown',
maintainer_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Fix minor merge conflic in whitespace | 'use strict';
import React, { Component } from 'react';
import Swiper from 'react-native-swiper';
import {
Text,
View,
StyleSheet,
Image,
} from 'react-native';
class DetailImages extends Component {
render(){
return (
<Swiper style={styles.wrapper} height={360} showsButtons={true}>
<View style={styles.slide1}>
<Image style={styles.image} source={{uri: this.props.photos}} />
</View>
<View style={styles.slide2}>
<Text style={styles.text}>Addtional photos here</Text>
</View>
<View style={styles.slide3}>
<Text style={styles.text}>Addtional photos here</Text>
</View>
</Swiper>
)
}
}
const styles = StyleSheet.create({
wrapper: {
},
slide1: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#9DD6EB',
},
slide2: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#97CAE5',
},
slide3: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#92BBD9',
},
text: {
color: '#fff',
fontSize: 30,
fontWeight: 'bold',
},
image:{
height:350,
width:375,
},
});
export default DetailImages;
| 'use strict';
import React, { Component } from 'react';
import Swiper from 'react-native-swiper';
import {
Text,
View,
StyleSheet,
Image,
} from 'react-native';
class DetailImages extends Component {
render(){
return (
<Swiper style={styles.wrapper} height={360} showsButtons={true}>
<View style={styles.slide1}>
<Image style={styles.image} source={{uri: this.props.photos}} />
</View>
<View style={styles.slide2}>
<Text style={styles.text}>Addtional photos here</Text>
</View>
<View style={styles.slide3}>
<Text style={styles.text}>Addtional photos here</Text>
</View>
</Swiper>
)
}
}
const styles = StyleSheet.create({
wrapper: {
},
slide1: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#9DD6EB',
},
slide2: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#97CAE5',
},
slide3: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#92BBD9',
},
text: {
color: '#fff',
fontSize: 30,
fontWeight: 'bold',
},
image:{
height:350,
width:375,
},
});
export default DetailImages;
|
Use BulkText instead of Text in input keyword
Fixes #164 | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input_value):
"""Writes text to a textbox.
``locator`` is the locator of the text box or Textbox item object.
Locator syntax is explained in `Item locators`.
``input_value`` is the text to write.
"""
text_box = self.state._get_typed_item_by_locator(TextBox, locator)
text_box.BulkText = input_value
@keyword
def verify_text_in_textbox(self, locator, expected):
"""Verifies text in a text box.
``locator`` is the locator of the text box or Textbox item object.
Locator syntax is explained in `Item locators`.
``expected`` is the expected text of the text box.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
self.state._verify_value(expected, textbox.Text)
@keyword
def get_text_from_textbox(self, locator):
"""Returns the text of a text box.
``locator`` is the locator of the text box or Textbox item object.
Locator syntax is explained in `Item locators`.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
return textbox.Text
| from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input_value):
"""Writes text to a textbox.
``locator`` is the locator of the text box or Textbox item object.
Locator syntax is explained in `Item locators`.
``input_value`` is the text to write.
"""
text_box = self.state._get_typed_item_by_locator(TextBox, locator)
text_box.Text = input_value
@keyword
def verify_text_in_textbox(self, locator, expected):
"""Verifies text in a text box.
``locator`` is the locator of the text box or Textbox item object.
Locator syntax is explained in `Item locators`.
``expected`` is the expected text of the text box.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
self.state._verify_value(expected, textbox.Text)
@keyword
def get_text_from_textbox(self, locator):
"""Returns the text of a text box.
``locator`` is the locator of the text box or Textbox item object.
Locator syntax is explained in `Item locators`.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
return textbox.Text
|
Setup: Define content type Markdown for description. | from setuptools import setup, find_packages
from foliant import __version__ as foliant_version
SHORT_DESCRIPTION = 'Modular, Markdown-based documentation generator that makes \
pdf, docx, html, and more.'
try:
with open('README.md', encoding='utf8') as readme:
LONG_DESCRIPTION = readme.read()
except FileNotFoundError:
LONG_DESCRIPTION = SHORT_DESCRIPTION
setup(
name='foliant',
version=foliant_version,
url='https://github.com/foliant-docs/foliant',
download_url='https://pypi.org/project/foliant',
license='MIT',
author='Konstantin Molchanov',
author_email='[email protected]',
description=SHORT_DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
packages=find_packages(),
platforms='any',
install_requires=[
'PyYAML',
'cliar>=1.1.9',
'halo>=0.0.10',
'prompt_toolkit'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
'Programming Language :: Python :: 3.6'
],
entry_points={
'console_scripts': [
'foliant=foliant.cli:entry_point'
]
}
)
| from setuptools import setup, find_packages
from foliant import __version__ as foliant_version
SHORT_DESCRIPTION = 'Modular, Markdown-based documentation generator that makes \
pdf, docx, html, and more.'
try:
with open('README.md', encoding='utf8') as readme:
LONG_DESCRIPTION = readme.read()
except FileNotFoundError:
LONG_DESCRIPTION = SHORT_DESCRIPTION
setup(
name='foliant',
version=foliant_version,
url='https://github.com/foliant-docs/foliant',
download_url='https://pypi.org/project/foliant',
license='MIT',
author='Konstantin Molchanov',
author_email='[email protected]',
description=SHORT_DESCRIPTION,
long_description=LONG_DESCRIPTION,
packages=find_packages(),
platforms='any',
install_requires=[
'PyYAML',
'cliar>=1.1.9',
'halo>=0.0.10',
'prompt_toolkit'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
'Programming Language :: Python :: 3.6'
],
entry_points={
'console_scripts': [
'foliant=foliant.cli:entry_point'
]
}
)
|
Add field `confirm_password` and `remember_me` to form | <?php
namespace User\Form;
use Zend\Form\Form;
class UserForm extends Form
{
public function __construct($name = null)
{
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'username',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'email',
'type' => 'Email',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'full_name',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'password',
'type' => 'Password',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'confirm_password',
'type' => 'Password',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'remember_me',
'type' => 'checkbox',
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
'id' => 'submit-btn',
'class' => 'btn btn-primary',
),
));
}
} | <?php
namespace User\Form;
use Zend\Form\Form;
class UserForm extends Form
{
public function __construct($name = null)
{
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'username',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'email',
'type' => 'Email',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'full_name',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'password',
'type' => 'Password',
'attributes' => array(
'class' => 'form-control',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
'id' => 'submit-btn',
'class' => 'btn btn-primary',
),
));
}
} |
Fix invalid path for Bootstrap js file | var elixir = require('laravel-elixir');
elixir(function(mix) {
mix.copy(
'node_modules/bootstrap/dist/fonts',
'public/build/fonts'
);
mix.copy(
'node_modules/font-awesome/fonts',
'public/build/fonts'
);
mix.copy(
'node_modules/ionicons/dist/fonts',
'public/build/fonts'
);
mix.scripts([
'../../../node_modules/jquery/dist/jquery.min.js',
'../../../vendor/twbs/bootstrap/dist/js/bootstrap.min.js'
], 'public/js/vendor.js');
mix.scripts([
'app.js'
], 'public/js/app.js');
mix.less([
'../../../vendor/twbs/bootstrap/less/bootstrap.less',
'../../../node_modules/font-awesome/less/font-awesome.less',
'../../../node_modules/ionicons/dist/css/ionicons.min.css',
'adminlte/AdminLTE.less',
'adminlte/skins/_all-skins.less'
], 'public/css/vendor.css');
mix.less([
'app.less'
], 'public/css/app.css');
mix.less([
'welcome.less'
], 'public/css/welcome.css');
mix.version([
'public/css/app.css',
'public/css/welcome.css',
'public/css/vendor.css',
'public/js/app.js',
'public/js/vendor.js'
]);
}); | var elixir = require('laravel-elixir');
elixir(function(mix) {
mix.copy(
'node_modules/bootstrap/dist/fonts',
'public/build/fonts'
);
mix.copy(
'node_modules/font-awesome/fonts',
'public/build/fonts'
);
mix.copy(
'node_modules/ionicons/dist/fonts',
'public/build/fonts'
);
mix.scripts([
'../../../node_modules/jquery/dist/jquery.min.js',
'../../../node_modules/bootstrap/dist/js/bootstrap.min.js'
], 'public/js/vendor.js');
mix.scripts([
'app.js'
], 'public/js/app.js');
mix.less([
'../../../vendor/twbs/bootstrap/less/bootstrap.less',
'../../../node_modules/font-awesome/less/font-awesome.less',
'../../../node_modules/ionicons/dist/css/ionicons.min.css',
'adminlte/AdminLTE.less',
'adminlte/skins/_all-skins.less'
], 'public/css/vendor.css');
mix.less([
'app.less'
], 'public/css/app.css');
mix.less([
'welcome.less'
], 'public/css/welcome.css');
mix.version([
'public/css/app.css',
'public/css/welcome.css',
'public/css/vendor.css',
'public/js/app.js',
'public/js/vendor.js'
]);
}); |
Use version 1.2 of TLS | var cp = require('child_process'),
ps = require('ps-node'),
Q = require('q'),
debug = require('debug')('cheapseats'),
phantomPath = require('phantomjs').path;
var webdriverProcess;
var driver = {
init: function (browser, config) {
return browser.init()
.setWindowSize(config.browserWidth, config.browserHeight)
.then(function () {
process.stdout.write('\nConnected to webdriver server on port ' + config.port + '\n');
}, function (err) {
if (err.code === 'ECONNREFUSED') {
var promise = Q.defer();
ps.lookup({
command: 'phantomjs',
arguments: ['--webdriver', config.port]
}, function (err, processes) {
if (!processes.length) {
process.stdout.write('No webdriver instance found on port ' + config.port + '. Starting phantomjs...');
webdriverProcess = cp.spawn(phantomPath, ['--webdriver', config.port, '--ssl-protocol', 'tlsv1.2'], {
stdio: 'ignore'
});
} else {
process.stdout.write('.');
}
setTimeout(function () {
promise.resolve();
}, 2000);
});
return promise.promise.then(function () {
return driver.init(browser, config);
});
} else {
return Q.reject(err);
}
});
},
kill: function () {
if (webdriverProcess) {
webdriverProcess.kill();
debug('Tearing down webdriver');
}
}
};
module.exports = driver;
| var cp = require('child_process'),
ps = require('ps-node'),
Q = require('q'),
debug = require('debug')('cheapseats'),
phantomPath = require('phantomjs').path;
var webdriverProcess;
var driver = {
init: function (browser, config) {
return browser.init()
.setWindowSize(config.browserWidth, config.browserHeight)
.then(function () {
process.stdout.write('\nConnected to webdriver server on port ' + config.port + '\n');
}, function (err) {
if (err.code === 'ECONNREFUSED') {
var promise = Q.defer();
ps.lookup({
command: 'phantomjs',
arguments: ['--webdriver', config.port]
}, function (err, processes) {
if (!processes.length) {
process.stdout.write('No webdriver instance found on port ' + config.port + '. Starting phantomjs...');
webdriverProcess = cp.spawn(phantomPath, ['--webdriver', config.port, '--ssl-protocol', 'tlsv1'], {
stdio: 'ignore'
});
} else {
process.stdout.write('.');
}
setTimeout(function () {
promise.resolve();
}, 2000);
});
return promise.promise.then(function () {
return driver.init(browser, config);
});
} else {
return Q.reject(err);
}
});
},
kill: function () {
if (webdriverProcess) {
webdriverProcess.kill();
debug('Tearing down webdriver');
}
}
};
module.exports = driver; |
Use ::class keyword to get class names | <?php
namespace AuthorBooks\Model;
use Maghead\Schema\DeclareSchema;
class AuthorSchema extends DeclareSchema
{
public function schema()
{
$this->column('name')
->varchar(128)
->findable()
;
$this->column('email')
->required()
->findable()
->varchar(128);
$this->column('account_brief')
->label('Account Brief')
->virtual()
->inflator(function ($value, $record) {
return $record->name . '(' . $record->email . ')';
});
$this->column('identity')
->unique()
->required()
->varchar(128)
->validator('StringLength', ['min' => 3, 'max' => 64])
->findable()
;
$this->column('confirmed')
->boolean()
->default(false);
$this->mixin('Maghead\\Schema\\Mixin\\MetadataMixinSchema');
$this->many('addresses', AddressSchema::class, 'author_id', 'id');
$this->many('unused_addresses', AddressSchema::class, 'author_id', 'id')
->where()->equal('unused', true);
$this->many('author_books', AuthorBookSchema::class, 'author_id', 'id');
$this->manyToMany('books', 'author_books', 'book');
}
}
| <?php
namespace AuthorBooks\Model;
use Maghead\Schema\DeclareSchema;
class AuthorSchema extends DeclareSchema
{
public function schema()
{
$this->column('name')
->varchar(128)
->findable()
;
$this->column('email')
->required()
->findable()
->varchar(128);
$this->column('account_brief')
->label('Account Brief')
->virtual()
->inflator(function ($value, $record) {
return $record->name . '(' . $record->email . ')';
});
$this->column('identity')
->unique()
->required()
->varchar(128)
->validator('StringLength', ['min' => 3, 'max' => 64])
->findable()
;
$this->column('confirmed')
->boolean()
->default(false);
$this->mixin('Maghead\\Schema\\Mixin\\MetadataMixinSchema');
$this->many('addresses', 'AuthorBooks\Model\AddressSchema', 'author_id', 'id');
$this->many('unused_addresses', 'AuthorBooks\Model\AddressSchema', 'author_id', 'id')
->where()
->equal('unused', true);
$this->many('author_books', 'AuthorBooks\Model\AuthorBookSchema', 'author_id', 'id');
$this->manyToMany('books', 'author_books', 'book');
}
}
|
Fix Laravel Scheduled Task monitoring | <?php
/*
* This file is part of the Blackfire SDK package.
*
* (c) Blackfire <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Blackfire\Bridge\Laravel;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Console\Events\ScheduledTaskFailed;
use Illuminate\Console\Events\ScheduledTaskFinished;
use Illuminate\Console\Events\ScheduledTaskStarting;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
class ObservableCommandProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Event::listen(
array(
CommandStarting::class,
ScheduledTaskStarting::class,
),
function ($event) {
$transactionName = 'artisan '.($event->input->__toString() ?? 'Unnamed Command');
\BlackfireProbe::startTransaction();
\BlackfireProbe::setTransactionName($transactionName);
}
);
Event::listen(
array(
CommandFinished::class,
ScheduledTaskFinished::class,
ScheduledTaskFailed::class,
),
function () {
\BlackfireProbe::stopTransaction();
}
);
}
}
| <?php
/*
* This file is part of the Blackfire SDK package.
*
* (c) Blackfire <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Blackfire\Bridge\Laravel;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Console\Events\ScheduledTaskFailed;
use Illuminate\Console\Events\ScheduledTaskFinished;
use Illuminate\Console\Events\ScheduledTaskStarting;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
class ObservableCommandProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Event::listen(
array(
CommandStarting::class,
ScheduledTaskStarting::class,
),
function (CommandStarting $event) {
$transactionName = 'artisan '.($event->input->__toString() ?? 'Unnamed Command');
\BlackfireProbe::startTransaction();
\BlackfireProbe::setTransactionName($transactionName);
}
);
Event::listen(
array(
CommandFinished::class,
ScheduledTaskFinished::class,
ScheduledTaskFailed::class,
),
function () {
\BlackfireProbe::stopTransaction();
}
);
}
}
|
Check if Buzz library is installed. | <?php
namespace Geocoder\Tests\HttpAdapter;
use Geocoder\Tests\TestCase;
use Geocoder\HttpAdapter\BuzzHttpAdapter;
/**
* @author William Durand <[email protected]>
*/
class BuzzHttpAdapterTest extends TestCase
{
protected function setUp()
{
if (!class_exists('Buzz\Browser')) {
$this->markTestSkipped('Buzz library has to be installed');
}
}
public function testGetNullContent()
{
$buzz = new BuzzHttpAdapter();
$this->assertNull($buzz->getContent(null));
}
public function testGetFalseContent()
{
$buzz = new BuzzHttpAdapter();
$this->assertNull($buzz->getContent(false));
}
public function testGetContentWithCustomBrowser()
{
$content = 'foobar content';
$browser = $this->getBrowserMock($content);
$buzz = new BuzzHttpAdapter($browser);
$this->assertEquals($content, $buzz->getContent('http://www.example.com'));
}
protected function getBrowserMock($content)
{
$mock = $this->getMock('\Buzz\Browser');
$mock
->expects($this->once())
->method('get')
->will($this->returnValue($this->getResponseMock($content)))
;
return $mock;
}
protected function getResponseMock($content)
{
$mock = $this->getMock('\Buzz\Message\Response');
$mock
->expects($this->once())
->method('getContent')
->will($this->returnValue($content));
return $mock;
}
}
| <?php
namespace Geocoder\Tests\HttpAdapter;
use Geocoder\Tests\TestCase;
use Geocoder\HttpAdapter\BuzzHttpAdapter;
/**
* @author William Durand <[email protected]>
*/
class BuzzHttpAdapterTest extends TestCase
{
public function testGetNullContent()
{
$buzz = new BuzzHttpAdapter();
$this->assertNull($buzz->getContent(null));
}
public function testGetFalseContent()
{
$buzz = new BuzzHttpAdapter();
$this->assertNull($buzz->getContent(false));
}
public function testGetContentWithCustomBrowser()
{
$content = 'foobar content';
$browser = $this->getBrowserMock($content);
$buzz = new BuzzHttpAdapter($browser);
$this->assertEquals($content, $buzz->getContent('http://www.example.com'));
}
protected function getBrowserMock($content)
{
$mock = $this->getMock('\Buzz\Browser');
$mock
->expects($this->once())
->method('get')
->will($this->returnValue($this->getResponseMock($content)))
;
return $mock;
}
protected function getResponseMock($content)
{
$mock = $this->getMock('\Buzz\Message\Response');
$mock
->expects($this->once())
->method('getContent')
->will($this->returnValue($content));
return $mock;
}
}
|
fix: Change reducers to return a new state
The changes in the comment reducer were not committed befire | import {
ADD_VOTE_COMMENT,
CREATE_COMMENT,
REMOVE_COMMENT,
REMOVE_VOTE_COMMENT,
SET_COMMENTS,
UPDATE_COMMENT
} from "../actions/Comment";
import {REMOVE_POST} from "../actions/Post";
const initialStateComments = {
comments:[]
};
export default function comment(state = initialStateComments, action) {
switch (action.type) {
case REMOVE_COMMENT :
let newState = {...state};
newState.comments.find(comment => comment.id === action.id).deleted = true;
return newState;
case REMOVE_POST :
let newState = {...state};
newState.comments.filter(comment => comment.parentId === action.id).map(comment => {
comment.parentDeleted = true;
});
return newState;
case CREATE_COMMENT:
let newState = {...state};
newState.comments.push(action.comment);
return newState;
case ADD_VOTE_COMMENT:
let newState = {...state};
newState.comments.find(comment => comment.id === action.id).voteScore += 1;
return newState;
case REMOVE_VOTE_COMMENT:
let newState = {...state};
newState.comments.find(comment => comment.id === action.id).voteScore -= 1;
return newState;
case UPDATE_COMMENT:
let newState = {...state};
newState.comments.find(comment => comment.id === action.comment.id).body = action.comment.body;
return newState;
case SET_COMMENTS:
return {
comments: action.comments
};
default :
return state
}
} | import {
ADD_VOTE_COMMENT,
CREATE_COMMENT,
REMOVE_COMMENT,
REMOVE_VOTE_COMMENT,
SET_COMMENTS,
UPDATE_COMMENT
} from "../actions/Comment";
import {REMOVE_POST} from "../actions/Post";
const initialStateComments = {
comments:[]
};
export default function comment(state = initialStateComments, action) {
switch (action.type) {
case REMOVE_COMMENT :
state.comments.find(comment => comment.id === action.id).deleted = true;
return state;
case REMOVE_POST :
state.comments.filter(comment => comment.parentId === action.id).map(comment => {
comment.parentDeleted = true;
});
return state;
case CREATE_COMMENT:
state.comments.push(action.comment);
return state;
case ADD_VOTE_COMMENT:
state.comments.find(comment => comment.id === action.id).voteScore += 1;
return state;
case REMOVE_VOTE_COMMENT:
state.comments.find(comment => comment.id === action.id).voteScore -= 1;
return state;
case UPDATE_COMMENT:
state.comments.find(comment => comment.id === action.comment.id).body = action.comment.body;
return state;
case SET_COMMENTS:
return {
comments: action.comments
};
default :
return state
}
} |
Add method to delete a category. | package com.github.cstroe.spendhawk.entity;
import com.github.cstroe.spendhawk.util.HibernateUtil;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import java.util.List;
/**
* The category for an expense. Categories are at the user level, so that
* many accounts can use the same categories to categorize their expenditures.
*/
public class Category {
private Long id;
private User user;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean save() {
Long id = (Long) HibernateUtil.getSessionFactory().getCurrentSession().save(this);
return id != null;
}
public void delete() {
HibernateUtil.getSessionFactory().getCurrentSession().delete(this);
}
@SuppressWarnings("unchecked")
public static List<Category> findAll() {
return (List<Category>) HibernateUtil.getSessionFactory().getCurrentSession()
.createCriteria(Category.class)
.addOrder(Order.asc("name"))
.list();
}
public static Category findById(Long id) {
return (Category) HibernateUtil.getSessionFactory().getCurrentSession()
.createCriteria(Category.class)
.add(Restrictions.eq("id", id))
.uniqueResult();
}
}
| package com.github.cstroe.spendhawk.entity;
import com.github.cstroe.spendhawk.util.HibernateUtil;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import java.util.List;
/**
* The category for an expense. Categories are at the user level, so that
* many accounts can use the same categories to categorize their expenditures.
*/
public class Category {
private Long id;
private User user;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean save() {
Long id = (Long) HibernateUtil.getSessionFactory().getCurrentSession().save(this);
return id != null;
}
@SuppressWarnings("unchecked")
public static List<Category> findAll() {
return (List<Category>) HibernateUtil.getSessionFactory().getCurrentSession()
.createCriteria(Category.class)
.addOrder(Order.asc("name"))
.list();
}
public static Category findById(Long id) {
return (Category) HibernateUtil.getSessionFactory().getCurrentSession()
.createCriteria(Category.class)
.add(Restrictions.eq("id", id))
.uniqueResult();
}
}
|
Remove es2015 from karma presets | const path = require('path')
module.exports = function(config) {
config.set({
files: [
// all files ending in 'test'
'test/e2e/*.spec.js'
// each file acts as entry point for the webpack configuration
],
// frameworks to use
frameworks: ['mocha'],
preprocessors: {
// only specify one entry point
// and require all tests in there
'test/e2e/*.spec.js': ['webpack']
},
reporters: ['spec', 'coverage'],
coverageReporter: {
dir: 'build/coverage/',
reporters: [
{ type: 'html' },
{ type: 'text' },
{ type: 'text-summary' }
]
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, 'node_modules'),
query: {
presets: ['env']
}
},
{
test: /\.json$/,
loader: 'json-loader',
},
]
},
externals: {
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
},
webpackServer: {
noInfo: true
},
plugins: [
require('karma-webpack'),
require('istanbul-instrumenter-loader'),
require('karma-mocha'),
require('karma-coverage'),
require('karma-spec-reporter'),
require('karma-chrome-launcher')
],
browsers: ['Chrome']
})
} | const path = require('path')
module.exports = function(config) {
config.set({
files: [
// all files ending in 'test'
'test/e2e/*.spec.js'
// each file acts as entry point for the webpack configuration
],
// frameworks to use
frameworks: ['mocha'],
preprocessors: {
// only specify one entry point
// and require all tests in there
'test/e2e/*.spec.js': ['webpack']
},
reporters: ['spec', 'coverage'],
coverageReporter: {
dir: 'build/coverage/',
reporters: [
{ type: 'html' },
{ type: 'text' },
{ type: 'text-summary' }
]
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, 'node_modules'),
query: {
presets: ['es2015']
}
},
{
test: /\.json$/,
loader: 'json-loader',
},
]
},
externals: {
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
},
webpackServer: {
noInfo: true
},
plugins: [
require('karma-webpack'),
require('istanbul-instrumenter-loader'),
require('karma-mocha'),
require('karma-coverage'),
require('karma-spec-reporter'),
require('karma-chrome-launcher')
],
browsers: ['Chrome']
})
} |
Use one of the stock examples for the open/save test | #!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(fpath)
source = os.path.join(path, "..", "examples", "example1", "world.rooms")
source = os.path.normpath(source)
dest = self.test_output
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
def tearDown(self):
# Cleanup the temporary file used for test purposes
os.unlink(self.test_output)
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
if __name__ == "__main__":
unittest.main()
|
Use String as lock key | package com.yahoo.concurrent.classlock;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BooleanSupplier;
/**
* @author valerijf
*/
public class ClassLocking {
private final Map<String, ClassLock> classLocks = new HashMap<>();
private final Object monitor = new Object();
public ClassLock lock(Class<?> clazz) {
return lockWhile(clazz, () -> true);
}
public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) {
synchronized (monitor) {
while (classLocks.containsKey(clazz.getName())) {
try {
monitor.wait();
} catch (InterruptedException ignored) {
}
if (!interruptCondition.getAsBoolean()) {
throw new LockInterruptException();
}
}
ClassLock classLock = new ClassLock(this, clazz);
classLocks.put(clazz.getName(), classLock);
return classLock;
}
}
void unlock(Class<?> clazz, ClassLock classLock) {
synchronized (monitor) {
if (classLock.equals(classLocks.get(clazz.getName()))) {
classLocks.remove(clazz.getName());
monitor.notifyAll();
} else {
throw new IllegalArgumentException("Lock has already been released");
}
}
}
public void interrupt() {
synchronized (monitor) {
monitor.notifyAll();
}
}
}
| package com.yahoo.concurrent.classlock;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BooleanSupplier;
/**
* @author valerijf
*/
public class ClassLocking {
private final Map<Class<?>, ClassLock> classLocks = new HashMap<>();
private final Object monitor = new Object();
public ClassLock lock(Class<?> clazz) {
return lockWhile(clazz, () -> true);
}
public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) {
synchronized (monitor) {
while (classLocks.containsKey(clazz)) {
try {
monitor.wait();
} catch (InterruptedException ignored) {
}
if (!interruptCondition.getAsBoolean()) {
throw new LockInterruptException();
}
}
ClassLock classLock = new ClassLock(this, clazz);
classLocks.put(clazz, classLock);
return classLock;
}
}
void unlock(Class<?> clazz, ClassLock classLock) {
synchronized (monitor) {
if (classLock.equals(classLocks.get(clazz))) {
classLocks.remove(clazz);
monitor.notifyAll();
} else {
throw new IllegalArgumentException("Lock has already been released");
}
}
}
public void interrupt() {
synchronized (monitor) {
monitor.notifyAll();
}
}
}
|
Use ijson to parse the test262 results.
Parsing the output all at once can cause out-of-memory errors in automated
testing. | #!/usr/bin/env python3
import ijson
import sys
PREFIXES = [
["FAIL", "PASS"],
["EXPECTED FAIL", "UNEXPECTED PASS"],
]
def parse_expected_failures():
expected_failures = set()
with open("expected-failures.txt", "r") as fp:
for line in fp:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
expected_failures.add(line)
return expected_failures
def main(filename):
expected_failures = parse_expected_failures()
with open(filename, "r") as fp:
results = ijson.items(fp, "item")
unexpected_results = []
for test in results:
expected_failure = test["file"] in expected_failures
actual_result = test["result"]["pass"]
print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"]))
if actual_result == expected_failure:
if not actual_result:
print(test["rawResult"]["stderr"])
print(test["rawResult"]["stdout"])
print(test["result"]["message"])
unexpected_results.append(test)
if unexpected_results:
print("{} unexpected results:".format(len(unexpected_results)))
for unexpected in unexpected_results:
print("- {}".format(unexpected["file"]))
return False
print("All results as expected.")
return True
if __name__ == "__main__":
sys.exit(0 if main(sys.argv[1]) else 1)
| #!/usr/bin/env python3
import json
import sys
PREFIXES = [
["FAIL", "PASS"],
["EXPECTED FAIL", "UNEXPECTED PASS"],
]
def parse_expected_failures():
expected_failures = set()
with open("expected-failures.txt", "r") as fp:
for line in fp:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
expected_failures.add(line)
return expected_failures
def main(filename):
expected_failures = parse_expected_failures()
with open(filename, "r") as fp:
results = json.load(fp)
unexpected_results = []
for test in results:
expected_failure = test["file"] in expected_failures
actual_result = test["result"]["pass"]
print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"]))
if actual_result == expected_failure:
if not actual_result:
print(test["rawResult"]["stderr"])
print(test["rawResult"]["stdout"])
print(test["result"]["message"])
unexpected_results.append(test)
if unexpected_results:
print("{} unexpected results:".format(len(unexpected_results)))
for unexpected in unexpected_results:
print("- {}".format(unexpected["file"]))
return False
print("All results as expected.")
return True
if __name__ == "__main__":
sys.exit(0 if main(sys.argv[1]) else 1)
|
Return json from all schema controller paths | <?php
namespace App\Http\Controllers;
use App\Repositories\SchemaRepository;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class SchemaController extends Controller
{
/**
* @var SchemaRepository
*/
protected $schemaRepository;
public function __construct(SchemaRepository $schemaRepository)
{
$this->schemaRepository = $schemaRepository;
}
public function index()
{
return $this->jsonResponse($this->schemaRepository->all());
}
public function listSchemaVersion($version)
{
return $this->jsonResponse($this->schemaRepository->getVersion($version));
}
public function getSchema(Filesystem $fs, $version, $entity)
{
try {
$schema = $this->schemaRepository->loadSchemaForEntity($version, $entity);
return $this->jsonResponse($schema);
} catch (FileNotFoundException $e) {
return $this->jsonResponse(['error' => 'File not found'], Response::HTTP_NOT_FOUND);
}
}
protected function jsonResponse(array $responseData, $status = Response::HTTP_OK): JsonResponse
{
return response()->json(
$responseData,
$status,
[
'Content-Type' => 'application/json; charset=utf-8',
'Access-Control-Allow-Origin' => '*',
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
}
}
| <?php
namespace App\Http\Controllers;
use App\Repositories\SchemaRepository;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class SchemaController extends Controller
{
/**
* @var SchemaRepository
*/
protected $schemaRepository;
public function __construct(SchemaRepository $schemaRepository)
{
$this->schemaRepository = $schemaRepository;
}
public function index()
{
return $this->jsonResponse($this->schemaRepository->all());
}
public function listSchemaVersion($version)
{
return $this->jsonResponse($this->schemaRepository->getVersion($version));
}
public function getSchema(Filesystem $fs, $version, $entity)
{
try {
$schema = $this->schemaRepository->loadSchemaForEntity($version, $entity);
return $this->jsonResponse($schema);
} catch (FileNotFoundException $e) {
return response('File not found.', 404, ['Content-type' => 'text/plain']);
}
}
protected function jsonResponse(array $responseData): JsonResponse
{
return response()->json(
$responseData,
Response::HTTP_OK,
[
'Content-Type' => 'application/json; charset=utf-8',
'Access-Control-Allow-Origin' => '*',
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
}
}
|
Fix pad_tx off by one error + nits
Summary: See title
Test Plan: test_runner.py
Reviewers: deadalnix, schancel, #bitcoin_abc
Reviewed By: schancel, #bitcoin_abc
Subscribers: teamcity
Differential Revision: https://reviews.bitcoinabc.org/D2096 | from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTransaction, FromHex, ToHex, CTxOut
from .script import OP_RETURN, CScript
import random
from binascii import hexlify, unhexlify
# Pad outputs until it reaches at least min_size
def pad_tx(tx, min_size=None):
if min_size is None:
min_size = MIN_TX_SIZE
curr_size = len(tx.serialize())
while curr_size < min_size:
# txout.value + txout.pk_script bytes + op_return
extra_bytes = 8 + 1 + 1
padding_len = max(0, min_size - curr_size - extra_bytes)
padding_len = min(padding_len, MAX_TXOUT_PUBKEY_SCRIPT)
if padding_len == 0:
tx.vout.append(CTxOut(0, CScript([OP_RETURN])))
else:
padding = random.randrange(
1 << 8 * padding_len - 2, 1 << 8 * padding_len - 1)
tx.vout.append(
CTxOut(0, CScript([padding, OP_RETURN])))
curr_size = len(tx.serialize())
tx.rehash()
# Pad outputs until it reaches at least min_size
def pad_raw_tx(rawtx_hex, min_size=None):
tx = CTransaction()
FromHex(tx, rawtx_hex)
pad_tx(tx, min_size)
return ToHex(tx)
| from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTransaction, FromHex, ToHex, CTxOut
from .script import OP_RETURN, CScript
import random
from binascii import hexlify, unhexlify
# Pad outputs until it reaches at least min_size
def pad_tx(tx, min_size=None):
if min_size is None:
min_size = MIN_TX_SIZE
curr_size = len(tx.serialize())
while curr_size < min_size:
# txout.value + txout.pk_script bytes + op_return
extra_bytes = 8 + 1 + 1
padding_len = max(0, min_size - curr_size - extra_bytes)
padding_len = min(padding_len, MAX_TXOUT_PUBKEY_SCRIPT)
if padding_len == 0:
tx.vout.append(CTxOut(0, CScript([OP_RETURN])))
else:
padding = random.randrange(
1 << 8 * padding_len - 1, 1 << 8 * padding_len)
tx.vout.append(
CTxOut(0, CScript([padding, OP_RETURN])))
curr_size = len(tx.serialize())
tx.rehash()
# Pad outputs until it reaches at least min_size
def pad_raw_tx(rawtx_hex, min_size=None):
tx = CTransaction()
FromHex(tx, rawtx_hex)
pad_tx(tx, min_size)
return ToHex(tx)
|
Use Date type for history on server side | module.exports = {
user: {
type: 'document',
schema: {
attributes: {
name: String
}
},
user: true
},
project: {
type: 'document',
schema: {
attributes: {
name: String,
description: String,
color: String,
project_owner: String,
scrum_master: String,
repository: String,
type: String,
extra: {}
},
hasMany: {
dependancies: { type: 'id', target: 'project' }
}
}
},
project_delivery: {
type: 'document',
schema: {
attributes: {
version: String,
status: String,
start_date: Date,
end_date: Date,
target_date: Date,
features: String
},
hasOne: {
project: { type: 'id', target: 'project' },
delivery: { type: 'id', target: 'delivery' }
}
}
},
delivery: {
type: 'document',
schema: {
attributes: {
version: String,
locked: Boolean,
description: String
}
}
},
histo: {
type: 'document',
schema: {
attributes: {
resource: String,
primaryKey: String,
action: String,
content: String,
date: Date,
username: String
}
}
},
service: {
type: 'document',
schema: {
attributes: {
name: String,
enabled: Boolean,
config: {}
}
}
}
};
| module.exports = {
user: {
type: 'document',
schema: {
attributes: {
name: String
}
},
user: true
},
project: {
type: 'document',
schema: {
attributes: {
name: String,
description: String,
color: String,
project_owner: String,
scrum_master: String,
repository: String,
type: String,
extra: {}
},
hasMany: {
dependancies: { type: 'id', target: 'project' }
}
}
},
project_delivery: {
type: 'document',
schema: {
attributes: {
version: String,
status: String,
start_date: Date,
end_date: Date,
target_date: Date,
features: String
},
hasOne: {
project: { type: 'id', target: 'project' },
delivery: { type: 'id', target: 'delivery' }
}
}
},
delivery: {
type: 'document',
schema: {
attributes: {
version: String,
locked: Boolean,
description: String
}
}
},
histo: {
type: 'document',
schema: {
attributes: {
resource: String,
primaryKey: String,
action: String,
content: String,
date: String,
username: String
}
}
},
service: {
type: 'document',
schema: {
attributes: {
name: String,
enabled: Boolean,
config: {}
}
}
}
};
|
Use class constants instead of strings | <?php
namespace SumoCoders\FrameworkMultiUserBundle\Form;
use SumoCoders\FrameworkMultiUserBundle\DataTransferObject\RequestPasswordDataTransferObject;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RequestPasswordType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'userName',
TextType::class,
[
'label' => 'sumocoders.multiuserbundle.form.user',
'required' => true,
]
)->add(
'submit',
SubmitType::class,
[
'label' => 'sumocoders.multiuserbundle.form.request_password',
]
);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'data_class' => RequestPasswordDataTransferObject::class,
]);
}
/**
* @return string
*/
public function getName()
{
return 'request_password';
}
}
| <?php
namespace SumoCoders\FrameworkMultiUserBundle\Form;
use SumoCoders\FrameworkMultiUserBundle\DataTransferObject\RequestPasswordDataTransferObject;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RequestPasswordType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'userName',
'text',
[
'label' => 'sumocoders.multiuserbundle.form.user',
'required' => true,
]
)->add(
'submit',
'submit',
[
'label' => 'sumocoders.multiuserbundle.form.request_password',
]
);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'data_class' => RequestPasswordDataTransferObject::class,
]);
}
/**
* @return string
*/
public function getName()
{
return 'request_password';
}
}
|
Fix big preventing some JS from executing | <?php if (!$_SKIP_HEADER) {?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<?php require_once(VIEW_DIR.'/_core/header_meta.php');?>
<!--[if lte IE 8]><script src="assets/css/ie/html5shiv.js"></script><![endif]-->
<?php require_once(VIEW_DIR.'/_core/header_css.php');?>
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie/v8.css" /><![endif]-->
<!--[if lte IE 8]><script src="assets/css/ie/respond.min.js"></script><![endif]-->
<script type="text/javascript" nonce="29af2i">
// this special function can only be declared here
var ValidateSubmit = {
isSubmitted: false,
submit: function() {
if (ValidateSubmit.isSubmitted) {
return false;
}
ValidateSubmit.isSubmitted = true;
$("input[type=submit]").attr("disabled", "disabled");
form.submit();
},
END: null
};
</script>
</head>
<?php }?> | <?php if (!$_SKIP_HEADER) {?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<?php require_once(VIEW_DIR.'/_core/header_meta.php');?>
<!--[if lte IE 8]><script src="assets/css/ie/html5shiv.js"></script><![endif]-->
<?php require_once(VIEW_DIR.'/_core/header_css.php');?>
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie/v8.css" /><![endif]-->
<!--[if lte IE 8]><script src="assets/css/ie/respond.min.js"></script><![endif]-->
<script type="text/javascript">
// this special function can only be declared here
var ValidateSubmit = {
isSubmitted: false,
submit: function() {
if (ValidateSubmit.isSubmitted) {
return false;
}
ValidateSubmit.isSubmitted = true;
$("input[type=submit]").attr("disabled", "disabled");
form.submit();
},
END: null
};
</script>
</head>
<?php }?> |
Remove deprecated class name props to Dropzone component | import React from "react";
import Dropzone from "react-dropzone";
import classNames from "classnames";
import "./DropHandler.css";
export default class DropHandler extends React.Component {
handleDrop = (files) => {
this.props.importSequenceFromFile(files[0]);
};
render() {
const { children, style, className, disabled } = this.props;
return (
<Dropzone
disabled={disabled}
onClick={(evt) => evt.preventDefault()}
multiple={false}
accept={[".gb", ".gbk", ".fasta", ".fa", ".gp", ".txt", ".dna"]}
onDropRejected={() => {
window.toastr.error("Error: Incorrect File Type");
}}
onDrop={this.handleDrop}
>
{({ getRootProps, isDragActive, isDragReject }) => (
<div
{...getRootProps()}
{...{
style,
className: classNames(className, {
isActive: isDragActive,
isRejected: isDragReject
})
}}
>
<DraggingMessage />
{children}
</div>
)}
</Dropzone>
);
}
}
function DraggingMessage() {
return (
<div className="dropzone-dragging-message">
Drop Fasta or Genbank files to view them in the editor. The following
extensions are accepted: .gb .gbk .fasta .fa .gp .txt
</div>
);
}
| import React from "react";
import Dropzone from "react-dropzone";
import classNames from "classnames";
import "./DropHandler.css";
export default class DropHandler extends React.Component {
handleDrop = (files) => {
this.props.importSequenceFromFile(files[0]);
};
render() {
const { children, style, className, disabled } = this.props;
return (
<Dropzone
disabled={disabled}
onClick={(evt) => evt.preventDefault()}
multiple={false}
accept={[".gb", ".gbk", ".fasta", ".fa", ".gp", ".txt", ".dna"]}
activeClassName="isActive"
rejectClassName="isRejected"
onDropRejected={() => {
window.toastr.error("Error: Incorrect File Type");
}}
onDrop={this.handleDrop}
>
{({ getRootProps, isDragActive }) => (
<div
{...getRootProps()}
{...{
style,
className: classNames(className, { isActive: isDragActive })
}}
>
<DraggingMessage />
{children}
</div>
)}
</Dropzone>
);
}
}
function DraggingMessage() {
return (
<div className="dropzone-dragging-message">
Drop Fasta or Genbank files to view them in the editor. The following
extensions are accepted: .gb .gbk .fasta .fa .gp .txt
</div>
);
}
|
Use SecureTemporaryFile for Source Interface requests | from io import BytesIO
from flask import wrappers
from secure_tempfile import SecureTemporaryFile
class RequestThatSecuresFileUploads(wrappers.Request):
def _secure_file_stream(self, total_content_length, content_type,
filename=None, content_length=None):
"""Storage class for data streamed in from requests.
If the data is relatively small (512KB), just store it in
memory. Otherwise, use the SecureTemporaryFile class to buffer
it on disk, encrypted with an ephemeral key to mitigate
forensic recovery of the plaintext.
"""
if total_content_length > 1024 * 512:
# We don't use `config.TEMP_DIR` here because that
# directory is exposed via X-Send-File and there is no
# reason for these files to be publicly accessible. See
# note in `config.py` for more info. Instead, we just use
# `/tmp`, which has the additional benefit of being
# automatically cleared on reboot.
return SecureTemporaryFile('/tmp')
return BytesIO()
def make_form_data_parser(self):
return self.form_data_parser_class(self._secure_file_stream,
self.charset,
self.encoding_errors,
self.max_form_memory_size,
self.max_content_length,
self.parameter_storage_class)
| from flask import wrappers
from tempfile import NamedTemporaryFile
from io import BytesIO
class RequestThatSecuresFileUploads(wrappers.Request):
def _secure_file_stream(self, total_content_length, content_type, filename=None,
content_length=None):
if total_content_length > 1024 * 512:
tf = NamedTemporaryFile(delete=False)
# Save the name of the temporary file on the request object so we can `shred` it later
self._temporary_file_name = tf.name
return tf
return BytesIO()
def make_form_data_parser(self):
return self.form_data_parser_class(self._secure_file_stream,
self.charset,
self.encoding_errors,
self.max_form_memory_size,
self.max_content_length,
self.parameter_storage_class)
|
Remove obsolete import of handleRequest function.
git-svn-id: fac99be8204c57f0935f741ea919b5bf0077cdf6@9490 688a9155-6ab5-4160-a077-9df41f55a9e9 | import('helma.webapp', 'webapp');
import('model');
// the main action is invoked for http://localhost:8080/
// this also shows simple skin rendering
function index_action(req, res) {
if (req.params.save) {
createBook(req, res);
}
if (req.params.remove) {
removeBook(req, res);
}
var books = model.Book.all();
res.render('skins/index.html', {
title: 'Storage Demo',
books: function(/*tag, skin, context*/) {
var buffer = [];
for (var i in books) {
var book = books[i]
buffer.push(book.getFullTitle(), getDeleteLink(book), "<br>\r\n");
}
return buffer.join(' ');
}
});
}
function createBook(req, res) {
var author = new model.Author({name: req.params.author});
var book = new model.Book({author: author, title: req.params.title});
// author is saved transitively
book.save();
res.redirect('/');
}
function removeBook(req, res) {
var book = model.Book.get(req.params.remove);
// author is removed through cascading delete
book.remove();
res.redirect('/');
}
function getDeleteLink(book) {
return '<a href="/?remove=' + book._id + '">delete</a>';
}
if (__name__ == "__main__") {
webapp.start();
}
| import('helma.webapp', 'webapp');
import('model');
var handleRequest = webapp.handleRequest;
// the main action is invoked for http://localhost:8080/
// this also shows simple skin rendering
function index_action(req, res) {
if (req.params.save) {
createBook(req, res);
}
if (req.params.remove) {
removeBook(req, res);
}
var books = model.Book.all();
res.render('skins/index.html', {
title: 'Storage Demo',
books: function(/*tag, skin, context*/) {
var buffer = [];
for (var i in books) {
var book = books[i]
buffer.push(book.getFullTitle(), getDeleteLink(book), "<br>\r\n");
}
return buffer.join(' ');
}
});
}
function createBook(req, res) {
var author = new model.Author({name: req.params.author});
var book = new model.Book({author: author, title: req.params.title});
// author is saved transitively
book.save();
res.redirect('/');
}
function removeBook(req, res) {
var book = model.Book.get(req.params.remove);
// author is removed through cascading delete
book.remove();
res.redirect('/');
}
function getDeleteLink(book) {
return '<a href="/?remove=' + book._id + '">delete</a>';
}
if (__name__ == "__main__") {
webapp.start();
}
|
Fix broken code, comment out sun.awt.X11.XLayerProtocol
git-svn-id: 67bc77c75b8364e4e9cdff0eb6560f5818674cd8@2216 ca793f91-a31e-0410-b540-2769d408b6a1 | package dr.inference.model;
import dr.xml.*;
//import sun.awt.X11.XLayerProtocol;
/**
* @author Joseph Heled
* Date: 4/09/2009
*/
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
public static String VALUES_POOL = "valuesPool";
public static String VALUES = "values";
public static String SELECTOR = "selector";
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final Variable pool = (Variable)xo.getElementFirstChild(VALUES);
final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR);
if( pool.getSize() != selector.getSize() ) {
throw new XMLParseException("variable Pool and selector must have equal length.");
}
return new ValuesPool(pool, selector);
}
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[] {
new ElementRule(VALUES, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) }),
new ElementRule(SELECTOR, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) })
};
}
public String getParserDescription() {
return "";
}
public Class getReturnType() {
return ValuesPool.class;
}
public String getParserName() {
return VALUES_POOL;
}
}
| package dr.inference.model;
import dr.xml.*;
import sun.awt.X11.XLayerProtocol;
/**
* @author Joseph Heled
* Date: 4/09/2009
*/
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
public static String VALUES_POOL = "valuesPool";
public static String VALUES = "values";
public static String SELECTOR = "selector";
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final Variable pool = (Variable)xo.getElementFirstChild(VALUES);
final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR);
if( pool.getSize() != selector.getSize() ) {
throw new XMLParseException("variable Pool and selector must have equal length.");
}
return new ValuesPool(pool, selector);
}
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[] {
new ElementRule(VALUES, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) }),
new ElementRule(SELECTOR, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) })
};
}
public String getParserDescription() {
return "";
}
public Class getReturnType() {
return ValuesPool.class;
}
public String getParserName() {
return VALUES_POOL;
}
}
|
Disable log component on test environment | <?php
return [
'request' => [
'class' => \blink\http\Request::class,
'middleware' => [],
],
'response' => [
'class' => \blink\http\Response::class,
'middleware' => [
\rethink\hrouter\restapi\middleware\ResponseFormatter::class,
],
],
'session' => [
'class' => 'blink\session\Manager',
'expires' => 3600 * 24 * 15,
'storage' => [
'class' => 'blink\session\FileStorage',
'path' => __DIR__ . '/../../runtime/sessions'
]
],
'auth' => [
'class' => 'blink\auth\Auth',
'model' => 'app\models\User',
],
'haproxy' => [
'class' => \rethink\hrouter\Haproxy::class,
],
'log' => [
'class' => 'blink\log\Logger',
'targets' => [
'file' => [
'class' => 'blink\log\StreamTarget',
'enabled' => BLINK_ENV != 'test',
'stream' => 'php://stderr',
'level' => 'info',
]
],
],
];
| <?php
return [
'request' => [
'class' => \blink\http\Request::class,
'middleware' => [],
],
'response' => [
'class' => \blink\http\Response::class,
'middleware' => [
\rethink\hrouter\restapi\middleware\ResponseFormatter::class,
],
],
'session' => [
'class' => 'blink\session\Manager',
'expires' => 3600 * 24 * 15,
'storage' => [
'class' => 'blink\session\FileStorage',
'path' => __DIR__ . '/../../runtime/sessions'
]
],
'auth' => [
'class' => 'blink\auth\Auth',
'model' => 'app\models\User',
],
'haproxy' => [
'class' => \rethink\hrouter\Haproxy::class,
],
'log' => [
'class' => 'blink\log\Logger',
'targets' => [
'file' => [
'class' => 'blink\log\StreamTarget',
'enabled' => true,
'stream' => 'php://stderr',
'level' => 'info',
]
],
],
];
|
Update 4chan plugin for 1.7.9 compatibility | <?php
class Af_4chan extends Plugin {
function about() {
return array(0.1, "Fetch full size image from 4chan /b/ feed", "Markus Wiik");
}
function init($host) {
$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
}
function hook_article_filter($article) {
$owner_uid = $article["owner_uid"];
if (preg_match('/4chan.org\/b\//', $article['link'])) {
if (strpos($article["plugin_data"], "4chan,$owner_uid:") === FALSE) {
$doc = new DOMDocument();
$doc->loadHTML($article['content']);
if ($doc) {
$xpath = new DOMXPath($doc);
$imgurl = $xpath->query('//a')->item(0)->getAttribute('href');
if (is_null($imgurl)) {
return $article;
}
$xpath->query('//img')->item(0)->setAttribute('src', $imgurl);
$article["content"] = $doc->saveHTML();
$article["plugin_data"] = "4chan,$owner_uid:" . $article["plugin_data"];
}
}
else if (isset($article["stored"]["content"])) {
$article["content"] = $article["stored"]["content"];
}
}
return $article;
}
function api_version() {
return 2;
}
}
?>
| <?php
class Af_4chan extends Plugin {
function about() {
return array(0.1, "Fetch full size image from 4chan /b/ feed", "Markus Wiik");
}
function init($host) {
$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
}
function hook_article_filter($article) {
$owner_uid = $article["owner_uid"];
if (preg_match('/4chan.org\/b\//', $article['link'])) {
if (strpos($article["plugin_data"], "4chan,$owner_uid:") === FALSE) {
$doc = new DOMDocument();
$doc->loadHTML($article['content']);
if ($doc) {
$xpath = new DOMXPath($doc);
$imgurl = $xpath->query('//a')->item(0)->getAttribute('href');
if (is_null($imgurl)) {
return $article;
}
$xpath->query('//img')->item(0)->setAttribute('src', $imgurl);
$article["content"] = $doc->saveHTML();
$article["plugin_data"] = "4chan,$owner_uid:" . $article["plugin_data"];
}
}
else if (isset($article["stored"]["content"])) {
$article["content"] = $article["stored"]["content"];
}
}
return $article;
}
}
?>
|
Change initialization method from cssParser() to init()
Change selectorFound event type to cssRuleFound | /*!
* cssParser Wef plugin
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
//requires: wef.events, console, cssParser
//exports: cssParser
/**
* The cssParser plugin
*/
(function () {
//TODO: CssParserAdapter
var cssParser = {
name:"cssParser",
version:"0.0.1",
description:"A CSS Parser. Wraps excellent JSCSSP library <http://glazman.org/JSCSSP/>",
authors:["Pablo Escalada <[email protected]>"],
licenses:["MIT"], //TODO: Licenses
init:function () {
return cssParser;
},
parse:function (text) {
var backend = new CSSParser();
var sheet = backend.parse(text);
sheet.cssRules.forEach(function (cssRule) {
//workaround. Not very glad of firing document events
var cssRuleEvent = document.createEvent("Event");
cssRuleEvent.initEvent("cssRuleFound", true, true);
cssRuleEvent.selectorText = cssRule.mSelectorText;
document.dispatchEvent(cssRuleEvent);
cssRule.declarations.forEach(function (declaration) {
var propertyEvent = document.createEvent("Event");
propertyEvent.initEvent("propertyFound", true, true);
propertyEvent.property = declaration.property;
document.dispatchEvent(propertyEvent);
});
});
}
};
wef.plugins.register("cssParser", cssParser);
})(); | /*!
* cssParser Wef plugin
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
//requires: wef.events, console, cssParser
//exports: cssParser
//events: onSelector, onProperty
/**
* The cssParser plugin
*/
(function () {
var cssParser = {
name:"cssParser",
version:"0.0.1",
description:"A CSS Parser ;-)",
authors:["Pablo Escalada <[email protected]>"],
licenses:["MIT"], //TODO: Licenses
cssParser:function () {
return cssParser;
},
parse:function (text) {
var backend = new CSSParser();
var sheet = backend.parse(text);
sheet.cssRules.forEach(function (cssRule) {
//workaround. No very glad of firing document events
var selectorEvent = document.createEvent("Event");
selectorEvent.initEvent("selectorFound", true, true);
selectorEvent.selectorText = cssRule.mSelectorText;
document.dispatchEvent(selectorEvent);
cssRule.declarations.forEach(function (declaration) {
var propertyEvent = document.createEvent("Event");
propertyEvent.initEvent("propertyFound", true, true);
propertyEvent.property = declaration.property;
document.dispatchEvent(propertyEvent);
});
});
}
};
wef.plugins.register("cssParser", cssParser);
})(); |
Clean up strings to use format and add better comments | '''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already present'.format(name)
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already absent'.format(name)
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
| '''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
|
Subsets and Splits