text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Clear Results for next submit | 'use strict';
// Declare app level module which depends on views, and components
/*angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/view1'});
}]);*/
var clientApp = angular.module('clientApp', []);
clientApp.controller('PathFinderController', ['$scope', function($scope) {
//Submit the Request to get the paths for the node text.
$scope.results = [];
$scope.paths = [];
$scope.submit = function() {
$scope.paths = [];
var enteredNode = $scope.nodeText;
var json = angular.fromJson($scope.enteredJson);
addJsonPaths(json, "");
console.log($scope.paths);
};
function addJsonPaths(theObject, path) {
var paths = [];
for (var property in theObject) {
if (theObject.hasOwnProperty(property)) {
if (theObject[property] instanceof Object) {
addJsonPaths(theObject[property], path + '/' + property);
} else {
var finalPath = path + '/' + property;
if(finalPath.indexOf($scope.nodeText) > -1) {
var nodeIndex = finalPath.indexOf($scope.nodeText);
$scope.paths.push(finalPath.substring(0, nodeIndex + $scope.nodeText.length));
}
}
}
}
}
}]);
| 'use strict';
// Declare app level module which depends on views, and components
/*angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/view1'});
}]);*/
var clientApp = angular.module('clientApp', []);
clientApp.controller('PathFinderController', ['$scope', function($scope) {
//Submit the Request to get the paths for the node text.
$scope.results = [];
$scope.paths = [];
$scope.submit = function() {
var enteredNode = $scope.nodeText;
var json = angular.fromJson($scope.enteredJson);
addJsonPaths(json, "");
console.log($scope.paths);
};
function addJsonPaths(theObject, path) {
var paths = [];
for (var property in theObject) {
if (theObject.hasOwnProperty(property)) {
if (theObject[property] instanceof Object) {
addJsonPaths(theObject[property], path + '/' + property);
} else {
var finalPath = path + '/' + property;
if(finalPath.indexOf($scope.nodeText) > -1) {
var nodeIndex = finalPath.indexOf($scope.nodeText);
$scope.paths.push(finalPath.substring(0, nodeIndex + $scope.nodeText.length));
}
}
}
}
}
}]);
|
Refactor bind_to spec to better performance | var vows = require('vows')
, assert = require('assert')
, Glue = require(__dirname + "/../lib/glue");
var suite = vows.describe('bindTo')
suite.addBatch({
"ensures": {
topic: new Glue({}),
"that the target object of glue is changed": function(topic) {
topic.target = {};
topic.bindTo({an: "object"});
assert.notDeepEqual(topic.topic, {});
assert.deepEqual(topic.target, {an: "object"});
},
"notifies listeners with the old and new target object": function(topic) {
var message = {};
topic.target = {};
topic.addListener('target', function(msg) {
message = msg;
});
topic.bindTo({ an: "object" });
assert.deepEqual(message, {
oldTarget: {}
, newTarget: { an: "object" }
});
this.target = { an: "object" }; //reset
},
"executes a callback if available": function(topic) {
var invoked = false;
topic.target = {};
topic.bindTo({an: "object"}, function() {
invoked = true;
});
assert.equal(invoked, true);
},
"when invoked, returns itself for chainability": function(topic) {
var returnedValue = topic.addListener(function(){});
assert.equal(topic, returnedValue);
}
}
});
suite.export(module);
| var vows = require('vows')
, assert = require('assert')
, Glue = require(__dirname + "/../lib/glue");
var suite = vows.describe('bindTo')
suite.addBatch({
"ensures": {
"that the target object of glue is changed": function() {
var topic = new Glue({an: "object"});
topic.bindTo({another: "object"});
assert.notDeepEqual(topic.topic, {an: "object"});
assert.deepEqual(topic.target, {another: "object"});
},
"notifies listeners with the old and new target object": function() {
var topic = new Glue({an: "object"})
, message = {};
topic.addListener('target', function(msg) {
message = msg;
});
topic.bindTo({ another: "object" });
assert.deepEqual(message, {
oldTarget: { an: "object" }
, newTarget: { another: "object" }
});
this.target = { an: "object" }; //reset
},
"executes a callback if available": function() {
var topic = new Glue({an: "object"})
, invoked = false;
topic.bindTo({}, function() {
invoked = true;
});
assert.equal(invoked, true);
},
"when invoked, returns itself for chainability": function() {
var topic = new Glue({an: "object"});
var returnedValue = topic.addListener(function(){});
assert.equal(topic, returnedValue);
}
}
});
suite.export(module);
|
Disable testcase3 with child node edgecase | package io.apiman.plugins.transformation_policy.transformer;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
@SuppressWarnings("nls")
public class JsonToXmlTransformerTest extends XMLTestCase {
static {
XMLUnit.setIgnoreWhitespace(true);
}
private JsonToXmlTransformer transformer = new JsonToXmlTransformer();
public void test_jsonToXml_1() throws Exception {
test("jsonToXml-input1.json", "jsonToXml-output1.xml");
}
public void test_jsonToXml_2() throws Exception {
test("jsonToXml-input2.json", "jsonToXml-output2.xml");
}
// public void test_jsonToXml_3() throws Exception {
// test("jsonToXml-input3.json", "jsonToXml-output3.xml");
// }
public void test_jsonToXml_4() throws Exception {
test("jsonToXml-input4.json", "jsonToXml-output4.xml");
}
private void test(String jsonFileName, String xmlFileName) throws Exception {
String json = readFile(jsonFileName);
String expectedXml = readFile(xmlFileName);
String actualXml = transformer.transform(json);
assertXMLEqual(expectedXml, actualXml);
}
private String readFile(String fileName) throws IOException {
return IOUtils.toString(getClass().getClassLoader().getResource("jsonToXml/" + fileName), "UTF-8");
}
}
| package io.apiman.plugins.transformation_policy.transformer;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
@SuppressWarnings("nls")
public class JsonToXmlTransformerTest extends XMLTestCase {
static {
XMLUnit.setIgnoreWhitespace(true);
}
private JsonToXmlTransformer transformer = new JsonToXmlTransformer();
public void test_jsonToXml_1() throws Exception {
test("jsonToXml-input1.json", "jsonToXml-output1.xml");
}
public void test_jsonToXml_2() throws Exception {
test("jsonToXml-input2.json", "jsonToXml-output2.xml");
}
public void test_jsonToXml_3() throws Exception {
test("jsonToXml-input3.json", "jsonToXml-output3.xml");
}
public void test_jsonToXml_4() throws Exception {
test("jsonToXml-input4.json", "jsonToXml-output4.xml");
}
private void test(String jsonFileName, String xmlFileName) throws Exception {
String json = readFile(jsonFileName);
String expectedXml = readFile(xmlFileName);
String actualXml = transformer.transform(json);
assertXMLEqual(expectedXml, actualXml);
}
private String readFile(String fileName) throws IOException {
return IOUtils.toString(getClass().getClassLoader().getResource("jsonToXml/" + fileName), "UTF-8");
}
}
|
Make debug log handle multiple arguments
Ex: console.log('delivery receipt', phone_number, timestamp)
// FREEBIE | /*
* vim: ts=4:sw=4:expandtab
*/
(function () {
'use strict';
var MAX_MESSAGES = 1000;
var PHONE_REGEX = /\+\d{7,12}(\d{3})/g;
var debugLog = [];
if (window.console) {
console._log = console.log;
console.log = function(){
console._log.apply(this, arguments);
if (debugLog.length > MAX_MESSAGES) {
debugLog.shift();
}
var args = Array.prototype.slice.call(arguments);
var str = args.join(' ').replace(PHONE_REGEX, "+[REDACTED]$1");
debugLog.push(str);
};
console.get = function() {
return debugLog.join('\n');
};
console.post = function(log) {
if (log === undefined) {
log = console.get();
}
return new Promise(function(resolve) {
$.post('https://api.github.com/gists', textsecure.utils.jsonThing({
"public": true,
"files": { "debugLog.txt": { "content": log } }
})).then(function(response) {
console._log('Posted debug log to ', response.html_url);
resolve(response.html_url);
}).fail(resolve);
});
};
}
})();
| /*
* vim: ts=4:sw=4:expandtab
*/
(function () {
'use strict';
var MAX_MESSAGES = 1000;
var PHONE_REGEX = /\+\d{7,12}(\d{3})/g;
var debugLog = [];
if (window.console) {
console._log = console.log;
console.log = function(thing){
console._log(thing);
if (debugLog.length > MAX_MESSAGES) {
debugLog.shift();
}
var str = ('' + thing).replace(PHONE_REGEX, "+[REDACTED]$1");
debugLog.push(str);
};
console.get = function() {
return debugLog.join('\n');
};
console.post = function(log) {
if (log === undefined) {
log = console.get();
}
return new Promise(function(resolve) {
$.post('https://api.github.com/gists', textsecure.utils.jsonThing({
"public": true,
"files": { "debugLog.txt": { "content": log } }
})).then(function(response) {
console._log('Posted debug log to ', response.html_url);
resolve(response.html_url);
}).fail(resolve);
});
};
}
})();
|
Fix missing closing bracket for redirect() method | <?php
/**
* Backend {{ moduleName }} {{ action }} action
*/
{% if action in ['index', 'add', 'edit', 'delete'] %}
class Backend{{ moduleName|capitalize }}{{ action|capitalize }} extends BackendBaseAction{{ action|capitalize }}
{% else %}
class Backend{{ moduleName|capitalize }}{{ action|capitalize }} extends BackendBaseAction
{% endif %}
{
/**
* Execute the action
*/
public function execute()
{
parent::execute();
{% if action == 'index' %}
$this->loadDataGrids();
{% elseif action in ['add', 'edit'] %}
$this->loadForm();
$this->validateForm();
{% endif %}
$this->parse();
$this->display();
}
{% if action == 'index' %}
/**
* Loads the datagrids
*/
private function loadDataGrids()
{
}
{% elseif action in ['add', 'edit'] %}
/**
* Load form
*/
public function loadForm()
{
// Create the form
$this->frm = new BackendForm('{{ action }}');
// Add fields
}
/**
* Validate form
*/
public function validateForm()
{
// Submitted?
if ($this->frm->isSubmitted()) {
// Check fields
// Correct?
if ($this->frm->isCorrect()) {
// Build item
// Save
// Redirect
$this->redirect(BackendModel::createURLForAction('index') . '&report={{ action }}ed');
}
}
}
{% endif %}
/**
* Parse method
*/
protected function parse()
{
parent::parse();
}
}
| <?php
/**
* Backend {{ moduleName }} {{ action }} action
*/
{% if action in ['index', 'add', 'edit', 'delete'] %}
class Backend{{ moduleName|capitalize }}{{ action|capitalize }} extends BackendBaseAction{{ action|capitalize }}
{% else %}
class Backend{{ moduleName|capitalize }}{{ action|capitalize }} extends BackendBaseAction
{% endif %}
{
/**
* Execute the action
*/
public function execute()
{
parent::execute();
{% if action == 'index' %}
$this->loadDataGrids();
{% elseif action in ['add', 'edit'] %}
$this->loadForm();
$this->validateForm();
{% endif %}
$this->parse();
$this->display();
}
{% if action == 'index' %}
/**
* Loads the datagrids
*/
private function loadDataGrids()
{
}
{% elseif action in ['add', 'edit'] %}
/**
* Load form
*/
public function loadForm()
{
// Create the form
$this->frm = new BackendForm('{{ action }}');
// Add fields
}
/**
* Validate form
*/
public function validateForm()
{
// Submitted?
if ($this->frm->isSubmitted()) {
// Check fields
// Correct?
if ($this->frm->isCorrect()) {
// Build item
// Save
// Redirect
$this->redirect(BackendModel::createURLForAction('index') . '&report={{ action }}ed';
}
}
}
{% endif %}
/**
* Parse method
*/
protected function parse()
{
parent::parse();
}
}
|
Add _init check for Vue.http being set | module.exports = {
_init: function () {
if ( ! this.options.Vue.http) {
return 'vue-resource.1.x.js : Vue.http must be set.';
}
},
_interceptor: function (req, res) {
var _this = this;
this.options.Vue.http.interceptors.push(function (request, next) {
if (req) { req.call(_this, request); }
next(function (response) {
if (res) { res.call(_this, response); }
});
});
},
_invalidToken: function (res) {
if (res.status === 401) {
this.logout();
}
},
_httpData: function (res) {
return res.data || {};
},
_http: function (data) {
this.options.Vue.http(data).then(data.success, data.error);
},
_getHeaders: function (res) {
var i,
data = {},
headers = res.headers.map;
for (i in headers) {
data[i] = headers[i][0];
}
return data;
},
_setHeaders: function (req, headers) {
var i;
for (i in headers) {
req.headers.set(i, headers[i]);
}
}
};
| module.exports = {
_interceptor: function (req, res) {
var _this = this;
this.options.Vue.http.interceptors.push(function (request, next) {
if (req) { req.call(_this, request); }
next(function (response) {
if (res) { res.call(_this, response); }
});
});
},
_invalidToken: function (res) {
if (res.status === 401) {
this.logout();
}
},
_httpData: function (res) {
return res.data || {};
},
_http: function (data) {
this.options.Vue.http(data).then(data.success, data.error);
},
_getHeaders: function (res) {
var i,
data = {},
headers = res.headers.map;
for (i in headers) {
data[i] = headers[i][0];
}
return data;
},
_setHeaders: function (req, headers) {
var i;
for (i in headers) {
req.headers.set(i, headers[i]);
}
}
}; |
Use normal query if no data is passed or using bind method if there is data passed | <?php
namespace DB;
include (SYSTEM_PATH . 'db/IDriver.php');
class DB
{
private $dbDriver;
public function __construct()
{
$config =& loadClass('Config', 'Core');
$cfg = $config->load('DB');
if ($cfg !== false)
{
$this->driver($cfg['driver']);
$this->connect($cfg['host'], $cfg['user'], $cfg['password']);
$this->database($cfg['database'], false);
}
}
public function driver($name)
{
$loader =& loadClass('Loader', 'Core');
$this->dbDriver = $loader->dbDriver($name);
}
public function connect($host, $user, $password='')
{
$this->dbDriver->connect($host, $user, $password);
}
public function database($name, $create=false)
{
$this->dbDriver->database($name);
}
public function query($sql, $data=[])
{
if (count($data) > 0)
{
return $this->dbDriver->bind($sql, $data);
}
else
{
return $this->dbDriver->query($sql);
}
}
}
?>
| <?php
namespace DB;
include (SYSTEM_PATH . 'db/IDriver.php');
class DB
{
private $dbDriver;
public function __construct()
{
$config =& loadClass('Config', 'Core');
$cfg = $config->load('DB');
if ($cfg !== false)
{
$this->driver($cfg['driver']);
$this->connect($cfg['host'], $cfg['user'], $cfg['password']);
$this->database($cfg['database'], false);
}
}
public function driver($name)
{
$loader =& loadClass('Loader', 'Core');
$this->dbDriver = $loader->dbDriver($name);
}
public function connect($host, $user, $password='')
{
$this->dbDriver->connect($host, $user, $password);
}
public function database($name, $create=false)
{
$this->dbDriver->database($name);
}
public function query($sql, $data=[])
{
}
}
?>
|
Remove logging and parameter from dismiss function
- The page routes have been updated to reflect the user model change for
moving posts to all connections rather than for each connection; as
such, /dismiss/all will remove all existing posts and the connection
parameter is no longer necessary
- Remove unneeded logging | function dismiss(id, el) {
$.post('/dismiss/' + id, function(data) {
var post = $(el).closest('div.row');
$.when(post.fadeOut()).then(function() {
post.remove().delay(1000);
if (id === 'all') window.location.reload();
});
});
}
function refresh() {
$('#refresh').attr('onclick', 'return false;');
$('#refresh').css('color', '#ffff00');
$.post('/refresh', function(data) {
Materialize.toast(data.message, 4000, '', function() {
if (data.refresh)
{
window.location.reload();
}
});
}).fail(function(data) {
Materialize.toast(data.responseJSON.message, 4000);
}).always(function(data) {
$('#refresh').attr('onclick', 'refresh(); return false;');
$('#refresh').css('color', '#fff');
});
}
$(document).ready(function() {
update = function() {
var times = $('.card.facebook p.timestamp').toArray();
times.forEach(function(time) {
$(time).hide().html(moment(new Date($(time).attr('data-timestamp')).toISOString()).fromNow()).fadeIn(1000);
});
};
setInterval(update, 600000);
}); | function dismiss(id, connection, el) {
$.post('/dismiss/' + connection + '/' + id, function(data) {
var post = $(el).closest('div.row');
$.when(post.fadeOut()).then(function() {
post.remove().delay(1000);
if (id === 'all') window.location.reload();
});
});
}
function refresh() {
$('#refresh').attr('onclick', 'return false;');
$('#refresh').css('color', '#ffff00');
$.post('/refresh', function(data) {
console.log(data);
Materialize.toast(data.message, 4000, '', function() {
if (data.refresh)
{
window.location.reload();
}
});
}).fail(function(data) {
Materialize.toast(data.responseJSON.message, 4000);
}).always(function(data) {
$('#refresh').attr('onclick', 'refresh(); return false;');
$('#refresh').css('color', '#fff');
});
}
$(document).ready(function() {
update = function() {
var times = $('.card.facebook p.timestamp').toArray();
times.forEach(function(time) {
$(time).hide().html(moment(new Date($(time).attr('data-timestamp')).toISOString()).fromNow()).fadeIn(1000);
});
};
setInterval(update, 600000);
}); |
Fix bad invocation of old, dead code | export default function createNodeIterator(root, whatToShow, filter = null) {
let document = root.ownerDocument;
var iter = document.createNodeIterator(root, whatToShow, filter, false);
return typeof(iter.referenceNode) === 'undefined' ? shim(iter, root) : iter;
}
function shim(iter, root) {
var _referenceNode = root;
var _pointerBeforeReferenceNode = true;
return Object.create(NodeIterator.prototype, {
root: {
get: () => iter.root
},
whatToShow: {
get: () => iter.whatToShow
},
filter: {
get: () => iter.filter
},
referenceNode: {
get: () => _referenceNode
},
pointerBeforeReferenceNode: {
get: () => _pointerBeforeReferenceNode
},
detach: {
get: () => iter.detach
},
nextNode: {
value: () => {
let result = iter.nextNode();
_pointerBeforeReferenceNode = false;
if (result === null) {
return null;
} else {
_referenceNode = result;
return _referenceNode;
}
}
},
previousNode: {
value: () => {
let result = iter.previousNode();
_pointerBeforeReferenceNode = true;
if (result === null) {
return null;
} else {
_referenceNode = result;
return _referenceNode;
}
}
}
});
}
| export default function createNodeIterator(root, whatToShow, filter = null) {
var iter = _create.call(window.document, root, whatToShow, filter, false);
return typeof(iter.referenceNode) === 'undefined' ? shim(iter, root) : iter;
}
function shim(iter, root) {
var _referenceNode = root;
var _pointerBeforeReferenceNode = true;
return Object.create(NodeIterator.prototype, {
root: {
get: () => iter.root
},
whatToShow: {
get: () => iter.whatToShow
},
filter: {
get: () => iter.filter
},
referenceNode: {
get: () => _referenceNode
},
pointerBeforeReferenceNode: {
get: () => _pointerBeforeReferenceNode
},
detach: {
get: () => iter.detach
},
nextNode: {
value: () => {
let result = iter.nextNode();
_pointerBeforeReferenceNode = false;
if (result === null) {
return null;
} else {
_referenceNode = result;
return _referenceNode;
}
}
},
previousNode: {
value: () => {
let result = iter.previousNode();
_pointerBeforeReferenceNode = true;
if (result === null) {
return null;
} else {
_referenceNode = result;
return _referenceNode;
}
}
}
});
}
|
Throw error if no frame is found. | define(['exports', 'module',
'events',
'class'],
function(exports, module, Emitter, clazz) {
function send(data, origin, win) {
if (!win) {
var frame;
for (var i = 0, len = window.frames.length; i < len; i++) {
frame = window.frames[i];
if (frame.location == origin) {
win = frame;
origin = frame.location.protocol + '//' + frame.location.host;
break;
}
}
}
if (!win) throw new Error('Unable to post message to "' + origin + '". No frame found.');
win.postMessage(data, origin);
}
function createListener(messageListener) {
var listener = new Listener();
if (messageListener) listener.on('message', messageListener);
return listener;
}
function Listener() {
Emitter.call(this);
}
clazz.inherits(Listener, Emitter);
Listener.prototype.listen = function() {
if (this._fn) return;
var self = this;
this._fn = function(e) {
self.emit('message', e.data, e.origin, e.source);
}
window.addEventListener('message', this._fn);
}
Listener.prototype.close = function() {
if (!this._fn) return;
window.removeEventListener('message', this._fn);
delete this._fn;
}
exports = module.exports = send;
exports.send = send;
exports.createListener = createListener;
exports.Listener = Listener;
});
| define(['exports', 'module',
'events',
'class'],
function(exports, module, Emitter, clazz) {
function send(data, origin, win) {
if (!win) {
var frame;
for (var i = 0, len = window.frames.length; i < len; i++) {
frame = window.frames[i];
if (frame.location == origin) {
win = frame;
origin = frame.location.protocol + '//' + frame.location.host;
break;
}
}
}
// TODO: If window is undefined, emit an error.
// TODO: If postMessage is not available, emit an error.
win.postMessage(data, origin);
}
function createListener(messageListener) {
var listener = new Listener();
if (messageListener) listener.on('message', messageListener);
return listener;
}
function Listener() {
Emitter.call(this);
}
clazz.inherits(Listener, Emitter);
Listener.prototype.listen = function() {
if (this._fn) return;
var self = this;
this._fn = function(e) {
self.emit('message', e.data, e.origin, e.source);
}
window.addEventListener('message', this._fn);
}
Listener.prototype.close = function() {
if (!this._fn) return;
window.removeEventListener('message', this._fn);
delete this._fn;
}
exports = module.exports = send;
exports.send = send;
exports.createListener = createListener;
exports.Listener = Listener;
});
|
Use the bin in node_modules | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
babel: {
options: {
sourceMap: false
},
dist: {
files: [{
expand: true,
cwd: 'src',
src: ['**/*.js'],
dest: "lib",
ext: ".js"
}]
}
},
jshint: {
options: {
jshintrc: '.jshintrc',
},
all: ['Gruntfile.js', 'src/**/*.js']
},
watch: {
scripts: {
files: ['src/*.js'],
tasks: ['default'],
options: {
spawn: false
},
},
},
shell: {
test: {
command: 'node_modules/.bin/jasmine',
options:{
stdout: true,
stderr: true,
failOnError: true
}
}
}
})
grunt.loadNpmTasks('grunt-babel')
grunt.loadNpmTasks('grunt-shell')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.registerTask('clean', function() { require('rimraf').sync('lib') })
grunt.registerTask('lint', ['jshint'])
grunt.registerTask('default', ['lint', 'babel'])
grunt.registerTask('test', ['default', 'shell:test'])
}
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
babel: {
options: {
sourceMap: false
},
dist: {
files: [{
expand: true,
cwd: 'src',
src: ['**/*.js'],
dest: "lib",
ext: ".js"
}]
}
},
jshint: {
options: {
jshintrc: '.jshintrc',
},
all: ['Gruntfile.js', 'src/**/*.js']
},
watch: {
scripts: {
files: ['src/*.js'],
tasks: ['default'],
options: {
spawn: false
},
},
},
shell: {
test: {
command: 'jasmine',
options:{
stdout: true,
stderr: true,
failOnError: true
}
}
}
})
grunt.loadNpmTasks('grunt-babel')
grunt.loadNpmTasks('grunt-shell')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.registerTask('clean', function() { require('rimraf').sync('lib') })
grunt.registerTask('lint', ['jshint'])
grunt.registerTask('default', ['lint', 'babel'])
grunt.registerTask('test', ['default', 'shell:test'])
}
|
Add title text to sync button | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { translate as $t, formatDate } from '../../helpers';
import { actions, get } from '../../store';
const Export = connect(
(state, props) => {
let access = get.accessById(state, props.account.bankAccess);
let canBeSynced = !get.bankByUuid(state, access.bank).deprecated && access.enabled;
return {
canBeSynced
};
},
(dispatch, ownProps) => {
return {
handleSync: () => {
actions.runOperationsSync(dispatch, ownProps.account.bankAccess);
}
};
}
)(props => {
const lastSyncText = (
<span>
{$t('client.operations.last_sync')}
{formatDate.fromNow(props.account.lastChecked).toLowerCase()}
</span>
);
if (props.canBeSynced) {
return (
<button
type="button"
onClick={props.handleSync}
title={$t('client.operations.sync_now')}
aria-label={$t('client.operations.sync_now')}
className="btn transparent">
{lastSyncText}
<span className="fa fa-refresh" />
</button>
);
}
return lastSyncText;
});
Export.propTypes = {
// Account to be resynced
account: PropTypes.object.isRequired
};
export default Export;
| import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { translate as $t, formatDate } from '../../helpers';
import { actions, get } from '../../store';
const Export = connect(
(state, props) => {
let access = get.accessById(state, props.account.bankAccess);
let canBeSynced = !get.bankByUuid(state, access.bank).deprecated && access.enabled;
return {
canBeSynced
};
},
(dispatch, ownProps) => {
return {
handleSync: () => {
actions.runOperationsSync(dispatch, ownProps.account.bankAccess);
}
};
}
)(props => {
const lastSyncText = (
<span>
{$t('client.operations.last_sync')}
{formatDate.fromNow(props.account.lastChecked).toLowerCase()}
</span>
);
if (props.canBeSynced) {
return (
<button type="button" onClick={props.handleSync} className="btn transparent">
{lastSyncText}
<span className="fa fa-refresh" />
</button>
);
}
return lastSyncText;
});
Export.propTypes = {
// Account to be resynced
account: PropTypes.object.isRequired
};
export default Export;
|
Fix install error on python 2.7 | #!/usr/bin/env python3
# encoding: UTF-8
"""Build tar.gz for pygubu
Needed packages to run (using Debian/Ubuntu package names):
python3-tk
"""
import os
from io import open
import pygubu
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = pygubu.__version__
_dirname_ = os.path.dirname(__file__)
readme_path = os.path.join(_dirname_, 'README.md')
setup(
name='pygubu',
version=VERSION,
license='MIT',
author='Alejandro Autalán',
author_email='[email protected]',
description='A tkinter GUI builder.',
long_description=open(readme_path, 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='https://github.com/alejandroautalan/pygubu',
packages=['pygubu', 'pygubu.builder',
'pygubu.builder.widgets', 'pygubu.widgets'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Topic :: Software Development :: User Interfaces",
],
)
| #!/usr/bin/env python3
# encoding: UTF-8
"""Build tar.gz for pygubu
Needed packages to run (using Debian/Ubuntu package names):
python3-tk
"""
import os
import pygubu
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = pygubu.__version__
_dirname_ = os.path.dirname(__file__)
readme_path = os.path.join(_dirname_, 'README.md')
setup(
name='pygubu',
version=VERSION,
license='MIT',
author='Alejandro Autalán',
author_email='[email protected]',
description='A tkinter GUI builder.',
long_description=open(readme_path, 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='https://github.com/alejandroautalan/pygubu',
packages=['pygubu', 'pygubu.builder',
'pygubu.builder.widgets', 'pygubu.widgets'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Topic :: Software Development :: User Interfaces",
],
)
|
Expand test to cover variables. | import json
from webtest import TestApp as Client
from wsgi_graphql import wsgi_graphql
from graphql.core.type import (
GraphQLObjectType,
GraphQLField,
GraphQLArgument,
GraphQLNonNull,
GraphQLSchema,
GraphQLString,
)
def raises(*_):
raise Exception("Raises!")
TestSchema = GraphQLSchema(
query=GraphQLObjectType(
'Root',
fields=lambda: {
'test': GraphQLField(
GraphQLString,
args={
'who': GraphQLArgument(
type=GraphQLString
)
},
resolver=lambda root, args, *_: 'Hello ' + (args['who'] or 'World')
),
'thrower': GraphQLField(
GraphQLNonNull(GraphQLString),
resolver=raises
)
}
)
)
def test_allows_GET_with_query_param():
wsgi = wsgi_graphql(TestSchema)
c = Client(wsgi)
response = c.get('/', {'query': '{test}'})
assert response.json == {
'data': {
'test': 'Hello World'
}
}
def test_allows_GET_with_variable_values():
wsgi = wsgi_graphql(TestSchema)
c = Client(wsgi)
response = c.get('/', {
'query': 'query helloWho($who: String){ test(who: $who) }',
'variables': json.dumps({'who': 'Dolly'})
})
assert response.json == {
'data': {
'test': 'Hello Dolly'
}
}
| from webtest import TestApp as Client
from wsgi_graphql import wsgi_graphql
from graphql.core.type import (
GraphQLEnumType,
GraphQLEnumValue,
GraphQLInterfaceType,
GraphQLObjectType,
GraphQLField,
GraphQLArgument,
GraphQLList,
GraphQLNonNull,
GraphQLSchema,
GraphQLString,
)
def raises(*_):
raise Exception("Raises!")
TestSchema = GraphQLSchema(
query=GraphQLObjectType(
'Root',
fields=lambda: {
'test': GraphQLField(
GraphQLString,
args={
'who': GraphQLArgument(
type=GraphQLString
)
},
resolver=lambda root, args, *_: 'Hello ' + (args['who'] or 'World')
),
'thrower': GraphQLField(
GraphQLNonNull(GraphQLString),
resolver=raises
)
}
)
)
def test_basic():
wsgi = wsgi_graphql(TestSchema)
c = Client(wsgi)
response = c.get('/?query={test}')
assert response.json == {
'data': {
'test': 'Hello World'
}
}
|
Remove default 'group' class name | import React from 'react';
import classNames from 'classnames';
import ListItem from './ListItem';
export default class List extends React.Component {
getListItems(list, childIndex) {
var that = this;
childIndex = childIndex || 0;
var items = list.map(function(item, parentIndex) {
var key = parentIndex + '.' + childIndex;
if (item.items) {
return (
<ListItem key={key} tag={item.tag} attributes={item.attributes}>
{that.getListItems(item.items, childIndex++)}
</ListItem>
);
} else {
return (
<ListItem key={key} tag={item.tag} attributes={item.attributes}>
{item.value}
</ListItem>
);
}
});
return items;
}
render() {
var defaultClasses = [
'list'
];
var classes = classNames(
defaultClasses.concat(
this.props.className.split(' '),
this.props.attributes.className.split(' ')
)
);
var Tag = this.props.tag;
return (
<Tag {...this.props} className={classes}>
{this.getListItems(this.props.items)}
</Tag>
);
}
}
List.defaultProps = {
attributes: {
className: ''
},
className: '',
tag: 'ul'
};
List.propTypes = {
attributes: React.PropTypes.object,
className: React.PropTypes.string,
items: React.PropTypes.array.isRequired,
tag: React.PropTypes.string
};
| import React from 'react';
import classNames from 'classnames';
import ListItem from './ListItem';
export default class List extends React.Component {
getListItems(list, childIndex) {
var that = this;
childIndex = childIndex || 0;
var items = list.map(function(item, parentIndex) {
var key = parentIndex + '.' + childIndex;
if (item.items) {
return (
<ListItem key={key} tag={item.tag} className="group" attributes={item.attributes}>
{that.getListItems(item.items, childIndex++)}
</ListItem>
);
} else {
return (
<ListItem key={key} tag={item.tag} attributes={item.attributes}>
{item.value}
</ListItem>
);
}
});
return items;
}
render() {
var defaultClasses = [
'list'
];
var classes = classNames(
defaultClasses.concat(
this.props.className.split(' '),
this.props.attributes.className.split(' ')
)
);
var Tag = this.props.tag;
return (
<Tag {...this.props} className={classes}>
{this.getListItems(this.props.items)}
</Tag>
);
}
}
List.defaultProps = {
attributes: {
className: ''
},
className: '',
tag: 'ul'
};
List.propTypes = {
attributes: React.PropTypes.object,
className: React.PropTypes.string,
items: React.PropTypes.array.isRequired,
tag: React.PropTypes.string
};
|
Use `str_replace` instead of `preg_replace` | <?php
/*
* This file is part of Psy Shell
*
* (c) 2013 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Formatter;
use Psy\Formatter\CodeFormatter;
class CodeFormatterTest extends \PHPUnit_Framework_TestCase
{
public function testFormat()
{
$expected = <<<EOS
private function ignoreThisMethod(\$arg)
{
echo "whot!";
}
EOS;
$this->assertEquals(
str_replace("\n", PHP_EOL, $expected),
CodeFormatter::format(new \ReflectionMethod($this, 'ignoreThisMethod'))
);
}
/**
* @dataProvider filenames
* @expectedException Psy\Exception\RuntimeException
*/
public function testCodeFormatterThrowsException($filename)
{
$reflector = $this->getMockBuilder('ReflectionClass')
->disableOriginalConstructor()
->getMock();
$reflector
->expects($this->once())
->method('getFileName')
->will($this->returnValue($filename));
CodeFormatter::format($reflector);
}
public function filenames()
{
return array(array(null), array('not a file'));
}
private function ignoreThisMethod($arg)
{
echo "whot!";
}
}
| <?php
/*
* This file is part of Psy Shell
*
* (c) 2013 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Formatter;
use Psy\Formatter\CodeFormatter;
class CodeFormatterTest extends \PHPUnit_Framework_TestCase
{
public function testFormat()
{
$expected = <<<EOS
private function ignoreThisMethod(\$arg)
{
echo "whot!";
}
EOS;
$this->assertEquals(
preg_replace("/\n/", PHP_EOL, $expected),
CodeFormatter::format(new \ReflectionMethod($this, 'ignoreThisMethod'))
);
}
/**
* @dataProvider filenames
* @expectedException Psy\Exception\RuntimeException
*/
public function testCodeFormatterThrowsException($filename)
{
$reflector = $this->getMockBuilder('ReflectionClass')
->disableOriginalConstructor()
->getMock();
$reflector
->expects($this->once())
->method('getFileName')
->will($this->returnValue($filename));
CodeFormatter::format($reflector);
}
public function filenames()
{
return array(array(null), array('not a file'));
}
private function ignoreThisMethod($arg)
{
echo "whot!";
}
}
|
Fix search reducer when no results are found | import values from 'lodash/values';
import queryString from 'query-string';
import { UPDATE_PATH } from 'redux-simple-router';
import Immutable from 'seamless-immutable';
import types from 'constants/ActionTypes';
import { pickSupportedFilters } from 'utils/SearchUtils';
const initialState = Immutable({
filters: {
date: '',
people: '',
purpose: '',
search: '',
},
results: [],
searchDone: false,
typeaheadSuggestions: [],
});
function searchReducer(state = initialState, action) {
switch (action.type) {
case types.API.SEARCH_RESULTS_GET_SUCCESS: {
const results = Object.keys(action.payload.entities.resources || {});
return state.merge({
results,
searchDone: true,
});
}
case types.API.TYPEAHEAD_SUGGESTIONS_GET_SUCCESS: {
const typeaheadSuggestions = values(action.payload.resource);
return state.merge({ typeaheadSuggestions });
}
case types.UI.CHANGE_SEARCH_FILTERS: {
const filters = pickSupportedFilters(action.payload);
return state.merge({ filters }, { deep: true });
}
case types.UI.CLEAR_SEARCH_RESULTS: {
return initialState;
}
case UPDATE_PATH: {
const query = queryString.extract(action.path);
const urlSearchFilters = pickSupportedFilters(queryString.parse(query));
return state.merge({ filters: urlSearchFilters }, { deep: true });
}
default: {
return state;
}
}
}
export default searchReducer;
| import values from 'lodash/values';
import queryString from 'query-string';
import { UPDATE_PATH } from 'redux-simple-router';
import Immutable from 'seamless-immutable';
import types from 'constants/ActionTypes';
import { pickSupportedFilters } from 'utils/SearchUtils';
const initialState = Immutable({
filters: {
date: '',
people: '',
purpose: '',
search: '',
},
results: [],
searchDone: false,
typeaheadSuggestions: [],
});
function searchReducer(state = initialState, action) {
switch (action.type) {
case types.API.SEARCH_RESULTS_GET_SUCCESS: {
const results = Object.keys(action.payload.entities.resources);
return state.merge({
results,
searchDone: true,
});
}
case types.API.TYPEAHEAD_SUGGESTIONS_GET_SUCCESS: {
const typeaheadSuggestions = values(action.payload.resource);
return state.merge({ typeaheadSuggestions });
}
case types.UI.CHANGE_SEARCH_FILTERS: {
const filters = pickSupportedFilters(action.payload);
return state.merge({ filters }, { deep: true });
}
case types.UI.CLEAR_SEARCH_RESULTS: {
return initialState;
}
case UPDATE_PATH: {
const query = queryString.extract(action.path);
const urlSearchFilters = pickSupportedFilters(queryString.parse(query));
return state.merge({ filters: urlSearchFilters }, { deep: true });
}
default: {
return state;
}
}
}
export default searchReducer;
|
Change the URL where the repository is hosted. | """Package setup configuration.
To Install package, run:
>>> python setup.py install
To install package with a symlink, so that changes to the source files will be immediately available, run:
>>> python setup.py develop
"""
from __future__ import print_function
from setuptools import setup, find_packages
__version__ = '0.1'
setup(
name='mutabletuple.mutabletuple',
version=__version__,
description='Mutable named tuple that behave like dict with fixed keys.',
long_description=open('README.rst').read() + '\n' + open('CHANGES.rst').read(),
url='https://github.com/nicolasbessou/mutabletuple',
include_package_data=True,
author='Nicolas BESSOU',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
install_requires=['namedlist'],
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
],
test_suite='mutabletuple.tests',
)
| """Package setup configuration.
To Install package, run:
>>> python setup.py install
To install package with a symlink, so that changes to the source files will be immediately available, run:
>>> python setup.py develop
"""
from __future__ import print_function
from setuptools import setup, find_packages
__version__ = '0.1'
setup(
name='mutabletuple.mutabletuple',
version=__version__,
description='Mutable named tuple that behave like dict with fixed keys.',
long_description=open('README.rst').read() + '\n' + open('CHANGES.rst').read(),
url='https://bitbucket.org/nicolas_bessou/mutabletuple',
include_package_data=True,
author='Nicolas BESSOU',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
install_requires=['namedlist'],
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
],
test_suite='mutabletuple.tests',
)
|
Apply PHP CS Fixer changes | <?php
declare(strict_types=1);
namespace Telegram\Bot\Tests\Unit\Objects;
use PHPUnit\Framework\TestCase;
use Telegram\Bot\Objects\Chat;
use Telegram\Bot\Objects\Update;
/** @covers \Telegram\Bot\Objects\Update */
class UpdateTest extends TestCase
{
/** @test */
public function it_parses_chat_relation_for_bot_kicked_event(): void
{
$update = new Update([
// there is no "message" key at this even type!
'my_chat_member' => [
'chat' => [
'id' => 42,
'first_name' => 'Firstname',
'last_name' => 'Lastname',
'type' => 'private',
],
],
'old_chat_member' => [
'user' => [], // doesn't matter in this case
'status' => 'member',
],
'new_chat_member' => [
'user' => [], // doesn't matter in this case
'status' => 'kicked',
'until_date' => 0,
],
]);
$this->assertInstanceOf(Chat::class, $update->getChat());
}
}
| <?php declare(strict_types=1);
namespace Telegram\Bot\Tests\Unit\Objects;
use PHPUnit\Framework\TestCase;
use Telegram\Bot\Objects\Chat;
use Telegram\Bot\Objects\Update;
/** @covers \Telegram\Bot\Objects\Update */
class UpdateTest extends TestCase
{
/** @test */
public function it_parses_chat_relation_for_bot_kicked_event(): void
{
$update = new Update([
// there is no "message" key at this even type!
'my_chat_member' => [
'chat' => [
'id' => 42,
'first_name' => 'Firstname',
'last_name' => 'Lastname',
'type' => 'private',
],
],
'old_chat_member' => [
'user' => [], // doesn't matter in this case
'status' => 'member',
],
'new_chat_member' => [
'user' => [], // doesn't matter in this case
'status' => 'kicked',
'until_date' => 0,
],
]);
$this->assertInstanceOf(Chat::class, $update->getChat());
}
}
|
Revert "Refactoring of various aspects of this directive" | angular.module('eee-c.angularBindPolymer', []).
directive('bindPolymer', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var attrMap = {};
for (var prop in attrs.$attr) {
if (prop != 'bindPolymer') {
var _attr = attrs.$attr[prop];
var _match = element.attr(_attr).match(/\{\{\s*([\.\w]+)\s*\}\}/);
if (_match) {
attrMap[_attr] = _match[1];
}
}
}
// When Polymer sees a change to the bound variable,
// $apply / $digest the changes here in Angular
new MutationObserver(function() { scope.$apply(); }).
observe(element[0], {attributes: true});
for (var _attr in attrMap) { watch (_attr); }
function watch(attr) {
scope.$watch(
function() { return element.attr(attr); },
function(value) {
var tokens = attrMap[attr].split(/\./);
var parent = scope;
for (var i=0; i<tokens.length-1; i++) {
if (typeof(parent[tokens[i]]) == 'undefined') {
parent[tokens[i]] = {};
}
parent = parent[tokens[i]];
}
parent[tokens[tokens.length - 1]] = value;
}
);
}
}
};
});
| angular.module('eee-c.angularBindPolymer', [])
.directive('bindPolymer', function() {
'use strict';
return {
restrict: 'A',
link: function($scope, $element, attributes) {
var attrs = {};
angular.forEach(attributes.$attr, function(keyName, key) {
var val;
if (key !== 'bindPolymer') {
attrs[keyName] = keyName;
val = $element.attr(keyName).match(/\{\{\s*([\.\w]+)\s*\}\}/);
if (angular.isDefined(val)) {
attrs[keyName] = val[1].split(/\./);
}
}
});
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var stored = attrs[mutation.attributeName];
var eAttr = $element.attr(mutation.attributeName);
if (angular.isDefined(stored)) {
var tmp = $scope;
var lastTmp;
angular.forEach(stored, function(key) {
if (angular.isDefined(tmp[key])) {
lastTmp = tmp;
tmp = tmp[key];
}
});
if (tmp !== $scope && tmp !== eAttr) {
lastTmp[stored[stored.length - 1]] = eAttr;
}
}
});
$scope.$apply();
});
observer.observe($element[0], {
attributes: true
});
$scope.$on('$destroy', function() {
observer.disconnect();
});
}
};
});
|
Add Tutorial to backend : get article by translated slug | <?php
namespace FBN\GuideBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* TutorialRepository.
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TutorialRepository extends EntityRepository
{
public function getArticlesImages($first = 0, $limit = Article::NUM_ITEMS)
{
$qb = $this->createQueryBuilder('t')
->leftJoin('t.image', 'i')
->addSelect('i')
->orderBy('t.datePublication', 'DESC')
->where('t.publication = :publication')
->setParameter('publication', 1);
$query = $qb->getQuery();
$query->setFirstResult($first)
->setMaxResults($limit);
return $query->getResult();
}
public function getTutorial($slug)
{
$qb = $this->createQueryBuilder('t')
->leftJoin('t.image', 'i')
->addSelect('i')
->leftJoin('t.tutorialSection', 'tr')
->addSelect('tr')
->leftJoin('t.tutorialChapter', 'tc')
->addSelect('tc')
->leftJoin('tc.tutorialChapterParas', 'tcp')
->addSelect('tcp')
->where('t.slug = :slug')
->setParameter('slug', $slug);
$query = $qb->getQuery();
$query->setHint(
\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
);
return $query->getOneOrNullResult();
}
}
| <?php
namespace FBN\GuideBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* TutorialRepository.
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TutorialRepository extends EntityRepository
{
public function getArticlesImages($first = 0, $limit = Article::NUM_ITEMS)
{
$qb = $this->createQueryBuilder('t')
->leftJoin('t.image', 'i')
->addSelect('i')
->orderBy('t.datePublication', 'DESC')
->where('t.publication = :publication')
->setParameter('publication', 1);
$query = $qb->getQuery();
$query->setFirstResult($first)
->setMaxResults($limit);
return $query->getResult();
}
public function getTutorial($slug)
{
$qb = $this->createQueryBuilder('t')
->leftJoin('t.image', 'i')
->addSelect('i')
->leftJoin('t.tutorialSection', 'tr')
->addSelect('tr')
->leftJoin('t.tutorialChapter', 'tc')
->addSelect('tc')
->leftJoin('tc.tutorialChapterParas', 'tcp')
->addSelect('tcp')
->where('t.slug = :slug')
->setParameter('slug', $slug);
return $qb->getQuery()
->getOneOrNullResult();
}
}
|
Fix Json error for Python3 compatibility | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pprint
import json
class View(object):
def service_list(self, service_list):
print('service LIST:')
for service in service_list:
print(service)
print('')
def service_information(self, action, name, *argv):
print('%s service %s' % (action, name) )
def service_not_found(self, name):
print('The service "%s" does not exist' % name)
def command_not_found(self, name):
print('The command "%s" does not exist' % name)
print('Available commands are: build, create or start')
def display_stream(self, line):
jsonstream = json.loads(line.decode())
stream = jsonstream.get('stream')
error = jsonstream.get('error')
if not error == None:
print(error)
if not stream == None:
print(stream)
def usage():
print('Commands are: build, run, rm, ip, ')
def stopping(self, tag):
print('Stoping container %s ...' % (tag))
def removing(self, tag):
print('Removing container %s ...' % (tag))
def notlaunched(self, tag):
print('Services %s not launched' % (tag))
def ip(self, tag, ipaddr):
print('Container %s on IP: %s' % (tag, ipaddr)) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pprint
import json
class View(object):
def service_list(self, service_list):
print('service LIST:')
for service in service_list:
print(service)
print('')
def service_information(self, action, name, *argv):
print('%s service %s with arguments:' % (action, name) )
for arg in argv:
print(arg)
print('')
def service_not_found(self, name):
print('The service "%s" does not exist' % name)
def command_not_found(self, name):
print('The command "%s" does not exist' % name)
print('Available commands are: build, create or start')
def display_stream(self, line):
jsonstream = json.loads(line)
stream = jsonstream.get('stream')
error = jsonstream.get('error')
if not error==None:
print(error)
if not stream==None:
print(stream)
def usage():
print('Commands are: build, run, rm, ip, ')
def stopping(self, tag):
print('Stoping container %s ...' % (tag))
def removing(self, tag):
print('Removing container %s ...' % (tag))
def notlaunched(self, tag):
print('Services %s not launched' % (tag))
def ip(self, tag, ipaddr):
print('Container %s on IP: %s' % (tag, ipaddr)) |
Set metadata as UI title only when someone changes it | 'use strict';
/*global Wodo*/
angular.module('manticoreApp')
.controller('TitleEditorCtrl', function ($scope, $timeout) {
function handleTitleChanged(changes) {
var title = changes.setProperties['dc:title'];
if (title !== undefined && title !== $scope.title) {
$timeout(function () {
$scope.title = title;
});
}
}
$scope.changeTitle = function () {
if ($scope.title !== $scope.editor.getMetadata('dc:title')) {
$scope.editor.setMetadata({
'dc:title': $scope.title
});
}
};
$scope.handleEnterKey = function ($event) {
if ($event.keyCode === 13) {
$event.target.blur();
}
};
$scope.$watch('joined', function (online) {
if (online === undefined) { return; }
if (online) {
$scope.editor.addEventListener(Wodo.EVENT_METADATACHANGED, handleTitleChanged);
} else {
$scope.editor.removeEventListener(Wodo.EVENT_METADATACHANGED, handleTitleChanged);
}
});
function init() {
$scope.title = $scope.document.title;
}
init();
});
| 'use strict';
/*global Wodo*/
angular.module('manticoreApp')
.controller('TitleEditorCtrl', function ($scope, $timeout) {
function handleTitleChanged(changes) {
var title = changes.setProperties['dc:title'];
if (title !== undefined && title !== $scope.title) {
$timeout(function () {
$scope.title = title;
});
}
}
$scope.changeTitle = function () {
if ($scope.title !== $scope.editor.getMetadata('dc:title')) {
$scope.editor.setMetadata({
'dc:title': $scope.title
});
}
};
$scope.handleEnterKey = function ($event) {
if ($event.keyCode === 13) {
$event.target.blur();
}
};
$scope.$watch('joined', function (online) {
if (online === undefined) { return; }
if (online) {
$scope.editor.addEventListener(Wodo.EVENT_METADATACHANGED, handleTitleChanged);
$scope.title = $scope.editor.getMetadata('dc:title');
} else {
$scope.editor.removeEventListener(Wodo.EVENT_METADATACHANGED, handleTitleChanged);
}
});
function init() {
$scope.title = $scope.document.title;
}
init();
});
|
Use extension method for Observer.checked | from six import add_metaclass
from rx import Observer
from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check_access()
try:
self._observer.on_next(value)
finally:
self._state = 0
def on_error(self, err):
self.check_access()
try:
self._observer.on_error(err)
finally:
self._state = 2
def on_completed(self):
self.check_access()
try:
self._observer.on_completed()
finally:
self._state = 2
def check_access(self):
if self._state == 1:
raise ReEntracyException()
if self._state == 2:
raise CompletedException()
if self._state == 0:
self._state = 1
@add_metaclass(ExtensionMethod)
class ObserverChecked(Observer):
"""Uses a meta class to extend Observable with the methods in this class"""
def checked(self):
"""Checks access to the observer for grammar violations. This includes
checking for multiple OnError or OnCompleted calls, as well as
reentrancy in any of the observer methods. If a violation is detected,
an Error is thrown from the offending observer method call.
Returns an observer that checks callbacks invocations against the
observer grammar and, if the checks pass, forwards those to the
specified observer."""
return CheckedObserver(self)
| from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check_access()
try:
self._observer.on_next(value)
finally:
self._state = 0
def on_error(self, err):
self.check_access()
try:
self._observer.on_error(err)
finally:
self._state = 2
def on_completed(self):
self.check_access()
try:
self._observer.on_completed()
finally:
self._state = 2
def check_access(self):
if self._state == 1:
raise ReEntracyException()
if self._state == 2:
raise CompletedException()
if self._state == 0:
self._state = 1
def checked(self):
"""Checks access to the observer for grammar violations. This includes
checking for multiple OnError or OnCompleted calls, as well as
reentrancy in any of the observer methods. If a violation is detected,
an Error is thrown from the offending observer method call.
Returns an observer that checks callbacks invocations against the
observer grammar and, if the checks pass, forwards those to the
specified observer.
"""
return CheckedObserver(self)
CheckedObserver.checked = checked
Observer.checked = checked
|
Clean up exception error message | export default function(tokens) {
const items = tokens.body;
function walk(token) {
// If no type exists, continue
if (!token || !token.valueType || token.valueType === "let") {
return;
}
const type = token.valueType;
const values = token.value;
for (let i = 0; i < values.length; i++) {
const elem = values[i];
if (
elem.type === "Identifier" &&
elem.type === "Operator" &&
elem.type === "Variable" &&
elem.type === "CallExpression"
) {
// We currently won't check types for these expressions
continue;
}
const hint = values.map(e => {
if (e.value) {
return e.value;
}
return e.token;
}).join(" ");
switch (elem.type) {
case "NumberLiteral":
if (type !== "int") {
throw new TypeError(
`Integer value is being assigned to a non-int variable near (${hint}).`
);
}
break;
case "DecimalLiteral":
if (type !== "decimal") {
throw new TypeError(
`Decimal value is being assigned to a non-decimal variable near (${hint}).`
);
}
break;
case "StringLiteral":
if (type !== "string") {
throw new TypeError(
`String value is being assigned to a non-string variable near (${hint}).`
);
}
break;
}
}
}
items.map(walk);
}
| export default function(tokens) {
const items = tokens.body;
function walk(token) {
// If no type exists, continue
if (!token || !token.valueType || token.valueType === "let") {
return;
}
const type = token.valueType;
const values = token.value;
for (let i = 0; i < values.length; i++) {
const elem = values[i];
if (
elem.type === "Identifier" &&
elem.type === "Operator" &&
elem.type === "Variable" &&
elem.type === "CallExpression"
) {
// We currently won't check types for these expressions
continue;
}
const hint = values.map(e => e.token).join(" ");
switch (elem.type) {
case "NumberLiteral":
if (type !== "int") {
throw new TypeError(
`Integer value is being assigned to a non-int variable near (${hint}).`
);
}
break;
case "DecimalLiteral":
if (type !== "decimal") {
throw new TypeError(
`Decimal value is being assigned to a non-int variable near (${hint}).`
);
}
break;
case "StringLiteral":
if (type !== "string") {
throw new TypeError(
`String value is being assigned to a non-int variable near (${hint}).`
);
}
break;
}
}
}
items.map(walk);
}
|
Update tests for nbgrader feedback | from .base import TestBase
from nbgrader.api import Gradebook
import os
import shutil
class TestNbgraderFeedback(TestBase):
def _setup_db(self):
dbpath = self._init_db()
gb = Gradebook(dbpath)
gb.add_assignment("ps1")
gb.add_student("foo")
return dbpath
def test_help(self):
"""Does the help display without error?"""
with self._temp_cwd():
self._run_command("nbgrader feedback --help-all")
def test_single_file(self):
"""Can feedback be generated for an unchanged assignment?"""
with self._temp_cwd(["files/submitted-unchanged.ipynb"]):
dbpath = self._setup_db()
os.makedirs('source/ps1')
shutil.copy('submitted-unchanged.ipynb', 'source/ps1/p1.ipynb')
self._run_command('nbgrader assign ps1 --db="{}" '.format(dbpath))
os.makedirs('submitted/foo/ps1')
shutil.move('submitted-unchanged.ipynb', 'submitted/foo/ps1/p1.ipynb')
self._run_command('nbgrader autograde ps1 --db="{}" '.format(dbpath))
self._run_command('nbgrader feedback ps1 --db="{}" '.format(dbpath))
assert os.path.exists('feedback/foo/ps1/p1.html')
| from .base import TestBase
from nbgrader.api import Gradebook
import os
class TestNbgraderFeedback(TestBase):
def _setup_db(self):
dbpath = self._init_db()
gb = Gradebook(dbpath)
gb.add_assignment("Problem Set 1")
gb.add_student("foo")
gb.add_student("bar")
return dbpath
def test_help(self):
"""Does the help display without error?"""
with self._temp_cwd():
self._run_command("nbgrader feedback --help-all")
def test_single_file(self):
"""Can feedback be generated for an unchanged assignment?"""
with self._temp_cwd(["files/submitted-unchanged.ipynb"]):
dbpath = self._setup_db()
self._run_command(
'nbgrader autograde submitted-unchanged.ipynb '
'--db="{}" '
'--assignment="Problem Set 1" '
'--AssignmentExporter.notebook_id=teacher '
'--student=foo'.format(dbpath))
self._run_command(
'nbgrader feedback submitted-unchanged.nbconvert.ipynb '
'--db="{}" '
'--assignment="Problem Set 1" '
'--AssignmentExporter.notebook_id=teacher '
'--student=foo'.format(dbpath))
assert os.path.exists('submitted-unchanged.nbconvert.nbconvert.html')
|
Increase sleep time to a more conservative level | package annis.gui;
import com.github.mvysny.kaributesting.v8.MockVaadin;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import org.slf4j.LoggerFactory;
public class TestHelper {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(TestHelper.class);
private TestHelper() {
// Static helper class
}
public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator,
Callable<String> message)
throws Exception {
long startTime = System.currentTimeMillis();
long maxExecutionTime = ((long) seconds) * 1000l;
boolean condition = false;
int attempt = 0;
while (!condition && (System.currentTimeMillis() - startTime) < maxExecutionTime) {
MockVaadin.INSTANCE.clientRoundtrip();
log.debug("Evaluating await condition (attempt {})", attempt++);
condition = conditionEvaluator.call();
if (!condition) {
// Wait until invoking the condition again
log.debug("Waiting 250 ms before checking condition again");
Thread.sleep(250); // NOSONAR The code should similar to the Karibu async example
}
}
MockVaadin.INSTANCE.clientRoundtrip();
if (!condition) {
throw new TimeoutException(message.call());
}
}
public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator)
throws Exception {
awaitCondition(seconds, conditionEvaluator,
() -> "Condition did not become true in " + seconds + " seconds.");
}
}
| package annis.gui;
import com.github.mvysny.kaributesting.v8.MockVaadin;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import org.slf4j.LoggerFactory;
public class TestHelper {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(TestHelper.class);
private TestHelper() {
// Static helper class
}
public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator,
Callable<String> message)
throws Exception {
long startTime = System.currentTimeMillis();
long maxExecutionTime = ((long) seconds) * 1000l;
boolean condition = false;
int attempt = 0;
while (!condition && (System.currentTimeMillis() - startTime) < maxExecutionTime) {
MockVaadin.INSTANCE.clientRoundtrip();
log.debug("Evaluating await condition (attempt {})", attempt++);
condition = conditionEvaluator.call();
if (!condition) {
// Wait until invoking the condition again
log.debug("Waiting 10 ms before checking condition again");
Thread.sleep(10); // NOSONAR The code should similar to the Karibu async example
}
}
MockVaadin.INSTANCE.clientRoundtrip();
if (!condition) {
throw new TimeoutException(message.call());
}
}
public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator)
throws Exception {
awaitCondition(seconds, conditionEvaluator,
() -> "Condition did not become true in " + seconds + " seconds.");
}
}
|
Change order of client registration | <?php
namespace Laravel\Scout;
use Illuminate\Support\ServiceProvider;
use Laravel\Scout\Console\FlushCommand;
use Laravel\Scout\Console\ImportCommand;
use MeiliSearch\Client as MeiliSearch;
class ScoutServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/scout.php', 'scout');
if (class_exists(MeiliSearch::class)) {
$this->app->singleton(MeiliSearch::class, function () {
return new MeiliSearch(config('meilisearch.host'), config('meilisearch.key'));
});
}
$this->app->singleton(EngineManager::class, function ($app) {
return new EngineManager($app);
});
if ($this->app->runningInConsole()) {
$this->commands([
ImportCommand::class,
FlushCommand::class,
]);
$this->publishes([
__DIR__.'/../config/scout.php' => $this->app['path.config'].DIRECTORY_SEPARATOR.'scout.php',
]);
}
}
}
| <?php
namespace Laravel\Scout;
use Illuminate\Support\ServiceProvider;
use Laravel\Scout\Console\FlushCommand;
use Laravel\Scout\Console\ImportCommand;
use MeiliSearch\Client as MeiliSearch;
class ScoutServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/scout.php', 'scout');
$this->app->singleton(EngineManager::class, function ($app) {
return new EngineManager($app);
});
if ($this->app->runningInConsole()) {
$this->commands([
ImportCommand::class,
FlushCommand::class,
]);
$this->publishes([
__DIR__.'/../config/scout.php' => $this->app['path.config'].DIRECTORY_SEPARATOR.'scout.php',
]);
}
if (class_exists(MeiliSearch::class)) {
$this->app->singleton(MeiliSearch::class, function () {
return new MeiliSearch(config('meilisearch.host'), config('meilisearch.key'));
});
}
}
}
|
Use dynamically updated cents value if available (total may change as shipping methods are changed, etc) | <?php defined('C5_EXECUTE') or die(_("Access Denied."));?>
<script src="https://checkout.stripe.com/checkout.js"></script>
<input type="hidden" value="" name="stripeToken" id="stripeToken" />
<script>
$(document).ready(function() {
var handler = StripeCheckout.configure({
key: '<?= $publicAPIKey; ?>',
locale: 'auto',
token: function (token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
$('#stripeToken').val(token.id);
$('#store-checkout-form-group-payment').submit();
}
});
$('.store-btn-complete-order').on('click', function (e) {
// Open Checkout with further options
var currentpmid = $('input[name="payment-method"]:checked:first').data('payment-method-id');
if (currentpmid == <?= $pmID; ?>) {
handler.open({
currency: "<?= strtolower($currency);?>",
amount: $('.store-total-amount').data('total-cents') ? $('.store-total-amount').data('total-cents') : '<?= ($amount); ?>',
email: $('#store-email').val() ? $('#store-email').val() : '<?= ($email); ?>'
});
e.preventDefault();
}
});
// Close Checkout on page navigation
$(window).on('popstate', function () {
handler.close();
});
});
</script> | <?php defined('C5_EXECUTE') or die(_("Access Denied."));?>
<script src="https://checkout.stripe.com/checkout.js"></script>
<input type="hidden" value="" name="stripeToken" id="stripeToken" />
<script>
$(document).ready(function() {
var handler = StripeCheckout.configure({
key: '<?= $publicAPIKey; ?>',
locale: 'auto',
token: function (token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
$('#stripeToken').val(token.id);
$('#store-checkout-form-group-payment').submit();
}
});
$('.store-btn-complete-order').on('click', function (e) {
// Open Checkout with further options
var currentpmid = $('input[name="payment-method"]:checked:first').data('payment-method-id');
if (currentpmid == <?= $pmID; ?>) {
handler.open({
currency: "<?= strtolower($currency);?>",
amount: <?= $amount; ?>,
email: $('#store-email').val() ? $('#store-email').val() : '<?= ($email); ?>'
});
e.preventDefault();
}
});
// Close Checkout on page navigation
$(window).on('popstate', function () {
handler.close();
});
});
</script> |
PUT services rather than POSTing them | #!/usr/bin/env python
import sys
import json
import os
import requests
import multiprocessing
def list_files(directory):
for root, subdirs, files in os.walk(directory):
print("ROOT: {}".format(root))
for file in files:
yield os.path.abspath(os.path.join(root, file))
for subdir in subdirs:
for subfile in list_files(subdir):
yield subfile
if __name__ == "__main__":
_, base_url, access_token, listing_dir = sys.argv
endpoint = "{}/services".format(base_url)
print("Base URL: {}".format(base_url))
print("Access token: {}".format(access_token))
print("Listing dir: {}".format(listing_dir))
def put_file(file_path):
with open(file_path) as f:
data = json.load(f)
data = {'services': data}
url = '{}/{}'.format(endpoint, data['services']['id'])
response = requests.put(
url,
data=json.dumps(data),
headers={
"content-type": "application/json",
"authorization": "Bearer {}".format(access_token),
})
return response
pool = multiprocessing.Pool(10)
for result in pool.imap(put_file, list_files(listing_dir)):
print(result)
| #!/usr/bin/env python
import sys
import os
import requests
import multiprocessing
def list_files(directory):
for root, subdirs, files in os.walk(directory):
print("ROOT: {}".format(root))
for file in files:
yield os.path.abspath(os.path.join(root, file))
for subdir in subdirs:
for subfile in list_files(subdir):
yield subfile
if __name__ == "__main__":
_, base_url, access_token, listing_dir = sys.argv
endpoint = "{}/services".format(base_url)
print("Base URL: {}".format(base_url))
print("Access token: {}".format(access_token))
print("Listing dir: {}".format(listing_dir))
def post_file(file_path):
with open(file_path) as f:
response = requests.post(
endpoint,
data='{"services":%s}' % f.read(),
headers={
"content-type": "application/json",
"authorization": "Bearer {}".format(access_token),
})
return response
pool = multiprocessing.Pool(10)
for result in pool.imap(post_file, list_files(listing_dir)):
print(result)
|
Switch back to DROP IF EXISTS | package me.xdrop.passlock.datasource.sqlite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLitePrepare {
private final static Logger LOG = LoggerFactory.getLogger(SQLitePrepare.class);
/**
* Creates the SQLite passwords table
*/
public static void createPassTable(Connection sqLiteConnection) {
String sql =
"CREATE TABLE IF NOT EXISTS passwords (id integer PRIMARY KEY ,\n" +
"ref TEXT UNIQUE NOT NULL, description TEXT, payload TEXT NOT NULL, salt TEXT NOT NULL,\n" +
"algo TEXT, iv TEXT NOT NULL, date_created INTEGER, last_updated INTEGER)";
performSingleTransaction(sqLiteConnection, sql);
}
/**
* Resets (deletes and recreates) the passwords table
*/
public static void resetTable(Connection sqLiteConnection) {
String sql = "DROP TABLE IF EXISTS passwords";
performSingleTransaction(sqLiteConnection, sql);
createPassTable(sqLiteConnection);
}
private static void performSingleTransaction(Connection sqLiteConnection, String sql) {
PreparedStatement statement = null;
try {
statement = sqLiteConnection.prepareStatement(sql);
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
LOG.debug("SQL exception occurred", e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
LOG.debug("Failed to close statement", e);
}
}
}
}
}
| package me.xdrop.passlock.datasource.sqlite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLitePrepare {
private final static Logger LOG = LoggerFactory.getLogger(SQLitePrepare.class);
/**
* Creates the SQLite passwords table
*/
public static void createPassTable(Connection sqLiteConnection) {
String sql =
"CREATE TABLE IF NOT EXISTS passwords (id integer PRIMARY KEY ,\n" +
"ref TEXT UNIQUE NOT NULL, description TEXT, payload TEXT NOT NULL, salt TEXT NOT NULL,\n" +
"algo TEXT, iv TEXT NOT NULL, date_created INTEGER, last_updated INTEGER)";
performSingleTransaction(sqLiteConnection, sql);
}
/**
* Resets (deletes and recreates) the passwords table
*/
public static void resetTable(Connection sqLiteConnection) {
String sql = "DROP TABLE passwords";
performSingleTransaction(sqLiteConnection, sql);
createPassTable(sqLiteConnection);
}
private static void performSingleTransaction(Connection sqLiteConnection, String sql) {
PreparedStatement statement = null;
try {
statement = sqLiteConnection.prepareStatement(sql);
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
LOG.debug("SQL exception occurred", e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
LOG.debug("Failed to close statement", e);
}
}
}
}
}
|
Enable min_priority again - seems to be working? | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
mn = state.get_move_number()
if mn == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
if depth > 4:
min_priority = 4
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
for pos in p_i:
# create an AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
def terminal_test(self, state):
return state.terminal()
| #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
if state.get_move_number() == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
for pos in p_i:
# create a AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
def terminal_test(self, state):
return state.terminal()
|
Add better __repr__s for commands errors. | class CommandsError(Exception):
pass
class CheckFailureError(Exception):
def __init__(self, ctx, check):
self.ctx = ctx
self.check = check
def __repr__(self):
if isinstance(self.check, list):
return "The checks for `{.name}` failed.".format(self.ctx)
return "The check `{.__name__}` for `{.name}` failed.".format(self.check, self.ctx)
__str__ = __repr__
class MissingArgumentError(Exception):
def __init__(self, ctx, arg):
self.ctx = ctx
self.arg = arg
def __repr__(self):
return "Missing required argument `{}` in `{.name}`.".format(self.arg, self.ctx)
__str__ = __repr__
class CommandInvokeError(Exception):
def __init__(self, ctx):
self.ctx = ctx
def __repr__(self):
return "Command {.name} failed to invoke with error `{}`.".format(self.ctx, self.__cause__)
__str__ = __repr__
class ConversionFailedError(Exception):
def __init__(self, ctx, arg: str, to_type: type):
self.ctx = ctx
self.arg = arg
self.to_type = to_type
def __repr__(self):
return "Cannot convert `{}` to type `{.__name__}`.".format(self.arg, self.to_type)
__str__ = __repr__
| class CommandsError(Exception):
pass
class CheckFailureError(Exception):
def __init__(self, ctx, check):
self.ctx = ctx
self.check = check
def __repr__(self):
if isinstance(self.check, list):
return "The checks for {.name} failed.".format(self.ctx)
return "The check {.__name__} for {.name} failed.".format(self.check, self.ctx)
__str__ = __repr__
class MissingArgumentError(Exception):
def __init__(self, ctx, arg):
self.ctx = ctx
self.arg = arg
def __repr__(self):
return "Missing required argument {} in {.name}.".format(self.arg, self.ctx)
__str__ = __repr__
class CommandInvokeError(Exception):
def __init__(self, ctx):
self.ctx = ctx
def __repr__(self):
return "Command {.name} failed to invoke with error {}".format(self.ctx, self.__cause__)
__str__ = __repr__
class ConversionFailedError(Exception):
def __init__(self, ctx, arg: str, to_type: type):
self.ctx = ctx
self.arg = arg
self.to_type = to_type
def __repr__(self):
return "Cannot convert {} to type {.__name__}".format(self.arg, self.to_type)
__str__ = __repr__
|
Fix MessageStack for model events | <?php
namespace SleepingOwl\Admin\Widgets\Messages;
use AdminTemplate;
use SleepingOwl\Admin\Widgets\Widget;
abstract class Messages extends Widget
{
/**
* @var string
*/
protected static $sessionName;
/**
* @var string
*/
protected $messageView;
/**
* Get content as a string of HTML.
*
* @return string
*/
public function toHtml()
{
return AdminTemplate::view($this->messageView, [
'messages' => $this->getMessage(),
])->render();
}
/**
* @return string|array
*/
public function template()
{
return AdminTemplate::getViewPath('_layout.inner');
}
/**
* @return string
*/
public function block()
{
return 'content.top';
}
/**
* @return string
*/
public function getMessageView()
{
return $this->messageView;
}
/**
* @param string $messageView
*/
public function setMessageView($messageView)
{
$this->messageView = $messageView;
}
/**
* @return mixed
*/
protected function getMessage()
{
return session(static::$sessionName);
}
/**
* @param string $text
* @return mixed
*/
public static function addMessage($text)
{
return session()->flash(static::$sessionName, $text);
}
}
| <?php
namespace SleepingOwl\Admin\Widgets\Messages;
use AdminTemplate;
use SleepingOwl\Admin\Widgets\Widget;
abstract class Messages extends Widget
{
/**
* @var string
*/
protected static $sessionName;
/**
* @var string
*/
protected $messageView;
/**
* Get content as a string of HTML.
*
* @return string
*/
public function toHtml()
{
return AdminTemplate::view($this->messageView, [
'messages' => $this->getMessage(),
])->render();
}
/**
* @return string|array
*/
public function template()
{
return AdminTemplate::getViewPath('_layout.inner');
}
/**
* @return string
*/
public function block()
{
return 'content.top';
}
/**
* @return string
*/
public function getMessageView()
{
return $this->messageView;
}
/**
* @param string $messageView
*/
public function setMessageView($messageView)
{
$this->messageView = $messageView;
}
/**
* @return mixed
*/
protected function getMessage()
{
return session(static::$sessionName);
}
/**
* @param string $text
* @return mixed
*/
public static function addMessage($text)
{
session()->flash(static::$sessionName, $text);
}
}
|
Allow target attribute on menu links | <section class="sidebar">
<ul class="sidebar-menu">
<el-menu default-active="1"
:default-openeds="['1']"
theme="dark">
@foreach ($menu as $menuItem)
<el-menu-item index="0">
<a href="{{ URL::route($menuItem['route']) }}" target="{{ $menuItem['target'] ?? null }}">
<i class="{{ $menuItem['icon'] }}" style="margin-right: .4em"></i>
<span slot="title">
{{ $menuItem['title'] }}
</span>
</a>
</el-menu-item>
@endforeach
<el-submenu index="1">
<template slot="title">
<i class="fa fa-th" style="margin-right: .4em"></i> Models
</template>
@foreach ($models as $key => $model)
<router-link :to="{name: 'index', params: {model: '{{ $model['slug'] }}'}}">
<el-menu-item index="1-{{ $key }}">{{ $model['title'] }}</el-menu-item>
</router-link>
@endforeach
</el-submenu>
</el-menu>
</ul>
</section>
<!-- /.sidebar --> | <section class="sidebar">
<ul class="sidebar-menu">
<el-menu default-active="1"
:default-openeds="['1']"
theme="dark">
@foreach ($menu as $menuItem)
<el-menu-item index="0">
<a href="{{ URL::route($menuItem['route']) }}">
<i class="{{ $menuItem['icon'] }}" style="margin-right: .4em"></i>
<span slot="title">
{{ $menuItem['title'] }}
</span>
</a>
</el-menu-item>
@endforeach
<el-submenu index="1">
<template slot="title">
<i class="fa fa-th" style="margin-right: .4em"></i> Models
</template>
@foreach ($models as $key => $model)
<router-link :to="{name: 'index', params: {model: '{{ $model['slug'] }}'}}">
<el-menu-item index="1-{{ $key }}">{{ $model['title'] }}</el-menu-item>
</router-link>
@endforeach
</el-submenu>
</el-menu>
</ul>
</section>
<!-- /.sidebar --> |
Remove ugly bold formatting in messages | package fr.aumgn.diamondrush.views;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.ChatColor;
public class MessagesView implements Iterable<String> {
private List<String> messages;
private StringBuilder current;
public MessagesView() {
this.messages = new ArrayList<String>();
this.current = new StringBuilder();
}
public void append(Object obj) {
current.append(obj);
}
public void nl() {
messages.add(current.toString());
current = new StringBuilder();
}
public void head(Object obj) {
append(ChatColor.UNDERLINE);
append(obj);
}
public void headLn(Object obj) {
head(obj.toString());
nl();
}
public void entry(Object name, Object value) {
append(ChatColor.BLUE);
append(name);
append(" : ");
append(ChatColor.YELLOW);
append(value);
}
public void entryLn(Object name, Object value) {
entry(name, value);
nl();
}
public void merge(StatisticsView statisticsView) {
for (String message : statisticsView) {
messages.add(message);
}
}
@Override
public Iterator<String> iterator() {
return messages.iterator();
}
}
| package fr.aumgn.diamondrush.views;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.ChatColor;
public class MessagesView implements Iterable<String> {
private List<String> messages;
private StringBuilder current;
public MessagesView() {
this.messages = new ArrayList<String>();
this.current = new StringBuilder();
}
public void append(Object obj) {
current.append(obj);
}
public void nl() {
messages.add(current.toString());
current = new StringBuilder();
}
public void head(Object obj) {
append(ChatColor.BOLD);
append(obj);
}
public void headLn(Object obj) {
head(obj.toString());
nl();
}
public void entry(Object name, Object value) {
append(ChatColor.BLUE);
append(name);
append(" : ");
append(ChatColor.YELLOW);
append(value);
}
public void entryLn(Object name, Object value) {
entry(name, value);
nl();
}
public void merge(StatisticsView statisticsView) {
for (String message : statisticsView) {
messages.add(message);
}
}
@Override
public Iterator<String> iterator() {
return messages.iterator();
}
}
|
Make Yeoman's greeting more cromulent. | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.generators.Base.extend({
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the most cromulent ' + chalk.red('Flask REST API') +
' generator!'
));
var prompts = [{
type: 'confirm',
name: 'someOption',
message: 'Would you like to enable this option?',
default: true
}];
this.prompt(prompts, function (props) {
this.props = props;
// To access props later use this.props.someOption;
done();
}.bind(this));
},
writing: {
app: function () {
this.fs.copy(
this.templatePath('_package.json'),
this.destinationPath('package.json')
);
this.fs.copy(
this.templatePath('_bower.json'),
this.destinationPath('bower.json')
);
},
projectfiles: function () {
this.fs.copy(
this.templatePath('editorconfig'),
this.destinationPath('.editorconfig')
);
this.fs.copy(
this.templatePath('jshintrc'),
this.destinationPath('.jshintrc')
);
}
},
install: function () {
this.installDependencies();
}
});
| 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.generators.Base.extend({
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the amazing ' + chalk.red('FlaskApi') + ' generator!'
));
var prompts = [{
type: 'confirm',
name: 'someOption',
message: 'Would you like to enable this option?',
default: true
}];
this.prompt(prompts, function (props) {
this.props = props;
// To access props later use this.props.someOption;
done();
}.bind(this));
},
writing: {
app: function () {
this.fs.copy(
this.templatePath('_package.json'),
this.destinationPath('package.json')
);
this.fs.copy(
this.templatePath('_bower.json'),
this.destinationPath('bower.json')
);
},
projectfiles: function () {
this.fs.copy(
this.templatePath('editorconfig'),
this.destinationPath('.editorconfig')
);
this.fs.copy(
this.templatePath('jshintrc'),
this.destinationPath('.jshintrc')
);
}
},
install: function () {
this.installDependencies();
}
});
|
Modify help text on page header component to not use bootstrap js | define(['react', 'components/common/glyphicon'], function(React, Glyphicon) {
var PageHeader = React.createClass({
getInitialState: function() {
return {showHelpText: false};
},
render: function() {
var help_button = [];
var help_text = [];
if (this.props.helpText) {
help_button = React.DOM.button({
type: 'button',
id: 'help-text-toggle-button',
className: 'btn btn-default',
onClick: this.showHelpText},
Glyphicon({name: 'question-sign'}));
help_text = React.DOM.div({
id: 'help-text',
style: {display: this.state.showHelpText ? 'block' : 'none'}},
React.DOM.div({className: 'well'}, this.props.helpText()));
}
return React.DOM.div({className: 'main-page-header'},
React.DOM.h1({}, this.props.title),
help_button,
help_text);
},
showHelpText: function() {
this.setState({showHelpText: !this.state.showHelpText});
}
});
return PageHeader;
});
| define(['react', 'components/common/glyphicon'], function(React, Glyphicon) {
var PageHeader = React.createClass({
render: function() {
var help_button = [];
var help_text = [];
if (this.props.helpText) {
help_button = React.DOM.button({
type: 'button',
id: 'help-text-toggle-button',
className: 'btn btn-default',
'data-toggle': 'collapse',
'data-target': '#help-text'},
Glyphicon({name: 'question-sign'}));
help_text = React.DOM.div({
id: 'help-text',
className: 'collapse'},
React.DOM.div({className: 'well'}, this.props.helpText()));
}
return React.DOM.div({className: 'main-page-header'},
React.DOM.h1({}, this.props.title),
help_button,
help_text);
}
});
return PageHeader;
});
|
posts: Add ability to filter posts by site | from django.contrib import admin
from reversion import VersionAdmin
from base.admin import PrettyFilterMixin, RestrictedCompetitionAdminMixin
from base.util import admin_commentable, editonly_fieldsets
from .models import Post
# Reversion-enabled Admin for problems
@admin_commentable
@editonly_fieldsets
class PostAdmin(RestrictedCompetitionAdminMixin,
VersionAdmin):
list_display = (
'title',
'published',
'get_sites',
'added_by',
'added_at',
)
list_filter = (
'published',
'sites',
'added_at',
'added_by'
)
search_fields = (
'text',
'title'
)
readonly_fields = (
'added_by',
'modified_by',
'added_at',
'modified_at'
)
prepopulated_fields = {"slug": ("title",)}
fieldsets = (
(None, {
'fields': ('title', 'slug', 'text', 'sites', 'published', 'gallery')
}),
)
editonly_fieldsets = (
('Details', {
'classes': ('grp-collapse', 'grp-closed'),
'fields': ('added_by', 'modified_by', 'added_at', 'modified_at')
}),
)
class Media:
js = [
'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
'grappelli/tinymce_setup/tinymce_setup.js',
]
# Register to the admin site
admin.site.register(Post, PostAdmin)
| from django.contrib import admin
from reversion import VersionAdmin
from base.admin import PrettyFilterMixin, RestrictedCompetitionAdminMixin
from base.util import admin_commentable, editonly_fieldsets
from .models import Post
# Reversion-enabled Admin for problems
@admin_commentable
@editonly_fieldsets
class PostAdmin(RestrictedCompetitionAdminMixin,
VersionAdmin):
list_display = (
'title',
'published',
'get_sites',
'added_by',
'added_at',
)
list_filter = (
'published',
'added_at',
'added_by'
)
search_fields = (
'text',
'title'
)
readonly_fields = (
'added_by',
'modified_by',
'added_at',
'modified_at'
)
prepopulated_fields = {"slug": ("title",)}
fieldsets = (
(None, {
'fields': ('title', 'slug', 'text', 'sites', 'published', 'gallery')
}),
)
editonly_fieldsets = (
('Details', {
'classes': ('grp-collapse', 'grp-closed'),
'fields': ('added_by', 'modified_by', 'added_at', 'modified_at')
}),
)
class Media:
js = [
'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
'grappelli/tinymce_setup/tinymce_setup.js',
]
# Register to the admin site
admin.site.register(Post, PostAdmin)
|
Add self to list of filtered users for editors
Closes #4412 | import AuthenticatedRoute from 'ghost/routes/authenticated';
import PaginationRouteMixin from 'ghost/mixins/pagination-route';
import styleBody from 'ghost/mixins/style-body';
var paginationSettings,
UsersIndexRoute;
paginationSettings = {
page: 1,
limit: 20,
status: 'active'
};
UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, {
classNames: ['settings-view-users'],
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
model: function () {
var self = this;
return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () {
return self.store.find('user', 'me').then(function (currentUser) {
if (currentUser.get('isEditor')) {
// Editors only see authors in the list
paginationSettings.role = 'Author';
}
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
return user.get('isAuthor') || user === currentUser;
}
return true;
});
});
});
},
actions: {
reload: function () {
this.refresh();
}
}
});
export default UsersIndexRoute;
| import AuthenticatedRoute from 'ghost/routes/authenticated';
import PaginationRouteMixin from 'ghost/mixins/pagination-route';
import styleBody from 'ghost/mixins/style-body';
var paginationSettings,
UsersIndexRoute;
paginationSettings = {
page: 1,
limit: 20,
status: 'active'
};
UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, {
classNames: ['settings-view-users'],
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
model: function () {
var self = this;
return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () {
return self.store.find('user', 'me').then(function (currentUser) {
if (currentUser.get('isEditor')) {
// Editors only see authors in the list
paginationSettings.role = 'Author';
}
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
return user.get('isAuthor');
}
return true;
});
});
});
},
actions: {
reload: function () {
this.refresh();
}
}
});
export default UsersIndexRoute;
|
Fix Config loading in DownloadCsv | <?php
namespace NemC\IP2LocLite\Commands;
use Illuminate\Support\Facades\Config,
Illuminate\Console\Command,
NemC\IP2LocLite\Services\IP2LocLiteService,
NemC\IP2LocLite\Exceptions\NotLoggedInResponseException,
NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException;
class DownloadCsvCommand extends Command
{
protected $name = 'ip2loclite:download-csv';
protected $description = 'Login to IP2Location user panel and download required csv';
protected $ip2LocLite;
public function __construct(IP2LocLiteService $IP2LocLiteService)
{
parent::__construct();
$this->ip2LocLite = $IP2LocLiteService;
}
public function fire()
{
$database = Config::get('ip2loc-lite.database');
try {
$this->ip2LocLite->isSupportedDatabase($database);
} catch (UnsupportedDatabaseCommandException $e) {
$this->error('Free IP2Location database "' . $database . '"" is not supported by IP2LocLite at this point');
return false;
}
try {
$this->ip2LocLite->login();
} catch (NotLoggedInResponseException $e) {
$this->error('Could not log you in with user authentication details provided');
return false;
}
$this->ip2LocLite->downloadCsv($database);
$this->info('Latest version of IP2Location database ' . $database . ' has been downloaded');
}
} | <?php
namespace NemC\IP2LocLite\Commands;
use Illuminate\Console\Config,
Illuminate\Console\Command,
NemC\IP2LocLite\Services\IP2LocLiteService,
NemC\IP2LocLite\Exceptions\NotLoggedInResponseException,
NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException;
class DownloadCsvCommand extends Command
{
protected $name = 'ip2loclite:download-csv';
protected $description = 'Login to IP2Location user panel and download required csv';
protected $ip2LocLite;
public function __construct(IP2LocLiteService $IP2LocLiteService)
{
parent::__construct();
$this->ip2LocLite = $IP2LocLiteService;
}
public function fire()
{
$database = Config::get('ip2loc-lite.database');
try {
$this->ip2LocLite->isSupportedDatabase($database);
} catch (UnsupportedDatabaseCommandException $e) {
$this->error('Free IP2Location database "' . $database . '"" is not supported by IP2LocLite at this point');
return false;
}
try {
$this->ip2LocLite->login();
} catch (NotLoggedInResponseException $e) {
$this->error('Could not log you in with user authentication details provided');
return false;
}
$this->ip2LocLite->downloadCsv($database);
$this->info('Latest version of IP2Location database ' . $database . ' has been downloaded');
}
} |
Add -Wno-writable-strings to clean up output | #!/usr/bin/env python
from os import listdir
import re
#reads in old makefile from folder
#parses for compiler arguments
#creates cmake lists file with parsed arguments as parent-scope variables
def readAndMake(folder):
inStream = open(folder+"/Makefile", "r")
oldMake = inStream.readlines()
inStream.close()
makeVars = {'CFLAGS': '-fno-builtin -Wno-int-to-pointer-cast -Wno-writable-strings '}
for line in oldMake:
line = re.sub('[\r\n\t]', '', line)
if "=" in line:
var, val = line.split('=', 1)
var = var.strip()
val = val.strip()
if var == "CFLAGS":
makeVars[var] += val.replace('-Werror', '')
else:
makeVars[var] = val
newMake = ""
for var, val in makeVars.iteritems():
newMake += 'set( {} "{}" )\n'.format(var, val)
newMake += 'buildCB(${CFLAGS})'
outStream = open(folder + "/CMakeLists.txt", "w")
outStream.write(newMake)
outStream.close()
#write makeFiles for all folders in path
def doAll(path):
dirs = listdir(path)
for folder in dirs:
folder = path + "/" + folder
#print folder
if "00" in folder:
print folder
readAndMake(folder)
if __name__ == '__main__':
path = "../cqe-challenges"
doAll(path) ##path should be folder containing multiple challenge binaries and nothing else.
| #!/usr/bin/env python
from os import listdir
import re
#reads in old makefile from folder
#parses for compiler arguments
#creates cmake lists file with parsed arguments as parent-scope variables
def readAndMake(folder):
inStream = open(folder+"/Makefile", "r")
oldMake = inStream.readlines()
inStream.close()
makeVars = {'CFLAGS': '-fno-builtin -Wno-int-to-pointer-cast '}
for line in oldMake:
line = re.sub('[\r\n\t]', '', line)
if "=" in line:
var, val = line.split('=', 1)
var = var.strip()
val = val.strip()
if var == "CFLAGS":
makeVars[var] += val.replace('-Werror', '')
else:
makeVars[var] = val
newMake = ""
for var, val in makeVars.iteritems():
newMake += 'set( {} "{}" )\n'.format(var, val)
newMake += 'buildCB(${CFLAGS})'
outStream = open(folder + "/CMakeLists.txt", "w")
outStream.write(newMake)
outStream.close()
#write makeFiles for all folders in path
def doAll(path):
dirs = listdir(path)
for folder in dirs:
folder = path + "/" + folder
#print folder
if "00" in folder:
print folder
readAndMake(folder)
if __name__ == '__main__':
path = "../cqe-challenges"
doAll(path) ##path should be folder containing multiple challenge binaries and nothing else.
|
Use more pythonic pattern for default attributes | import urllib
import urllib.error
import urllib.request
from rasp.constants import DEFAULT_USER_AGENT
from rasp.errors import EngineError
class Engine(object):
def get_page_source(self, url):
raise NotImplemented("get_page_source not implemented for {}"
.format(str(self.__class__.__name__)))
def cleanup(self):
return
class DefaultEngine(Engine):
def __init__(self, data=None, headers=None):
self.data = data
self.headers = headers or {'User-Agent': DEFAULT_USER_AGENT}
def __copy__(self):
return DefaultEngine(self.data, self.headers)
def get_page_source(self, url, data=None):
if not url:
return EngineError('url needs to be specified')
data = self.data or data
try:
req = urllib.request.Request(url, data, self.headers)
source = str(urllib.request.urlopen(req).read())
return Webpage(url, source)
except urllib.error.HTTPError as e:
return
class Webpage(object):
def __init__(self, url=None, source=None):
self.url = url
self.source = source
def set_source(self, source):
self.source = source
def set_url(self, url):
self.url = url
def __repr__(self):
return "url: {}".format(self.url)
| import urllib
import urllib.error
import urllib.request
from rasp.constants import DEFAULT_USER_AGENT
from rasp.errors import EngineError
class Engine(object):
def get_page_source(self, url):
raise NotImplemented("get_page_source not implemented for {}"
.format(str(self.__class__.__name__)))
def cleanup(self):
return
class DefaultEngine(Engine):
def __init__(self, data=None, headers=None):
self.data = data
if headers is None:
self.headers = {'User-Agent': DEFAULT_USER_AGENT}
else:
self.headers = headers
def __copy__(self):
return DefaultEngine(self.data, self.headers)
def get_page_source(self, url, data=None):
if not url:
return EngineError('url needs to be specified')
data = self.data or data
try:
req = urllib.request.Request(url, data, self.headers)
source = str(urllib.request.urlopen(req).read())
return Webpage(url, source)
except urllib.error.HTTPError as e:
return
class Webpage(object):
def __init__(self, url=None, source=None):
self.url = url
self.source = source
def set_source(self, source):
self.source = source
def set_url(self, url):
self.url = url
def __repr__(self):
return "url: {}".format(self.url)
|
Rewrite Api tests to ES2015 | 'use strict';
const assert = require('assert');
const sinon = require('sinon');
const Api = require('../../lib/endpoints/api');
const Request = require('../../lib/request');
describe('endpoints/api', () => {
describe('listFunctions', () => {
it('should set the request URL', () => {
const request = new Request();
const api = new Api(request);
const stub = sinon.stub(request, 'get', (url) => {
assert.strictEqual(url, '/api/listfunctions');
});
api.listFunctions();
assert.ok(stub.called);
});
});
describe('maintenance', () => {
it('should set the request URL', () => {
const request = new Request();
const api = new Api(request);
const stub = sinon.stub(request, 'get', (url) => {
assert.strictEqual(url, '/api/maintenance');
});
api.maintenance();
assert.ok(stub.called);
});
});
describe('serviceInfo', () => {
it('should set the request URL', () => {
const request = new Request();
const api = new Api(request);
const stub = sinon.stub(request, 'get', (url) => {
assert.strictEqual(url, '/api/serviceinfo');
});
api.serviceInfo();
assert.ok(stub.called);
});
});
});
| 'use strict';
var assert = require('assert');
var sinon = require('sinon');
var Api = require('../../lib/endpoints/api');
var Request = require('../../lib/request');
describe('endpoints/api', function () {
describe('listFunctions', function () {
it('should set the request URL', function () {
var request = new Request();
var api;
var stub;
stub = sinon.stub(request, 'get', function (url) {
assert.strictEqual(url, '/api/listfunctions');
});
api = new Api(request);
api.listFunctions();
assert.ok(stub.called);
});
});
describe('maintenance', function () {
it('should set the request URL', function () {
var request = new Request();
var api;
var stub;
stub = sinon.stub(request, 'get', function (url) {
assert.strictEqual(url, '/api/maintenance');
});
api = new Api(request);
api.maintenance();
assert.ok(stub.called);
});
});
describe('serviceInfo', function () {
it('should set the request URL', function () {
var request = new Request();
var api;
var stub;
stub = sinon.stub(request, 'get', function (url) {
assert.strictEqual(url, '/api/serviceinfo');
});
api = new Api(request);
api.serviceInfo();
assert.ok(stub.called);
});
});
});
|
Fix para que robotina no utilice sus propios mensajes como comando | var Discord = require('discord.io');
var bot = new Discord.Client({
autorun: true,
token: "MjUzNTcyNjgwNjYwMjg3NDg5.CyCfAA.12c7GJ7PCeEgt_XYRDDlVdB6b0g"
});
bot.on('ready', function(event) {
console.log('Logged in as %s - %s\n', bot.username, bot.id);
});
bot.on('message', function(user, userID, channelID, message, event) {
if (message.indexOf('!placeholder') != -1 && user != bot.username) {
var arguments = message.split(" ");
if (arguments.length !=3) {
bot.sendMessage({
to: channelID,
message: "`Modo de uso: !placeholder <ancho> <alto>`"
});
}
else {
bot.sendMessage({
to: channelID,
message: "http://placekitten.com/" + arguments[1] + "/" + arguments[2]
});
}
}
});
bot.on('message', function(user, userID, channelID, message, event) {
if (message.indexOf('!help') != -1) {
bot.sendMessage({
to: channelID,
message: "Todavía no me enseñaron nada =( :robot: beep boop :robot:"
});
}
});
| var Discord = require('discord.io');
var bot = new Discord.Client({
autorun: true,
token: "MjUzNTcyNjgwNjYwMjg3NDg5.CyCfAA.12c7GJ7PCeEgt_XYRDDlVdB6b0g"
});
bot.on('ready', function(event) {
console.log('Logged in as %s - %s\n', bot.username, bot.id);
});
bot.on('message', function(user, userID, channelID, message, event) {
if (message.indexOf('!placeholder') != -1) {
var arguments = message.split(" ");
if (arguments.length !=3) {
bot.sendMessage({
to: channelID,
message: "`Modo de uso: !placeholder <ancho> <alto>`"
});
}
else {
bot.sendMessage({
to: channelID,
message: "http://placekitten.com/" + arguments[1] + "/" + arguments[2]
});
}
}
});
bot.on('message', function(user, userID, channelID, message, event) {
if (message.indexOf('!help') != -1) {
bot.sendMessage({
to: channelID,
message: "Todavía no me enseñaron nada =( :robot: beep boop :robot:"
});
}
});
|
Remove redundant empty paragraph tag under IE family. | /*
jquery.popline.justify.js 0.1.0-dev
Version: 0.1.0-dev
Updated: Aug 11th, 2014
(c) 2014 by kenshin54
*/
;(function($) {
var removeRedundantParagraphTag = function(popline, align) {
if ($.popline.utils.browser.ie) {
$paragraphs = popline.target.find("p[align=" + align + "]");
$paragraphs.each(function(i, obj){
if (obj.childNodes.length === 1 && obj.childNodes[0].nodeType === 3 && !/\S/.test(obj.childNodes[0].nodeValue)) {
$(obj).remove();
}
})
}
}
$.popline.addButton({
justify: {
iconClass: "fa fa-align-justify",
mode: "edit",
buttons: {
justifyLeft: {
iconClass: "fa fa-align-left",
action: function(event, popline) {
document.execCommand("JustifyLeft");
removeRedundantParagraphTag(popline, "left");
}
},
justifyCenter: {
iconClass: "fa fa-align-center",
action: function(event, popline) {
document.execCommand("JustifyCenter");
removeRedundantParagraphTag(popline, "center");
}
},
justifyRight: {
iconClass: "fa fa-align-right",
action: function(event, popline) {
document.execCommand("JustifyRight");
removeRedundantParagraphTag(popline, "right");
}
},
indent: {
iconClass: "fa fa-indent",
action: function(event) {
document.execCommand("indent");
}
},
outdent: {
iconClass: "fa fa-dedent",
action: function(event) {
document.execCommand("outdent");
}
}
}
}
});
})(jQuery);
| /*
jquery.popline.justify.js 0.1.0-dev
Version: 0.1.0-dev
Updated: Aug 11th, 2014
(c) 2014 by kenshin54
*/
;(function($) {
$.popline.addButton({
justify: {
iconClass: "fa fa-align-justify",
mode: "edit",
buttons: {
justifyLeft: {
iconClass: "fa fa-align-left",
action: function(event) {
document.execCommand("JustifyLeft");
}
},
justifyCenter: {
iconClass: "fa fa-align-center",
action: function(event) {
document.execCommand("JustifyCenter");
}
},
justifyRight: {
iconClass: "fa fa-align-right",
action: function(event) {
document.execCommand("JustifyRight");
}
},
indent: {
iconClass: "fa fa-indent",
action: function(event) {
document.execCommand("indent");
}
},
outdent: {
iconClass: "fa fa-dedent",
action: function(event) {
document.execCommand("outdent");
}
}
}
}
});
})(jQuery);
|
Add gauge Helper so card disappears | /*global define*/
define([
'jquery',
'underscore',
'backbone',
'templates',
'dygraphs',
'helpers/gauge-helper',
'marionette',
], function($, _, Backbone, JST, Dygraph, gaugeHelper) {
'use strict';
var IopsDashView = Backbone.Marionette.ItemView.extend({
className: 'custom-gutter col-sm-12 col-xs-12 col-lg-9 col-md-9',
template: JST['app/scripts/templates/iops-dash.ejs'],
ui: {
'canvas': '.iopscanvas',
'headline': '.headline'
},
initialize: function() {
this.Dygraph = Dygraph;
_.bindAll(this, 'postRender');
this.App = Backbone.Marionette.getOption(this, 'App');
this.listenToOnce(this, 'render', this.postRender);
gaugeHelper(this);
},
data: [
[1, 10, 120],
[2, 20, 80],
[3, 50, 60],
[4, 70, 80]
],
postRender: function() {
this.d = new Dygraph(this.ui.canvas[0], this.data, {
axisLabelFontSize: 10,
drawYAxis: false,
height: 100,
width: 400
});
this.ui.headline.text('lotta');
}
});
return IopsDashView;
});
| /*global define*/
define([
'jquery',
'underscore',
'backbone',
'templates',
'dygraphs',
'marionette'
], function($, _, Backbone, JST, Dygraph) {
'use strict';
var IopsDashView = Backbone.Marionette.ItemView.extend({
className: 'custom-gutter col-sm-12 col-xs-12 col-lg-9 col-md-9',
template: JST['app/scripts/templates/iops-dash.ejs'],
ui: {
'canvas': '.iopscanvas',
'headline': '.headline'
},
initialize: function() {
this.Dygraph = Dygraph;
_.bindAll(this, 'postRender');
this.listenToOnce(this, 'render', this.postRender);
},
data: [
[1, 10, 120],
[2, 20, 80],
[3, 50, 60],
[4, 70, 80]
],
postRender: function() {
this.d = new Dygraph(this.ui.canvas[0], this.data, {
axisLabelFontSize: 10,
drawYAxis: false,
height: 100,
width: 400
});
this.ui.headline.text('lotta');
}
});
return IopsDashView;
});
|
Enforce consistent artisan command tag namespacing | <?php
declare(strict_types=1);
namespace Rinvex\Tags\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:publish:tags {--f|force : Overwrite any existing files.} {--r|resource=all}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Rinvex Tags Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
switch ($this->option('resource')) {
case 'config':
$this->call('vendor:publish', ['--tag' => 'rinvex/tags::config', '--force' => $this->option('force')]);
break;
case 'migrations':
$this->call('vendor:publish', ['--tag' => 'rinvex/tags::migrations', '--force' => $this->option('force')]);
break;
default:
$this->call('vendor:publish', ['--tag' => 'rinvex/tags::config', '--force' => $this->option('force')]);
$this->call('vendor:publish', ['--tag' => 'rinvex/tags::migrations', '--force' => $this->option('force')]);
break;
}
$this->line('');
}
}
| <?php
declare(strict_types=1);
namespace Rinvex\Tags\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:publish:tags {--f|force : Overwrite any existing files.} {--r|resource=all}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Rinvex Tags Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
switch ($this->option('resource')) {
case 'config':
$this->call('vendor:publish', ['--tag' => 'rinvex-tags-config', '--force' => $this->option('force')]);
break;
case 'migrations':
$this->call('vendor:publish', ['--tag' => 'rinvex-tags-migrations', '--force' => $this->option('force')]);
break;
default:
$this->call('vendor:publish', ['--tag' => 'rinvex-tags-config', '--force' => $this->option('force')]);
$this->call('vendor:publish', ['--tag' => 'rinvex-tags-migrations', '--force' => $this->option('force')]);
break;
}
$this->line('');
}
}
|
Rewrite text-fill directive to use isolated scope. [IQSLDSH-382] | /*global angular*/
(function () {
'use strict';
// member attribute = member in slide to watch for changes
// min-font-size attribute = minimum font size in pixels
// max-font-size attribute = maximum font size in pixels
// Directive must be used on the parent of an element with the .text-fill class
angular.module('core').directive('textFill', ["$timeout", function ($timeout) {
return {
scope: {
member: "@",
minFontSize: "=",
maxFontSize: "=",
},
link: function postLink(scope, element, attrs) {
if ($(element).find('.text-fill').length === 0) {
return;
}
var applyTextFill = function() {
$(element).textfill({
minFontPixels: scope.minFontSize,
maxFontPixels: scope.maxFontSize,
innerTag: '.text-fill'
});
}
scope.$on('updateSlideContentPart', function (event, content, member, slidePartId) {
if (member === scope.member) {
$timeout(applyTextFill, 100, false);
}
});
scope.$on("currentSlideChanged", function () {
$timeout(applyTextFill, 100, false);
});
scope.$on("slideTemplateLoaded", function () {
$timeout(applyTextFill, 100, false);
});
$timeout(applyTextFill, 100, false);
}
};
}]);
}());
| /*global angular*/
(function () {
'use strict';
// min-font-size attribute = minimum font size in pixels
// max-font-size attribute = maximum font size in pixels
// Directive must be used on the parent of an element with the .text-fill class
angular.module('core').directive('textFill', ["$timeout", function ($timeout) {
return {
link: function postLink(scope, element, attrs) {
if ($(element).find('.text-fill').length === 0) {
return;
}
var minFontSize = parseFloat(attrs.minFontSize);
var maxFontSize = parseFloat(attrs.maxFontSize);
if (!minFontSize || !maxFontSize) {
return;
}
var applyTextFill = function() {
$(element).textfill({
minFontPixels: minFontSize,
maxFontPixels: maxFontSize,
innerTag: '.text-fill'
});
}
scope.$on('updateSlideContentPart', function (event, content, member, slidePartId) {
if (member === attrs.member) {
$timeout(applyTextFill, 100, false);
}
});
scope.$on("currentSlideChanged", function () {
$timeout(applyTextFill, 100, false);
});
scope.$on("slideTemplateLoaded", function () {
$timeout(applyTextFill, 100, false);
});
$timeout(applyTextFill, 100, false);
}
};
}]);
}());
|
Fix assumption that tornado.web was imported. | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
import tornado.web
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop, PeriodicCallback
from gunicorn.workers.base import Worker
from gunicorn import __version__ as gversion
def patch_request_handler():
web = sys.modules.pop("tornado.web")
old_clear = web.RequestHandler.clear
def clear(self):
old_clear(self)
self._headers["Server"] += " (Gunicorn/%s)" % gversion
web.RequestHandler.clear = clear
sys.modules["tornado.web"] = web
class TornadoWorker(Worker):
@classmethod
def setup(cls):
patch_request_handler()
def watchdog(self):
self.notify()
if self.ppid != os.getppid():
self.log.info("Parent changed, shutting down: %s" % self)
self.ioloop.stop()
def run(self):
self.socket.setblocking(0)
self.ioloop = IOLoop.instance()
PeriodicCallback(self.watchdog, 1000, io_loop=self.ioloop).start()
server = HTTPServer(self.app, io_loop=self.ioloop)
server._socket = self.socket
server.start(num_processes=1)
self.ioloop.start()
| # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop, PeriodicCallback
from gunicorn.workers.base import Worker
from gunicorn import __version__ as gversion
def patch_request_handler():
web = sys.modules.pop("tornado.web")
old_clear = web.RequestHandler.clear
def clear(self):
old_clear(self)
self._headers["Server"] += " (Gunicorn/%s)" % gversion
web.RequestHandler.clear = clear
sys.modules["tornado.web"] = web
class TornadoWorker(Worker):
@classmethod
def setup(cls):
patch_request_handler()
def watchdog(self):
self.notify()
if self.ppid != os.getppid():
self.log.info("Parent changed, shutting down: %s" % self)
self.ioloop.stop()
def run(self):
self.socket.setblocking(0)
self.ioloop = IOLoop.instance()
PeriodicCallback(self.watchdog, 1000, io_loop=self.ioloop).start()
server = HTTPServer(self.app, io_loop=self.ioloop)
server._socket = self.socket
server.start(num_processes=1)
self.ioloop.start()
|
Fix roles check if no roles present | <?php namespace GeneaLabs\LaravelGovernor\Policies;
use GeneaLabs\LaravelGovernor\Permission;
class LaravelGovernorPolicy
{
protected $permissions;
public function __construct()
{
$this->permissions = Permission::with('role')->get();
}
protected function validatePermissions($user, $action, $entity, $entityCreatorId)
{
if (! $user->roles) {
return false;
}
$user->load('roles');
$ownership = 'other';
if ($user->id === $entityCreatorId) {
$ownership = 'own';
}
$filteredPermissions = $this->filterPermissions($action, $entity, $ownership);
foreach ($filteredPermissions as $permission) {
if ($user->roles->contains($permission->role)) {
return true;
}
}
return false;
}
protected function filterPermissions($action, $entity, $ownership)
{
$filteredPermissions = $this->permissions->filter(function ($permission) use ($action, $entity, $ownership) {
return ($permission->action_key === $action
&& $permission->entity_key === $entity
&& in_array($permission->ownership_key, [$ownership, 'any']));
});
return $filteredPermissions;
}
}
| <?php namespace GeneaLabs\LaravelGovernor\Policies;
use GeneaLabs\LaravelGovernor\Permission;
class LaravelGovernorPolicy
{
protected $permissions;
public function __construct()
{
$this->permissions = Permission::with('role')->get();
}
protected function validatePermissions($user, $action, $entity, $entityCreatorId)
{
if (! $user->roles->count()) {
return false;
}
$user->load('roles');
$ownership = 'other';
if ($user->id === $entityCreatorId) {
$ownership = 'own';
}
$filteredPermissions = $this->filterPermissions($action, $entity, $ownership);
foreach ($filteredPermissions as $permission) {
if ($user->roles->contains($permission->role)) {
return true;
}
}
return false;
}
protected function filterPermissions($action, $entity, $ownership)
{
$filteredPermissions = $this->permissions->filter(function ($permission) use ($action, $entity, $ownership) {
return ($permission->action_key === $action
&& $permission->entity_key === $entity
&& in_array($permission->ownership_key, [$ownership, 'any']));
});
return $filteredPermissions;
}
}
|
[page] Add the cartrige left compoennt in the mixin. | var isFunction = require('lodash/lang/isFunction');
var dispatcher = require('focus').dispatcher;
var Empty = require('../../common/empty').component;
module.exports = {
/**
* Register the cartridge.
*/
_registerCartridge: function registerCartridge(){
this.cartridgeConfiguration = this.cartridgeConfiguration || this.props.cartridgeConfiguration;
if(!isFunction(this.cartridgeConfiguration)){
this.cartridgeConfiguration = function cartridgeConfiguration(){
return {};
};
console.warn(`
Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
It should be a component attribute return by a function.
function cartridgeConfiguration(){
var cartridgeConfiguration = {
summary: {component: "A React Component", props: {id: this.props.id}},
cartridge: {component: "A React Component"},
actions: {components: "react actions"}
};
return cartridgeConfiguration;
}
`);
}
var cartridgeConf = this.cartridgeConfiguration();
dispatcher.handleViewAction({
data: {
cartridgeComponent: cartridgeConf.cartridge || {component: Empty},
summaryComponent: cartridgeConf.summary|| {component: Empty},
actions: cartridgeConf.actions|| {primary: [], secondary: Empty},
barContentLeftComponent: cartridgeConf.barLeft || {component: Empty}
},
type: 'update'
});
},
componentWillMount: function pageMixinWillMount(){
this._registerCartridge();
}
};
| var isFunction = require('lodash/lang/isFunction');
var dispatcher = require('focus').dispatcher;
module.exports = {
/**
* Register the cartridge.
*/
_registerCartridge: function registerCartridge(){
this.cartridgeConfiguration = this.cartridgeConfiguration || this.props.cartridgeConfiguration;
if(!isFunction(this.cartridgeConfiguration)){
this.cartridgeConfiguration = function cartridgeConfiguration(){
return {};
};
console.warn(`
Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
It should be a component attribute return by a function.
function cartridgeConfiguration(){
var cartridgeConfiguration = {
summary: {component: "A React Component", props: {id: this.props.id}},
cartridge: {component: "A React Component"},
actions: {components: "react actions"}
};
return cartridgeConfiguration;
}
`);
}
var cartridgeConf = this.cartridgeConfiguration();
dispatcher.handleViewAction({
data: {
cartridgeComponent: cartridgeConf.cartridge,
summaryComponent: cartridgeConf.summary,
actions: cartridgeConf.actions
},
type: 'update'
});
},
componentWillMount: function pageMixinWillMount(){
this._registerCartridge();
}
};
|
Tweak PayPal output to use Payee and Memo fields | #!/usr/bin/env python3
import argparse
import csv
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='path to file containing column header mappings', required=True)
parser.add_argument('--csv-file', help='path to CSV file', required=True)
parser.add_argument('--skip-headers', help='skip first line of file as headers', action='store_true')
args = parser.parse_args()
skipped_headers = False
with open(args.config, 'r') as config_file:
column_headings = config_file.readline().strip()
column_headings = column_headings.split()
with open(args.csv_file, newline='') as csv_file:
csv_reader = csv.DictReader(csv_file, fieldnames=column_headings)
print('!Type:Bank')
for row in csv_reader:
if args.skip_headers and not skipped_headers:
skipped_headers = True
else:
print('D' + row['date'])
print('T' + row['gross'])
print('P' + row['from_name'])
print('M' + row['description'])
print('^')
# Process fee as separate transaction - PayPal puts it on one line
fee = float(row['fee'])
if fee < 0 or fee > 0:
print('D' + row['date'])
print('T' + row['fee'])
print('P' + 'PayPal')
print('M' + 'PayPal fee')
print('^')
| #!/usr/bin/env python3
import argparse
import csv
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='path to file containing column header mappings', required=True)
parser.add_argument('--csv-file', help='path to CSV file', required=True)
parser.add_argument('--skip-headers', help='skip first line of file as headers', action='store_true')
args = parser.parse_args()
skipped_headers = False
with open(args.config, 'r') as config_file:
column_headings = config_file.readline().strip()
column_headings = column_headings.split()
with open(args.csv_file, newline='') as csv_file:
csv_reader = csv.DictReader(csv_file, fieldnames=column_headings)
print('!Type:Bank')
for row in csv_reader:
if args.skip_headers and not skipped_headers:
skipped_headers = True
else:
print('D' + row['date'])
print('T' + row['gross'])
print('P' + row['description'])
print('^')
# Process fee as separate transaction - PayPal puts it on one line
fee = float(row['fee'])
if fee < 0 or fee > 0:
print('D' + row['date'])
print('T' + row['fee'])
print('P' + 'PayPal fee')
print('^')
|
Return array instead of null because return value is evaluated in foreach | <?php
class Susy_Kwc_TextImage_Layout extends Susy_Layout
{
protected function _isSupportedContext($context)
{
if ($context['spans'] < 3) return false;
return true;
}
public function getChildContexts(Kwf_Component_Data $data, Kwf_Component_Data $child)
{
$ownContexts = parent::getChildContexts($data, $child);
if ($child->id == 'image') {
if (!$data->getComponent()->getRow()->image) {
return array();
}
$imageWidth = $data->getComponent()->getRow()->image_width;
if (!$imageWidth) $imageWidth = 25;
$widthCalc = 100/$imageWidth;
$ret = array();
$masterLayouts = Susy_Helper::getLayouts();
foreach ($ownContexts as $context) {
$breakpoint = $masterLayouts[$context['masterLayout']][$context['breakpoint']];
//same logic in scss
if (!isset($breakpoint['breakpoint']) || (int)$breakpoint['breakpoint'] * $context['spans'] / $breakpoint['columns'] < 300) {
//full width
$ret[] = $context;
} else {
$context['spans'] = floor($context['spans'] * $widthCalc);
if ($context['spans'] < 1) {
$context['spans'] = 1;
}
$ret[] = $context;
}
}
return $ret;
} else {
return $ownContexts;
}
}
}
| <?php
class Susy_Kwc_TextImage_Layout extends Susy_Layout
{
protected function _isSupportedContext($context)
{
if ($context['spans'] < 3) return false;
return true;
}
public function getChildContexts(Kwf_Component_Data $data, Kwf_Component_Data $child)
{
$ownContexts = parent::getChildContexts($data, $child);
if ($child->id == 'image') {
if (!$data->getComponent()->getRow()->image) {
return null;
}
$imageWidth = $data->getComponent()->getRow()->image_width;
if (!$imageWidth) $imageWidth = 25;
$widthCalc = 100/$imageWidth;
$ret = array();
$masterLayouts = Susy_Helper::getLayouts();
foreach ($ownContexts as $context) {
$breakpoint = $masterLayouts[$context['masterLayout']][$context['breakpoint']];
//same logic in scss
if (!isset($breakpoint['breakpoint']) || (int)$breakpoint['breakpoint'] * $context['spans'] / $breakpoint['columns'] < 300) {
//full width
$ret[] = $context;
} else {
$context['spans'] = floor($context['spans'] * $widthCalc);
if ($context['spans'] < 1) {
$context['spans'] = 1;
}
$ret[] = $context;
}
}
return $ret;
} else {
return $ownContexts;
}
}
}
|
Fix bug where specified bias is ignored. | package com.github.klane.wann.core;
import com.github.klane.wann.function.activation.ActivationFunction;
import com.github.klane.wann.function.input.InputFunction;
import com.google.common.base.Preconditions;
import javafx.util.Builder;
public abstract class WANNBuilder<T, U extends WANNBuilder<T, U>> implements Builder<T> {
ActivationFunction activationFunction;
Double bias;
boolean biasFlag;
InputFunction inputFunction;
String name;
public U activationFunction(final ActivationFunction activationFunction) {
if (this.activationFunction == null) {
this.activationFunction = activationFunction;
}
return this.get();
}
public U bias(final boolean biasFlag) {
if (this.bias == null) {
this.biasFlag = biasFlag;
}
return this.get();
}
public U bias(final Double bias) {
if (this.bias == null) {
this.bias = bias;
this.biasFlag = true;
}
return this.get();
}
@Override
public abstract T build();
public U inputFunction(final InputFunction inputFunction) {
if (this.inputFunction == null) {
this.inputFunction = inputFunction;
}
return this.get();
}
public U name(final String name) {
Preconditions.checkNotNull(name);
if (this.name == null) {
this.name = name;
}
return this.get();
}
abstract U get();
}
| package com.github.klane.wann.core;
import com.github.klane.wann.function.activation.ActivationFunction;
import com.github.klane.wann.function.input.InputFunction;
import com.google.common.base.Preconditions;
import javafx.util.Builder;
public abstract class WANNBuilder<T, U extends WANNBuilder<T, U>> implements Builder<T> {
ActivationFunction activationFunction;
Double bias;
boolean biasFlag;
InputFunction inputFunction;
String name;
public U activationFunction(final ActivationFunction activationFunction) {
if (this.activationFunction == null) {
this.activationFunction = activationFunction;
}
return this.get();
}
public U bias(final boolean biasFlag) {
this.biasFlag = biasFlag;
return this.get();
}
public U bias(final Double bias) {
if (this.bias == null) {
this.bias = bias;
this.biasFlag = true;
}
return this.get();
}
@Override
public abstract T build();
public U inputFunction(final InputFunction inputFunction) {
if (this.inputFunction == null) {
this.inputFunction = inputFunction;
}
return this.get();
}
public U name(final String name) {
Preconditions.checkNotNull(name);
if (this.name == null) {
this.name = name;
}
return this.get();
}
abstract U get();
}
|
Use "FormHttpMessageConverter" for form based requests | package at.create.android.ffc.http;
import java.net.URI;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @author Philipp Ullmann
* Authenticate with username and password.
*/
public final class FormBasedAuthentication extends HttpBase {
private static final String PATH = "/authentication";
private final String username;
private final String password;
/**
* Stores the given parameters into instance variables.
* @param username Username
* @param password Password
* @param baseUri Base uri to Fat Free CRM web application
*/
public FormBasedAuthentication(final String username, final String password, final String baseUri) {
super(baseUri);
this.username = username;
this.password = password;
}
@Override
protected String getUrl() {
return baseUri + PATH;
}
/**
* Authentication via username and password.
* @return True if the authentication succeeded, otherwise false is returned.
*/
public boolean authenticate() {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("authentication[username]", username);
formData.add("authentication[password]", password);
formData.add("authentication[remember_me]", "1");
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
URI uri = restTemplate.postForLocation(getUrl(), formData);
return !uri.getPath().equals("/login");
}
}
| package at.create.android.ffc.http;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @author Philipp Ullmann
* Authenticate with username and password.
*/
public final class FormBasedAuthentication extends HttpBase {
private static final String PATH = "/authentication";
private final String username;
private final String password;
/**
* Stores the given parameters into instance variables.
* @param username Username
* @param password Password
* @param baseUri Base uri to Fat Free CRM web application
*/
public FormBasedAuthentication(final String username, final String password, final String baseUri) {
super(baseUri);
this.username = username;
this.password = password;
}
@Override
protected String getUrl() {
return baseUri + PATH;
}
/**
* Authentication via username and password.
* @return True if the authentication succeeded, otherwise false is returned.
*/
public boolean authenticate() {
MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
formData.add("authentication[username]", username);
formData.add("authentication[password]", password);
formData.add("authentication[remember_me]", "1");
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);
ResponseEntity<String> response = restTemplate.exchange(getUrl(),
HttpMethod.POST,
requestEntity,
String.class);
return !response.getHeaders().getLocation().getPath().equals("/login");
}
}
|
fix(global-options): Allow --sort to be configured from file | "use strict";
module.exports = globalOptions;
function globalOptions(yargs, { ci = false, loglevel = "info", progress = true }) {
// the global options applicable to _every_ command
const opts = {
loglevel: {
default: loglevel,
describe: "What level of logs to report.",
type: "string",
},
concurrency: {
defaultDescription: "4",
describe: "How many processes to use when lerna parallelizes tasks.",
type: "number",
requiresArg: true,
},
"reject-cycles": {
describe: "Fail if a cycle is detected among dependencies.",
type: "boolean",
},
progress: {
default: !ci && progress,
describe: "Enable progress bars. (Always off in CI)\nPass --no-progress to disable.",
type: "boolean",
},
sort: {
defaultDescription: "true",
describe: "Sort packages topologically (dependencies before dependents).\nPass --no-sort to disable.",
type: "boolean",
},
"max-buffer": {
describe: "Set max-buffer (in bytes) for subcommand execution",
type: "number",
requiresArg: true,
},
};
// group options under "Global Options:" header
const globalKeys = Object.keys(opts).concat(["help", "version"]);
return yargs
.options(opts)
.group(globalKeys, "Global Options:")
.option("ci", {
default: ci,
hidden: true,
type: "boolean",
});
}
| "use strict";
module.exports = globalOptions;
function globalOptions(yargs, { ci = false, loglevel = "info", progress = true }) {
// the global options applicable to _every_ command
const opts = {
loglevel: {
default: loglevel,
describe: "What level of logs to report.",
type: "string",
},
concurrency: {
defaultDescription: "4",
describe: "How many processes to use when lerna parallelizes tasks.",
type: "number",
requiresArg: true,
},
"reject-cycles": {
describe: "Fail if a cycle is detected among dependencies.",
type: "boolean",
},
progress: {
default: !ci && progress,
describe: "Enable progress bars. (Always off in CI)\nPass --no-progress to disable.",
type: "boolean",
},
sort: {
default: true,
describe: "Sort packages topologically (dependencies before dependents).\nPass --no-sort to disable.",
type: "boolean",
},
"max-buffer": {
describe: "Set max-buffer (in bytes) for subcommand execution",
type: "number",
requiresArg: true,
},
};
// group options under "Global Options:" header
const globalKeys = Object.keys(opts).concat(["help", "version"]);
return yargs
.options(opts)
.group(globalKeys, "Global Options:")
.option("ci", {
default: ci,
hidden: true,
type: "boolean",
});
}
|
Allow configuration of debug on prod lol | <?php
declare(strict_types=1);
if (!getenv('HEROKU')) {
return [];
}
return [
'debug' => (bool)\getenv('DEBUG'),
'config_cache_enabled' => true,
'doctrine' => [
'connection' => [
'orm_default' => [
'params' => [
'url' => \getenv('DATABASE_URL'),
],
],
],
],
'phph-site' => [
's3' => [
'credentials' => [
'key' => \getenv('AWS_S3_KEY'),
'secret' => \getenv('AWS_S3_SECRET'),
],
'region' => \getenv('AWS_S3_REGION'),
'version' => 'latest',
'bucket' => \getenv('AWS_S3_BUCKET'),
],
'google-recaptcha' => [
'site-key' => \getenv('GOOGLE_RECAPTCHA_SITE_KEY'),
'secret-key' => \getenv('GOOGLE_RECAPTCHA_SECRET_KEY'),
],
'twitter' => [
'identifier' => \getenv('TWITTER_IDENTIFIER'),
'secret' => \getenv('TWITTER_SECRET'),
'callback_uri' => \getenv('TWITTER_CALLBACK_URL'),
],
'github' => [
'clientId' => \getenv('GITHUB_CLIENT_ID'),
'clientSecret' => \getenv('GITHUB_CLIENT_SECRET'),
'redirectUri' => \getenv('GITHUB_REDIRECT_URI'),
],
],
];
| <?php
declare(strict_types=1);
if (!getenv('HEROKU')) {
return [];
}
return [
'debug' => false,
'config_cache_enabled' => false,
'doctrine' => [
'connection' => [
'orm_default' => [
'params' => [
'url' => \getenv('DATABASE_URL'),
],
],
],
],
'phph-site' => [
's3' => [
'credentials' => [
'key' => \getenv('AWS_S3_KEY'),
'secret' => \getenv('AWS_S3_SECRET'),
],
'region' => \getenv('AWS_S3_REGION'),
'version' => 'latest',
'bucket' => \getenv('AWS_S3_BUCKET'),
],
'google-recaptcha' => [
'site-key' => \getenv('GOOGLE_RECAPTCHA_SITE_KEY'),
'secret-key' => \getenv('GOOGLE_RECAPTCHA_SECRET_KEY'),
],
'twitter' => [
'identifier' => \getenv('TWITTER_IDENTIFIER'),
'secret' => \getenv('TWITTER_SECRET'),
'callback_uri' => \getenv('TWITTER_CALLBACK_URL'),
],
'github' => [
'clientId' => \getenv('GITHUB_CLIENT_ID'),
'clientSecret' => \getenv('GITHUB_CLIENT_SECRET'),
'redirectUri' => \getenv('GITHUB_REDIRECT_URI'),
],
],
];
|
Deal with case that item lines already exist before SI finalised | import Realm from 'realm';
import {
addLineToParent,
generateUUID,
getTotal,
} from '../utilities';
export class Transaction extends Realm.Object {
get isFinalised() {
return this.status === 'finalised';
}
get isConfirmed() {
return this.status === 'confirmed';
}
get totalPrice() {
return getTotal(this.items, 'totalPrice');
}
// Adds a TransactionLine, incorporating it into a matching TransactionItem
addLine(database, transactionLine) {
addLineToParent(transactionLine, this, () =>
database.create('TransactionItem', {
id: generateUUID(),
item: transactionLine.itemLine.item,
transaction: this,
})
);
}
finalise(database, user) {
if (this.type === 'supplier_invoice') { // If a supplier invoice, add item lines to inventory
this.enteredBy = user;
this.items.forEach((transactionItem) => {
transactionItem.lines.forEach((transactionLine) => {
const itemLine = transactionLine.itemLine;
itemLine.packSize = transactionLine.packSize;
itemLine.numberOfPacks = itemLine.numberOfPacks + transactionLine.numberOfPacks;
itemLine.expiryDate = transactionLine.expiryDate;
itemLine.batch = transactionLine.batch;
itemLine.costPrice = transactionLine.costPrice;
itemLine.sellPrice = transactionLine.sellPrice;
database.save('ItemLine', itemLine);
database.save('TransactionLine', transactionLine);
});
});
}
this.status = 'finalised';
}
}
| import Realm from 'realm';
import {
addLineToParent,
generateUUID,
getTotal,
} from '../utilities';
export class Transaction extends Realm.Object {
get isFinalised() {
return this.status === 'finalised';
}
get totalPrice() {
return getTotal(this.items, 'totalPrice');
}
// Adds a TransactionLine, incorporating it into a matching TransactionItem
addLine(database, transactionLine) {
addLineToParent(transactionLine, this, () =>
database.create('TransactionItem', {
id: generateUUID(),
item: transactionLine.itemLine.item,
transaction: this,
})
);
}
finalise(database, user) {
this.status = 'finalised';
if (this.type === 'supplier_invoice') { // If a supplier invoice, add item lines to inventory
this.enteredBy = user;
this.items.forEach((transactionItem) => {
transactionItem.lines.forEach((transactionLine) => {
const itemLine = transactionLine.itemLine;
itemLine.packSize = transactionLine.packSize;
itemLine.numberOfPacks = transactionLine.numberOfPacks;
itemLine.expiryDate = transactionLine.expiryDate;
itemLine.batch = transactionLine.batch;
itemLine.costPrice = transactionLine.costPrice;
itemLine.sellPrice = transactionLine.sellPrice;
database.save('ItemLine', itemLine);
database.save('TransactionLine', transactionLine);
});
});
}
}
}
|
Include all gin files in pip package.
PiperOrigin-RevId: 318120480 | """Install Mesh TensorFlow."""
from setuptools import find_packages
from setuptools import setup
setup(
name='mesh-tensorflow',
version='0.1.15',
description='Mesh TensorFlow',
author='Google Inc.',
author_email='[email protected]',
url='http://github.com/tensorflow/mesh',
license='Apache 2.0',
packages=find_packages(),
package_data={
# Include gin files.
'': ['*.gin'],
},
scripts=[],
install_requires=[
'absl-py',
'future',
'gin-config',
'six',
],
extras_require={
'auto_mtf': ['ortools'],
'tensorflow': ['tensorflow>=1.15.0'],
'transformer': ['tensorflow-datasets'],
},
tests_require=[
'ortools',
'pytest',
'tensorflow',
'tensorflow-datasets',
],
setup_requires=['pytest-runner'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning',
)
| """Install Mesh TensorFlow."""
from setuptools import find_packages
from setuptools import setup
setup(
name='mesh-tensorflow',
version='0.1.14',
description='Mesh TensorFlow',
author='Google Inc.',
author_email='[email protected]',
url='http://github.com/tensorflow/mesh',
license='Apache 2.0',
packages=find_packages(),
package_data={
# Include gin files.
'transformer': ['transformer/gin/*.gin'],
},
scripts=[],
install_requires=[
'absl-py',
'future',
'gin-config',
'six',
],
extras_require={
'auto_mtf': ['ortools'],
'tensorflow': ['tensorflow>=1.15.0'],
'transformer': ['tensorflow-datasets'],
},
tests_require=[
'ortools',
'pytest',
'tensorflow',
'tensorflow-datasets',
],
setup_requires=['pytest-runner'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning',
)
|
Drinks: Check the response whether null or empty | (function (env) {
"use strict";
function getInfoBoxData(item) {
var infoboxData = [{
heading: 'Ingredients:'
}];
for (var i = 1; i <= 15; i++) {
if(item["strIngredient" + i] !== "") {
infoboxData.push({
label: item["strMeasure" + i] + "" + item["strIngredient" + i]
});
}
}
return infoboxData;
}
env.ddg_spice_drinks = function(api_result){
if (!api_result || api_result.error || !api_result.drinks || api_result.drinks.length === 0) {
return Spice.failed('drinks');
}
var drink = api_result.drinks[0];
Spice.add({
id: 'drinks',
data: drink,
name: "Drinks",
meta: {
sourceUrl: "http://www.thecocktaildb.com/drink.php?c=" + drink.idDrink,
sourceName: 'TheCocktailDB'
},
normalize: function(item) {
return {
description: item.strInstructions,
title: item.strDrink,
infoboxData: getInfoBoxData(item)
};
},
templates: {
group: 'info'
}
});
};
}(this)); | (function (env) {
"use strict";
function getInfoBoxData(item) {
var infoboxData = [{
heading: 'Ingredients:'
}];
for (var i = 1; i <= 15; i++) {
if(item["strIngredient" + i] !== "") {
infoboxData.push({
label: item["strMeasure" + i] + "" + item["strIngredient" + i]
});
}
}
return infoboxData;
}
env.ddg_spice_drinks = function(api_result){
if (!api_result || api_result.error) {
return Spice.failed('drinks');
}
var drink = api_result.drinks[0];
Spice.add({
id: 'drinks',
data: drink,
name: "Drinks",
meta: {
sourceUrl: "http://www.thecocktaildb.com/drink.php?c=" + drink.idDrink,
sourceName: 'TheCocktailDB'
},
normalize: function(item) {
return {
description: item.strInstructions,
title: item.strDrink,
infoboxData: getInfoBoxData(item)
};
},
templates: {
group: 'info'
}
});
};
}(this)); |
Remove intent warning and allow zero values for settings | import React from 'react';
import PropTypes from 'prop-types';
import { InputGroup } from '@blueprintjs/core';
const Option = ({ intent, title, type, value, unit, onChange, inputStyles }) => (
<label className="pt-label pt-inline">
<div className="d-inline-block w-exact-225">{title} {unit && `(${unit})`}</div>
{type === 'number' ? (
<InputGroup
min="0"
type="number"
intent={intent}
value={value}
onChange={(e) => {
const val = +e.target.value;
if (!Option.isValidNumber(val)) return;
onChange(val);
}}
className={inputStyles}
/>
) : (
<InputGroup
type={type}
intent={intent}
value={value}
onChange={onChange}
className={inputStyles}
/>
)}
</label>
);
Option.propTypes = {
intent: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
unit: PropTypes.string,
onChange: PropTypes.func.isRequired,
inputStyles: PropTypes.string
};
Option.isValidNumber = (n) => n % 1 === 0;
export default Option;
| import React from 'react';
import PropTypes from 'prop-types';
import { InputGroup, Intent } from '@blueprintjs/core';
const Option = ({ intent, title, type, value, unit, onChange, inputStyles }) => (
<label className="pt-label pt-inline">
<div className="d-inline-block w-exact-225">{title} {unit && `(${unit})`}</div>
{type === 'number' ? (
<InputGroup
min="1"
type="number"
intent={value ? intent : Intent.DANGER}
value={value}
onChange={(e) => {
const val = +e.target.value;
if (!Option.isValidNumber(val)) return;
onChange(val);
}}
className={inputStyles}
/>
) : (
<InputGroup
type={type}
intent={intent}
value={value}
onChange={onChange}
className={inputStyles}
/>
)}
</label>
);
Option.propTypes = {
intent: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
unit: PropTypes.string,
onChange: PropTypes.func.isRequired,
inputStyles: PropTypes.string
};
Option.isValidNumber = (n) => n % 1 === 0;
export default Option;
|
Clean up existing gRPC bridge test (make it like t_tcpmapping.py)
- Remove redundant HTTP status assertions
- Adjust formatting
- Remove unused import | from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, EGRPC
class AcceptanceGrpcBridgeTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = EGRPC()
def config(self):
yield self, self.format("""
---
apiVersion: ambassador/v0
kind: Module
name: ambassador
config:
enable_grpc_http11_bridge: True
""")
yield self, self.format("""
---
apiVersion: ambassador/v0
kind: Mapping
grpc: True
prefix: /echo.EchoService/
rewrite: /echo.EchoService/
name: {self.target.path.k8s}
service: {self.target.path.k8s}
""")
def queries(self):
# [0]
yield Query(self.url("echo.EchoService/Echo"),
headers={ "content-type": "application/grpc", "requested-status": "0" },
expected=200)
# [1]
yield Query(self.url("echo.EchoService/Echo"),
headers={ "content-type": "application/grpc", "requested-status": "7" },
expected=200)
def check(self):
# [0]
assert self.results[0].headers["Grpc-Status"] == ["0"]
# [1]
assert self.results[1].headers["Grpc-Status"] == ["7"]
| import json
from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, EGRPC
class AcceptanceGrpcBridgeTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = EGRPC()
def config(self):
yield self, self.format("""
---
apiVersion: ambassador/v0
kind: Module
name: ambassador
config:
enable_grpc_http11_bridge: True
""")
yield self, self.format("""
---
apiVersion: ambassador/v0
kind: Mapping
grpc: True
prefix: /echo.EchoService/
rewrite: /echo.EchoService/
name: {self.target.path.k8s}
service: {self.target.path.k8s}
""")
def queries(self):
# [0]
yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc",
"requested-status": "0" }, expected=200)
# [1]
yield Query(self.url("echo.EchoService/Echo"), headers={ "content-type": "application/grpc",
"requested-status": "7" }, expected=200)
def check(self):
# [0]
assert self.results[0].status == 200
assert self.results[0].headers["Grpc-Status"] == ["0"]
# [0]
assert self.results[1].status == 200
assert self.results[1].headers["Grpc-Status"] == ["7"]
|
Attach custom result popup menu to widget
Call gtk.Menu.attach_to_widget() on the popup menu for custom results.
This should have little practical result one way or the other, though
it is theoretically "right", but it has the useful side-effect of getting
the menu into the right GtkWindowGroup. Again that should have little
practical effect, but importantly it works around a gtk-quartz bug
that otherwise causes the menu not to pop down when clicking away.
(http://bugzilla.gnome.org/show_bug.cgi?id=557894) | # Copyright 2007 Owen Taylor
#
# This file is part of Reinteract and distributed under the terms
# of the BSD license. See the file COPYING in the Reinteract
# distribution for full details.
#
########################################################################
import gtk
class CustomResult(object):
def create_widget(self):
raise NotImplementedError()
def show_menu(widget, event, save_callback=None):
"""Convenience function to create a right-click menu with a Save As option"""
toplevel = widget.get_toplevel()
menu = gtk.Menu()
menu.attach_to_widget(widget, None)
menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS)
menu_item.show()
menu.add(menu_item)
def on_selection_done(menu):
menu.destroy()
menu.connect('selection-done', on_selection_done)
def on_activate(menu):
chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
response = chooser.run()
filename = None
if response == gtk.RESPONSE_OK:
filename = chooser.get_filename()
chooser.destroy()
if filename != None:
save_callback(filename)
menu_item.connect('activate', on_activate)
menu.popup(None, None, None, event.button, event.time)
| # Copyright 2007 Owen Taylor
#
# This file is part of Reinteract and distributed under the terms
# of the BSD license. See the file COPYING in the Reinteract
# distribution for full details.
#
########################################################################
import gtk
class CustomResult(object):
def create_widget(self):
raise NotImplementedError()
def show_menu(widget, event, save_callback=None):
"""Convenience function to create a right-click menu with a Save As option"""
toplevel = widget.get_toplevel()
menu = gtk.Menu()
menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS)
menu_item.show()
menu.add(menu_item)
def on_selection_done(menu):
menu.destroy()
menu.connect('selection-done', on_selection_done)
def on_activate(menu):
chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
response = chooser.run()
filename = None
if response == gtk.RESPONSE_OK:
filename = chooser.get_filename()
chooser.destroy()
if filename != None:
save_callback(filename)
menu_item.connect('activate', on_activate)
menu.popup(None, None, None, event.button, event.time)
|
Use jsonp() instead of generate_jsonp() | <?
include '../scat.php';
$days= (int)$_REQUEST['days'];
if (!$days) $days= 30;
$q= "SELECT DATE_FORMAT(filled, '%Y-%m-%d') day,
SUM(subtotal) AS total
FROM (SELECT
filled,
CAST(ROUND_TO_EVEN(
SUM(IF(type = 'customer', -1, 1) * allocated *
CASE discount_type
WHEN 'percentage'
THEN retail_price * ((100 - discount) / 100)
WHEN 'relative'
THEN (retail_price - discount)
WHEN 'fixed'
THEN (discount)
ELSE retail_price
END), 2) AS DECIMAL(9,2))
AS subtotal
FROM txn
LEFT JOIN txn_line ON (txn.id = txn_line.txn)
WHERE filled IS NOT NULL
AND filled > DATE(NOW()) - INTERVAL $days DAY
AND type = 'customer'
GROUP BY txn.id
) t
GROUP BY 1 DESC";
$r= $db->query($q)
or die_query($db, $q);
$sales= array();
while ($row= $r->fetch_assoc()) {
$row['total']= (float)$row['total'];
$sales[]= $row;
}
echo jsonp(array("days" => $days, "sales" => $sales));
| <?
include '../scat.php';
$days= (int)$_REQUEST['days'];
if (!$days) $days= 30;
$q= "SELECT DATE_FORMAT(filled, '%Y-%m-%d') day,
SUM(subtotal) AS total
FROM (SELECT
filled,
CAST(ROUND_TO_EVEN(
SUM(IF(type = 'customer', -1, 1) * allocated *
CASE discount_type
WHEN 'percentage'
THEN retail_price * ((100 - discount) / 100)
WHEN 'relative'
THEN (retail_price - discount)
WHEN 'fixed'
THEN (discount)
ELSE retail_price
END), 2) AS DECIMAL(9,2))
AS subtotal
FROM txn
LEFT JOIN txn_line ON (txn.id = txn_line.txn)
WHERE filled IS NOT NULL
AND filled > DATE(NOW()) - INTERVAL $days DAY
AND type = 'customer'
GROUP BY txn.id
) t
GROUP BY 1 DESC";
$r= $db->query($q)
or die_query($db, $q);
$sales= array();
while ($row= $r->fetch_assoc()) {
$row['total']= (float)$row['total'];
$sales[]= $row;
}
echo generate_jsonp(array("days" => $days, "sales" => $sales));
|
Fix copy&pasted extension config root node name | <?php
namespace OwsProxy3\CoreBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Christian Wygoda
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ows_proxy3_core');
$rootNode
->children()
->scalarNode('logging')
->defaultTrue()
->end()
->scalarNode('obfuscate_client_ip')
->defaultTrue()
->end()
->arrayNode("proxy")
->canBeUnset()
->addDefaultsIfNotSet()
->children()
->scalarNode('host')->defaultNull()->end()
->scalarNode('port')->defaultNull()->end()
->scalarNode('connecttimeout')->defaultNull()->end()
->scalarNode('timeout')->defaultNull()->end()
->scalarNode('user')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()
->scalarNode('checkssl')->defaultNull()->end()
->arrayNode("noproxy")
->prototype('scalar')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace OwsProxy3\CoreBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Christian Wygoda
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('fom_user');
$rootNode
->children()
->scalarNode('logging')
->defaultTrue()
->end()
->scalarNode('obfuscate_client_ip')
->defaultTrue()
->end()
->arrayNode("proxy")
->canBeUnset()
->addDefaultsIfNotSet()
->children()
->scalarNode('host')->defaultNull()->end()
->scalarNode('port')->defaultNull()->end()
->scalarNode('connecttimeout')->defaultNull()->end()
->scalarNode('timeout')->defaultNull()->end()
->scalarNode('user')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()
->scalarNode('checkssl')->defaultNull()->end()
->arrayNode("noproxy")
->prototype('scalar')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
} |
Fix missing comma in sohm al triggers | // Sohm Al (normal)
// Nobody remembers what to do here, so here's triggers.
[{
zoneRegex: /^Sohm Al$/,
triggers: [
{
id: 'Sohm Al Myath Stack',
regex: /1B:........:(\y{Name}):....:....:0017:0000:0000:0000:/,
alertText: function(data) {
if (data.matches[1] == data.me)
return 'Stack on YOU';
return 'Stack on ' + matches[1];
},
},
{
id: 'Sohm Al Myath Spread',
regex: /1B:........:(\y{Name}):....:....:00AE:0000:0000:0000:/,
alertText: function(data) {
if (data.matches[1] == data.me)
return 'Move away from others';
return 'Move away from ' + matches[1];
},
},
{
id: 'Sohm Al Myath Chyme',
regex: /:Added new combatant Chyme Of The Mountain/
alertText: function(data) { return 'Kill Chyme Add'; },
},
{
id: 'Sohm Al Tioman Meteor',
regex: /1B:........:(\y{Name}):....:....:0007:0000:0000:0000:/,
alertText: function(data) {
if (data.matches[1] == data.me)
return 'place meteor on edge';
},
},
]
}]
| // Sohm Al (normal)
// Nobody remembers what to do here, so here's triggers.
[{
zoneRegex: /^Sohm Al$/
triggers: [
{
id: 'Sohm Al Myath Stack',
regex: /1B:........:(\y{Name}):....:....:0017:0000:0000:0000:/,
alertText: function(data) {
if (data.matches[1] == data.me)
return 'Stack on YOU';
return 'Stack on ' + matches[1];
},
},
{
id: 'Sohm Al Myath Spread',
regex: /1B:........:(\y{Name}):....:....:00AE:0000:0000:0000:/,
alertText: function(data) {
if (data.matches[1] == data.me)
return 'Move away from others';
return 'Move away from ' + matches[1];
},
},
{
id: 'Sohm Al Myath Chyme',
regex: /:Added new combatant Chyme Of The Mountain/
alertText: function(data) { return 'Kill Chyme Add'; },
},
{
id: 'Sohm Al Tioman Meteor',
regex: /1B:........:(\y{Name}):....:....:0007:0000:0000:0000:/,
alertText: function(data) {
if (data.matches[1] == data.me)
return 'place meteor on edge';
},
},
]
}]
|
Add build as a possible environment option | """Add application.properties to Application's S3 Bucket directory."""
import logging
import argparse
from .create_archaius import init_properties
LOG = logging.getLogger(__name__)
def main():
"""Create application.properties for a given application."""
logging.basicConfig()
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument('-d',
'--debug',
action='store_const',
const=logging.DEBUG,
default=logging.INFO,
help='Set DEBUG output')
parser.add_argument('-e',
'--env',
choices=('build', 'dev', 'stage', 'prod'),
default='dev',
help='Deploy environment')
parser.add_argument('-g',
'--group',
default='extra',
help='Application Group name, e.g. forrest')
parser.add_argument('-a',
'--app',
default='unnecessary',
help='Application name, e.g. forrestcore')
args = parser.parse_args()
LOG.setLevel(args.debug)
logging.getLogger(__package__).setLevel(args.debug)
vars(args).pop('debug')
LOG.debug('Args: %s', vars(args))
init_properties(env=args.env, group=args.group, app=args.app)
if __name__ == '__main__':
main()
| """Add application.properties to Application's S3 Bucket directory."""
import logging
import argparse
from .create_archaius import init_properties
LOG = logging.getLogger(__name__)
def main():
"""Create application.properties for a given application."""
logging.basicConfig()
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument('-d',
'--debug',
action='store_const',
const=logging.DEBUG,
default=logging.INFO,
help='Set DEBUG output')
parser.add_argument('-e',
'--env',
choices=('dev', 'stage', 'prod'),
default='dev',
help='Deploy environment')
parser.add_argument('-g',
'--group',
default='extra',
help='Application Group name, e.g. forrest')
parser.add_argument('-a',
'--app',
default='unnecessary',
help='Application name, e.g. forrestcore')
args = parser.parse_args()
LOG.setLevel(args.debug)
logging.getLogger(__package__).setLevel(args.debug)
vars(args).pop('debug')
LOG.debug('Args: %s', vars(args))
init_properties(env=args.env, group=args.group, app=args.app)
if __name__ == '__main__':
main()
|
Move annotation type information before final keyword
Signed-off-by: Sebastian Hoß <[email protected]> | /*
* Copyright © 2013 Sebastian Hoß <[email protected]>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.github.sebhoss.nullanalysis;
import javax.annotation.Nullable;
/**
* Utility classes which helps working with legacy (nullable) APIs.
*/
public final class Nullsafe {
private Nullsafe() {
// utility class
}
/**
* @param reference
* A possible <code>null</code> reference.
* @return Either the reference itself, or an {@link NullPointerException}, in case the reference was
* <code>null</code>.
*/
public static <T> T nullsafe(final @Nullable T reference) {
if (reference != null) {
return reference;
}
throw new NullPointerException(); // NOPMD - we want to throw NPE here
}
/**
* @param reference
* A possible <code>null</code> reference.
* @param message
* The exception message to throw.
* @return Either the reference itself, or an {@link NullPointerException}, in case the reference was
* <code>null</code>.
*/
public static <T> T nullsafe(final @Nullable T reference, final String message) {
if (reference != null) {
return reference;
}
throw new NullPointerException(message); // NOPMD - we want to throw NPE here
}
}
| /*
* Copyright © 2013 Sebastian Hoß <[email protected]>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.github.sebhoss.nullanalysis;
import javax.annotation.Nullable;
/**
* Utility classes which helps working with legacy (nullable) APIs.
*/
public final class Nullsafe {
/**
* @param reference
* A possible <code>null</code> reference.
* @return Either the reference itself, or an {@link NullPointerException}, in case the reference was
* <code>null</code>.
*/
public static <T> T nullsafe(@Nullable final T reference) {
if (reference != null) {
return reference;
}
throw new NullPointerException(); // NOPMD - we want to throw NPE here
}
/**
* @param reference
* A possible <code>null</code> reference.
* @param message
* The exception message to throw.
* @return Either the reference itself, or an {@link NullPointerException}, in case the reference was
* <code>null</code>.
*/
public static <T> T nullsafe(@Nullable final T reference, final String message) {
if (reference != null) {
return reference;
}
throw new NullPointerException(message); // NOPMD - we want to throw NPE here
}
private Nullsafe() {
// utility class
}
}
|
Modify whitespaces according to ESLint, remove unused key and onClick | import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.copyBtnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
state = {
tooltipAttrs: {},
};
componentDidMount() {
this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
text: () => this.props.content,
});
this.clipboardRef.current.on('success', () => {
const self = this;
this.setState({
tooltipAttrs: {
'data-balloon': '複製成功!',
'data-balloon-visible': '',
'data-balloon-pos': 'up',
},
});
setTimeout(function() {
self.setState({ tooltipAttrs: {} });
}, 1000);
});
}
render() {
const { tooltipAttrs } = this.state;
return (
<button
ref={this.copyBtnRef}
className="btn-copy"
{...tooltipAttrs}
>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
| import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.copyBtnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
state = {
tooltipAttrs: {},
};
componentDidMount() {
this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
text: () => this.props.content,
});
this.clipboardRef.current.on('success', () => {
const self = this;
this.setState({
tooltipAttrs: {
'data-balloon': '複製成功!',
'data-balloon-visible': '',
'data-balloon-pos': 'up',
}});
setTimeout(function() {
self.setState({ tooltipAttrs: {} });
}, 1000);
});
}
render() {
return (
<button
ref={this.copyBtnRef}
key="copy"
onClick={() => {}}
className="btn-copy"
{ ...this.state.tooltipAttrs }
>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
|
Change truncate to delete from in db abstraction. Truncate is not getting rolled back in the new h2 db version, leaving things in a dirty state after failed block application. | package nxt.db;
import nxt.Nxt;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class DerivedDbTable {
protected final String table;
protected DerivedDbTable(String table) {
this.table = table;
Nxt.getBlockchainProcessor().registerDerivedTable(this);
}
public void rollback(int height) {
if (!Db.isInTransaction()) {
throw new IllegalStateException("Not in transaction");
}
try (Connection con = Db.getConnection();
PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
pstmtDelete.setInt(1, height);
pstmtDelete.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public void truncate() {
if (!Db.isInTransaction()) {
throw new IllegalStateException("Not in transaction");
}
try (Connection con = Db.getConnection();
Statement stmt = con.createStatement()) {
stmt.executeUpdate("DELETE FROM " + table);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public void trim(int height) {
//nothing to trim
}
public void finish() {
}
}
| package nxt.db;
import nxt.Nxt;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class DerivedDbTable {
protected final String table;
protected DerivedDbTable(String table) {
this.table = table;
Nxt.getBlockchainProcessor().registerDerivedTable(this);
}
public void rollback(int height) {
if (!Db.isInTransaction()) {
throw new IllegalStateException("Not in transaction");
}
try (Connection con = Db.getConnection();
PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
pstmtDelete.setInt(1, height);
pstmtDelete.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public void truncate() {
if (!Db.isInTransaction()) {
throw new IllegalStateException("Not in transaction");
}
try (Connection con = Db.getConnection();
Statement stmt = con.createStatement()) {
stmt.executeUpdate("TRUNCATE TABLE " + table);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public void trim(int height) {
//nothing to trim
}
public void finish() {
}
}
|
Change the way a method is called | window.$claudia = {
throttle: function (func, time) {
var wait = false
return function () {
if (wait) return
wait = true
setTimeout(function () {
func()
wait = false
}, time || 100)
}
},
fadeInImage: function(imgs, imageLoadedCallback) {
var images = imgs || document.querySelectorAll('.js-img-fadeIn')
function loaded(event) {
var image = event.currentTarget
image.style.transition = 'opacity 320ms'
image.style.opacity = 1
imageLoadedCallback && imageLoadedCallback(image)
}
images.forEach(function (img) {
if (img.complete) {
return loaded({ currentTarget: img })
}
img.addEventListener('load', loaded)
})
},
blurBackdropImg: function(image) {
if (!image.dataset.backdrop) return
var parent = image.parentElement //TODO: Not finish yes, must be a pure function
var parentWidth = Math.round(parent.getBoundingClientRect().width)
var childImgWidth = Math.round(image.getBoundingClientRect().width)
var isCovered = parentWidth === childImgWidth
var blurImg = parent.previousElementSibling //TODO: Not finish yes, must be a pure function
isCovered ? blurImg.classList.add('is-hidden') : blurImg.classList.remove('is-hidden')
},
}
| window.$claudia = {
imgAddLoadedEvent: function () {
var images = document.querySelectorAll('.js-progressive-loading')
// TODO: type is image ?
// TODO: read data-backdrop
function loaded(event) {
var image = event.currentTarget
var parent = image.parentElement
var parentWidth = Math.round(parent.getBoundingClientRect().width)
var childImgWidth = Math.round(image.getBoundingClientRect().width)
image.style.opacity = 1
var isCovered = parentWidth === childImgWidth
var blurImg = parent.previousElementSibling
if (isCovered) {
blurImg.classList.add('is-hidden')
return
}
blurImg.classList.remove('is-hidden')
}
function eachImage(noNeedLoadEvt) {
images.forEach(function (img) {
if (img.complete) {
loaded({ currentTarget: img })
return
}
if (noNeedLoadEvt) return
img.addEventListener('load', loaded)
})
}
// 截流
function throttle(func, time) {
var wait = false
return function () {
if (wait) return
wait = true
setTimeout(function () {
func()
wait = false
}, time)
}
}
window.addEventListener('resize', throttle(function () { eachImage(true) }, 100))
eachImage()
}
}
document.addEventListener('DOMContentLoaded', function () {
$claudia.imgAddLoadedEvent()
})
|
Fix failing API gen test | import unittest
from falafel.tools import generate_api_config
class TestAPIGen(unittest.TestCase):
@classmethod
def setUpClass(cls):
from falafel.mappers import * # noqa
pass
def setUp(self):
self.latest = generate_api_config.APIConfigGenerator(plugin_package="falafel").serialize_data_spec()
def tearDown(self):
self.latest = None
def test_top_level(self):
# these sections must exist and not be empty
for each in ['version', 'files', 'commands', 'specs', 'pre_commands', 'meta_specs']:
self.assertIn(each, self.latest)
self.assertGreater(len(self.latest[each]), 0)
def test_meta_specs(self):
# these sections must exist in the meta_specs, have a 'archive_file_name' field,
# and it must not be empty
for each in ['analysis_target', 'branch_info', 'machine-id', 'uploader_log']:
self.assertIn(each, self.latest['meta_specs'])
self.assertIn('archive_file_name', self.latest['meta_specs'][each])
self.assertGreater(len(self.latest['meta_specs'][each]['archive_file_name']), 0)
def test_specs(self):
# check that each spec only has target sections for known targets
for eachspec in self.latest['specs']:
for eachtarget in self.latest['specs'][eachspec]:
self.assertIn(eachtarget, ['host', 'docker_container', 'docker_image'])
| import unittest
from tools import generate_api_config
class TestAPIGen(unittest.TestCase):
@classmethod
def setUpClass(cls):
from falafel.mappers import * # noqa
pass
def setUp(self):
self.latest = generate_api_config.APIConfigGenerator(plugin_package="falafel").serialize_data_spec()
def tearDown(self):
self.latest = None
def test_top_level(self):
# these sections must exist and not be empty
for each in ['version', 'files', 'commands', 'specs', 'pre_commands', 'meta_specs']:
self.assertIn(each, self.latest)
self.assertGreater(len(self.latest[each]), 0)
def test_meta_specs(self):
# these sections must exist in the meta_specs, have a 'archive_file_name' field,
# and it must not be empty
for each in ['analysis_target', 'branch_info', 'machine-id', 'uploader_log']:
self.assertIn(each, self.latest['meta_specs'])
self.assertIn('archive_file_name', self.latest['meta_specs'][each])
self.assertGreater(len(self.latest['meta_specs'][each]['archive_file_name']), 0)
def test_specs(self):
# check that each spec only has target sections for known targets
for eachspec in self.latest['specs']:
for eachtarget in self.latest['specs'][eachspec]:
self.assertIn(eachtarget, ['host', 'docker_container', 'docker_image'])
|
Remove Sf4.2 deprecation on TreeBuilder constructor | <?php
namespace AlterPHP\EasyAdminExtensionBundle\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/configuration.html}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('easy_admin_extension');
$treeBuilder
->getRootNode()
->children()
->arrayNode('custom_form_types')
->useAttributeAsKey('short_name')
->prototype('scalar')
->validate()
->ifTrue(function ($v) {
return !\class_exists($v);
})
->thenInvalid('Class %s for custom type does not exist !')
->end()
->end()
->end()
->scalarNode('minimum_role')
->defaultNull()
->end()
->arrayNode('embedded_list')
->addDefaultsIfNotSet()
->children()
->booleanNode('open_new_tab')
->defaultTrue()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
| <?php
namespace AlterPHP\EasyAdminExtensionBundle\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/configuration.html}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('easy_admin_extension');
$rootNode
->children()
->arrayNode('custom_form_types')
->useAttributeAsKey('short_name')
->prototype('scalar')
->validate()
->ifTrue(function ($v) {
return !\class_exists($v);
})
->thenInvalid('Class %s for custom type does not exist !')
->end()
->end()
->end()
->scalarNode('minimum_role')
->defaultNull()
->end()
->arrayNode('embedded_list')
->addDefaultsIfNotSet()
->children()
->booleanNode('open_new_tab')
->defaultTrue()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
|
Move requires to the top of the template | /*
* Copyright 2011 eBay Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var varNameRegExp = /^[A-Za-z_][A-Za-z0-9_]*$/;
function RequireNode(props) {
RequireNode.$super.call(this);
if (props) {
this.setProperties(props);
}
}
RequireNode.prototype = {
javaScriptOnly: true,
doGenerateCode: function (template) {
var module = this.getProperty('module');
var varName = this.getProperty('var');
if (!module) {
this.addError('"module" attribute is required');
}
if (!varName) {
this.addError('"varName" attribute is required');
}
if (module && varName) {
template.addStaticVar(varName, 'require(' + module + ')');
}
}
};
require('raptor-util').inherit(RequireNode, require('../../compiler').Node);
module.exports = RequireNode; | /*
* Copyright 2011 eBay Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var varNameRegExp = /^[A-Za-z_][A-Za-z0-9_]*$/;
function RequireNode(props) {
RequireNode.$super.call(this);
if (props) {
this.setProperties(props);
}
}
RequireNode.prototype = {
javaScriptOnly: true,
doGenerateCode: function (template) {
var module = this.getProperty('module');
var varName = this.getProperty('var');
if (!module) {
this.addError('"module" attribute is required');
}
if (!varName) {
this.addError('"varName" attribute is required');
}
if (module && varName) {
template.statement('var ' + varName + '=require(' + module + ');');
}
}
};
require('raptor-util').inherit(RequireNode, require('../../compiler').Node);
module.exports = RequireNode; |
Fix summary - pypi doesn't allow multiple lines | from setuptools import setup
setup(
name='django-markwhat',
version=".".join(map(str, __import__('django_markwhat').__version__)),
packages=['django_markwhat', 'django_markwhat.templatetags'],
url='http://pypi.python.org/pypi/django-markwhat',
license=open('LICENSE').read(),
author='Alireza Savand',
author_email='[email protected]',
install_requires=['Django', ],
description="A collection of template filters that implement " + \
"common markup languages.",
long_description=open('README.rst').read(),
keywords=[
'django',
'markdown',
'markup',
'textile',
'rst',
'reStructuredText',
'docutils',
'commonmark',
'web'
],
platforms='OS Independent',
classifiers=[
"Development Status :: 5 - Production/Stable",
"Development Status :: 6 - Mature",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
],
)
| from setuptools import setup
setup(
name='django-markwhat',
version=".".join(map(str, __import__('django_markwhat').__version__)),
packages=['django_markwhat', 'django_markwhat.templatetags'],
url='http://pypi.python.org/pypi/django-markwhat',
license=open('LICENSE').read(),
author='Alireza Savand',
author_email='[email protected]',
install_requires=['Django', ],
description="""A collection of template filters that implement
common markup languages.""",
long_description=open('README.rst').read(),
keywords=[
'django',
'markdown',
'markup',
'textile',
'rst',
'reStructuredText',
'docutils',
'commonmark',
'web'
],
platforms='OS Independent',
classifiers=[
"Development Status :: 5 - Production/Stable",
"Development Status :: 6 - Mature",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
],
)
|
Add view __call method for testing. | <?php
/**
* \YafUnit\View 通过模拟一个无法渲染无法读取模板的视图引擎获取视图中变量
* 子类\Yaf\View\Simple
* @author Lancer He <[email protected]>
* @since 2014-04-18
* @update 2015-07-10
*/
namespace YafUnit\View;
final class Simple extends \Yaf\View\Simple {
protected static $_instance = null;
/**
* 初始化一个单例对象,不需要模板路径以及任何渲染参数,随意设置一个模板路径
* @return View object
*/
public static function getInstance() {
if ( ! self::$_instance) {
self::$_instance = new self( __DIR__, [] );
}
return self::$_instance;
}
/**
* 渲染为空
* @param string $view_path 视图路径
* @param array $tpl_vars 变量
* @return false
*/
public function render( $view_path, $tpl_vars = null ) {
return false;
}
/**
* 读取模板为空
* @param string $view_path 视图路径
* @param array $tpl_vars 变量
* @return false
*/
public function display( $view_path, $tpl_vars = null) {
return false;
}
/**
* 继承Simple类的其他方法通过assign做验收测试
*/
public function __call($name, $args) {
$this->assign($name, $args);
}
} | <?php
/**
* \YafUnit\View 通过模拟一个无法渲染无法读取模板的视图引擎获取视图中变量
* 子类\Yaf\View\Simple
* @author Lancer He <[email protected]>
* @since 2014-04-18
* @update 2015-07-10
*/
namespace YafUnit\View;
final class Simple extends \Yaf\View\Simple {
protected static $_instance = null;
/**
* 初始化一个单例对象,不需要模板路径以及任何渲染参数,随意设置一个模板路径
* @return View object
*/
public static function getInstance() {
if ( ! self::$_instance) {
self::$_instance = new self( __DIR__, [] );
}
return self::$_instance;
}
/**
* 渲染为空
* @param string $view_path 视图路径
* @param array $tpl_vars 变量
* @return false
*/
public function render( $view_path, $tpl_vars = null ) {
return false;
}
/**
* 读取模板为空
* @param string $view_path 视图路径
* @param array $tpl_vars 变量
* @return false
*/
public function display( $view_path, $tpl_vars = null) {
return false;
}
} |
Resolve all paths to CWD | var metaRouter = require('../');
var DataHolder = require('raptor-async/DataHolder');
var nodePath = require('path');
module.exports = function match(routes) {
var matcher;
var matcherDataHolder;
if (typeof routes === 'string') {
routes = nodePath.resolve(process.cwd(), routes);
matcherDataHolder = new DataHolder();
metaRouter.routesLoader.load(routes, function(err, routes) {
if (err) {
return matcherDataHolder.reject(err);
}
matcher = metaRouter.buildMatcher(routes);
matcherDataHolder.resolve(matcher);
});
} else {
matcher = metaRouter.buildMatcher(routes);
}
function go(matcher, req, res, next) {
var match = matcher.match(req.method, req.path);
if (match) {
req.route = match;
}
next();
}
return function(req, res, next) {
if (matcher) {
go(matcher, req, res, next);
} else {
matcherDataHolder.done(function(err, matcher) {
if (err) {
return next(err);
}
go(matcher, req, res, next);
});
}
};
}; | var metaRouter = require('../');
var DataHolder = require('raptor-async/DataHolder');
module.exports = function match(routes) {
var matcher;
var matcherDataHolder;
if (typeof routes === 'string') {
matcherDataHolder = new DataHolder();
metaRouter.routesLoader.load(routes, function(err, routes) {
if (err) {
return matcherDataHolder.reject(err);
}
matcher = metaRouter.buildMatcher(routes);
matcherDataHolder.resolve(matcher);
});
} else {
matcher = metaRouter.buildMatcher(routes);
}
function go(matcher, req, res, next) {
var match = matcher.match(req.method, req.path);
if (match) {
req.route = match;
}
next();
}
return function(req, res, next) {
if (matcher) {
go(matcher, req, res, next);
} else {
matcherDataHolder.done(function(err, matcher) {
if (err) {
return next(err);
}
go(matcher, req, res, next);
});
}
};
}; |
Fix path to packaged sinon test dependency | module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ],
plugins: [
'karma-mocha',
'karma-coverage',
'karma-coveralls',
'karma-phantomjs-launcher',
'karma-mocha-reporter'
],
frameworks: [ 'mocha' ],
reporters: [ 'mocha', 'coverage', 'coveralls' ],
client: {
mocha: {
ui: 'bdd'
}
},
basePath: '../',
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/sinon/pkg/sinon.js',
'node_modules/unexpected/unexpected.js',
'node_modules/unexpected-sinon/lib/unexpected-sinon.js',
'src/*.js',
'src/**/*.js',
'test/bootstrap.js',
'test/**/*.spec.js'
],
preprocessors: {
'src/**/*.js': [ 'coverage' ]
},
coverageReporter: {
type : 'lcov',
dir : 'coverage/'
},
singleRun: true
});
};
| module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ],
plugins: [
'karma-mocha',
'karma-coverage',
'karma-coveralls',
'karma-phantomjs-launcher',
'karma-mocha-reporter'
],
frameworks: [ 'mocha' ],
reporters: [ 'mocha', 'coverage', 'coveralls' ],
client: {
mocha: {
ui: 'bdd'
}
},
basePath: '../',
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/sinon/pkg/sinon-1.17.4.js',
'node_modules/unexpected/unexpected.js',
'node_modules/unexpected-sinon/lib/unexpected-sinon.js',
'src/*.js',
'src/**/*.js',
'test/bootstrap.js',
'test/**/*.spec.js'
],
preprocessors: {
'src/**/*.js': [ 'coverage' ]
},
coverageReporter: {
type : 'lcov',
dir : 'coverage/'
},
singleRun: true
});
};
|
Allow compilation even in debug mode | import os
import subprocess
import tempfile
from webassets.filter import Filter
from webassets.exceptions import FilterError
__all__ = ('TypeScript',)
class TypeScript(Filter):
"""Compile `TypeScript <http://www.typescriptlang.org`_ to JavaScript.
TypeScript is an external tool written for NodeJS.
This filter assumes that the ``tsc`` executable is in the path. Otherwise, you
may define the ``TYPESCRIPT_BIN`` setting.
"""
name = 'typescript'
max_debug_level = None
options = {
'binary': 'TYPESCRIPT_BIN',
}
def output(self, _in, out, **kw):
# The typescript compiler cannot read a file which does not have
# the .ts extension
input_filename = tempfile.mktemp() + ".ts"
output_filename = tempfile.mktemp()
with open(input_filename, 'wb') as f:
f.write(_in.read())
args = [self.binary or 'tsc', '--out', output_filename, input_filename]
proc = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise FilterError("typescript: subprocess had error: stderr=%s," % stderr +
"stdout=%s, returncode=%s" % (stdout, proc.returncode))
with open(output_filename, 'rb') as f:
out.write(f.read())
os.unlink(input_filename)
os.unlink(output_filename)
| import os
import subprocess
import tempfile
from webassets.filter import Filter
from webassets.exceptions import FilterError
__all__ = ('TypeScript',)
class TypeScript(Filter):
"""Compile `TypeScript <http://www.typescriptlang.org`_ to JavaScript.
TypeScript is an external tool written for NodeJS.
This filter assumes that the ``tsc`` executable is in the path. Otherwise, you
may define the ``TYPESCRIPT_BIN`` setting.
"""
name = 'typescript'
options = {
'binary': 'TYPESCRIPT_BIN',
}
def output(self, _in, out, **kw):
# The typescript compiler cannot read a file which does not have
# the .ts extension
input_filename = tempfile.mktemp() + ".ts"
output_filename = tempfile.mktemp()
with open(input_filename, 'wb') as f:
f.write(_in.read())
args = [self.binary or 'tsc', '--out', output_filename, input_filename]
proc = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise FilterError("typescript: subprocess had error: stderr=%s," % stderr +
"stdout=%s, returncode=%s" % (stdout, proc.returncode))
with open(output_filename, 'rb') as f:
out.write(f.read())
os.unlink(input_filename)
os.unlink(output_filename)
|
Fix one more style error | package seedu.bulletjournal.logic.parser;
/**
* Provides variations of commands Note: hard-coded for v0.2, will implement nlp
* for future versions
* @author Tu An - arishuynhvan
*/
public class FlexibleCommand {
private String commandFromUser = "";
private String[] commandGroups = new String[] { "add a adds create creates new", "clear clr c clears empty empties",
"delete d deletes del remove removes rm", "edit edits e change changes",
"exit exits close closes logout logouts", "find finds f search searches lookup",
"help helps h manual instruction instructions", "list lists l ls show shows display displays showall",
"select selects s choose chooses" };
/**
* Constructor must take in a valid string input
* @param cfu
*/
public FlexibleCommand(String cfu) {
commandFromUser = cfu;
}
/**
* @return the correct command string that matches COMMAND_WORD of command
* classes
*/
public String getCommandWord() {
for (String commandGroup : commandGroups) {
for (String command : commandGroup.split(" ")) {
if (commandFromUser.equals(command)) {
return commandGroup.split(" ")[0];
}
}
}
return commandFromUser;
}
public boolean isValidCommand() {
for (String commandGroup : commandGroups) {
for (String command : commandGroup.split(" ")) {
if (commandFromUser.equals(command))
return true;
}
}
return false;
}
}
| package seedu.bulletjournal.logic.parser;
/**
* Provides variations of commands Note: hard-coded for v0.2, will implement nlp
* for future versions
* @author Tu An - arishuynhvan
*/
public class FlexibleCommand {
private String commandFromUser = "";
private String[] commandGroups = new String[] { "add a adds create creates new", "clear clr c clears empty empties",
"delete d deletes del remove removes rm", "edit edits e change changes",
"exit exits close closes logout logouts", "find finds f search searches lookup",
"help helps h manual instruction instructions", "list lists l ls show shows display displays showall",
"select selects s choose chooses" };
/**
* Constructor must take in a valid string input
* @param cfu
*/
public FlexibleCommand(String cfu) {
commandFromUser = cfu;
}
/**
* @return the correct command string that matches COMMAND_WORD of command
* classes
*/
public String getCommandWord() {
for (String commandGroup : commandGroups) {
for (String command : commandGroup.split(" ")) {
if (commandFromUser.equals(command))
return commandGroup.split(" ")[0];
}
}
return commandFromUser;
}
public boolean isValidCommand() {
for (String commandGroup : commandGroups) {
for (String command : commandGroup.split(" ")) {
if (commandFromUser.equals(command))
return true;
}
}
return false;
}
}
|
Increase version and switch location to new upstream. | from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"update_catalog": babel.update_catalog,}
except ImportError:
cmdclass = {}
setup(name="django-money",
version="0.2",
description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as the money implementation.",
url="https://github.com/reinbach/django-money",
packages=["djmoney",
"djmoney.forms",
"djmoney.models"],
install_requires=['setuptools',
'Django >= 1.2',
'py-moneyed > 0.4'],
cmdclass = cmdclass,
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Django",])
| from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"update_catalog": babel.update_catalog,}
except ImportError:
cmdclass = {}
setup(name="django-money",
version="0.1",
description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.",
url="https://github.com/jakewins/django-money",
packages=["djmoney",
"djmoney.forms",
"djmoney.models"],
install_requires=['setuptools',
'Django >= 1.2',
'py-moneyed > 0.4'],
cmdclass = cmdclass,
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Django",])
|
Clean up now that we're no longer trying to use CSV_URL. | import os
try:
from urllib.parse import urljoin
from urllib.request import urlopen
except:
# for Python 2.7 compatibility
from urlparse import urljoin
from urllib2 import urlopen
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.conf import settings
class DataFileView(View):
file_name = None
def get(self, request):
csv = self._get_csv()
return HttpResponse(csv)
def _get_csv(self):
try:
url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name)
with urlopen(url) as response:
data = response.read()
except ValueError:
url = urljoin('file://', getattr(settings, 'CSV_ROOT', None))
url = urljoin(url, self.file_name)
with urlopen(url) as response:
data = response.read()
except Exception as err:
data = "Error: {}".format(err)
return data
class MajorCourse(DataFileView):
file_name = "Majors_and_Courses.csv"
class DataMap(DataFileView):
file_name = "Data_Map.csv"
class StudentData(DataFileView):
file_name = "Student_Data_All_Majors.csv"
class StatusLookup(DataFileView):
file_name = "Status_Lookup.csv"
| import os
try:
from urllib.parse import urljoin
from urllib.request import urlopen
except:
# for Python 2.7 compatibility
from urlparse import urljoin
from urllib2 import urlopen
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.conf import settings
class DataFileView(View):
file_name = None
def get(self, request):
csv = self._get_csv()
return HttpResponse(csv)
def _get_csv(self):
if hasattr(settings, 'CSV_URL') and settings.CSV_URL is not None and settings.CSV_URL != '':
url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name)
elif hasattr(settings, 'CSV_ROOT') and settings.CSV_ROOT is not None and settings.CSV_ROOT != '':
url = urljoin('file://', getattr(settings, 'CSV_ROOT', None))
url = urljoin(url, self.file_name)
with urlopen(url) as response:
data = response.read()
return data
class MajorCourse(DataFileView):
file_name = "Majors_and_Courses.csv"
class DataMap(DataFileView):
file_name = "Data_Map.csv"
class StudentData(DataFileView):
file_name = "Student_Data_All_Majors.csv"
class StatusLookup(DataFileView):
file_name = "Status_Lookup.csv"
|
Set the POI being saved on the Favourite model | define(['jquery', 'backbone', 'underscore', 'moxie.conf', 'hbs!places/templates/detail', 'hbs!places/templates/busrti', 'hbs!places/templates/trainrti'],
function($, Backbone, _, conf, detailTemplate, busRTITemplate, trainRTITemplate){
var RTI_REFRESH = 15000; // 15 seconds
var DetailView = Backbone.View.extend({
initialize: function() {
Backbone.trigger('domchange:title', this.model.get('name'));
Backbone.on('favourited', _.bind(this.favourited, this));
},
attributes: {
'class': 'detail-map'
},
serialize: function() {
var poi = this.model.toJSON();
return {
poi: poi,
multiRTI: poi.RTI.length > 1,
alternateRTI: this.model.getAlternateRTI(),
currentRTI: this.model.getCurrentRTI()
};
},
template: detailTemplate,
manage: true,
afterRender: function() {
if (this.model.get('RTI')) {
this.refreshID = this.model.renderRTI(this.$('#poi-rti')[0], RTI_REFRESH);
}
},
favourited: function(fav) {
fav.set('options', {model: this.model.toJSON()});
fav.set('type', 'poi:'+this.model.get('type'));
fav.save();
},
cleanup: function() {
Backbone.off('favourited');
clearInterval(this.refreshID);
}
});
return DetailView;
});
| define(['jquery', 'backbone', 'underscore', 'moxie.conf', 'hbs!places/templates/detail', 'hbs!places/templates/busrti', 'hbs!places/templates/trainrti'],
function($, Backbone, _, conf, detailTemplate, busRTITemplate, trainRTITemplate){
var RTI_REFRESH = 15000; // 15 seconds
var DetailView = Backbone.View.extend({
attributes: {
'class': 'detail-map'
},
serialize: function() {
var poi = this.model.toJSON();
return {
poi: poi,
multiRTI: poi.RTI.length > 1,
alternateRTI: this.model.getAlternateRTI(),
currentRTI: this.model.getCurrentRTI()
};
},
template: detailTemplate,
manage: true,
afterRender: function() {
Backbone.trigger('domchange:title', this.model.get('name'));
if (this.model.get('RTI')) {
this.refreshID = this.model.renderRTI(this.$('#poi-rti')[0], RTI_REFRESH);
}
},
cleanup: function() {
clearInterval(this.refreshID);
}
});
return DetailView;
});
|
Update iDeal plugin for Symfony 3 | <?php
namespace Ruudk\Payment\MultisafepayBundle\Plugin;
use JMS\Payment\CoreBundle\Model\FinancialTransactionInterface;
use JMS\Payment\CoreBundle\Model\PaymentInstructionInterface;
use JMS\Payment\CoreBundle\Plugin\ErrorBuilder;
use Ruudk\Payment\MultisafepayBundle\Form\IdealType;
class IdealPlugin extends DefaultPlugin
{
public function processes($name)
{
return $name === IdealType::class;
}
public function checkPaymentInstruction(PaymentInstructionInterface $instruction)
{
$errorBuilder = new ErrorBuilder();
/**
* @var \JMS\Payment\CoreBundle\Entity\ExtendedData $data
*/
$data = $instruction->getExtendedData();
if(!$data->get('bank')) {
$errorBuilder->addDataError('data_Ruudk_Payment_MultisafepayBundle_Form_IdealType.bank', 'form.error.bank_required');
}
if ($errorBuilder->hasErrors()) {
throw $errorBuilder->getException();
}
}
/**
* @param FinancialTransactionInterface $transaction
* @return array
*/
protected function getPurchaseParameters(FinancialTransactionInterface $transaction)
{
/**
* @var \JMS\Payment\CoreBundle\Model\ExtendedDataInterface $data
*/
$data = $transaction->getExtendedData();
$parameters = parent::getPurchaseParameters($transaction);
$parameters['issuer'] = $data->get('bank');
return $parameters;
}
}
| <?php
namespace Ruudk\Payment\MultisafepayBundle\Plugin;
use JMS\Payment\CoreBundle\Model\FinancialTransactionInterface;
use JMS\Payment\CoreBundle\Model\PaymentInstructionInterface;
use JMS\Payment\CoreBundle\Plugin\ErrorBuilder;
class IdealPlugin extends DefaultPlugin
{
public function processes($name)
{
return 'multisafepay_ideal' === $name;
}
public function checkPaymentInstruction(PaymentInstructionInterface $instruction)
{
$errorBuilder = new ErrorBuilder();
/**
* @var \JMS\Payment\CoreBundle\Entity\ExtendedData $data
*/
$data = $instruction->getExtendedData();
if(!$data->get('bank')) {
$errorBuilder->addDataError('data_multisafepay_ideal.bank', 'form.error.bank_required');
}
if ($errorBuilder->hasErrors()) {
throw $errorBuilder->getException();
}
}
/**
* @param FinancialTransactionInterface $transaction
* @return array
*/
protected function getPurchaseParameters(FinancialTransactionInterface $transaction)
{
/**
* @var \JMS\Payment\CoreBundle\Model\ExtendedDataInterface $data
*/
$data = $transaction->getExtendedData();
$parameters = parent::getPurchaseParameters($transaction);
$parameters['issuer'] = $data->get('bank');
return $parameters;
}
}
|
Use native method to get status code from response | <?php
namespace Omnipay\GoPay\Message;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;
class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
/**
* Is the response successful?
*
* @return boolean
*/
public function isSuccessful()
{
$redirectUrl = $this->getRedirectUrl();
return is_string($redirectUrl);
}
/**
* Gets the redirect target url.
*/
public function getRedirectUrl()
{
if (!is_array($this->data) || !isset($this->data['gw_url']) || !is_string($this->data['gw_url'])) {
return null;
}
return $this->data['gw_url'];
}
/**
* Get the required redirect method (either GET or POST).
*/
public function getRedirectMethod()
{
return 'GET';
}
/**
* Gets the redirect form data array, if the redirect method is POST.
*/
public function getRedirectData()
{
return null;
}
public function getCode()
{
if (isset($this->data['state'])) {
return $this->data['state'];
}
return null;
}
public function getTransactionReference()
{
if (isset($this->data['id'])) {
return $this->data['id'];
}
return null;
}
public function getTransactionId()
{
if (isset($this->data['order_number'])) {
return $this->data['order_number'];
}
return null;
}
} | <?php
namespace Omnipay\GoPay\Message;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;
class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
/**
* Is the response successful?
*
* @return boolean
*/
public function isSuccessful()
{
$redirectUrl = $this->getRedirectUrl();
return is_string($redirectUrl);
}
/**
* Gets the redirect target url.
*/
public function getRedirectUrl()
{
if (!is_array($this->data) || !isset($this->data['gw_url']) || !is_string($this->data['gw_url'])) {
return null;
}
return $this->data['gw_url'];
}
/**
* Get the required redirect method (either GET or POST).
*/
public function getRedirectMethod()
{
return 'GET';
}
/**
* Gets the redirect form data array, if the redirect method is POST.
*/
public function getRedirectData()
{
return null;
}
/**
* @return string
*/
public function getState()
{
return $this->data['state'];
}
public function getTransactionReference()
{
if (isset($this->data['id'])) {
return $this->data['id'];
}
return null;
}
public function getTransactionId()
{
if (isset($this->data['order_number'])) {
return $this->data['order_number'];
}
return null;
}
} |
Add photo to avatar if possible | import React from 'react'
import { ScrollView, View } from 'react-native'
import { List, ListItem, SearchBar } from 'react-native-elements'
import PropTypes from 'prop-types'
function PersonListView({colors, styles, list, handlePress}) {
return (
<View style={styles.container}>
<SearchBar
lightTheme
placeholderTextColor={colors.tintColor}
textColor={colors.tintColor}
containerStyle={styles.searchBarContainer}
inputStyle={styles.searchBarInput}
icon={{color: colors.tintColor}}
clearButtonMode='always'
placeholder='Buscar'
/>
<ScrollView style={styles.container}>
<List containerStyle={styles.list}>
{
list.map((l, i) => (
<ListItem
roundAvatar
avatar={{uri:l.photos.length > 0? l.photos[0].url : undefined}}
key={i}
subtitle={l.subtitle}
title={l.name}
onPress={() => handlePress(l)}
/>
))
}
</List>
</ScrollView>
</View>
)
}
PersonListView.propTypes = {
colors: PropTypes.object.isRequired,
styles: PropTypes.object.isRequired,
list: PropTypes.array.isRequired,
handlePress: PropTypes.func.isRequired,
}
export default PersonListView
| import React from 'react'
import { ScrollView, View } from 'react-native'
import { List, ListItem, SearchBar } from 'react-native-elements'
import PropTypes from 'prop-types'
function PersonListView({colors, styles, list, handlePress}) {
return (
<View style={styles.container}>
<SearchBar
lightTheme
placeholderTextColor={colors.tintColor}
textColor={colors.tintColor}
containerStyle={styles.searchBarContainer}
inputStyle={styles.searchBarInput}
icon={{color: colors.tintColor}}
clearButtonMode='always'
placeholder='Buscar'
/>
<ScrollView style={styles.container}>
<List containerStyle={styles.list}>
{
list.map((l, i) => (
<ListItem
roundAvatar
avatar={{uri:undefined}}
key={i}
subtitle={l.subtitle}
title={l.name}
onPress={() => handlePress(l)}
/>
))
}
</List>
</ScrollView>
</View>
)
}
PersonListView.propTypes = {
colors: PropTypes.object.isRequired,
styles: PropTypes.object.isRequired,
list: PropTypes.array.isRequired,
handlePress: PropTypes.func.isRequired,
}
export default PersonListView
|
Check if mail config exists | <?php
/*
* This file is part of WordPlate.
*
* (c) Vincent Klaiber <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WordPlate\WordPress\Components;
use PHPMailer;
/**
* This is the mail component.
*
* @author Vincent Klaiber <[email protected]>
*/
final class Mail extends Component
{
/**
* Bootstrap the component.
*
* @return void
*/
public function register()
{
$this->action->add('phpmailer_init', [$this, 'mail']);
}
/**
* Register custom SMTP mailer.
*
* @param \PHPMailer $mail
*
* @return \PHPMailer
*/
public function mail(PHPMailer $mail)
{
if (config('mail')) {
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = config('mail.host');
$mail->Port = config('mail.port');
$mail->Username = config('mail.username');
$mail->Password = config('mail.password');
if (empty($mail->From)) {
$mail->From = config('mail.from.address');
}
if (empty($mail->FromName)) {
$mail->From = config('mail.from.name');
}
return $mail;
}
}
}
| <?php
/*
* This file is part of WordPlate.
*
* (c) Vincent Klaiber <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WordPlate\WordPress\Components;
use PHPMailer;
/**
* This is the mail component.
*
* @author Vincent Klaiber <[email protected]>
*/
final class Mail extends Component
{
/**
* Bootstrap the component.
*
* @return void
*/
public function register()
{
if (config('mail.host') && config('mail.username') && config('mail.password')) {
$this->action->add('phpmailer_init', [$this, 'mail']);
}
}
/**
* Register custom SMTP mailer.
*
* @param \PHPMailer $mail
*
* @return \PHPMailer
*/
public function mail(PHPMailer $mail)
{
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = config('mail.host');
$mail->Port = config('mail.port');
$mail->Username = config('mail.username');
$mail->Password = config('mail.password');
if (empty($mail->From)) {
$mail->From = config('mail.from.address');
}
if (empty($mail->FromName)) {
$mail->From = config('mail.from.name');
}
return $mail;
}
}
|
Set whether to use count walker for iterator count
Can get the following error:
```
Cannot count query that uses a HAVING clause. Use the output walkers for pagination
```
This can happen when attempting to iterate over a query containing a 'HAVING' clause. Allowing the user to set that a count walker shouldn't be used to get a count, the error won't happen.
Seen when performing a bulk action on a datagrid with a filter enabled that has the `filter_by_having` property set to `true`. | <?php
namespace Oro\Bundle\DataGridBundle\Datasource\Orm;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\DataGridBundle\Datasource\ResultRecord;
use Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator;
/**
* Iterates query result with elements of ResultRecord type
*/
class IterableResult extends BufferedQueryResultIterator implements IterableResultInterface
{
/**
* @var QueryBuilder|Query
*/
private $source;
/**
* Current ResultRecord, populated from query result row
*
* @var mixed
*/
private $current = null;
/**
* Constructor
*
* @param QueryBuilder|Query $source
* @param null|bool $useCountWalker
*/
public function __construct($source, $useCountWalker = null)
{
parent::__construct($source, $useCountWalker);
$this->source = $source;
}
/**
* {@inheritDoc}
*/
public function current()
{
return $this->current;
}
/**
* {@inheritDoc}
*/
public function next()
{
parent::next();
$current = parent::current();
$this->current = $current === null
? null
: new ResultRecord($current);
}
/**
* {@inheritDoc}
*/
public function getSource()
{
return $this->source;
}
}
| <?php
namespace Oro\Bundle\DataGridBundle\Datasource\Orm;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\DataGridBundle\Datasource\ResultRecord;
use Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator;
/**
* Iterates query result with elements of ResultRecord type
*/
class IterableResult extends BufferedQueryResultIterator implements IterableResultInterface
{
/**
* @var QueryBuilder|Query
*/
private $source;
/**
* Current ResultRecord, populated from query result row
*
* @var mixed
*/
private $current = null;
/**
* Constructor
*
* @param QueryBuilder|Query $source
*/
public function __construct($source)
{
parent::__construct($source);
$this->source = $source;
}
/**
* {@inheritDoc}
*/
public function current()
{
return $this->current;
}
/**
* {@inheritDoc}
*/
public function next()
{
parent::next();
$current = parent::current();
$this->current = $current === null
? null
: new ResultRecord($current);
}
/**
* {@inheritDoc}
*/
public function getSource()
{
return $this->source;
}
}
|
tests: Replace control hasher with constant hexdigest.
Signed-off-by: Michael Markert <[email protected]> | from hashlib import sha1
from tempfile import TemporaryFile
from contextlib import contextmanager
from penchy.compat import unittest, nested, update_hasher, unicode_
class NestedTest(unittest.TestCase):
def test_reraising_exception(self):
e = Exception('reraise this')
with self.assertRaises(Exception) as raised:
with nested(TemporaryFile(), TemporaryFile()) as (a, b):
raise e
self.assertEqual(raised.exception, e)
def test_raising_on_exit(self):
@contextmanager
def raising_cm(exception):
yield
raise exception
on_exit = Exception('throw on exit')
with self.assertRaises(Exception) as raised:
with nested(raising_cm(on_exit)):
pass
self.assertEqual(raised.exception, on_exit)
class HasherTest(unittest.TestCase):
def setUp(self):
self.control = sha1()
self.h = sha1()
def test_str_hash(self):
s = str('foo')
update_hasher(self.h, s)
self.assertEqual(self.h.hexdigest(),
'0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33')
def test_unicode_hash(self):
u = unicode_('foo')
update_hasher(self.h, u)
self.assertEqual(self.h.hexdigest(),
'0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33')
| from hashlib import sha1
from tempfile import TemporaryFile
from contextlib import contextmanager
from penchy.compat import unittest, nested, update_hasher
class NestedTest(unittest.TestCase):
def test_reraising_exception(self):
e = Exception('reraise this')
with self.assertRaises(Exception) as raised:
with nested(TemporaryFile(), TemporaryFile()) as (a, b):
raise e
self.assertEqual(raised.exception, e)
def test_raising_on_exit(self):
@contextmanager
def raising_cm(exception):
yield
raise exception
on_exit = Exception('throw on exit')
with self.assertRaises(Exception) as raised:
with nested(raising_cm(on_exit)):
pass
self.assertEqual(raised.exception, on_exit)
class HasherTest(unittest.TestCase):
def setUp(self):
self.control = sha1()
self.h = sha1()
def test_str_hash(self):
s = 'foo'
self.control.update(s)
update_hasher(self.h, s)
self.assertEqual(self.control.hexdigest(),
self.h.hexdigest())
def test_unicode_hash(self):
u = u'foo'
self.control.update(u.encode('utf8'))
update_hasher(self.h, u)
self.assertEqual(self.control.hexdigest(),
self.h.hexdigest())
|
Add support of Google Guice dependency injection at integration tests | package com.centurylinkcloud.servers.service;
import com.centurylinkcloud.servers.config.ServersModule;
import com.centurylinkcloud.servers.domain.*;
import com.centurylinkcloud.servers.domain.datacenter.DataCenters;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.junit.Before;
import org.junit.Test;
import static com.centurylinkcloud.servers.domain.InstanceType.STANDARD;
/**
* @author ilya.drabenia
*/
public class ServerServiceTest {
@Inject
private ServerService serverService;
@Before
public void setUp() {
Guice
.createInjector(new ServersModule())
.injectMembers(this);
}
@Test
public void testCreate() throws Exception {
serverService.create("ALTR", new Server()
.name("ALTRS1")
.type(STANDARD)
.group(new Group()
.datacenter(DataCenters.DE_FRANKFURT)
.name("Group3")
)
.machine(new Machine()
.cpuCount(1)
.ram(2)
)
.template(new Template()
.name("CENTOS-6-64-TEMPLATE")
)
);
}
}
| package com.centurylinkcloud.servers.service;
import com.centurylinkcloud.servers.config.ServersModule;
import com.centurylinkcloud.servers.domain.*;
import com.centurylinkcloud.servers.domain.datacenter.DataCenters;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.junit.Before;
import org.junit.Test;
import static com.centurylinkcloud.servers.domain.InstanceType.STANDARD;
/**
* @author ilya.drabenia
*/
public class ServerServiceTest {
@Inject
private ServerService serverService;
@Before
public void setUp() {
Guice.createInjector(new ServersModule()).injectMembers(this);
}
@Test
public void testCreate() throws Exception {
serverService.create("ALTR", new Server()
.name("ALTRS1")
.type(STANDARD)
.group(new Group()
.datacenter(DataCenters.DE_FRANKFURT)
.name("Group3")
)
.machine(new Machine()
.cpuCount(1)
.ram(2)
)
.template(new Template()
.name("CENTOS-6-64-TEMPLATE")
)
);
}
}
|
Remove a logging call, not needed anymore. | import time
from contextlib import contextmanager
import six
import inspect
import importlib
import logging
from redis.exceptions import RedisError
from django_redis import get_redis_connection
logger = logging.getLogger('cq')
def to_import_string(func):
if inspect.isfunction(func) or inspect.isbuiltin(func):
name = '{0}.{1}'.format(func.__module__, func.__name__)
elif isinstance(func, six.string_types):
name = str(func)
elif inspect.isclass(func):
return '{0}.{1}'.format(func.__module__, func.__name__)
else:
msg = 'Expected a callable or a string, but got: {}'.format(func)
raise TypeError(msg)
return name
def import_attribute(name):
"""Return an attribute from a dotted path name (e.g. "path.to.func").
"""
module_name, attribute = name.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr(module, attribute)
@contextmanager
def redis_connection(retries=3, sleep_time=0.5):
while 1:
try:
conn = get_redis_connection()
break
except RedisError:
if retries is None or retries == 0:
raise
retries -= 1
time.sleep(sleep_time)
try:
yield conn
finally:
pass
# This is actually not needed. The call to `get_redis_connection`
# shares a single connection.
# conn.release()
| import time
from contextlib import contextmanager
import six
import inspect
import importlib
import logging
from redis.exceptions import RedisError
from django_redis import get_redis_connection
logger = logging.getLogger('cq')
def to_import_string(func):
if inspect.isfunction(func) or inspect.isbuiltin(func):
name = '{0}.{1}'.format(func.__module__, func.__name__)
elif isinstance(func, six.string_types):
name = str(func)
elif inspect.isclass(func):
return '{0}.{1}'.format(func.__module__, func.__name__)
else:
msg = 'Expected a callable or a string, but got: {}'.format(func)
raise TypeError(msg)
return name
def import_attribute(name):
"""Return an attribute from a dotted path name (e.g. "path.to.func").
"""
module_name, attribute = name.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr(module, attribute)
@contextmanager
def redis_connection(retries=3, sleep_time=0.5):
while 1:
try:
conn = get_redis_connection()
break
except RedisError:
if retries is None or retries == 0:
raise
retries -= 1
time.sleep(sleep_time)
try:
logger.debug('Using connection, {}, at {}'.format(conn, hex(id(conn))))
yield conn
finally:
pass
# This is actually not needed. The call to `get_redis_connection`
# shares a single connection.
# conn.release()
|
Rewrite Scope with prototypal notation | // Heavily inspired by coffee-script again
(function() {
var Scope;
exports.Scope = Scope = (function () {
Scope.root = null;
function Scope(parent) {
this.parent = parent;
if (!this.parent) {
Scope.root = this;
}
// where we keep the variables names for this scope
this.variables = {};
};
// add a variable to the scope
Scope.prototype.add = function (name) {
if (this.variables[name]) {
throw "Variable " + name + " already defined";
} else {
this.variables[name] = true;
}
};
// check the existence of a variable in this scope or any parent
Scope.prototype.check = function (name) {
return !!this.variables[name] || this.parent.check(name);
};
// generate a temporary variable name
Scope.prototype.temporary = function (name, index) {
return '_' + name + index;
};
// create a temporary variable with an available name
Scope.prototype.addTempVar = function (name, reserve) {
var index = 0,
newName = this.temporary(name, index);
while (this.check(newName)) {
index++;
newName = this.temporary(name, index);
}
if (reserve) {
this.add(newName);
}
return newName;
};
return Scope;
})();
}).call(this);
| // Heavily inspired by coffee-script again
exports.Scope = function (parent) {
var self = this;
if (parent) {
self.root = null;
} else {
self.root = self;
}
self.parent = parent;
// where we keep the variables names for this scope
self.variables = {};
// add a variable to the scope
self.add = function (name) {
if (self.variables[name]) {
throw "Variable " + name + " already defined";
} else {
self.variables[name] = true;
}
}
// check the existence of a variable in this scope or any parent
self.check = function (name) {
return !!self.variables[name] || self.parent.check(name);
}
// generate a temporary variable name
self.temporary = function (name, index) {
return '_' + name + index;
}
// create a temporary variable with an available name
self.addTempVar = function (name, reserve) {
var index = 0,
newName = self.temporary(name, index);
while (self.check(newName)) {
index++;
newName = self.temporary(name, index);
}
if (reserve) {
self.add(newName);
}
return newName;
}
}
|
Remove matplotlib from required dependencies | from setuptools import setup
from tools.generate_pyi import generate_pyi
def main():
# Generate .pyi files
import pyxtf.xtf_ctypes
generate_pyi(pyxtf.xtf_ctypes)
import pyxtf.vendors.kongsberg
generate_pyi(pyxtf.vendors.kongsberg)
# Run setup script
setup(name='pyxtf',
version='0.1',
description='eXtended Triton Format (XTF) file interface',
author='Oystein Sture',
author_email='[email protected]',
url='https://github.com/oysstu/pyxtf',
license='MIT',
setup_requires=['numpy'],
install_requires=['numpy'],
packages=['pyxtf', 'pyxtf.vendors'],
package_data={'':['*.pyi']},
use_2to3=False,
classifiers=[
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Intended Audience :: Other Audience',
'Intended Audience :: Science/Research',
'Natural Language :: English',
'Topic :: Scientific/Engineering',
'Programming Language:: Python:: 3:: Only'
])
if __name__ == '__main__':
main() | from setuptools import setup
from tools.generate_pyi import generate_pyi
def main():
# Generate .pyi files
import pyxtf.xtf_ctypes
generate_pyi(pyxtf.xtf_ctypes)
import pyxtf.vendors.kongsberg
generate_pyi(pyxtf.vendors.kongsberg)
# Run setup script
setup(name='pyxtf',
version='0.1',
description='eXtended Triton Format (XTF) file interface',
author='Oystein Sture',
author_email='[email protected]',
url='https://github.com/oysstu/pyxtf',
license='MIT',
setup_requires=['numpy'],
install_requires=['numpy', 'matplotlib'],
packages=['pyxtf', 'pyxtf.vendors'],
package_data={'':['*.pyi']},
use_2to3=False,
classifiers=[
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Intended Audience :: Other Audience',
'Intended Audience :: Science/Research',
'Natural Language :: English',
'Topic :: Scientific/Engineering',
'Programming Language:: Python:: 3:: Only'
])
if __name__ == '__main__':
main() |
Fix broken build in IE11
Don't use array.includes, it is not supported in IE11 | "use strict";
var assert = require("@sinonjs/referee").assert;
var createSet = require("./create-set");
describe("createSet", function() {
describe("when called without arguments", function() {
it("returns an empty Set", function() {
var set = createSet();
assert.isSet(set);
assert.equals(set.size, 0);
});
});
describe("when called with a non-empty Array", function() {
it("returns a Set with the same (distinct) members", function() {
var array = [0, 1, 1, 1, 1, 2, 3, 4];
var set = createSet(array);
set.forEach(function(value) {
assert.isTrue(array.indexOf(value) !== -1);
});
});
});
describe("when called with non-Array or empty Array argument", function() {
it("throws a TypeError", function() {
var invalids = [
{},
new Date(),
new Set(),
new Map(),
null,
undefined
];
invalids.forEach(function(value) {
assert.exception(function() {
createSet(value);
}, /createSet can be called with either no arguments or an Array/);
});
});
});
});
| "use strict";
var assert = require("@sinonjs/referee").assert;
var createSet = require("./create-set");
describe("createSet", function() {
describe("when called without arguments", function() {
it("returns an empty Set", function() {
var set = createSet();
assert.isSet(set);
assert.equals(set.size, 0);
});
});
describe("when called with a non-empty Array", function() {
it("returns a Set with the same (distinct) members", function() {
var array = [0, 1, 1, 1, 1, 2, 3, 4];
var set = createSet(array);
set.forEach(function(value) {
assert.isTrue(array.includes(value));
});
});
});
describe("when called with non-Array or empty Array argument", function() {
it("throws a TypeError", function() {
var invalids = [
{},
new Date(),
new Set(),
new Map(),
null,
undefined
];
invalids.forEach(function(value) {
assert.exception(function() {
createSet(value);
}, /createSet can be called with either no arguments or an Array/);
});
});
});
});
|
Add 'nullable' validation to password field | <?php
namespace Nodes\Backend\Models\User\Validation;
use Nodes\Validation\AbstractValidator;
/**
* Class UserValidation.
*/
class UserValidator extends AbstractValidator
{
/**
* Validation rules.
*
* @var array
*/
protected $rules = [
'create' => [
'name' => ['required'],
'email' => ['required', 'email', 'unique:backend_users,email,{:id}', 'max:190'],
'password' => [
'required_without:id',
'nullable',
'min:8',
'confirmed',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/'
],
'user_role' => ['required', 'exists:backend_roles,slug'],
'image' => ['mimes:jpeg,png'],
],
'update-password' => [
'password' => [
'required_without:id',
'nullable',
'min:8',
'confirmed',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/'
],
'image' => ['mimes:jpeg,png'],
],
];
}
| <?php
namespace Nodes\Backend\Models\User\Validation;
use Nodes\Validation\AbstractValidator;
/**
* Class UserValidation.
*/
class UserValidator extends AbstractValidator
{
/**
* Validation rules.
*
* @var array
*/
protected $rules = [
'create' => [
'name' => ['required'],
'email' => ['required', 'email', 'unique:backend_users,email,{:id}', 'max:190'],
'password' => [
'required_without:id',
'min:8',
'confirmed',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/'
],
'user_role' => ['required', 'exists:backend_roles,slug'],
'image' => ['mimes:jpeg,png'],
],
'update-password' => [
'password' => [
'required_without:id',
'min:8',
'confirmed',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/'
],
'image' => ['mimes:jpeg,png'],
],
];
}
|
Fix a bug with livereload | var elixir = require('laravel-elixir');
require('laravel-elixir-livereload');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function (mix) {
mix
.less(
'app.less'
)
.styles([
'style.css'
])
.scripts([
'../../../bower_components/jquery/dist/jquery.js',
'../../../bower_components/angular/angular.js',
'../../../bower_components/ngstorage/ngStorage.js',
'../../../bower_components/angular-route/angular-route.js',
'../../../bower_components/angular-resource/angular-resource.js',
'../../../bower_components/bootstrap/dist/js/bootstrap.js',
'app.js',
'appRoutes.js',
'controllers/**/*.js',
'services/**/*.js',
'directives/**/*.js'
])
.version([
'css/all.css',
'js/all.js'
])
.copy(
'public/js/all.js.map', 'public/build/js/all.js.map'
)
.copy(
'public/css/all.css.map', 'public/build/css/all.css.map'
)
.livereload();
}); | var elixir = require('laravel-elixir');
require('laravel-elixir-livereload');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function (mix) {
mix
.less(
'app.less'
)
.styles([
'style.css'
])
.scripts([
'../../../bower_components/jquery/dist/jquery.js',
'../../../bower_components/angular/angular.js',
'../../../bower_components/ngstorage/ngStorage.js',
'../../../bower_components/angular-route/angular-route.js',
'../../../bower_components/angular-resource/angular-resource.js',
'../../../bower_components/bootstrap/dist/js/bootstrap.js',
'app.js',
'appRoutes.js',
'controllers/**/*.js',
'services/**/*.js',
'directives/**/*.js'
])
.version([
'css/all.css',
'js/all.js'
])
.copy(
'public/js/all.js.map', 'public/build/js/all.js.map'
)
.copy(
'public/css/all.css.map', 'public/build/css/all.css.map'
);
.livereload();
}); |
Fix running when pytest.ini is not present. | try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
import pytest
CLI_OPTION_PREFIX = '--'
class CollectConfig(object):
"""
A pytest plugin to gets the configuration file.
"""
def __init__(self):
self.path = None
def pytest_cmdline_main(self, config):
if config.inifile:
self.path = str(config.inifile)
def merge_config(args):
collect_config = CollectConfig()
pytest.main(['--collect-only'], plugins=[collect_config])
if not collect_config.path:
return
config = ConfigParser()
config.read(collect_config.path)
if not config.has_section('pytest-watch'):
return
for cli_name in args:
if not cli_name.startswith(CLI_OPTION_PREFIX):
continue
config_name = cli_name[len(CLI_OPTION_PREFIX):]
# Let CLI options take precedence
if args[cli_name]:
continue
# Find config option
if not config.has_option('pytest-watch', config_name):
continue
# Merge config option using the expected type
if isinstance(args[cli_name], bool):
args[cli_name] = config.getboolean('pytest-watch', config_name)
else:
args[cli_name] = config.get('pytest-watch', config_name)
| try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
import pytest
CLI_OPTION_PREFIX = '--'
class CollectConfig(object):
"""
A pytest plugin to gets the configuration file.
"""
def __init__(self):
self.path = None
def pytest_cmdline_main(self, config):
self.path = str(config.inifile)
def merge_config(args):
collect_config = CollectConfig()
pytest.main(['--collect-only'], plugins=[collect_config])
if not collect_config.path:
return
config = ConfigParser()
config.read(collect_config.path)
if not config.has_section('pytest-watch'):
return
for cli_name in args:
if not cli_name.startswith(CLI_OPTION_PREFIX):
continue
config_name = cli_name[len(CLI_OPTION_PREFIX):]
# Let CLI options take precedence
if args[cli_name]:
continue
# Find config option
if not config.has_option('pytest-watch', config_name):
continue
# Merge config option using the expected type
if isinstance(args[cli_name], bool):
args[cli_name] = config.getboolean('pytest-watch', config_name)
else:
args[cli_name] = config.get('pytest-watch', config_name)
|
Add files to Country Reports | var superagent = require('superagent');
var superagentQ = require('superagent-promises');
class CountryReportMapper {
//============================================================
//
//
//============================================================
async query () {
var res = await superagent.get("https://chm.cbd.int/api/v2013/index/select?fl=id,title_t,government_s,createdDate_dt,updatedDate_dt,url_ss,reportType_s,documentLinks_s&q=NOT+version_s:*+AND+realm_ss:chm+AND+schema_s:*+AND+(+schema_s:nationalReport+)+AND+(*:*+NOT+reportType_s:B0EBAE91-9581-4BB2-9C02-52FCF9D82721+)&rows=9999&start=0&wt=json").use(superagentQ).end();
return res.body.response.docs.map(document => new CountryReport({
protocolVersion: 1,
id: document.id,
treaty: 'cbd',
country: document.government_s.toUpperCase(),
title: [ { language: 'en', value: document.title_t } ],
submission: document.createdDate_dt,
url: document.url_ss[0],
files: JSON.parse(document.documentLinks_s||'[]').map(link => new File({
filename: link.name,
url: link.url
})),
updated: document.updatedOn_dt
}));
}
}
export default new CountryReportMapper();
| var superagent = require('superagent');
var superagentQ = require('superagent-promises');
class CountryReportMapper {
//============================================================
//
//
//============================================================
async query () {
var res = await superagent.get('https://chm.cbd.int/api/v2013/index/select?fl=id,government_s,title_t,createdDate_dt,url_ss,updatedOn_dt&q=realm_ss:chm+AND+schema_s:nationalReport&rows=9999&sort=createdDate_dt+desc,+title_t+asc&start=0&wt=json').use(superagentQ).end();
return res.body.response.docs.map(document => new CountryReport({
protocolVersion: 1,
id: document.id,
treaty: 'cbd',
country: document.government_s.toUpperCase(),
title: [ { language: 'en', value: document.title_t } ],
submission: document.createdDate_dt,
// url: document....,
files: (document.url_ss||[]).map(url => new File({
// id:
url: url
// content:
// mimeType:
// language:
// filename:
})),
updated: document.updatedOn_dt
}));
}
}
export default new CountryReportMapper();
|
Fix news & announcements to be reverse sorted. | 'use strict';
// =========================================================================
//
// Controller for orgs
//
// =========================================================================
var path = require('path');
var DBModel = require (path.resolve('./modules/core/server/controllers/core.dbmodel.controller'));
var _ = require ('lodash');
var mongoose = require ('mongoose');
var Model = mongoose.model ('RecentActivity');
module.exports = DBModel.extend ({
name : 'RecentActivity',
plural : 'recentactivities',
// -------------------------------------------------------------------------
//
// get activities which are active, sorted by Public Comment period, then
// subsorted on type
//
// -------------------------------------------------------------------------
getRecentActivityActive: function () {
var p = Model.find ({active:true},
{},
{}).sort({dateUpdated: -1}).limit(10); // Quick hack to limit the front page loads.
return new Promise (function (resolve, reject) {
p.then(function (doc) {
var pcSort = _.partition(doc, { type: "Public Comment Period" });
var pcp = pcSort[0];
var news = pcSort[1];
var pcSortPriority = _.sortBy(pcp, function (o) {
return o.priority;
});
var newsSortPriority = _.sortBy(news, function (o) {
return o.priority;
});
resolve(pcSortPriority.concat(newsSortPriority));
}, reject);
});
}
});
| 'use strict';
// =========================================================================
//
// Controller for orgs
//
// =========================================================================
var path = require('path');
var DBModel = require (path.resolve('./modules/core/server/controllers/core.dbmodel.controller'));
var _ = require ('lodash');
var mongoose = require ('mongoose');
var Model = mongoose.model ('RecentActivity');
module.exports = DBModel.extend ({
name : 'RecentActivity',
plural : 'recentactivities',
// -------------------------------------------------------------------------
//
// get activities which are active, sorted by Public Comment period, then
// subsorted on type
//
// -------------------------------------------------------------------------
getRecentActivityActive: function () {
var p = Model.find ({active:true},
{},
{}).limit(10); // Quick hack to limit the front page loads.
return new Promise (function (resolve, reject) {
p.then(function (doc) {
var pcSort = _.partition(doc, { type: "Public Comment Period" });
var pcp = pcSort[0];
var news = pcSort[1];
var pcSortPriority = _.sortBy(pcp, function (o) {
return o.priority;
});
var newsSortPriority = _.sortBy(news, function (o) {
return o.priority;
});
resolve(pcSortPriority.concat(newsSortPriority));
}, reject);
});
}
});
|
Subsets and Splits