text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Print all the messages on a QueryException (not just the length). | package net.ripe.db.whois.common;
import javax.annotation.concurrent.Immutable;
@Immutable
public final class Message {
private final Messages.Type type;
private final String text;
private final Object[] args;
private final String formattedText;
public Message(final Messages.Type type, final String text, final Object... args) {
this.type = type;
this.text = text;
this.args = args;
this.formattedText = args.length == 0 ? text : String.format(text, args);
}
@Override
public String toString() {
return formattedText;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Message message = (Message) o;
return type == message.type && formattedText.equals(message.formattedText);
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + formattedText.hashCode();
return result;
}
public Messages.Type getType() {
return type;
}
public String getFormattedText() {
return formattedText;
}
public String getText() {
return text;
}
public Object[] getArgs() {
return args;
}
}
| package net.ripe.db.whois.common;
import javax.annotation.concurrent.Immutable;
import java.util.regex.Pattern;
@Immutable
public final class Message {
public static final Pattern BEGINNING_OF_LINE_PERCENT_SIGNS = Pattern.compile("^%+ ");
private final Messages.Type type;
private final String text;
private final Object[] args;
private final String formattedText;
public Message(final Messages.Type type, final String text, final Object... args) {
this.type = type;
this.text = text;
this.args = args;
this.formattedText = args.length == 0 ? text : String.format(text, args);
}
@Override
public String toString() {
return formattedText;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Message message = (Message) o;
return type == message.type && formattedText.equals(message.formattedText);
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + formattedText.hashCode();
return result;
}
public Messages.Type getType() {
return type;
}
public String getFormattedText() {
return formattedText;
}
public String getText() {
return text;
}
public Object[] getArgs() {
return args;
}
}
|
Remove unnecessary (and debatable) comment. | """
OrderedDict variants of the default base classes.
"""
try:
# Python 2.7+
from collections import OrderedDict
except ImportError:
# Oython 2.6
try:
from ordereddict import OrderedDict
except ImportError:
OrderedDict = None
from .graph import Graph
from .multigraph import MultiGraph
from .digraph import DiGraph
from .multidigraph import MultiDiGraph
__all__ = []
if OrderedDict is not None:
__all__.extend([
'OrderedGraph',
'OrderedDiGraph',
'OrderedMultiGraph',
'OrderedMultiDiGraph'
])
class OrderedGraph(Graph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
class OrderedDiGraph(DiGraph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
class OrderedMultiGraph(MultiGraph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_key_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
class OrderedMultiDiGraph(MultiDiGraph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_key_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
| """
OrderedDict variants of the default base classes.
These classes are especially useful for doctests and unit tests.
"""
try:
# Python 2.7+
from collections import OrderedDict
except ImportError:
# Oython 2.6
try:
from ordereddict import OrderedDict
except ImportError:
OrderedDict = None
from .graph import Graph
from .multigraph import MultiGraph
from .digraph import DiGraph
from .multidigraph import MultiDiGraph
__all__ = []
if OrderedDict is not None:
__all__.extend([
'OrderedGraph',
'OrderedDiGraph',
'OrderedMultiGraph',
'OrderedMultiDiGraph'
])
class OrderedGraph(Graph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
class OrderedDiGraph(DiGraph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
class OrderedMultiGraph(MultiGraph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_key_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
class OrderedMultiDiGraph(MultiDiGraph):
node_dict_factory = OrderedDict
adjlist_dict_factory = OrderedDict
edge_key_dict_factory = OrderedDict
edge_attr_dict_factory = OrderedDict
|
Update to set register user after logged in | 'use strict';
angular.module('lightweight').controller('CheckoutAsGuestController',
['$scope', '$rootScope', '$location', '$state', '$timeout', '$stateParams', '$window', 'Global', 'UserService','CartService',
function($scope, $rootScope, $location, $state, $timeout, $stateParams, $window, Global, UserService, CartService) {
$scope.global = Global;
var returnState = $stateParams.returnUrl;
$scope.userCredential = {};
$scope.items = [];
CartService.getItemsWithoutPopulate()
.$promise
.then(function (items) {
$scope.items = items;
});
$scope.loginFromCheckout = function() {
if($scope.items && $scope.items.length) {
$scope.user.items = $scope.items;
UserService.signInUserWithGuestUserItems($scope.user)
.$promise
.then(function(user) {
$rootScope.$emit('cart:updated');
$timeout(function() {
$scope.global.user = user;
$scope.global.isRegistered = true;
$state.go(returnState);
});
}, function(error) {
$scope.errorLogin = error.data.message;
});
}
};
$scope.checkoutAsGuest = function() {
$state.go(returnState);
};
}
]);
| 'use strict';
angular.module('lightweight').controller('CheckoutAsGuestController',
['$scope', '$rootScope', '$location', '$state', '$timeout', '$stateParams', '$window', 'Global', 'UserService','CartService',
function($scope, $rootScope, $location, $state, $timeout, $stateParams, $window, Global, UserService, CartService) {
$scope.global = Global;
var returnState = $stateParams.returnUrl;
$scope.userCredential = {};
$scope.items = [];
CartService.getItemsWithoutPopulate()
.$promise
.then(function (items) {
$scope.items = items;
});
$scope.loginFromCheckout = function() {
if($scope.items && $scope.items.length) {
$scope.user.items = $scope.items;
UserService.signInUserWithGuestUserItems($scope.user)
.$promise
.then(function(user) {
$scope.global.user = user;
//$window.location.reload();
$rootScope.$emit('cart:updated');
$timeout(function() {
$state.go(returnState, {}, { reload: true });
});
}, function(error) {
console.log('error== ',error);
$scope.errorLogin = error.data.message;
});
}
};
$scope.checkoutAsGuest = function() {
$state.go(returnState);
};
}
]);
|
Fix compilation error with Kotlin 1.0 | package org.jetbrains.kotlin.android.xmlconverter;
import kotlin.text.Charsets;
import org.junit.Rule;
import org.junit.rules.TestName;
import sun.plugin.dom.exception.InvalidStateException;
import java.io.File;
import static kotlin.collections.SetsKt.*;
import static kotlin.io.FilesKt.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BaseXmlConverterTest {
@Rule
public TestName name = new TestName();
protected void doLayoutTest() {
File testDataDir = new File("xml-converter/testData");
String testName = name.getMethodName();
if (!testName.startsWith("test")) {
throw new InvalidStateException("Test name must start with a 'test' preffix");
}
File testDir = new File(testDataDir, decapitalize(testName.substring("test".length())));
File inputFile = new File(testDir, "layout.xml");
File outputFile = new File(testDir, "layout.kt");
assertTrue(inputFile + " does not exist", inputFile.exists());
assertTrue(outputFile + " does not exist", outputFile.exists());
String actual = XmlConverter.INSTANCE.convert(readText(inputFile, Charsets.UTF_8), setOf("raw"));
String expected = readText(outputFile, Charsets.UTF_8);
assertEquals(expected, actual);
}
private String decapitalize(String original) {
if (original.isEmpty()) return original;
return Character.toLowerCase(original.charAt(0)) + original.substring(1);
}
}
| package org.jetbrains.kotlin.android.xmlconverter;
import org.junit.Rule;
import org.junit.rules.TestName;
import sun.plugin.dom.exception.InvalidStateException;
import java.io.File;
import static kotlin.collections.SetsKt.*;
import static kotlin.io.FilesKt.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BaseXmlConverterTest {
@Rule
public TestName name = new TestName();
protected void doLayoutTest() {
File testDataDir = new File("xml-converter/testData");
String testName = name.getMethodName();
if (!testName.startsWith("test")) {
throw new InvalidStateException("Test name must start with a 'test' preffix");
}
File testDir = new File(testDataDir, decapitalize(testName.substring("test".length())));
File inputFile = new File(testDir, "layout.xml");
File outputFile = new File(testDir, "layout.kt");
assertTrue(inputFile + " does not exist", inputFile.exists());
assertTrue(outputFile + " does not exist", outputFile.exists());
String actual = XmlConverter.INSTANCE.convert(readText(inputFile, "UTF-8"), setOf("raw"));
String expected = readText(outputFile, "UTF-8");
assertEquals(expected, actual);
}
private String decapitalize(String original) {
if (original.isEmpty()) return original;
return Character.toLowerCase(original.charAt(0)) + original.substring(1);
}
}
|
Remove unused param & rename param from docblock | <?php
/**
* @file
* Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginBlockGenerator extends Generator
{
/**
* Generator Plugin Block
* @param $module
* @param $class_name
* @param $plugin_label
* @param $plugin_id
* @param $services
*/
public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
{
$path = DRUPAL_ROOT.'/'.drupal_get_path('module', $module);
$path_plugin = $path.'/src/Plugin/Block';
// set syntax for arguments
$args = ', ';
$i = 0;
foreach ($services as $service) {
$args .= $service['short'] . ' $' . $service['machine_name'];
if ( ++$i != count($services)) {
$args .= ', ';
}
}
$parameters = [
'module' => $module,
'class' => [
'name' => $class_name,
'underscore' => $this->camelCaseToUnderscore($class_name)
],
'plugin_label' => $plugin_label,
'plugin_id' => $plugin_id,
'services' => $services,
'args' => $args
];
$this->renderFile(
'module/plugin-block.php.twig',
$path_plugin.'/'.$class_name.'.php',
$parameters
);
}
}
| <?php
/**
* @file
* Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginBlockGenerator extends Generator
{
/**
* Generator Plugin Block
* @param $module
* @param $class_name
* @param $plugin_label
* @param $plugin_id
* @param $description
* @param $build_services
*/
public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
{
$path = DRUPAL_ROOT.'/'.drupal_get_path('module', $module);
$path_plugin = $path.'/src/Plugin/Block';
// set syntax for arguments
$args = ', ';
$i = 0;
foreach ($services as $service) {
$args .= $service['short'] . ' $' . $service['machine_name'];
if ( ++$i != count($services)) {
$args .= ', ';
}
}
$parameters = [
'module' => $module,
'class' => [
'name' => $class_name,
'underscore' => $this->camelCaseToUnderscore($class_name)
],
'plugin_label' => $plugin_label,
'plugin_id' => $plugin_id,
'services' => $services,
'args' => $args
];
$this->renderFile(
'module/plugin-block.php.twig',
$path_plugin.'/'.$class_name.'.php',
$parameters
);
}
}
|
Move statement to 2 lines | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var config = require('../config.js');
var User = require('../models/user.js');
router.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if(token) {
jwt.verify(token, 'supersecret', function(err, decoded) {
if(err) {
return res.json({
success: false,
message: 'Failed to authenticate'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided'
});
}
});
/* GET users listing. */
router.get('/', function(req, res, next) {
User.find({}, function(err, users) {
res.json(users);
});
});
module.exports = router;
| var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var config = require('../config.js');
var User = require('../models/user.js');
router.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if(token) {
jwt.verify(token, 'supersecret', function(err, decoded) {
if(err) {
return res.json({
success: false,
message: 'Failed to authenticate'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided'
});
}
});
/* GET users listing. */
router.get('/', function(req, res, next) {
User.find({}, function(err, users) {
res.json(users);
});
});
module.exports = router;
|
Correct url to project details | define(['app', 'bloodhound'], function(app, Bloodhound) {
'use strict';
return {
parent: 'admin_layout',
url: 'new/project/',
templateUrl: 'partials/admin/project-create.html',
controller: function($scope, $http, $state) {
$scope.searchRepositories = function(value) {
return $http.get('/api/0/repositories/', {
params: {
query: value
}
}).success(function(data){
var results = [];
angular.forEach(data, function(item){
results.push(item.url);
});
return results;
});
};
var bloodhound = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.url); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/api/0/repositories/?query=%QUERY'
});
bloodhound.initialize();
$scope.repoTypeaheadData = {
displayKey: 'url',
source: bloodhound.ttAdapter()
};
$scope.createProject = function() {
$http.post('/api/0/projects/', $scope.project)
.success(function(data){
return $state.go('admin_project_details', {project_id: data.slug});
});
};
$scope.project = {};
}
};
});
| define(['app', 'bloodhound'], function(app, Bloodhound) {
'use strict';
return {
parent: 'admin_layout',
url: 'new/project/',
templateUrl: 'partials/admin/project-create.html',
controller: function($scope, $http, $state) {
$scope.searchRepositories = function(value) {
return $http.get('/api/0/repositories/', {
params: {
query: value
}
}).success(function(data){
var results = [];
angular.forEach(data, function(item){
results.push(item.url);
});
return results;
});
};
var bloodhound = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.url); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/api/0/repositories/?query=%QUERY'
});
bloodhound.initialize();
$scope.repoTypeaheadData = {
displayKey: 'url',
source: bloodhound.ttAdapter()
};
$scope.createProject = function() {
$http.post('/api/0/projects/', $scope.project)
.success(function(data){
return $state.go('admin_project_settings', {project_id: data.slug});
});
};
$scope.project = {};
}
};
});
|
Change conditional rendering and this bindings | import React from 'react'
import FeedbackLink from '../components/FeedbackLink.js'
class FeedbackSection extends React.Component {
constructor(props) {
super(props)
this.state = {
rateMessage: 'How was it? Rate it:',
showButtons: true
}
}
handleClick = () => {
this.setState({
rateMessage: 'Thanks!',
showButtons: false
})
}
render() {
return (
<div className="feedback">
<div>
<h4>{this.state.rateMessage}</h4>
<p>Your feedback is greatly appreciated!</p>
</div>
{this.state.showButtons ? (
<div>
<FeedbackLink
className="m-r-1"
text="Good π"
value="good"
onClick={this.handleClick}
/>
<FeedbackLink
className="m-r-1"
text="Too long π"
value="long"
onClick={this.handleClick}
/>
<FeedbackLink
className="m-r-1"
text="Too short π"
value="short"
onClick={this.handleClick}
/>
<FeedbackLink
className="m-r-1"
text="Bad π"
value="bad"
onClick={this.handleClick}
/>
</div>
) : null}
</div>
)
}
}
export default FeedbackSection
| import React from 'react'
import FeedbackLink from '../components/FeedbackLink.js'
class FeedbackSection extends React.Component {
constructor(props) {
super(props)
this.state = {
rateMessage: 'How was it? Rate it:',
showButtons: true
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({
rateMessage: 'Thanks!',
showButtons: false
})
}
render() {
return (
<div className="feedback">
<div>
<h4>{this.state.rateMessage}</h4>
<p>Your feedback is greatly appreciated!</p>
</div>
{this.state.showButtons ? (
<div>
<FeedbackLink
className="m-r-1"
text="Good π"
value="good"
onClick={this.handleClick}
/>
<FeedbackLink
className="m-r-1"
text="Too long π"
value="long"
onClick={this.handleClick}
/>
<FeedbackLink
className="m-r-1"
text="Too short π"
value="short"
onClick={this.handleClick}
/>
<FeedbackLink
className="m-r-1"
text="Bad π"
value="bad"
onClick={this.handleClick}
/>
</div>
) : (
<div />
)}
</div>
)
}
}
export default FeedbackSection
|
Fix static db connection. Singleton pattern. | <?php
/**
* DronePHP (http://www.dronephp.com)
*
* @link http://github.com/Pleets/DronePHP
* @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
* @license http://www.dronephp.com/license
*/
namespace Drone\Db;
abstract class AbstractTableGateway
{
/**
* Handle
*
* @var Driver
*/
private static $db;
/**
* Constructor
*
* @param string $abstract_connection_string
* @param boolean $auto_connect
*
* @return null
*/
public function __construct($abstract_connection_string = "default", $auto_connect = true)
{
$dbsettings = include(__DIR__ . "/../../../config/database.config.php");
$drivers = array(
"Oci8" => "Drone\Sql\Oracle",
"Mysqli" => "Drone\Sql\MySQL",
"Sqlsrv" => "Drone\Sql\SQLServer",
);
$drv = $dbsettings[$abstract_connection_string]["driver"];
if (!array_key_exists($drv, $drivers))
throw new Exception("The Database driver '$drv' does not exists");
if (array_key_exists($drv, $drivers) && !isset(self::$db))
self::$db = new $drivers[$drv]($dbsettings[$abstract_connection_string]);
}
/**
* Returns the handle instance
*
* @return Driver
*/
public static function getDb()
{
return self::$db;
}
} | <?php
/**
* DronePHP (http://www.dronephp.com)
*
* @link http://github.com/Pleets/DronePHP
* @copyright Copyright (c) 2016 DronePHP. (http://www.dronephp.com)
* @license http://www.dronephp.com/license
*/
namespace Drone\Db;
abstract class AbstractTableGateway
{
/**
* Handle
*
* @var Driver
*/
private static $db;
/**
* Constructor
*
* @param string $abstract_connection_string
* @param boolean $auto_connect
*
* @return null
*/
public function __construct($abstract_connection_string = "default", $auto_connect = true)
{
$dbsettings = include(__DIR__ . "/../../../config/database.config.php");
$drivers = array(
"Oci8" => "Drone\Sql\Oracle",
"Mysqli" => "Drone\Sql\MySQL",
"Sqlsrv" => "Drone\Sql\SQLServer",
);
$drv = $dbsettings[$abstract_connection_string]["driver"];
if (array_key_exists($drv, $drivers))
self::$db = new $drivers[$drv]($dbsettings[$abstract_connection_string]);
else
throw new Exception("The Database driver '$drv' does not exists");
}
/**
* Returns the handle instance
*
* @return Driver
*/
public function getDb()
{
return self::$db;
}
} |
Set the file permission to public instead of private | /* jshint loopfunc: true */
'use strict';
/**
* @ngdoc function
* @name bannerPreviewApp.controller:BannersEditCtrl
* @description
* # BannersEditCtrl
* Controller of the bannerPreviewApp
*/
angular.module('bannerPreviewApp')
.controller('BannersEditCtrl', function ($scope, $upload, BannerService, banner, configuration) {
$scope.selectedFiles = [];
$scope.progress = [];
$scope.banner = banner;
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
var index = $scope.selectedFiles.push(file) - 1;
$upload.upload({
url: configuration.AWS.url,
method: 'POST',
data : {
key: $scope.banner.$id + '/' + file.name,
AWSAccessKeyId: configuration.AWS.AccessKeyId,
acl: 'public',
policy: configuration.AWS.policy,
signature: configuration.AWS.signature,
'Content-Type': file.type !== '' ? file.type : 'application/octet-stream',
filename: file.name
},
file: file,
}).progress(function(event) {
$scope.progress[index] = parseInt(100.0 * event.loaded / event.total);
}).success(function() {
$scope.selectedFiles.splice(index, 1);
BannerService.addFile($scope.banner.$id, file);
});
}
};
});
| /* jshint loopfunc: true */
'use strict';
/**
* @ngdoc function
* @name bannerPreviewApp.controller:BannersEditCtrl
* @description
* # BannersEditCtrl
* Controller of the bannerPreviewApp
*/
angular.module('bannerPreviewApp')
.controller('BannersEditCtrl', function ($scope, $upload, BannerService, banner, configuration) {
$scope.selectedFiles = [];
$scope.progress = [];
$scope.banner = banner;
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
var index = $scope.selectedFiles.push(file) - 1;
$upload.upload({
url: configuration.AWS.url,
method: 'POST',
data : {
key: $scope.banner.$id + '/' + file.name,
AWSAccessKeyId: configuration.AWS.AccessKeyId,
acl: 'private',
policy: configuration.AWS.policy,
signature: configuration.AWS.signature,
'Content-Type': file.type !== '' ? file.type : 'application/octet-stream',
filename: file.name
},
file: file,
}).progress(function(event) {
$scope.progress[index] = parseInt(100.0 * event.loaded / event.total);
}).success(function() {
$scope.selectedFiles.splice(index, 1);
BannerService.addFile($scope.banner.$id, file);
});
}
};
});
|
Reduce required numbers to match current coverage | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 98,
statements: 97
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
} | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 100,
statements: 99
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
} |
Change command title and placeholder | define([
"text!src/templates/file.html",
"less!src/stylesheets/main.less"
], function(fileTemplate) {
var _ = codebox.require("hr/utils");
var commands = codebox.require("core/commands");
var rpc = codebox.require("core/rpc");
var dialogs = codebox.require("utils/dialogs");
commands.register({
id: "find.files",
title: "Find: Jump to file",
shortcuts: [
"mod+p"
],
run: function() {
return dialogs.list(function(query) {
return rpc.execute("find/files", {
query: query,
start: 0,
limit: 100
})
.get("results")
.then(function(results) {
return _.map(results, function(result) {
return {
'path': result,
'filename': result.split('/').pop()
}
});
});
}, {
template: fileTemplate,
placeholder: "Jump to a file"
})
.then(function(file) {
return commands.run("file.open", {
'path': file.get("path")
});
});
}
});
}); | define([
"text!src/templates/file.html",
"less!src/stylesheets/main.less"
], function(fileTemplate) {
var _ = codebox.require("hr/utils");
var commands = codebox.require("core/commands");
var rpc = codebox.require("core/rpc");
var dialogs = codebox.require("utils/dialogs");
commands.register({
id: "find.files",
title: "Find: Browse Files",
shortcuts: [
"mod+p"
],
run: function() {
return dialogs.list(function(query) {
return rpc.execute("find/files", {
query: query,
start: 0,
limit: 100
})
.get("results")
.then(function(results) {
return _.map(results, function(result) {
return {
'path': result,
'filename': result.split('/').pop()
}
});
});
}, {
template: fileTemplate,
placeholder: "Browse Files"
})
.then(function(file) {
return commands.run("file.open", {
'path': file.get("path")
});
});
}
});
}); |
Copy file permissions for all files | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
copy: {
jquery: {
expand: true,
flatten: true,
src: 'bower_components/jquery/dist/jquery.min.js',
dest: 'dist/share/git-webui/webui/js/',
},
bootstrap: {
expand: true,
flatten: true,
src: 'bower_components/bootstrap/dist/js/bootstrap.min.js',
dest: 'dist/share/git-webui/webui/js/',
},
git_webui: {
options: {
mode: true,
},
expand: true,
cwd: 'src',
src: ['lib/**', 'share/**', '!**/less', '!**/*.less'],
dest: 'dist',
},
},
less: {
options: {
paths: 'bower_components/bootstrap/less',
},
files: {
expand: true,
cwd: 'src',
src: 'share/git-webui/webui/css/*.less',
dest: 'dist',
ext: '.css',
},
},
clean: ['dist'],
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('default', ['copy', 'less']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
copy: {
jquery: {
expand: true,
flatten: true,
src: 'bower_components/jquery/dist/jquery.min.js',
dest: 'dist/share/git-webui/webui/js/',
},
bootstrap: {
expand: true,
flatten: true,
src: 'bower_components/bootstrap/dist/js/bootstrap.min.js',
dest: 'dist/share/git-webui/webui/js/',
},
git_webui: {
expand: true,
cwd: 'src',
src: ['lib/**', 'share/**', '!**/less', '!**/*.less'],
dest: 'dist',
},
},
less: {
options: {
paths: 'bower_components/bootstrap/less',
},
files: {
expand: true,
cwd: 'src',
src: 'share/git-webui/webui/css/*.less',
dest: 'dist',
ext: '.css',
},
},
clean: ['dist'],
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('default', ['copy', 'less']);
};
|
Remove copy constructor for PDAStack
The copy() method is already sufficient. | #!/usr/bin/env python3
"""Classes and methods for working with PDA stacks."""
class PDAStack(object):
"""A PDA stack."""
def __init__(self, stack):
"""Initialize the new PDA stack."""
self.stack = list(stack)
def top(self):
"""Return the symbol at the top of the stack."""
if self.stack:
return self.stack[-1]
else:
return ''
def pop(self):
"""Pop the stack top from the stack."""
self.stack.pop()
def replace(self, symbols):
"""
Replace the top of the stack with the given symbols.
The first symbol in the given sequence becomes the new stack top.
"""
self.stack.pop()
self.stack.extend(reversed(symbols))
def copy(self):
"""Return a deep copy of the stack."""
return self.__class__(**self.__dict__)
def __len__(self):
"""Return the number of symbols on the stack."""
return len(self.stack)
def __iter__(self):
"""Return an interator for the stack."""
return iter(self.stack)
def __repr__(self):
"""Return a string representation of the stack."""
return '{}({})'.format(self.__class__.__name__, self.stack)
def __eq__(self, other):
"""Check if two stacks are equal."""
return self.__dict__ == other.__dict__
| #!/usr/bin/env python3
"""Classes and methods for working with PDA stacks."""
class PDAStack(object):
"""A PDA stack."""
def __init__(self, stack, **kwargs):
"""Initialize the new PDA stack."""
if isinstance(stack, PDAStack):
self._init_from_stack_obj(stack)
else:
self.stack = list(stack)
def _init_from_stack_obj(self, stack_obj):
"""Initialize this Stack as a deep copy of the given Stack."""
self.__init__(stack_obj.stack)
def top(self):
"""Return the symbol at the top of the stack."""
if self.stack:
return self.stack[-1]
else:
return ''
def pop(self):
"""Pop the stack top from the stack."""
self.stack.pop()
def replace(self, symbols):
"""
Replace the top of the stack with the given symbols.
The first symbol in the given sequence becomes the new stack top.
"""
self.stack.pop()
self.stack.extend(reversed(symbols))
def copy(self):
"""Return a deep copy of the stack."""
return self.__class__(self)
def __len__(self):
"""Return the number of symbols on the stack."""
return len(self.stack)
def __iter__(self):
"""Return an interator for the stack."""
return iter(self.stack)
def __repr__(self):
"""Return a string representation of the stack."""
return '{}({})'.format(self.__class__.__name__, self.stack)
def __eq__(self, other):
"""Check if two stacks are equal."""
return self.__dict__ == other.__dict__
|
Update job detail step to handle cancelled waiting jobs | import React from "react";
import { ClipLoader } from "halogenium";
import { Icon } from "../../base";
import { getTaskDisplayName } from "../../utils";
const JobStep = ({ step, isDone }) => {
let hasBar;
let stateIcon;
let entryStyle;
switch (step.state) {
case "running":
hasBar = isDone;
stateIcon = isDone ? "check fa-fw" : "";
entryStyle = isDone ? "success" : "primary";
break;
case "complete":
hasBar = false;
stateIcon = "check fa-fw";
entryStyle = "success";
break;
case "error":
case "cancelled":
hasBar = false;
stateIcon = "times fa-fw";
entryStyle = "danger";
break;
default:
return null;
}
if (step.stage) {
return (
<div className="step-entry">
<div className="step-entry-icon">
{stateIcon.length
? <Icon name={stateIcon} bsStyle={entryStyle} />
: <ClipLoader size="14px" color="#07689d" style={{padding: "0 1.5px"}} />
}
</div>
<div className="step-entry-content">
{getTaskDisplayName(step.stage)}
</div>
<div
className={hasBar ? `step-entry-bar-${entryStyle}` : "step-entry-nobar"}
/>
</div>
);
}
return null;
};
export default JobStep;
| import React from "react";
import { ClipLoader } from "halogenium";
import { Icon } from "../../base";
import { getTaskDisplayName } from "../../utils";
const JobStep = ({ step, isDone }) => {
let hasBar;
let stateIcon;
let entryStyle;
switch (step.state) {
case "running":
hasBar = isDone;
stateIcon = isDone ? "check fa-fw" : "";
entryStyle = isDone ? "success" : "primary";
break;
case "complete":
hasBar = false;
stateIcon = "check fa-fw";
entryStyle = "success";
break;
case "error":
case "cancelled":
hasBar = false;
stateIcon = "times fa-fw";
entryStyle = "danger";
break;
default:
return null;
}
const stepEntry = (
<div className="step-entry">
<div className="step-entry-icon">
{stateIcon.length
? <Icon name={stateIcon} bsStyle={entryStyle} />
: <ClipLoader size="14px" color="#07689d" style={{padding: "0 1.5px"}} />
}
</div>
<div className="step-entry-content">
{getTaskDisplayName(step.stage)}
</div>
<div
className={hasBar ? `step-entry-bar-${entryStyle}` : "step-entry-nobar"}
/>
</div>
);
return stepEntry;
};
export default JobStep;
|
Update template loaders analyzer to target Django 1.5 | import ast
from .base import BaseAnalyzer, Result
class TemplateLoadersVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.template.loaders.app_directories.load_template_source':
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.load_template_source':
'django.template.loaders.eggs.Loader',
'django.template.loaders.filesystem.load_template_source':
'django.template.loaders.filesystem.Loader',
}
def visit_Str(self, node):
if node.s in self.removed_items.keys():
self.found.append((node.s, node))
class TemplateLoadersAnalyzer(BaseAnalyzer):
def analyze_file(self, filepath, code):
if not isinstance(code, ast.AST):
return
visitor = TemplateLoadersVisitor()
visitor.visit(code)
for name, node in visitor.found:
propose = visitor.removed_items[name]
result = Result(
description = (
'%r function has been deprecated in Django 1.2 and '
'removed in 1.4. Use %r class instead.' % (name, propose)
),
path = filepath,
line = node.lineno)
lines = self.get_file_lines(filepath, node.lineno, node.lineno)
for lineno, important, text in lines:
result.source.add_line(lineno, text, important)
result.solution.add_line(lineno, text.replace(name, propose), important)
yield result
| import ast
from .base import BaseAnalyzer, Result
class TemplateLoadersVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
deprecated_items = {
'django.template.loaders.app_directories.load_template_source':
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.load_template_source':
'django.template.loaders.eggs.Loader',
'django.template.loaders.filesystem.load_template_source':
'django.template.loaders.filesystem.Loader',
}
def visit_Str(self, node):
if node.s in self.deprecated_items.keys():
self.found.append((node.s, node))
class TemplateLoadersAnalyzer(BaseAnalyzer):
def analyze_file(self, filepath, code):
if not isinstance(code, ast.AST):
return
visitor = TemplateLoadersVisitor()
visitor.visit(code)
for name, node in visitor.found:
propose = visitor.deprecated_items[name]
result = Result(
description = (
'%r function is deprecated, use %r class instead' % (name, propose)
),
path = filepath,
line = node.lineno)
lines = self.get_file_lines(filepath, node.lineno, node.lineno)
for lineno, important, text in lines:
result.source.add_line(lineno, text, important)
result.solution.add_line(lineno, text.replace(name, propose), important)
yield result
|
chore(analytics): Fix client ID not being sent to GA | import nanoid from 'nanoid';
const GA_KEY = 'GA:clientID';
let clientId = localStorage.getItem(GA_KEY);
export default class Ga {
constructor (db) {
this.db = db;
this.load();
}
load () {
if (!clientId) {
clientId = nanoid();
localStorage.setItem(GA_KEY, clientId);
}
}
report (event, service) {
this.db.get('sendUsageStatistics')
.then((sendUsageStatistics) => {
if (sendUsageStatistics) {
const request = new XMLHttpRequest();
const message =
'v=1&tid=' +
process.env.GA_TRACKING_ID +
'&cid=' +
clientId +
'&aip=1' +
'&ds=extension&t=event&ec=' +
event +
'&ea=' +
service;
request.open('POST', 'https://www.google-analytics.com/collect', true);
request.send(message);
}
});
}
reportEvent (event, service) {
this.report(event, event + '-' + service);
}
reportOs () {
chrome.runtime.getPlatformInfo((info) => {
this.report('os', 'os-' + info.os);
});
}
reportSettings (event, service) {
}
}
| import nanoid from 'nanoid';
const GA_KEY = 'GA:clientID';
let clientId = localStorage.getItem(GA_KEY);
export default class Ga {
constructor (db) {
this.db = db;
this.load();
}
load () {
if (!clientId) {
clientId = nanoid();
localStorage.setItem(GA_KEY, clientId);
}
}
report (event, service) {
this.db.get('sendUsageStatistics')
.then((sendUsageStatistics) => {
if (sendUsageStatistics) {
const request = new XMLHttpRequest();
const message =
'v=1&tid=' +
process.env.GA_TRACKING_ID +
'&cid=' +
this.clientId +
'&aip=1' +
'&ds=extension&t=event&ec=' +
event +
'&ea=' +
service;
request.open('POST', 'https://www.google-analytics.com/collect', true);
request.send(message);
}
});
}
reportEvent (event, service) {
this.report(event, event + '-' + service);
}
reportOs () {
chrome.runtime.getPlatformInfo((info) => {
this.report('os', 'os-' + info.os);
});
}
reportSettings (event, service) {
}
}
|
Add buzzapi_job create reason text to the breakdown | <?php
declare(strict_types=1);
namespace App\Nova\Metrics;
use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Nova\Metrics\Partition;
use Laravel\Nova\Metrics\PartitionResult;
class CreateReasonBreakdown extends Partition
{
/**
* The displayable name of the metric.
*
* @var string
*/
public $name = 'User Create Reason';
/**
* Calculate the value of the metric.
*/
public function calculate(Request $request): PartitionResult
{
return $this->count($request, User::class, 'create_reason')->label(static function (?string $value): string {
switch ($value) {
case 'phpunit':
return 'PHPUnit';
case 'cas_login':
return 'CAS login';
case 'factory':
return 'Database\Factories\UserFactory';
case 'nova_action':
return 'Nova action';
case 'attendance':
return 'Attendance';
case 'historical_dues_import':
return 'Historical dues import';
// This isn't created by code, but a lot of records in prod have this.
case 'buzzapi_job':
return 'BuzzAPI job';
case null:
return 'Unknown';
default:
return ucfirst($value);
}
});
}
/**
* Get the URI key for the metric.
*/
public function uriKey(): string
{
return 'create-reasons';
}
}
| <?php
declare(strict_types=1);
namespace App\Nova\Metrics;
use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Nova\Metrics\Partition;
use Laravel\Nova\Metrics\PartitionResult;
class CreateReasonBreakdown extends Partition
{
/**
* The displayable name of the metric.
*
* @var string
*/
public $name = 'User Create Reason';
/**
* Calculate the value of the metric.
*/
public function calculate(Request $request): PartitionResult
{
return $this->count($request, User::class, 'create_reason')->label(static function (?string $value): string {
switch ($value) {
case 'phpunit':
return 'PHPUnit';
case 'cas_login':
return 'CAS login';
case 'factory':
return 'Database\Factories\UserFactory';
case 'nova_action':
return 'Nova action';
case 'attendance':
return 'Attendance';
case 'historical_dues_import':
return 'Historical dues import';
case null:
return 'Unknown';
default:
return ucfirst($value);
}
});
}
/**
* Get the URI key for the metric.
*/
public function uriKey(): string
{
return 'create-reasons';
}
}
|
Use named function syntax, more white space. Factor out myRender. | import { select, local } from "d3-selection";
var myLocal = local(),
noop = function (){};
function myRender(props){
var my = myLocal.get(this);
my.props = props;
my.render();
}
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
selector = className ? "." + className : tagName;
function myCreate(){
var my = myLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
create(my.selection, function setState(state){
Object.assign(my.state, state);
my.render();
});
my.render = function (){
render(my.selection, my.props, my.state);
};
}
function myDestroy(props){
destroy(myLocal.get(this).state);
}
function component(selection, props){
var components = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]);
components
.enter().append(tagName)
.attr("class", className)
.each(myCreate)
.merge(components)
.each(myRender);
components
.exit()
.each(myDestroy)
.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
| import { select, local } from "d3-selection";
var myLocal = local(),
noop = function (){};
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
myCreate = function (){
var my = myLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
create(my.selection, function setState(state){
Object.assign(my.state, state);
my.render();
});
my.render = function (){
render(my.selection, my.props, my.state);
};
},
myRender = function (props){
var my = myLocal.get(this);
my.props = props;
my.render();
},
myDestroy = function (props){
destroy(myLocal.get(this).state);
},
selector = className ? "." + className : tagName,
component = function(selection, props){
var components = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]);
components
.enter().append(tagName)
.attr("class", className)
.each(myCreate)
.merge(components)
.each(myRender);
components
.exit()
.each(myDestroy)
.remove();
};
component.render = function(_) { render = _; return component; };
component.create = function(_) { create = _; return component; };
component.destroy = function(_) { destroy = _; return component; };
return component;
};
|
Support case when expiration_datetime is None | from datetime import datetime, timedelta
from invisibleroads_macros_security import make_random_string
class DictionarySafe(dict):
def __init__(self, key_length):
self.key_length = key_length
def put(self, value, time_in_seconds=None):
while True:
key = make_random_string(self.key_length)
try:
self[key]
except KeyError:
break
self.set(key, value, time_in_seconds)
return key
def set(self, key, value, time_in_seconds=None):
self[key] = value, get_expiration_datetime(time_in_seconds)
def get(self, key):
value, expiration_datetime = self[key]
if expiration_datetime and datetime.now() > expiration_datetime:
del self[key]
raise KeyError
return value
def get_expiration_datetime(time_in_seconds):
if not time_in_seconds:
return
return datetime.now() + timedelta(seconds=time_in_seconds)
def evaluate_expression(expression_string, value_by_name):
# https://realpython.com/python-eval-function
code = compile(expression_string, '<string>', 'eval')
for name in code.co_names:
if name not in value_by_name:
raise NameError(f'{name} not defined')
return eval(code, {'__builtins__': {}}, value_by_name)
| from datetime import datetime, timedelta
from invisibleroads_macros_security import make_random_string
class DictionarySafe(dict):
def __init__(self, key_length):
self.key_length = key_length
def put(self, value, time_in_seconds=None):
while True:
key = make_random_string(self.key_length)
try:
self[key]
except KeyError:
break
self.set(key, value, time_in_seconds)
return key
def set(self, key, value, time_in_seconds=None):
self[key] = value, get_expiration_datetime(time_in_seconds)
def get(self, key):
value, expiration_datetime = self[key]
if datetime.now() > expiration_datetime:
del self[key]
raise KeyError
return value
def get_expiration_datetime(time_in_seconds):
if not time_in_seconds:
return
return datetime.now() + timedelta(seconds=time_in_seconds)
def evaluate_expression(expression_string, value_by_name):
# https://realpython.com/python-eval-function
code = compile(expression_string, '<string>', 'eval')
for name in code.co_names:
if name not in value_by_name:
raise NameError(f'{name} not defined')
return eval(code, {'__builtins__': {}}, value_by_name)
|
[Java] Use service loader for ObjectFactory | package cucumber.runtime.java;
import cucumber.api.java.ObjectFactory;
import cucumber.runtime.CucumberException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* This class has package scope so it doesn't get loaded by reflection,
* thereby colliding with other DI implementations.
*/
class DefaultJavaObjectFactory implements ObjectFactory {
private final Map<Class<?>, Object> instances = new HashMap<Class<?>, Object>();
public void start() {
// No-op
}
public void stop() {
instances.clear();
}
public boolean addClass(Class<?> clazz) {
return true;
}
public <T> T getInstance(Class<T> type) {
T instance = type.cast(instances.get(type));
if (instance == null) {
instance = cacheNewInstance(type);
}
return instance;
}
private <T> T cacheNewInstance(Class<T> type) {
try {
Constructor<T> constructor = type.getConstructor();
T instance = constructor.newInstance();
instances.put(type, instance);
return instance;
} catch (NoSuchMethodException e) {
throw new CucumberException(String.format("%s doesn't have an empty constructor. If you need DI, put cucumber-picocontainer on the classpath", type), e);
} catch (Exception e) {
throw new CucumberException(String.format("Failed to instantiate %s", type), e);
}
}
}
| package cucumber.runtime.java;
import cucumber.api.java.ObjectFactory;
import cucumber.runtime.CucumberException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* This class has package scope so it doesn't get loaded by reflection,
* thereby colliding with other DI implementations.
*/
class DefaultJavaObjectFactory implements ObjectFactory {
private final Map<Class<?>, Object> instances = new HashMap<Class<?>, Object>();
public void start() {
// No-op
}
public void stop() {
instances.clear();
}
public boolean addClass(Class<?> clazz) {
return true;
}
public <T> T getInstance(Class<T> type) {
T instance = type.cast(instances.get(type));
if (instance == null) {
instance = cacheNewInstance(type);
}
return instance;
}
private <T> T cacheNewInstance(Class<T> type) {
try {
Constructor<T> constructor = type.getConstructor();
T instance = constructor.newInstance();
instances.put(type, instance);
return instance;
} catch (NoSuchMethodException e) {
throw new CucumberException(String.format("%s doesn't have an empty constructor. If you need DI, put cucumber-picocontainer on the classpath", type), e);
} catch (Exception e) {
throw new CucumberException(String.format("Failed to instantiate %s", type), e);
}
}
}
|
Fix auth API usage (this is why we wait for CI) | import json
from zeus import auth
from zeus.api import client
from zeus.exceptions import ApiError
from zeus.models import Email, Identity
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
try:
user_response = client.get('/users/me')
except ApiError as exc:
if exc.code == 401:
return {
'isAuthenticated': False,
}
user = json.loads(user_response.data)
identity_list = list(Identity.query.filter(
Identity.user_id == user['id'],
))
email_list = list(Email.query.filter(
Email.user_id == user['id'],
))
return {
'isAuthenticated': True,
'user': user,
'emails': emails_schema.dump(email_list).data,
'identities': identities_schema.dump(identity_list).data,
}
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
| import json
from zeus import auth
from zeus.api import client
from zeus.exceptions import ApiError
from zeus.models import Email, Identity
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
try:
user_response = client.get('/users/me')
except ApiError as exc:
if exc.code == 401:
return {
'isAuthenticated': False,
}
identity_list = list(Identity.query.filter(
Identity.user_id == user_response.data['id'],
))
email_list = list(Email.query.filter(
Email.user_id == user_response.data['id'],
))
return {
'isAuthenticated': True,
'user': json.loads(user_response.data),
'emails': emails_schema.dump(email_list).data,
'identities': identities_schema.dump(identity_list).data,
}
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
|
Add "full scale" to antler settings. | from caribou.settings.setting_types import *
from caribou.i18n import _
AntlerSettings = SettingsTopGroup(
_("Antler Preferences"), "/org/gnome/antler/", "org.gnome.antler",
[SettingsGroup("antler", _("Antler"), [
SettingsGroup("appearance", _("Appearance"), [
StringSetting(
"keyboard_type", _("Keyboard Type"), "touch",
_("The keyboard geometery Caribou should use"),
_("The keyboard geometery determines the shape "
"and complexity of the keyboard, it could range from "
"a 'natural' look and feel good for composing simple "
"text, to a fullscale keyboard."),
allowed=[(('touch'), _('Touch')),
(('fullscale'), _('Full scale')),
(('scan'), _('Scan'))]),
BooleanSetting("use_system", _("Use System Theme"),
True, _("Use System Theme")),
FloatSetting("min_alpha", _("Minimum Alpha"),
0.2, _("Minimal opacity of keyboard"),
min=0.0, max=1.0),
FloatSetting("max_alpha", _("Maximum Alpha"),
1.0, _("Maximal opacity of keyboard"),
min=0.0, max=1.0),
IntegerSetting("max_distance", _("Maximum Distance"),
100, _("Maximum distance when keyboard is hidden"),
min=0, max=1024)
])
])
])
| from caribou.settings.setting_types import *
from caribou.i18n import _
AntlerSettings = SettingsTopGroup(
_("Antler Preferences"), "/org/gnome/antler/", "org.gnome.antler",
[SettingsGroup("antler", _("Antler"), [
SettingsGroup("appearance", _("Appearance"), [
StringSetting(
"keyboard_type", _("Keyboard Type"), "touch",
_("The keyboard geometery Caribou should use"),
_("The keyboard geometery determines the shape "
"and complexity of the keyboard, it could range from "
"a 'natural' look and feel good for composing simple "
"text, to a fullscale keyboard."),
allowed=[(('touch'), _('Touch')),
(('scan'), _('Scan'))]),
BooleanSetting("use_system", _("Use System Theme"),
True, _("Use System Theme")),
FloatSetting("min_alpha", _("Minimum Alpha"),
0.2, _("Minimal opacity of keyboard"),
min=0.0, max=1.0),
FloatSetting("max_alpha", _("Maximum Alpha"),
1.0, _("Maximal opacity of keyboard"),
min=0.0, max=1.0),
IntegerSetting("max_distance", _("Maximum Distance"),
100, _("Maximum distance when keyboard is hidden"),
min=0, max=1024)
])
])
])
|
BAP-9376: Create unit tests for ApiBundle. Fix ExpandRelatedEntities and FilterFieldsByExtra. Unit tests for ExpandRelatedEntities, FilterFieldsByExtra, CompleteDefinition, EnsureInitialized | <?php
namespace Oro\Bundle\ApiBundle\Config;
use Oro\Bundle\ApiBundle\Processor\Config\ConfigContext;
/**
* An instance of this class can be added to the config extras of the Context
* to request to add related entities to a result.
*/
class ExpandRelatedEntitiesConfigExtra implements ConfigExtraInterface
{
const NAME = 'expand_related_entities';
/** @var string[] */
protected $expandedEntities;
/**
* @param string[] $expandedEntities The list of related entities.
* Each item can be an association name or a path to a nested association.
* Example: ["comments", "comments.author"]
* Where "comments" is an association under a primary entity,
* "author" is an association under the "comments" entity.
*/
public function __construct(array $expandedEntities)
{
$this->expandedEntities = $expandedEntities;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return self::NAME;
}
/**
* {@inheritdoc}
*/
public function configureContext(ConfigContext $context)
{
$context->set(self::NAME, $this->expandedEntities);
}
/**
* {@inheritdoc}
*/
public function isInheritable()
{
return false;
}
/**
* {@inheritdoc}
*/
public function getCacheKeyPart()
{
return 'expand:' . implode(',', $this->expandedEntities);
}
}
| <?php
namespace Oro\Bundle\ApiBundle\Config;
use Oro\Bundle\ApiBundle\Processor\Config\ConfigContext;
/**
* An instance of this class can be added to the config extras of the Context
* to request to add related entities to a result.
*/
class ExpandRelatedEntitiesConfigExtra implements ConfigExtraInterface
{
const NAME = 'expand_related_entities';
/** @var string[] */
protected $expandedEntities;
/**
* @param string[] $expandedEntities The list of related entities.
* Each item can be an association name or a path to a nested association.
* Example: ["comments", "comments.author"]
* Where "comments" is an association under the "articles" entity,
* "author" is an association under the "comments" entity.
*/
public function __construct(array $expandedEntities)
{
$this->expandedEntities = $expandedEntities;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return self::NAME;
}
/**
* {@inheritdoc}
*/
public function configureContext(ConfigContext $context)
{
$context->set(self::NAME, $this->expandedEntities);
}
/**
* {@inheritdoc}
*/
public function isInheritable()
{
return false;
}
/**
* {@inheritdoc}
*/
public function getCacheKeyPart()
{
return 'expand:' . implode(',', $this->expandedEntities);
}
}
|
Add assert for response status code | package com.skogsrud.halvard.springmvc.spike.controller;
import com.skogsrud.halvard.springmvc.spike.tomcat.Server;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.ServerSocket;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class HelloWorldControllerIT {
private static Server server;
private static int port;
private static OkHttpClient client;
@BeforeClass
public static void beforeClass() throws Exception {
port = findRandomOpenPort();
server = new Server(port);
server.start();
client = new OkHttpClient();
}
@AfterClass
public static void afterClass() throws Exception {
server.stop();
}
@Test
public void testHelloWorld() throws Exception {
Request request = new Request.Builder()
.url("http://localhost:" + port + "/app/hello")
.build();
Response response = client.newCall(request).execute();
assertThat(response.code(), equalTo(200));
assertThat(response.body().string(), equalTo("Hello world"));
}
private static int findRandomOpenPort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
}
| package com.skogsrud.halvard.springmvc.spike.controller;
import com.skogsrud.halvard.springmvc.spike.tomcat.Server;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.ServerSocket;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class HelloWorldControllerIT {
private static Server server;
private static int port;
private static OkHttpClient client;
@BeforeClass
public static void beforeClass() throws Exception {
port = findRandomOpenPort();
server = new Server(port);
server.start();
client = new OkHttpClient();
}
@AfterClass
public static void afterClass() throws Exception {
server.stop();
}
@Test
public void testHelloWorld() throws Exception {
Request request = new Request.Builder()
.url("http://localhost:" + port + "/app/hello")
.build();
Response response = client.newCall(request).execute();
assertThat(response.body().string(), equalTo("Hello world"));
}
private static int findRandomOpenPort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
}
|
Clean up this code a bit (no functional change) | from django.forms import Widget
from django.template.loader import render_to_string
from ..utils import static_url
class GenericKeyWidget(Widget):
template = "admin/hatband/widgets/generickey.html"
class Media:
js = (static_url("visualsearch/dependencies.js"),
static_url("visualsearch/visualsearch.js"),
static_url("generickey.js"),
)
css = {
"all": (static_url("visualsearch/visualsearch.css"),
static_url("hatband/css/generickey.css"),
)
}
def __init__(self, object_id_name="object_id",
content_type_name="content_type", *args, **kwargs):
super(GenericKeyWidget, self).__init__(*args, **kwargs)
self.object_id_name = object_id_name
self.content_type_name = content_type_name
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
final_attrs.update({
"value": value,
"is_templated": final_attrs["id"].find("__prefix__") > -1,
"object_id_name": self.object_id_name,
"content_type_name": self.content_type_name,
})
return render_to_string(self.template, final_attrs)
| from django.forms import Widget
from django.template.loader import render_to_string
from ..utils import static_url
class GenericKeyWidget(Widget):
template = "admin/hatband/widgets/generickey.html"
class Media:
js = (static_url("visualsearch/dependencies.js"),
static_url("visualsearch/visualsearch.js"),
static_url("generickey.js"),
)
css = {
"all": (static_url("visualsearch/visualsearch.css"),
static_url("hatband/css/generickey.css"),
)
}
def __init__(self, object_id_name="object_id",
content_type_name="content_type", *args, **kwargs):
super(GenericKeyWidget, self).__init__(*args, **kwargs)
self.object_id_name = object_id_name
self.content_type_name = content_type_name
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
final_attrs["value"] = value
final_attrs["is_templated"] = final_attrs["id"].find("__prefix__") > -1
final_attrs["object_id_name"] = self.object_id_name
final_attrs["content_type_name"] = self.content_type_name
return render_to_string(self.template, final_attrs)
|
BB-4083: Remove information from ORM engine
- refactor to accept object and array to delete method | <?php
namespace Oro\Bundle\SearchBundle\Engine;
interface IndexerInterface
{
/**
* Save one of several entities to search index
*
* @param object|array $entity
* @param array $context
*
* @return bool
*/
public function save($entity, array $context = []);
/**
* Delete one or several entities from search index
*
* @param object|array $entity
* @param array $context
*
* @return bool
*/
public function delete($entity, array $context = []);
/**
* Returns classes required to reindex for one or several classes
* Returns all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*
* @return string[]
*/
public function getClassesForReindex($class = null, array $context = []);
/**
* Resets data for one or several classes in index
* Resets data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*/
public function resetIndex($class = null, array $context = []);
/**
* Reindex data for one or several classes in index
* Reindex data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*
* @return int Number of reindexed entities
*/
public function reindex($class = null, array $context = []);
}
| <?php
namespace Oro\Bundle\SearchBundle\Engine;
interface IndexerInterface
{
/**
* Save one of several entities to search index
*
* @param object|array $entity
* @param array $context
*
* @return bool
*/
public function save($entity, array $context = []);
/**
* Delete one or several entities from search index
*
* @param array $entity
* @param array $context
*
* @return bool
*/
public function delete(array $entity, array $context = []);
/**
* Returns classes required to reindex for one or several classes
* Returns all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*
* @return string[]
*/
public function getClassesForReindex($class = null, array $context = []);
/**
* Resets data for one or several classes in index
* Resets data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*/
public function resetIndex($class = null, array $context = []);
/**
* Reindex data for one or several classes in index
* Reindex data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*
* @return int Number of reindexed entities
*/
public function reindex($class = null, array $context = []);
}
|
Fix method to always return a value. | Application.Services.factory('Events', ['$filter', EventsService]);
function EventsService($filter) {
var service = {
date: '',
addConvertedTime: function (project) {
project.reviews = service.update(project.open_reviews);
project.samples = service.update(project.samples);
project.processes = service.update(project.processes);
project.notes = service.update(project.notes);
project.drafts = service.update(project.drafts);
return project;
},
update: function (items) {
items.forEach(function (item) {
var item_date = new Date(0);
item_date.setUTCSeconds(item.mtime.epoch_time);
item.converted_mtime = Date.UTC(item_date.getUTCFullYear(), item_date.getUTCMonth(), item_date.getUTCDay());
});
return items;
},
prepareCalendarEvent: function (items) {
var calendar_event = [];
if (items.length !== 0) {
var grouped_by_convertedtime = $filter('groupBy')(items, 'converted_mtime');
Object.keys(grouped_by_convertedtime).forEach(function (key) {
var d = new Date(0);
var value = grouped_by_convertedtime[key][0];
d.setUTCSeconds(value.mtime.epoch_time);
calendar_event.push({title: value.title, start: d});
});
}
return calendar_event;
},
updateDate: function (project, date) {
project.date = date;
return project;
}
};
return service;
}
| Application.Services.factory('Events', ['$filter', EventsService]);
function EventsService($filter) {
var service = {
date: '',
addConvertedTime: function (project) {
project.reviews = service.update(project.open_reviews);
project.samples = service.update(project.samples);
project.processes = service.update(project.processes);
project.notes = service.update(project.notes);
project.drafts = service.update(project.drafts);
return project;
},
update: function (items) {
items.forEach(function (item) {
var item_date = new Date(0);
item_date.setUTCSeconds(item.mtime.epoch_time);
item.converted_mtime = Date.UTC(item_date.getUTCFullYear(), item_date.getUTCMonth(), item_date.getUTCDay());
});
return items;
},
prepareCalendarEvent: function (items) {
var calendar_event = [];
if (items.length !== 0) {
var grouped_by_convertedtime = $filter('groupBy')(items, 'converted_mtime');
Object.keys(grouped_by_convertedtime).forEach(function (key) {
var d = new Date(0);
var value = grouped_by_convertedtime[key][0];
d.setUTCSeconds(value.mtime.epoch_time);
calendar_event.push({title: value.title, start: d});
});
return calendar_event;
}
},
updateDate: function (project, date) {
project.date = date;
return project;
}
};
return service;
}
|
Change key and value to more descriptive names |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, str):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, str):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
|
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, str):
value = [value]
errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value])
else:
if isinstance(message, str):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
|
Add error for non text file | <?php
namespace fennecweb\ajax\upload;
use \PDO as PDO;
/**
* Web Service.
* Uploads Project biom files and save them in the database
*/
class Project extends \fennecweb\WebService
{
/**
* @param $querydata[]
* @returns result of file upload
*/
public function execute($querydata)
{
$db = $this->openDbConnection($querydata);
$files = array();
for ($i=0; $i<sizeof($_FILES['files']['tmp_names']); $i++) {
$valid = $this->validateFile($_FILES['files']['tmp_names'][$i]);
$file = array(
"name" => $_FILES['files']['names'][$i],
"size" => $_FILES['files']['sizes'][$i],
"error" => ($valid === true ? null : $valid)
);
$files[] = $file;
}
return array("files" => $files);
}
/**
* Function that checks the uploaded file for validity
* @param String $filename the uploaded file to check
* @returns Either TRUE if the file is valid or a String containing the error message
*/
protected function validateFile($filename)
{
if (!is_uploaded_file($filename)) {
return "Error. There was an error in your request.";
}
$contents = file_get_contents($filename);
if ($contents === false) {
return "Error. Not a text file.";
}
}
}
| <?php
namespace fennecweb\ajax\upload;
use \PDO as PDO;
/**
* Web Service.
* Uploads Project biom files and save them in the database
*/
class Project extends \fennecweb\WebService
{
/**
* @param $querydata[]
* @returns result of file upload
*/
public function execute($querydata)
{
$db = $this->openDbConnection($querydata);
$files = array();
for ($i=0; $i<sizeof($_FILES['files']['tmp_names']); $i++) {
$valid = $this->validateFile($_FILES['files']['tmp_names'][$i]);
$file = array(
"name" => $_FILES['files']['names'][$i],
"size" => $_FILES['files']['sizes'][$i],
"error" => ($valid === true ? null : $valid)
);
$files[] = $file;
}
return array("files" => $files);
}
/**
* Function that checks the uploaded file for validity
* @param String $filename the uploaded file to check
* @returns Either TRUE if the file is valid or a String containing the error message
*/
protected function validateFile($filename)
{
if (!is_uploaded_file($filename)) {
return "Error. There was an error in your request.";
}
}
}
|
Remove version from minified filename | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
mini_src: {
options: {
banner: '/*! <%= pkg.name %>.min.js v<%= pkg.version %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
files: {
'./<%= pkg.name %>.min.js': 'src/<%= pkg.name %>.js'
}
}
},
less: {
development: {
files: {
"example/styles/clndr.css": "example/styles/clndr.less"
}
},
production: {
options: {
compress: true,
report: "min",
sourceMap: true
},
files: {
"example/styles/clndr.css": "example/styles/clndr.less"
}
}
},
watch: {
options: {
livereload: true
},
uglify: {
files: ['src/*.js'],
tasks: ['uglify'],
options: {
spawn: false,
debounceDelay: 1000 // Don't call uglify more than once per second
}
},
less: {
files: ['example/styles/*.less'],
tasks: ['less:development']
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['uglify', 'less:development']);
}; | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
mini_src: {
options: {
banner: '/*! <%= pkg.name %>.min.js v<%= pkg.version %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
files: {
'./<%= pkg.name %>-<%= pkg.version %>.min.js': 'src/<%= pkg.name %>.js'
}
}
},
less: {
development: {
files: {
"example/styles/clndr.css": "example/styles/clndr.less"
}
},
production: {
options: {
compress: true,
report: "min",
sourceMap: true
},
files: {
"example/styles/clndr.css": "example/styles/clndr.less"
}
}
},
watch: {
options: {
livereload: true
},
uglify: {
files: ['src/*.js'],
tasks: ['uglify'],
options: {
spawn: false,
debounceDelay: 1000 // Don't call uglify more than once per second
}
},
less: {
files: ['example/styles/*.less'],
tasks: ['less:development']
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['uglify', 'less:development']);
}; |
Implement setCredentials on the mock OAuth2 client
Fixes broken unit tests.
The implementation looks kind of ridiculous, but it's not terribly different
from what Google does themselves as of 1.1.3:
https://github.com/google/google-api-nodejs-client/blob/bd356c38efc5ac460f319e4d0b005425013720cb/lib/auth/authclient.js#L33-L39 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const assert = require('assert');
const querystring = require('querystring');
var MockOAuth2Client = {
generateAuthUrl: function (options) {
return this.options.url + '?' + querystring.stringify(options);
},
getToken: function (code, callback) {
callback(null, 'token');
},
setCredentials: function(credentials) {
this.credentials = credentials;
}
};
var MockUserInfo = {
get: function (params, callback) {
// make sure the credentials get set to the expected token
if (params.auth.credentials === 'token') {
callback(null, {
/*jshint camelcase: false*/
verified_email: this.options.result.authenticated,
email: this.options.result.email
});
}
}
};
module.exports = function mockid(options) {
return {
auth: {
OAuth2: function (clientId, clientSecret, redirectUri) {
assert.ok(clientId);
assert.ok(clientSecret);
assert.ok(redirectUri);
var client = Object.create(MockOAuth2Client);
client.options = options;
return client;
}
},
oauth2: function (version) {
assert.ok(version);
var userInfo = Object.create(MockUserInfo);
userInfo.options = options;
return {
userinfo: userInfo
};
}
};
};
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const assert = require('assert');
const querystring = require('querystring');
var MockOAuth2Client = {
generateAuthUrl: function (options) {
return this.options.url + '?' + querystring.stringify(options);
},
getToken: function (code, callback) {
callback(null, 'token');
}
};
var MockUserInfo = {
get: function (params, callback) {
// make sure the credentials get set to the expected token
if (params.auth.credentials === 'token') {
callback(null, {
/*jshint camelcase: false*/
verified_email: this.options.result.authenticated,
email: this.options.result.email
});
}
}
};
module.exports = function mockid(options) {
return {
auth: {
OAuth2: function (clientId, clientSecret, redirectUri) {
assert.ok(clientId);
assert.ok(clientSecret);
assert.ok(redirectUri);
var client = Object.create(MockOAuth2Client);
client.options = options;
return client;
}
},
oauth2: function (version) {
assert.ok(version);
var userInfo = Object.create(MockUserInfo);
userInfo.options = options;
return {
userinfo: userInfo
};
}
};
};
|
Add script/lint --fix which fixes some code formatting issues via eslint | 'use strict'
const path = require('path')
const {spawn} = require('child_process')
const process = require('process')
const CONFIG = require('../config')
module.exports = async function () {
return new Promise((resolve, reject) => {
const eslintArgs = ['--cache', '--format', 'json']
if (process.argv.includes('--fix')) {
eslintArgs.push('--fix')
}
const eslint = spawn(
path.join('script', 'node_modules', '.bin', 'eslint'),
[...eslintArgs, '.'],
{ cwd: CONFIG.repositoryRootPath }
)
let output = ''
let errorOutput = ''
eslint.stdout.on('data', data => {
output += data.toString()
})
eslint.stderr.on('data', data => {
errorOutput += data.toString()
})
eslint.on('error', error => reject(error))
eslint.on('close', exitCode => {
const errors = []
let files
try {
files = JSON.parse(output)
} catch (_) {
reject(errorOutput)
return
}
for (const file of files) {
for (const error of file.messages) {
errors.push({
path: file.filePath,
message: error.message,
lineNumber: error.line,
rule: error.ruleId
})
}
}
resolve(errors)
})
})
}
| 'use strict'
const path = require('path')
const {spawn} = require('child_process')
const CONFIG = require('../config')
module.exports = async function () {
return new Promise((resolve, reject) => {
const eslint = spawn(
path.join('script', 'node_modules', '.bin', 'eslint'),
['--cache', '--format', 'json', '.'],
{ cwd: CONFIG.repositoryRootPath }
)
let output = ''
let errorOutput = ''
eslint.stdout.on('data', data => {
output += data.toString()
})
eslint.stderr.on('data', data => {
errorOutput += data.toString()
})
eslint.on('error', error => reject(error))
eslint.on('close', exitCode => {
const errors = []
let files
try {
files = JSON.parse(output)
} catch (_) {
reject(errorOutput)
return
}
for (const file of files) {
for (const error of file.messages) {
errors.push({
path: file.filePath,
message: error.message,
lineNumber: error.line,
rule: error.ruleId
})
}
}
resolve(errors)
})
})
}
|
Remove nom_port from options. This should be infered by the controller name. Add a name member for that. For now, infer the controller from the commandline string' | import itertools
import string
class ControllerConfig(object):
_port_gen = itertools.count(8888)
def __init__(self, cmdline="", address="127.0.0.1", port=None):
'''
Store metadata for the controller.
- cmdline is an array of command line tokens.
Note: if you need to pass in the address and port to controller's
command line, use the aliases __address__ and __port__ to have the
values interpolated automatically
- address and port are the sockets switches will bind to
'''
if cmdline == "":
raise RuntimeError("Must specify boot parameters.")
self.cmdline_string = cmdline
self.address = address
if not port:
port = self._port_gen.next()
self.port = port
if "pox" in self.cmdline_string:
self.name = "pox"
self.cmdline = map(lambda(x): string.replace(x, "__port__", str(port)),
map(lambda(x): string.replace(x, "__address__",
str(address)), cmdline.split()))
@property
def uuid(self):
return (self.address, self.port)
def __repr__(self):
return self.__class__.__name__ + "(cmdline=\"" + self.cmdline_string +\
"\",address=\"" + self.address + "\",port=" + self.port.__repr__() + ")"
| import itertools
import string
class ControllerConfig(object):
_port_gen = itertools.count(8888)
def __init__(self, cmdline="", address="127.0.0.1", port=None, nom_port=None):
'''
Store metadata for the controller.
- cmdline is an array of command line tokens.
Note: if you need to pass in the address and port to controller's
command line, use the aliases __address__ and __port__ to have the
values interpolated automatically
- address and port are the sockets switches will bind to
- address and nom_port is the socket the simulator will use to grab the
NOM from (None for no correspondence checking)
'''
self.address = address
if cmdline == "":
raise RuntimeError("Must specify boot parameters.")
self.cmdline_string = cmdline
if not port:
port = self._port_gen.next()
self.port = port
self.nom_port = nom_port
self.cmdline = map(lambda(x): string.replace(x, "__port__", str(port)),
map(lambda(x): string.replace(x, "__address__",
str(address)), cmdline.split()))
@property
def uuid(self):
return (self.address, self.port)
def __repr__(self):
return self.__class__.__name__ + "(cmdline=\"" + self.cmdline_string +\
"\",address=\"" + self.address + "\",port=" + self.port.__repr__() +\
",nom_port=" + self.nom_port.__repr__() + ")"
|
Fix issue with switching when there is dual supply | $(document).on("turbolinks:load", function() {
$(".first-date-picker").datepicker(
{
dateFormat: 'DD, d MM yy',
altFormat: 'yy-mm-dd',
altField: $(".first-date-picker").parents("form:first").find("#first_date"),
// minDate: -42,
maxDate: -1,
orientation: 'bottom',
changeMonth: true,
changeYear: true
});
$(".to-date-picker").datepicker(
{
dateFormat: 'DD, d MM yy',
altFormat: 'yy-mm-dd',
altField: $(".first-date-picker").parents("form:first").find("#to_date"),
// minDate: -42,
maxDate: -1,
orientation: 'bottom',
changeMonth: true,
changeYear: true
});
});
function updateChart(el) {
chart_id = el.form.id.replace("-filter", "");
chart = Chartkick.charts[chart_id];
current_source = chart.getDataSource();
new_source = current_source.split("?")[0] + "?" + $(el.form).serialize();
chart.updateData(new_source);
chart.getChartObject().showLoading();
}
$(document).on('change', '.meter-filter', function() {
updateChart(this);
});
$(document).on('change', '.first-date-picker', function() {
updateChart(this);
});
$(document).on('change', '.to-date-picker', function() {
updateChart(this);
});
| $(document).on("turbolinks:load", function() {
$(".first-date-picker").datepicker(
{
dateFormat: 'DD, d MM yy',
altFormat: 'yy-mm-dd',
altField: "#first_date",
// minDate: -42,
maxDate: -1,
orientation: 'bottom',
changeMonth: true,
changeYear: true
});
$(".to-date-picker").datepicker(
{
dateFormat: 'DD, d MM yy',
altFormat: 'yy-mm-dd',
altField: "#to_date",
// minDate: -42,
maxDate: -1,
orientation: 'bottom',
changeMonth: true,
changeYear: true
});
});
function updateChart(el) {
chart_id = el.form.id.replace("-filter", "");
chart = Chartkick.charts[chart_id];
current_source = chart.getDataSource();
new_source = current_source.split("?")[0] + "?" + $(el.form).serialize();
chart.updateData(new_source);
chart.getChartObject().showLoading();
}
$(document).on('change', '.meter-filter', function() {
updateChart(this);
});
$(document).on('change', '.first-date-picker', function() {
updateChart(this);
});
$(document).on('change', '.to-date-picker', function() {
updateChart(this);
});
|
Use "meta" block for logging variables | <?php
namespace Rogue\Services;
use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a GraphQL query using the client and return the data result.
*
* @param $query String
* @param $variables Array
* @return array|null
*/
public function query($query, $variables)
{
// Use try/catch to avoid any GraphQL related errors breaking the application.
try {
$response = $this->client->query($query, $variables);
} catch (\Exception $exception) {
Log::error('GraphQL request failed.', [
'query' => $query,
'variables' => $variables,
'exception' => $exception->getMessage(),
]);
return null;
}
return $response ? $response->getData() : null;
}
/**
* Query for a CampaignWebsite by campaignId field.
*
* @param $campaignId String
* @return array|null
*/
public function getCampaignWebsiteByCampaignId($campaignId)
{
$query = '
query GetCampaignWebsiteByCampaignId($campaignId: String!) {
campaignWebsiteByCampaignId(campaignId: $campaignId) {
title
slug
}
}';
$variables = [
'campaignId' => $campaignId,
];
return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
}
}
| <?php
namespace Rogue\Services;
use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a GraphQL query using the client and return the data result.
*
* @param $query String
* @param $variables Array
* @return array|null
*/
public function query($query, $variables)
{
// Use try/catch to avoid any GraphQL related errors breaking the application.
try {
$response = $this->client->query($query, $variables);
} catch (\Exception $exception) {
Log::error(
'GraphQL request failed. Query: '.$query
.' Variables: '.json_encode($variables).' Exception: '.$exception->getMessage()
);
return null;
}
return $response ? $response->getData() : null;
}
/**
* Query for a CampaignWebsite by campaignId field.
*
* @param $campaignId String
* @return array|null
*/
public function getCampaignWebsiteByCampaignId($campaignId)
{
$query = '
query GetCampaignWebsiteByCampaignId($campaignId: String!) {
campaignWebsiteByCampaignId(campaignId: $campaignId) {
title
slug
}
}';
$variables = [
'campaignId' => $campaignId,
];
return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
}
}
|
Add more assertions for Favicon | <?php namespace Arcanedev\Head\Tests\Entities;
use Arcanedev\Head\Entities\Favicon;
/**
* Class FaviconTest
* @package Arcanedev\Head\Tests\Entities
*/
class FaviconTest extends TestCase
{
/* ------------------------------------------------------------------------------------------------
| Properties
| ------------------------------------------------------------------------------------------------
*/
/** @var Favicon */
private $favicon;
/* ------------------------------------------------------------------------------------------------
| Main Functions
| ------------------------------------------------------------------------------------------------
*/
public function setUp()
{
parent::setUp();
$this->favicon = new Favicon('favicon');
}
public function tearDown()
{
parent::tearDown();
unset($this->favicon);
}
/* ------------------------------------------------------------------------------------------------
| Test Functions
| ------------------------------------------------------------------------------------------------
*/
/** @test */
public function test_can_be_instantiated()
{
$this->favicon = new Favicon;
$this->assertInstanceOf(Favicon::class, $this->favicon);
$this->assertEmpty($this->favicon->render());
}
/** @test */
public function test_can_render()
{
$this->assertEquals(
implode(PHP_EOL, [
'<link href="' . base_url('favicon.ico') . '" rel="icon" type="image/x-icon"/>',
'<link href="' . base_url('favicon.png') . '" rel="icon" type="image/png"/>'
]),
$this->favicon->render()
);
}
}
| <?php namespace Arcanedev\Head\Tests\Entities;
use Arcanedev\Head\Entities\Favicon;
/**
* Class FaviconTest
* @package Arcanedev\Head\Tests\Entities
*/
class FaviconTest extends TestCase
{
/* ------------------------------------------------------------------------------------------------
| Properties
| ------------------------------------------------------------------------------------------------
*/
/** @var Favicon */
private $favicon;
/* ------------------------------------------------------------------------------------------------
| Main Functions
| ------------------------------------------------------------------------------------------------
*/
public function setUp()
{
parent::setUp();
$this->favicon = new Favicon('favicon');
}
public function tearDown()
{
parent::tearDown();
unset($this->favicon);
}
/* ------------------------------------------------------------------------------------------------
| Test Functions
| ------------------------------------------------------------------------------------------------
*/
/** @test */
public function test_can_be_instantiated()
{
$this->assertInstanceOf(Favicon::class, $this->favicon);
}
/** @test */
public function test_can_render()
{
$this->assertEquals(
implode(PHP_EOL, [
'<link href="' . base_url('favicon.ico') . '" rel="icon" type="image/x-icon"/>',
'<link href="' . base_url('favicon.png') . '" rel="icon" type="image/png"/>'
]),
$this->favicon->render()
);
}
}
|
Make donuts display raw values | function toggleDisp(){
var txt = document.getElementById('asText');
var box = document.getElementById('asBoxed');
if (txt.style.display == 'none') {
box.style.display = 'none';
txt.style.display = 'block';
}
else {
txt.style.display = 'none';
box.style.display = 'block';
}
}
function addGraphs(){
addPie("Code Point Ages", "ages");
addPie("Block Names", "blocks");
addBar("Bytes to Encode", "sizes")
}
function addPie(title, data){
c3.generate({
bindto: '#'+data,
data: {
columns: toGraph[data] ,
type : 'donut'
},
donut: {
title: title,
label: {
format: function (value, ratio, id) {
return value;
}
}
}
});
}
function addBar(title, data){
c3.generate({
bindto: '#'+data,
data: {
columns: toGraph[data],
type: 'bar'
},
bar: {
title: title
},
axis: {
x: {
show: false,
ratio: 1
},
y:{
tick: {
format: function(d){return d + "B"}
}
},
rotated: true
},
tooltip: {
grouped: false,
format:{
title: function () { return 'Bytes to encode'}
}
},
grid: {
x:{
show:false
}
}
});
}
addGraphs(); | function toggleDisp(){
var txt = document.getElementById('asText');
var box = document.getElementById('asBoxed');
if (txt.style.display == 'none') {
box.style.display = 'none';
txt.style.display = 'block';
}
else {
txt.style.display = 'none';
box.style.display = 'block';
}
}
function addGraphs(){
addPie("Code Point Ages", "ages");
addPie("Block Names", "blocks");
addBar("Bytes to Encode", "sizes")
}
function addPie(title, data){
c3.generate({
bindto: '#'+data,
data: {
columns: toGraph[data] ,
type : 'donut'
},
donut: {
title: title
}
});
}
function addBar(title, data){
c3.generate({
bindto: '#'+data,
data: {
columns: toGraph[data],
type: 'bar'
},
bar: {
title: title
},
axis: {
x: {
show: false,
ratio: 1
},
y:{
tick: {
format: function(d){return d + "B"}
}
},
rotated: true
},
tooltip: {
grouped: false,
format:{
title: function () { return 'Bytes to encode'}
}
},
grid: {
x:{
show:false
}
}
});
}
addGraphs(); |
Fix crash in FAB background tint am: 9d42ab847a
am: 3b28559aa3
* commit '3b28559aa396a40992b1c9e7e1e8af215340cd05':
Fix crash in FAB background tint
GitOrigin-RevId=84921ceb7940a7ce40affb58f22b4a11b35a3e60
PiperOrigin-RevId: 140551245 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.design.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageButton;
class VisibilityAwareImageButton extends ImageButton {
private int mUserSetVisibility;
public VisibilityAwareImageButton(Context context) {
this(context, null);
}
public VisibilityAwareImageButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mUserSetVisibility = getVisibility();
}
@Override
public void setVisibility(int visibility) {
internalSetVisibility(visibility, true);
}
final void internalSetVisibility(int visibility, boolean fromUser) {
super.setVisibility(visibility);
if (fromUser) {
mUserSetVisibility = visibility;
}
}
final int getUserSetVisibility() {
return mUserSetVisibility;
}
}
| /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.design.widget;
import android.content.Context;
import android.support.v7.widget.AppCompatImageButton;
import android.util.AttributeSet;
class VisibilityAwareImageButton extends AppCompatImageButton {
private int mUserSetVisibility;
public VisibilityAwareImageButton(Context context) {
this(context, null);
}
public VisibilityAwareImageButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mUserSetVisibility = getVisibility();
}
@Override
public void setVisibility(int visibility) {
internalSetVisibility(visibility, true);
}
final void internalSetVisibility(int visibility, boolean fromUser) {
super.setVisibility(visibility);
if (fromUser) {
mUserSetVisibility = visibility;
}
}
final int getUserSetVisibility() {
return mUserSetVisibility;
}
}
|
Fix script not working from bash | #!/usr/bin/env python3
import subprocess
class NvidiaCommandsLayerException(Exception):
pass
class NvidiaCommandsLayer(object):
@staticmethod
def set_fan_percentage(
value: int
) -> None:
if value < 0 or value > 100:
raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100')
result = subprocess.run(
'nvidia-settings '
'-a "[gpu:0]/GPUFanControlState=1" '
'-a "[fan:0]/GPUTargetFanSpeed={}"'.format(value),
stdout=subprocess.PIPE,
shell=True
)
if result.returncode != 0:
raise NvidiaCommandsLayerException('Could not set the fan speed')
@staticmethod
def read_temperature(
) -> int:
result = subprocess.run(
[
'nvidia-smi',
'--query-gpu=temperature.gpu',
'--format=csv,noheader,nounits'
],
stdout=subprocess.PIPE
)
if result.returncode == 0:
# the result is a string with a '\n' at the end, convert it to a decimal
return int(result.stdout[:-1])
else:
raise NvidiaCommandsLayerException('Could not read the temperature')
| #!/usr/bin/env python3.5
import subprocess
class NvidiaCommandsLayerException(Exception):
pass
class NvidiaCommandsLayer(object):
@staticmethod
def set_fan_percentage(
value: int
) -> None:
if value < 0 or value > 100:
raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100')
result = subprocess.run(
[
'nvidia-settings',
'-a',
'"[gpu:0]/GPUFanControlState=1"',
'-a',
'"[fan:0]/GPUTargetFanSpeed={}"'.format(value)
],
stdout=subprocess.PIPE
)
if result.returncode != 0:
raise NvidiaCommandsLayerException('Could not set the fan speed')
@staticmethod
def read_temperature(
) -> int:
result = subprocess.run(
[
'nvidia-smi',
'--query-gpu=temperature.gpu',
'--format=csv,noheader,nounits'
],
stdout=subprocess.PIPE
)
if result.returncode == 0:
# the result is a string with a '\n' at the end, convert it to a decimal
return int(result.stdout[:-1])
else:
raise NvidiaCommandsLayerException('Could not read the temperature')
|
Add support for deleting relationship | import { decamelize } from 'humps';
function serializeRelationships(resources = []) {
return resources.map((resource) => serializeRelationship(resource));
}
function serializeRelationship({ id, _type } = {}) {
return { id, type: _type };
}
function serialize({ id, _type, _meta, ...otherAttributes }) {
let resource = {};
if (id) resource = { ...resource, id };
resource = { ...resource, type: _type }
resource = Object.keys(otherAttributes).reduce((resource, key) => {
if (typeof otherAttributes[key] === 'function') {
const data = otherAttributes[key].call();
if (Array.isArray(data)) {
return {
...resource,
relationships: {
...resource.relationships,
[decamelize(key)]: {
data: serializeRelationships(data),
},
},
};
}
return {
...resource,
relationships: {
...resource.relationships,
[decamelize(key)]: {
data: data && serializeRelationship(data),
},
},
};
}
return {
...resource,
attributes: {
...resource.attributes,
[decamelize(key)]: otherAttributes[key],
},
};
}, resource);
if (_meta) resource = { ...resource, meta: _meta };
return resource;
}
export default serialize;
| import { decamelize } from 'humps';
function serializeRelationships(resources = []) {
return resources.map((resource) => serializeRelationship(resource));
}
function serializeRelationship({ id, _type } = {}) {
return { id, type: _type };
}
function serialize({ id, _type, _meta, ...otherAttributes }) {
let resource = {};
if (id) resource = { ...resource, id };
resource = { ...resource, type: _type }
resource = Object.keys(otherAttributes).reduce((resource, key) => {
if (typeof otherAttributes[key] === 'function') {
const data = otherAttributes[key].call();
if (data) {
if (Array.isArray(data)) {
return {
...resource,
relationships: {
...resource.relationships,
[decamelize(key)]: {
data: serializeRelationships(data),
},
},
};
}
return {
...resource,
relationships: {
...resource.relationships,
[decamelize(key)]: {
data: serializeRelationship(data),
},
},
};
}
}
return {
...resource,
attributes: {
...resource.attributes,
[decamelize(key)]: otherAttributes[key],
},
};
}, resource);
if (_meta) resource = { ...resource, meta: _meta };
return resource;
}
export default serialize;
|
Add return to method (corrected typo) | <?php
namespace Coreplex\Meta\Eloquent;
use Coreplex\Meta\Contracts\Variant;
trait HasMetaData
{
/**
* Retrieve the meta data for this model
*
* @param Variant $variant
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function meta(Variant $variant = null)
{
if ( ! $variant) {
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
}
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
->where('variant_id', $variant->getKey())
->where('variant_type', $variant->getType());
}
/**
* Check if the meta has been set for the metable item, if a variant is
* passed then check if it is set for the variant.
*
* @param Variant|null $variant
* @return bool
*/
public function hasMeta(Variant $variant = null)
{
if (! empty($variant)) {
return $this->meta($variant)->exists();
}
return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->exists();
}
/**
* Get the meta data for the metable item.
*
* @param Variant|null $variant
* @return mixed
*/
public function getMeta(Variant $variant = null)
{
if ($variant) {
return $this->meta($variant)->getResults();
}
return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
}
}
| <?php
namespace Coreplex\Meta\Eloquent;
use Coreplex\Meta\Contracts\Variant;
trait HasMetaData
{
/**
* Retrieve the meta data for this model
*
* @param Variant $variant
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function meta(Variant $variant = null)
{
if ( ! $variant) {
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
}
return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
->where('variant_id', $variant->getKey())
->where('variant_type', $variant->getType());
}
/**
* Check if the meta has been set for the metable item, if a variant is
* passed then check if it is set for the variant.
*
* @param Variant|null $variant
* @return bool
*/
public function hasMeta(Variant $variant = null)
{
if (! empty($variant)) {
return $this->meta($variant)->exists();
}
$this->meta()->whereNull('variant_type')->whereNull('variant_id')->exists();
}
/**
* Get the meta data for the metable item.
*
* @param Variant|null $variant
* @return mixed
*/
public function getMeta(Variant $variant = null)
{
if ($variant) {
return $this->meta($variant)->getResults();
}
return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
}
}
|
Use weights a the layer indicator of point weight | CityDashboard.PointHeatmap = function(layer_params, attr, map, assoc_layer) {
var data = [];
var len = layer_params.points.length;
if (layer_params.weights && layer_params.weights.length >= len) {
for (var i = 0; i < len; i++) {
data[i] = {
location: new google.maps.LatLng(
parseFloat(layer_params.points[i].lat),
parseFloat(layer_params.points[i].lng)
),
weight: layer_params.weights[i]
}
}
} else {
for (var i = 0; i < len; i++) {
data[i] = new google.maps.LatLng(
parseFloat(layer_params.points[i].lat),
parseFloat(layer_params.points[i].lng)
);
}
}
var pointArray = new google.maps.MVCArray(data);
this.heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray,
radius: attr.radius || 10
});
this.heatmap.setMap(map);
};
CityDashboard.PointHeatmap.prototype = Object.create(CityDashboard.Heatmap.prototype);
CityDashboard.PointHeatmap.prototype = {
constructor: CityDashboard.PointHeatmap,
};
| CityDashboard.PointHeatmap = function(layer_params, attr, map, assoc_layer) {
var data = [];
var len = layer_params.points.length;
if (layer_params.weight && layer_params.weight.length >= len) {
for (var i = 0; i < len; i++) {
data[i] = {
location: new google.maps.LatLng(
parseFloat(layer_params.points[i].lat),
parseFloat(layer_params.points[i].lng)
),
weight: layer_params.weight[i]
}
}
} else {
for (var i = 0; i < len; i++) {
data[i] = new google.maps.LatLng(
parseFloat(layer_params.points[i].lat),
parseFloat(layer_params.points[i].lng)
);
}
}
var pointArray = new google.maps.MVCArray(data);
this.heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray,
radius: attr.radius || 10
});
this.heatmap.setMap(map);
};
CityDashboard.PointHeatmap.prototype = Object.create(CityDashboard.Heatmap.prototype);
CityDashboard.PointHeatmap.prototype = {
constructor: CityDashboard.PointHeatmap,
};
|
Add necessary data to server response and improve error handling | const _ = require('lodash');
const config = require('../../../../config/ilmomasiina.config'); // eslint-disable-line
const md5 = require('md5');
module.exports = () => (hook) => {
const models = hook.app.get('models');
const id = hook.id;
const editToken = hook.params.query.editToken;
const fields = [];
const userAnswers = [];
if (editToken !== md5(`${`${hook.id}`}${config.editTokenSalt}`)) {
throw new Error('Invalid editToken');
}
return models.answer
.findAll({ where: { signupId: id } })
.then(answers => answers.map(answer => userAnswers.push(answer.dataValues)))
.then(() => models.signup
.findOne({
where: {
id,
},
})
.then(signup => {
if (signup === null) { // Event not found with id, probably deleted
hook.result = {
signup,
event: null,
};
return hook;
}
return models.quota
.findOne({
where: {
id: signup.quotaId,
},
})
.then(quota =>
models.event
.findOne({
where: {
id: quota.eventId,
},
})
.then((event) =>
event.getQuestions().then((questions) => {
questions.map((question) => {
const answer = _.find(userAnswers, { questionId: question.id });
if (answer) {
fields.push({
...question.dataValues,
answer: answer.answer,
answerId: answer.id,
});
}
});
hook.result = {
signup: { ...signup.dataValues, answers: fields },
event,
};
return hook;
}),
),
);
}),
);
};
| const config = require('../../../../config/ilmomasiina.config'); // eslint-disable-line
const md5 = require('md5');
module.exports = () => (hook) => {
const models = hook.app.get('models');
const id = hook.id;
const editToken = hook.params.query.editToken;
if (editToken !== md5(`${`${hook.id}`}${config.editTokenSalt}`)) {
throw new Error('Invalid editToken');
}
return models.signup
.findOne({
where: {
id,
},
})
.then(signup =>
models.quota
.findOne({
where: {
id: signup.quotaId,
},
})
.then(quota =>
models.event
.findOne({
where: {
id: quota.eventId,
},
})
.then((event) => {
hook.result = {
signup,
event,
};
return hook;
}),
),
);
};
|
[AC-7469] Merge remote-tracking branch 'origin/development' into AC-7469 | # Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(name=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
| # Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(user=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
|
Fix typo in inheritence/super call | """This contains code for setting up parallel tempering calcs"""
########################################################################
# #
# This script was written by Thomas Heavey in 2019. #
# [email protected] [email protected] #
# #
# Copyright 2019 Thomas J. Heavey IV #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or #
# implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
########################################################################
from .simulation import Simulation
class PTSimulation(Simulation):
def __init__(self, *args, **kwargs):
super(PTSimulation, self).__init__(*args, **kwargs)
| """This contains code for setting up parallel tempering calcs"""
########################################################################
# #
# This script was written by Thomas Heavey in 2019. #
# [email protected] [email protected] #
# #
# Copyright 2019 Thomas J. Heavey IV #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or #
# implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
########################################################################
from .simulation import Simulation
class PTSimulation(Simulation):
def __init__(self, *args, **kwargs):
super(Simulation, self).__init__(*args, **kwargs)
|
Revert "Rebug sur le bouton ajouter quand on est en mode ajout le bouton n'est pas affichΓ©"
This reverts commit 039afa977340c9ae0342dd5cf9b03114768a3db1. | <span class="ombre"></span>
<div id="col_scroller">
<div id="col_scroller_cont" class="clearfix">
<?php foreach ($details as $key => $detail): ?>
<?php if (in_array($detail_action_mode, array('add', 'update')) && $key == $detail_key): ?>
<?php include_partial('detailItemForm', array('detail' => $detail, 'key' => $key, 'onglets' => $onglets, 'form' => $form, 'is_new' => ($detail_action_mode == 'add'))) ?>
<?php else: ?>
<?php
include_partial('detailItem', array('detail' => $detail,
'key' => $key,
'onglets' => $onglets,
'acheteurs' => $acheteurs,
'has_acheteurs_mout' => $has_acheteurs_mout)) ?>
<?php endif; ?>
<?php endforeach; ?>
<?php if (! $onglets->getCurrentCepage()->getConfig()->hasOnlyOneDetail() || !count($details) ) :?>
<a href="<?php echo url_for($onglets->getUrl('recolte_add')->getRawValue()) ?>" id="ajout_col" class=""><img src="/images/boutons/btn_ajouter_colonne.png" alt="Ajouter une colonne" /></a>
<?php endif; ?>
</div>
</div>
<span class="ombre ombre_droite"></span> | <span class="ombre"></span>
<div id="col_scroller">
<div id="col_scroller_cont" class="clearfix">
<?php foreach ($details as $key => $detail): ?>
<?php if (in_array($detail_action_mode, array('add', 'update')) && $key == $detail_key): ?>
<?php include_partial('detailItemForm', array('detail' => $detail, 'key' => $key, 'onglets' => $onglets, 'form' => $form, 'is_new' => ($detail_action_mode == 'add'))) ?>
<?php else: ?>
<?php
include_partial('detailItem', array('detail' => $detail,
'key' => $key,
'onglets' => $onglets,
'acheteurs' => $acheteurs,
'has_acheteurs_mout' => $has_acheteurs_mout)) ?>
<?php endif; ?>
<?php endforeach; ?>
<?php if (!$onglets->getCurrentCepage()->getConfig()->hasOnlyOneDetail() && $detail_action_mode != 'add') :?>
<a href="<?php echo url_for($onglets->getUrl('recolte_add')->getRawValue()) ?>" id="ajout_col" class=""><img src="/images/boutons/btn_ajouter_colonne.png" alt="Ajouter une colonne" /></a>
<?php endif; ?>
</div>
</div>
<span class="ombre ombre_droite"></span> |
Add set_included function to twig to change the status of a template | <?php
namespace Common\Core\Twig\Extensions;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
final class IncludeOnceExtension extends AbstractExtension
{
/** @var array */
private $includedTemplates = [];
public function getFunctions(): array
{
return [
new TwigFunction(
'include_once',
[$this, 'includeOnce'],
['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]
),
new TwigFunction(
'is_included',
[$this, 'isIncluded']
),
new TwigFunction(
'set_included',
[$this, 'setIncluded']
),
];
}
public function includeOnce(
Environment $env,
array $context,
string $template,
array $variables = [],
bool $withContext = true,
bool $ignoreMissing = false,
bool $sandboxed = false
): string {
if ($this->isIncluded($template)) {
return '';
}
$output = twig_include($env, $context, $template, $variables, $withContext, $ignoreMissing, $sandboxed);
// this needs to happen after we capture the output so we can check if it was previously included
$this->setIncluded($template);
return $output;
}
public function isIncluded(string $template): bool
{
return $this->includedTemplates[$template] ?? false;
}
public function setIncluded(string $template, bool $isIncluded = true): void
{
$this->includedTemplates[$template] = $isIncluded;
}
}
| <?php
namespace Common\Core\Twig\Extensions;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
final class IncludeOnceExtension extends AbstractExtension
{
/** @var array */
private $includedTemplates = [];
public function getFunctions(): array
{
return [
new TwigFunction(
'include_once',
[$this, 'includeOnce'],
['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]
),
new TwigFunction(
'is_included',
[$this, 'isIncluded']
),
];
}
public function includeOnce(
Environment $env,
array $context,
string $template,
array $variables = [],
bool $withContext = true,
bool $ignoreMissing = false,
bool $sandboxed = false
): string {
if ($this->isIncluded($template)) {
return '';
}
$this->includedTemplates[$template] = true;
return twig_include($env, $context, $template, $variables, $withContext, $ignoreMissing, $sandboxed);
}
public function isIncluded(string $template): bool
{
return array_key_exists($template, $this->includedTemplates);
}
}
|
Set up email templates for the accounts package only if email delivery is enabled | import { Accounts } from 'meteor/accounts-base';
import { GlobalSettings } from './GlobalSettings';
function setupEmailTemplatesForAccounts() {
Accounts.emailTemplates.siteName = GlobalSettings.getSiteName();
Accounts.emailTemplates.from = Accounts.emailTemplates.siteName + '<' + GlobalSettings.getDefaultEmailSenderAddress() + '>';
Accounts.emailTemplates.verifyEmail = {
subject() {
return '[' + Accounts.emailTemplates.siteName + '] Verify Your Email Address';
},
text(user, url) {
let emailAddress = user.emails[0].address,
urlWithoutHash = url.replace('#/', ''),
emailBody = 'To verify your email address ' + emailAddress + ' visit the following link:\n\n' +
urlWithoutHash +
'\n\n If you did not request this verification, please ignore this email. ' +
'If you feel something is wrong, please contact your admin team';
return emailBody;
}
};
Accounts.emailTemplates.resetPassword = {
subject() {
return '[' + Accounts.emailTemplates.siteName + '] Reset Your Password';
},
text(user, url) {
let emailAddress = user.emails[0].address,
urlWithoutHash = url.replace('#/', ''),
emailBody = 'To reset your password for ' + emailAddress + ' visit the following link:\n\n' +
urlWithoutHash +
'\n\n If you did not request to reset your password, please ignore this email. ' +
'If you feel something is wrong, please contact your admin team';
return emailBody;
}
};
}
if (GlobalSettings.isEMailDeliveryEnabled()) {
setupEmailTemplatesForAccounts();
} | import { Accounts } from 'meteor/accounts-base';
import {GlobalSettings} from './GlobalSettings';
Accounts.emailTemplates.siteName = GlobalSettings.getSiteName();
Accounts.emailTemplates.from = Accounts.emailTemplates.siteName + '<' + GlobalSettings.getDefaultEmailSenderAddress() + '>';
Accounts.emailTemplates.verifyEmail = {
subject() {
return '[' + Accounts.emailTemplates.siteName + '] Verify Your Email Address';
},
text( user, url ) {
let emailAddress = user.emails[0].address,
urlWithoutHash = url.replace( '#/', '' ),
emailBody = 'To verify your email address ' + emailAddress + ' visit the following link:\n\n' +
urlWithoutHash +
'\n\n If you did not request this verification, please ignore this email. ' +
'If you feel something is wrong, please contact your admin team';
return emailBody;
}
};
Accounts.emailTemplates.resetPassword = {
subject() {
return '[' + Accounts.emailTemplates.siteName + '] Reset Your Password';
},
text( user, url ) {
let emailAddress = user.emails[0].address,
urlWithoutHash = url.replace( '#/', '' ),
emailBody = 'To reset your password for ' + emailAddress + ' visit the following link:\n\n' +
urlWithoutHash +
'\n\n If you did not request to reset your password, please ignore this email. ' +
'If you feel something is wrong, please contact your admin team';
return emailBody;
}
};
|
Fix KeyError in alerts implementation
- Fix for alert that wasn't dismissing after refreshing the page | from django.core.urlresolvers import reverse
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.utils.translation import ugettext as _
from books.forms import BookForm
from shared.models import BookType
def index(request):
book_list = BookType.objects.all()
args = {'book_list': book_list}
if 'success_msg' in request.session:
args['success_msg'] = {
'book_added': _("The book was added successfully!")
}[request.session['success_msg']]
del request.session['success_msg']
return render(request, 'books/index.html', args)
def add_book(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
book_type = BookType(publisher=form.cleaned_data['publisher'], title=form.cleaned_data['title'],
issue=form.cleaned_data['issue'], issue_year=form.cleaned_data['issue_year'],
price=form.cleaned_data['price'] * 100)
book_type.save()
request.session['success_msg'] = 'book_added'
return HttpResponseRedirect(reverse('index'))
else:
form = BookForm()
return render(request, 'books/add.html', {'form': form})
def edit_book(request, book_id):
return HttpResponse("Hello world!")
def remove_book(request, book_id):
return HttpResponse("Hello world!")
| from django.core.urlresolvers import reverse
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.utils.translation import ugettext as _
from books.forms import BookForm
from shared.models import BookType
def index(request):
book_list = BookType.objects.all()
args = {'book_list': book_list}
if request.session['success_msg']:
args['success_msg'] = {
'book_added': _("The book was added successfully!")
}[request.session['success_msg']]
return render(request, 'books/index.html', args)
def add_book(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
book_type = BookType(publisher=form.cleaned_data['publisher'], title=form.cleaned_data['title'],
issue=form.cleaned_data['issue'], issue_year=form.cleaned_data['issue_year'],
price=form.cleaned_data['price'] * 100)
book_type.save()
request.session['success_msg'] = 'book_added'
return HttpResponseRedirect(reverse('index'))
else:
form = BookForm()
return render(request, 'books/add.html', {'form': form})
def edit_book(request, book_id):
return HttpResponse("Hello world!")
def remove_book(request, book_id):
return HttpResponse("Hello world!")
|
Update property of corporation name returned in search. | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Classes\EsiConnection;
use Illuminate\Support\Facades\Log;
class SearchController extends Controller
{
public function search(Request $request)
{
$esi = new EsiConnection;
$result = $esi->esi->setQueryString([
'categories' => 'character',
'search' => $request->q,
'strict' => 'true',
])->invoke('get', '/search/');
Log::info('SearchController: results returned by /search query', [
'result' => $result,
]);
// If there are more than ten matching results, we want them to keep typing.
if (isset($result) && isset($result->character))
{
$character_id = $result->character[0];
$character = $esi->esi->invoke('get', '/characters/{character_id}/', [
'character_id' => $character_id,
]);
$character->id = $character_id;
$portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [
'character_id' => $character_id,
]);
$character->portrait = $portrait->px128x128;
$corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [
'corporation_id' => $character->corporation_id,
]);
$character->corporation = $corporation->name;
return $character;
}
else
{
return 'No matches returned, API may be unreachable...';
}
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Classes\EsiConnection;
use Illuminate\Support\Facades\Log;
class SearchController extends Controller
{
public function search(Request $request)
{
$esi = new EsiConnection;
$result = $esi->esi->setQueryString([
'categories' => 'character',
'search' => $request->q,
'strict' => 'true',
])->invoke('get', '/search/');
Log::info('SearchController: results returned by /search query', [
'result' => $result,
]);
// If there are more than ten matching results, we want them to keep typing.
if (isset($result) && isset($result->character))
{
$character_id = $result->character[0];
$character = $esi->esi->invoke('get', '/characters/{character_id}/', [
'character_id' => $character_id,
]);
$character->id = $character_id;
$portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [
'character_id' => $character_id,
]);
$character->portrait = $portrait->px128x128;
$corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [
'corporation_id' => $character->corporation_id,
]);
$character->corporation = $corporation->corporation_name;
return $character;
}
else
{
return 'No matches returned, API may be unreachable...';
}
}
}
|
Set the default identifier to null | <?php
namespace BinSoul\Net\Mqtt\Packet;
/**
* Provides methods for packets with an identifier.
*/
trait IdentifiablePacket
{
/** @var int */
private static $nextIdentifier = 0;
/** @var int|null */
protected $identifier;
/**
* Returns the identifier or generates a new one.
*
* @return int
*/
protected function generateIdentifier()
{
if ($this->identifier === null) {
++self::$nextIdentifier;
self::$nextIdentifier &= 0xFFFF;
$this->identifier = self::$nextIdentifier;
}
return $this->identifier;
}
/**
* Returns the identifier.
*
* @return int|null
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Sets the identifier.
*
* @param int|null $value
*
* @throws \InvalidArgumentException
*/
public function setIdentifier($value)
{
if ($value !== null && ($value < 0 || $value > 0xFFFF)) {
throw new \InvalidArgumentException(
sprintf(
'Expected an identifier between 0x0000 and 0xFFFF but got %x',
$value
)
);
}
$this->identifier = $value;
}
}
| <?php
namespace BinSoul\Net\Mqtt\Packet;
/**
* Provides methods for packets with an identifier.
*/
trait IdentifiablePacket
{
/** @var int */
private static $nextIdentifier = 0;
/** @var int */
protected $identifier = 0;
/**
* Returns the identifier or generates a new one.
*
* @return int
*/
protected function generateIdentifier()
{
if ($this->identifier <= 0) {
++self::$nextIdentifier;
self::$nextIdentifier &= 0xFFFF;
$this->identifier = self::$nextIdentifier;
}
return $this->identifier;
}
/**
* Returns the identifier.
*
* @return int
*/
public function getIdentifier()
{
return $this->generateIdentifier();
}
/**
* Sets the identifier.
*
* @param int $value
*
* @throws \InvalidArgumentException
*/
public function setIdentifier($value)
{
if ($value < 0 || $value > 0xFFFF) {
throw new \InvalidArgumentException(
sprintf(
'Expected an identifier between 0x0000 and 0xFFFF but got %x',
$value
)
);
}
$this->identifier = $value;
}
}
|
Change protected members to private | package com.sleekbyte.tailor.grammar;
import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class GrammarTest {
private static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";
private ByteArrayOutputStream errContent;
private ByteArrayOutputStream outContent;
private File[] swiftFiles;
@Before
public void setUp() {
File curDir = new File(TEST_INPUT_DIR);
swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
}
@After
public void tearDown() {
System.setOut(null);
}
@Test
public void testGrammar() {
for (File swiftFile: swiftFiles) {
errContent = new ByteArrayOutputStream();
System.setErr(new PrintStream(errContent));
String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
Tailor.main(command);
assertEquals("", errContent.toString());
System.setErr(null);
}
}
}
| package com.sleekbyte.tailor.grammar;
import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
public class GrammarTest {
protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";
protected ByteArrayOutputStream errContent;
protected ByteArrayOutputStream outContent;
protected File[] swiftFiles;
@Before
public void setUp() {
File curDir = new File(TEST_INPUT_DIR);
swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
}
@After
public void tearDown() {
System.setOut(null);
}
@Test
public void testGrammar() {
for (File swiftFile: swiftFiles) {
errContent = new ByteArrayOutputStream();
System.setErr(new PrintStream(errContent));
String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
Tailor.main(command);
assertEquals("", errContent.toString());
System.setErr(null);
}
}
}
|
Make webpack dev server work for nested route paths. | const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
inject: 'true',
template: 'app/index.html'
});
const extractLess = new ExtractTextPlugin({
filename: "[name].css",
});
module.exports = (options) => ({
entry: './app/app.jsx',
output: Object.assign({
path: path.resolve(__dirname, "build"),
publicPath: "/"
}, options.output),
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015','react']
}
},
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015','react']
}
},
{
test: /\.css$/,
use: "css-loader",
},
{
test: /\.less$/,
use: extractLess.extract({
use: [
{
loader: "css-loader",
options: {
url: false,
import: false,
}
},
{
loader: "less-loader",
options: {
relativeUrls: false,
}
}
],
fallback: "style-loader"
}),
},
]
},
plugins: options.plugins.concat([HtmlWebpackPluginConfig, new ExtractTextPlugin('[name].css', {allChunks: true})])
});
| const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
inject: 'true',
template: 'app/index.html'
});
const extractLess = new ExtractTextPlugin({
filename: "[name].css",
});
module.exports = (options) => ({
entry: './app/app.jsx',
output: Object.assign({
path: path.resolve(__dirname, "build"),
}, options.output),
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015','react']
}
},
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015','react']
}
},
{
test: /\.css$/,
use: "css-loader",
},
{
test: /\.less$/,
use: extractLess.extract({
use: [
{
loader: "css-loader",
options: {
url: false,
import: false,
}
},
{
loader: "less-loader",
options: {
relativeUrls: false,
}
}
],
fallback: "style-loader"
}),
},
]
},
plugins: options.plugins.concat([HtmlWebpackPluginConfig, new ExtractTextPlugin('[name].css', {allChunks: true})])
});
|
Make WE use additive and multiplicative constants | from nalaf.features import FeatureGenerator
from gensim.models import Word2Vec
class WordEmbeddingsFeatureGenerator(FeatureGenerator):
"""
DOCSTRING
"""
def __init__(self, model_file, additive=0, multiplicative=1):
self.model = Word2Vec.load(model_file)
self.additive = additive
self.multiplicative = multiplicative
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for token in dataset.tokens():
if token.word.lower() in self.model:
for index, value in enumerate(self.model[token.word.lower()]):
# value.item() since value is a numpy float
# and we want native python floats
token.features['embedding_{}'.format(index)] = (self.additive + value.item()) * self.multiplicative
class BrownClusteringFeatureGenerator(FeatureGenerator):
"""
DOCSTRING
"""
def __init__(self, model_file, weight=1):
with open(model_file, encoding='utf-8') as file:
self.clusters = {str(line.split()[1]): line.split()[0] for line in file.readlines()}
self.weight = weight
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for token in dataset.tokens():
if token.word in self.clusters:
assignment = self.clusters[token.word]
for i in range(len(assignment)):
token.features['brown'] = assignment[:i+1]
| from nalaf.features import FeatureGenerator
from gensim.models import Word2Vec
class WordEmbeddingsFeatureGenerator(FeatureGenerator):
"""
DOCSTRING
"""
def __init__(self, model_file, weight=1):
self.model = Word2Vec.load(model_file)
self.weight = weight
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for token in dataset.tokens():
if token.word.lower() in self.model:
for index, value in enumerate(self.model[token.word.lower()]):
# value.item() since value is a numpy float
# and we want native python floats
token.features['embedding_{}'.format(index)] = self.weight * value.item()
class BrownClusteringFeatureGenerator(FeatureGenerator):
"""
DOCSTRING
"""
def __init__(self, model_file, weight=1):
with open(model_file, encoding='utf-8') as file:
self.clusters = {str(line.split()[1]): line.split()[0] for line in file.readlines()}
self.weight = weight
def generate(self, dataset):
"""
:type dataset: nalaf.structures.data.Dataset
"""
for token in dataset.tokens():
if token.word in self.clusters:
assignment = self.clusters[token.word]
for i in range(len(assignment)):
token.features['brown'] = assignment[:i+1]
|
Test file loops over all the mounts | import os
import importlib
import warnings
class TestOptronMount:
mount = None
def setup(self):
print ("TestMount:setup() before each test method")
def teardown(self):
print ("TestMount:teardown() after each test method")
@classmethod
def setup_class(cls):
mount_dir = os.path.dirname(__file__) + '/../mount/'
print ("setup_class() before any methods in this class")
_Mounts = []
for name in os.listdir(os.path.dirname(mount_dir)):
if not name.startswith('_') and name.endswith('.py'):
name = '.' + os.path.splitext(name)[0]
try:
module = importlib.import_module(name,'panoptes.mount')
_Mounts.append(module)
except ImportError as err:
warnings.warn('Failed to load mount plugin: {}'.format(err))
@classmethod
def teardown_class(cls):
print ("teardown_class() after any methods in this class")
def test_is_connected_false(self):
pass
def test_connect(self):
pass
def test_is_connected_true(self):
pass
def test_is_slewing(self):
pass
def test_check_coordinates(self):
pass
def test_sync_coordinates(self):
pass
def test_slew_to_coordinates(self):
pass
def test_slew_to_park(self):
pass
def test_echo(self):
pass
| from panoptes.mount.ioptron import iOptronMount
class TestOptronMount:
mount = None
def setup(self):
print ("TestMount:setup() before each test method")
def teardown(self):
print ("TestMount:teardown() after each test method")
@classmethod
def setup_class(cls):
print ("setup_class() before any methods in this class")
_Mounts = []
for name in os.listdir(os.path.dirname(__file__)):
if not name.startswith('_') and name.endswith('.py'):
name = '.' + os.path.splitext(name)[0]
try:
module = importlib.import_module(name,'panoptes')
_Mounts.append(module)
except ImportError as err:
self.logger.warn('Failed to load mount plugin: {}'.format(err))
@classmethod
def teardown_class(cls):
print ("teardown_class() after any methods in this class")
def test_is_connected_false(self):
pass
def test_connect(self):
pass
def test_is_connected_true(self):
pass
def test_is_slewing(self):
pass
def test_check_coordinates(self):
pass
def test_sync_coordinates(self):
pass
def test_slew_to_coordinates(self):
pass
def test_slew_to_park(self):
pass
def test_echo(self):
pass
|
Update the project Development Status | """Package Keysmith."""
import codecs
import os.path
import setuptools # type: ignore
import keysmith # This project only depends on the standard library.
def read(*parts):
"""Read a file in this repository."""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *parts), 'r') as file_:
return file_.read()
ENTRY_POINTS = {
'console_scripts': [
'{name}={module}:{function}'.format(
name=keysmith.CONSOLE_SCRIPT,
module=keysmith.__name__,
function=keysmith.main.__name__,
),
],
}
if __name__ == '__main__':
setuptools.setup(
name=keysmith.__name__,
version=keysmith.__version__,
description='Passphrase Generator',
long_description=read('README.rst'),
author='David Tucker',
author_email='[email protected]',
license='BSD 3-Clause License',
url='https://github.com/dmtucker/keysmith',
python_requires='~=3.5',
py_modules=[keysmith.__name__],
entry_points=ENTRY_POINTS,
keywords='diceware generator keygen passphrase password',
classifiers=['Development Status :: 7 - Inactive'],
)
| """Package Keysmith."""
import codecs
import os.path
import setuptools # type: ignore
import keysmith # This project only depends on the standard library.
def read(*parts):
"""Read a file in this repository."""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *parts), 'r') as file_:
return file_.read()
ENTRY_POINTS = {
'console_scripts': [
'{name}={module}:{function}'.format(
name=keysmith.CONSOLE_SCRIPT,
module=keysmith.__name__,
function=keysmith.main.__name__,
),
],
}
if __name__ == '__main__':
setuptools.setup(
name=keysmith.__name__,
version=keysmith.__version__,
description='Passphrase Generator',
long_description=read('README.rst'),
author='David Tucker',
author_email='[email protected]',
license='BSD 3-Clause License',
url='https://github.com/dmtucker/keysmith',
python_requires='~=3.5',
py_modules=[keysmith.__name__],
entry_points=ENTRY_POINTS,
keywords='diceware generator keygen passphrase password',
classifiers=['Development Status :: 5 - Production/Stable'],
)
|
Add onMove function to options | /* global console, Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 86400000,
editable: {
add: false,
updateTime: true,
updateGroup: false,
remove: true
},
groupOrder: function (a, b) {
if (a.id === "Demos") {
return -1;
}
if (b.id === "Demos") {
return 1;
}
var groups = [a.id, b.id];
groups.sort();
if (a.id === groups[0]) {
return -1;
} else {
return 1;
}
},
onMove: function (item, callback) {
item.title = item.content + "\n" + "Start: " + item.Start + "\n" + "End: " + item.end;
callback(item);
}
});
$(document).ready(function(){
$('.vis-center>.vis-content').on('scroll', function () {
$('.vis-left>.vis-content').scrollTop($(this).scrollTop());
});
$('.vis-left>.vis-content').on('scroll', function () {
$('.vis-center>.vis-content').scrollTop($(this).scrollTop());
});
});
})(); | /* global console, Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 86400000,
editable: {
add: false,
updateTime: true,
updateGroup: false,
remove: true
},
groupOrder: function (a, b) {
if (a.id === "Demos") {
return -1;
}
if (b.id === "Demos") {
return 1;
}
var groups = [a.id, b.id];
groups.sort();
if (a.id === groups[0]) {
return -1;
} else {
return 1;
}
}
});
$(document).ready(function(){
$('.vis-center>.vis-content').on('scroll', function () {
$('.vis-left>.vis-content').scrollTop($(this).scrollTop());
});
$('.vis-left>.vis-content').on('scroll', function () {
$('.vis-center>.vis-content').scrollTop($(this).scrollTop());
});
});
})(); |
Add helper private method (isNullable) | <?php
/**
* This file is part of Railt package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Railt\Reflection\Base\Behavior;
use Railt\Reflection\Contracts\Behavior\AllowsTypeIndication;
use Railt\Reflection\Contracts\Behavior\Inputable;
/**
* Trait BaseTypeIndicator
* @mixin AllowsTypeIndication
*/
trait BaseTypeIndicator
{
/**
* @var Inputable
*/
protected $type;
/**
* @var bool
*/
protected $isNonNull = false;
/**
* @var bool
*/
protected $isList = false;
/**
* @var bool
*/
protected $isNonNullList = false;
/**
* @return Inputable
*/
public function getType(): Inputable
{
return $this->resolve()->type;
}
/**
* @return bool
*/
public function isList(): bool
{
return $this->resolve()->isList;
}
/**
* @return bool
*/
public function isNonNull(): bool
{
return $this->resolve()->isNonNull;
}
/**
* @return bool
*/
public function isNonNullList(): bool
{
return $this->resolve()->isList && $this->isNonNullList;
}
/**
* @return bool
*/
private function isNullable(): bool
{
return !($this->isNonNull() || $this->isNonNullList());
}
}
| <?php
/**
* This file is part of Railt package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Railt\Reflection\Base\Behavior;
use Railt\Reflection\Contracts\Behavior\AllowsTypeIndication;
use Railt\Reflection\Contracts\Behavior\Inputable;
/**
* Trait BaseTypeIndicator
* @mixin AllowsTypeIndication
*/
trait BaseTypeIndicator
{
/**
* @var Inputable
*/
protected $type;
/**
* @var bool
*/
protected $isNonNull = false;
/**
* @var bool
*/
protected $isList = false;
/**
* @var bool
*/
protected $isNonNullList = false;
/**
* @return Inputable
*/
public function getType(): Inputable
{
return $this->resolve()->type;
}
/**
* @return bool
*/
public function isList(): bool
{
return $this->resolve()->isList;
}
/**
* @return bool
*/
public function isNonNull(): bool
{
return $this->resolve()->isNonNull;
}
/**
* @return bool
*/
public function isNonNullList(): bool
{
return $this->resolve()->isList && $this->isNonNullList;
}
}
|
Add audio type checks for MP3 and OGG Vorbis | /*global _:true, App:true, Backbone:true */
/*jshint forin:false, plusplus:false, sub:true */
'use strict';
define([
'zepto',
'install',
'datastore',
'collections/episodes',
'collections/podcasts',
'models/episode',
'models/podcast',
'views/app'
], function($, install, DataStore, Episodes, Podcasts, Episode, Podcast, AppView) {
var GLOBALS = {
DATABASE_NAME: 'podcasts',
HAS: {
audioSupportMP3: (function() {
var a = window.document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
})(),
audioSupportOGG: (function() {
var a = window.document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/ogg;').replace(/no/, ''));
})(),
nativeScroll: (function() {
return 'WebkitOverflowScrolling' in window.document.createElement('div').style;
})()
},
OBJECT_STORE_NAME: 'podcasts',
TIME_TO_UPDATE: 3600 * 5 // Update podcasts every five hours
}
window.GLOBALS = GLOBALS;
function initialize(callback) {
if (GLOBALS.HAS.nativeScroll) {
$('body').addClass('native-scroll');
}
DataStore.load(function() {
var app = new AppView();
});
}
function timestamp(date) {
if (!date) {
date = new Date()
}
return Math.round(date.getTime() / 1000)
}
window.timestamp = timestamp;
return {
initialize: initialize
};
});
| /*global _:true, App:true, Backbone:true */
/*jshint forin:false, plusplus:false, sub:true */
'use strict';
define([
'zepto',
'install',
'datastore',
'collections/episodes',
'collections/podcasts',
'models/episode',
'models/podcast',
'views/app'
], function($, install, DataStore, Episodes, Podcasts, Episode, Podcast, AppView) {
var GLOBALS = {
DATABASE_NAME: 'podcasts',
HAS: {
nativeScroll: (function() {
return 'WebkitOverflowScrolling' in window.document.createElement('div').style;
})()
},
OBJECT_STORE_NAME: 'podcasts',
TIME_TO_UPDATE: 3600 * 5 // Update podcasts every five hours
}
window.GLOBALS = GLOBALS;
function initialize(callback) {
if (GLOBALS.HAS.nativeScroll) {
$('body').addClass('native-scroll');
}
DataStore.load(function() {
var app = new AppView();
});
}
function timestamp(date) {
if (!date) {
date = new Date()
}
return Math.round(date.getTime() / 1000)
}
window.timestamp = timestamp;
return {
initialize: initialize
};
});
|
[bugfix][ORANGE-293] Fix zero mount for doses | (function () {
"use strict";
angular
.module('orange')
.directive('onlyNumbers', onlyNumbers);
function onlyNumbers() {
return {
require: '?ngModel',
scope: {},
link: function (scope, element, attributes, ngModel) {
var _value;
ngModel.$parsers.unshift(function (val) {
if (_value === undefined) {
_value = ngModel.$modelValue;
}
if (val === undefined || val === null) {
val = '';
}
if (val.toString().match(/^(\d+\.?\d*)?$/g) && val != 0) {
_value = val;
}
ngModel.$viewValue = _value;
ngModel.$render();
return _value;
});
}
}
}
})();
| (function () {
"use strict";
angular
.module('orange')
.directive('onlyNumbers', onlyNumbers);
function onlyNumbers() {
return {
require: '?ngModel',
scope: {},
link: function (scope, element, attributes, ngModel) {
var _value;
ngModel.$parsers.unshift(function (val) {
if (_value === undefined) {
_value = ngModel.$modelValue;
}
if (val === undefined || val === null) {
val = '';
}
if (val.toString().match(/^(\d+\.?\d*)?$/g)) {
_value = val;
}
ngModel.$viewValue = _value;
ngModel.$render();
return _value;
});
}
}
}
})();
|
Make sure correct type is excluded | from collections import OrderedDict
def form_questions(form):
d = OrderedDict()
children = form['children']
for child in children:
if 'pathstr' in child and 'control' not in child and child['type'] != 'group':
d.update({child['pathstr']: ''})
elif 'children' in child:
for minor in child['children']:
if 'pathstr' in minor:
d.update({minor['pathstr']: ''})
if 'Contact_number' in d:
del d['Contact_number']
if 'Full_name' in d:
del d['Full_name']
if 'Monitor_name' in d:
del d['Monitor_name']
if 'phonenumber' in d:
del d['phonenumber']
if 'capturer' in d:
del d['capturer']
if 'surveyor' in d:
del d['surveyor']
if 'Monitor_Name' in d:
del d['Monitor_Name']
if 'phone_number' in d:
del d['phone_number']
return d
def export_row(answer, fields):
obj = answer.answers
for k in fields.keys():
try:
fields[k] = obj[k]
except KeyError:
del fields[k]
return fields
| from collections import OrderedDict
def form_questions(form):
d = OrderedDict()
children = form['children']
for child in children:
if 'pathstr' in child and 'control' not in child:
d.update({child['pathstr']: ''})
elif 'children' in child:
for minor in child['children']:
if 'pathstr' in minor:
d.update({minor['pathstr']: ''})
if 'Contact_number' in d:
del d['Contact_number']
if 'Full_name' in d:
del d['Full_name']
if 'Monitor_name' in d:
del d['Monitor_name']
if 'phonenumber' in d:
del d['phonenumber']
if 'capturer' in d:
del d['capturer']
if 'surveyor' in d:
del d['surveyor']
if 'Monitor_Name' in d:
del d['Monitor_Name']
if 'phone_number' in d:
del d['phone_number']
return d
def export_row(answer, fields):
obj = answer.answers
for k in fields.keys():
try:
fields[k] = obj[k]
except KeyError:
del fields[k]
return fields
|
[refactor] Use $document for unit test suppport. | /* global angular */
(function() {
angular.module("googlechart")
.factory("agcScriptTagHelper", agcScriptTagHelperFactory);
agcScriptTagHelperFactory.$inject = ["$q", "$document"];
function agcScriptTagHelperFactory($q, $document)
{
/** Add a script tag to the document's head section and return an angular
* promise that resolves when the script has loaded.
*/
function agcScriptTagHelper(url)
{
var deferred = $q.defer();
var head = $document.getElementsByTagName('head')[0];
var script = $document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = url;
if (script.addEventListener) { // Standard browsers (including IE9+)
script.addEventListener('load', onLoad, false);
script.onerror = onError;
} else { // IE8 and below
script.onreadystatechange = function () {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null;
onLoad();
}
};
}
head.appendChild(script);
function onLoad() {
deferred.resolve();
}
function onError() {
deferred.reject();
}
return deferred.promise;
}
return agcScriptTagHelper;
}
})();
| /* global angular */
(function() {
angular.module("googlechart")
.factory("agcScriptTagHelper", agcScriptTagHelperFactory);
agcScriptTagHelperFactory.$inject = ["$q"];
function agcScriptTagHelperFactory($q)
{
/** Add a script tag to the document's head section and return an angular
* promise that resolves when the script has loaded.
*/
function agcScriptTagHelper(url)
{
var deferred = $q.defer();
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = url;
if (script.addEventListener) { // Standard browsers (including IE9+)
script.addEventListener('load', onLoad, false);
script.onerror = onError;
} else { // IE8 and below
script.onreadystatechange = function () {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null;
onLoad();
}
};
}
head.appendChild(script);
function onLoad() {
deferred.resolve();
}
function onError() {
deferred.reject();
}
return deferred.promise;
}
return agcScriptTagHelper;
}
})();
|
Use same identifier as previous plugin version | const path = require('path');
const GitBook = require('gitbook-core');
const DisqusThread = require('react-disqus-thread');
const { React, Immutable } = GitBook;
const DisqusFooter = React.createClass({
propTypes: {
defaultIdentifier: React.PropTypes.string,
page: GitBook.Shapes.Page,
shortName: React.PropTypes.string.isRequired,
useIdentifier: React.PropTypes.bool
},
render() {
const { defaultIdentifier, page, shortName, useIdentifier } = this.props;
// Get disqus config for this page
const pageConfig = page.attributes.get(['disqus'], Immutable.Map());
// Disqus is disabled for this page
if (pageConfig === false) {
return null;
}
// Page frontmatter can define a custom identifier or use the default one
const identifier = useIdentifier ?
pageConfig.get('identifier', defaultIdentifier)
: null;
return (
<GitBook.Panel>
<DisqusThread
shortname={shortName}
title={page.title}
identifier={identifier}
url={(typeof window !== 'undefined') ? window.location.href : null}
/>
</GitBook.Panel>
);
}
});
function mapStateToProps({ config, file, page, languages }) {
const defaultIdentifier = languages.current ?
path.join(languages.current, file.url) : file.url;
return {
page,
defaultIdentifier,
shortName: config.getIn(['pluginsConfig', 'disqus', 'shortName']),
useIdentifier: config.getIn(['pluginsConfig', 'disqus', 'useIdentifier'])
};
}
module.exports = GitBook.connect(DisqusFooter, mapStateToProps);
| const GitBook = require('gitbook-core');
const DisqusThread = require('react-disqus-thread');
const { React, Immutable } = GitBook;
const DisqusFooter = React.createClass({
propTypes: {
page: GitBook.Shapes.Page,
shortName: React.PropTypes.string.isRequired,
useIdentifier: React.PropTypes.bool
},
render() {
const { page, shortName, useIdentifier } = this.props;
// Default identifier
const defaultIdentifier = '';
// Get disqus config for this page
const pageConfig = page.attributes.get(['disqus'], Immutable.Map());
// Disqus is disabled for this page
if (pageConfig === false) {
return null;
}
// Page frontmatter can define a custom identifier or use the default one
const identifier = useIdentifier ?
pageConfig.get('identifier', defaultIdentifier)
: null;
return (
<GitBook.Panel>
<DisqusThread
shortname={shortName}
title={page.title}
identifier={identifier}
url={(typeof window !== 'undefined') ? window.location.href : null}
/>
</GitBook.Panel>
);
}
});
function mapStateToProps({ config, page }) {
return {
shortName: config.getIn(['pluginsConfig', 'disqus', 'shortName']),
useIdentifier: config.getIn(['pluginsConfig', 'disqus', 'useIdentifier']),
page
};
}
module.exports = GitBook.connect(DisqusFooter, mapStateToProps);
|
Fix toolbar scrolling when scrolling basic comment editor | package com.gh4a.widget;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.view.MotionEvent;
import android.view.View;
public class ToggleableAppBarLayoutBehavior extends AppBarLayout.Behavior {
private boolean mEnabled = true;
public void setEnabled(boolean enabled) {
mEnabled = enabled;
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child,
View directTargetChild, View target, int nestedScrollAxes) {
return mEnabled && super.onStartNestedScroll(parent, child, directTargetChild, target,
nestedScrollAxes);
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout,
AppBarLayout child, View target, int dx, int dy, int[] consumed) {
if (mEnabled) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
}
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target,
int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
if (mEnabled) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed,
dxUnconsumed, dyUnconsumed);
}
}
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout,
AppBarLayout child, View target) {
if (mEnabled) {
super.onStopNestedScroll(coordinatorLayout, child, target);
}
}
@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent,
AppBarLayout child, MotionEvent ev) {
return mEnabled && super.onInterceptTouchEvent(parent, child, ev);
}
}
| package com.gh4a.widget;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.view.MotionEvent;
import android.view.View;
public class ToggleableAppBarLayoutBehavior extends AppBarLayout.Behavior {
private boolean mEnabled = true;
public void setEnabled(boolean enabled) {
mEnabled = enabled;
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child,
View directTargetChild, View target, int nestedScrollAxes) {
return mEnabled && super.onStartNestedScroll(parent, child, directTargetChild, target,
nestedScrollAxes);
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout,
AppBarLayout child, View target, int dx, int dy, int[] consumed) {
if (mEnabled) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
}
}
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout,
AppBarLayout child, View target) {
if (mEnabled) {
super.onStopNestedScroll(coordinatorLayout, child, target);
}
}
@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent,
AppBarLayout child, MotionEvent ev) {
return mEnabled && super.onInterceptTouchEvent(parent, child, ev);
}
}
|
Return errors in json only | import os
import json
import httplib as http
import tornado.web
import tornado.ioloop
from dinosaurs import api
from dinosaurs import settings
class SingleStatic(tornado.web.StaticFileHandler):
def initialize(self, path):
self.dirname, self.filename = os.path.split(path)
super(SingleStatic, self).initialize(self.dirname)
def get(self, path=None, include_body=True):
super(SingleStatic, self).get(self.filename, include_body)
class DomainAPIHandler(tornado.web.RequestHandler):
def get(self):
self.write({
'availableDomains': settings.DOMAINS.keys()
})
class EmailAPIHandler(tornado.web.RequestHandler):
def write_error(self, status_code, **kwargs):
self.finish({
"code": status_code,
"message": self._reason,
})
def post(self):
try:
req_json = json.loads(self.request.body)
except ValueError:
raise tornado.web.HTTPError(http.BAD_REQUEST)
email = req_json.get('email')
domain = req_json.get('domain')
connection = api.get_connection(domain)
if not email or not domain or not connection:
raise tornado.web.HTTPError(http.BAD_REQUEST)
try:
ret, passwd = api.create_email(connection, email)
except api.YandexException as e:
if e.message != 'occupied':
raise
self.write({})
raise tornado.web.HTTPError(http.FORBIDDEN)
self.write({
'password': passwd,
'email': ret['login'],
'domain': ret['domain']
})
self.set_status(http.CREATED)
| import os
import json
import httplib as http
import tornado.web
import tornado.ioloop
from dinosaurs import api
from dinosaurs import settings
class SingleStatic(tornado.web.StaticFileHandler):
def initialize(self, path):
self.dirname, self.filename = os.path.split(path)
super(SingleStatic, self).initialize(self.dirname)
def get(self, path=None, include_body=True):
super(SingleStatic, self).get(self.filename, include_body)
class DomainAPIHandler(tornado.web.RequestHandler):
def get(self):
self.write({
'availableDomains': settings.DOMAINS.keys()
})
class EmailAPIHandler(tornado.web.RequestHandler):
def post(self):
try:
req_json = json.loads(self.request.body)
except ValueError:
raise tornado.web.HTTPError(http.BAD_REQUEST)
email = req_json.get('email')
domain = req_json.get('domain')
connection = api.get_connection(domain)
if not email or not domain or not connection:
raise tornado.web.HTTPError(http.BAD_REQUEST)
ret, passwd = api.create_email(connection, email)
self.write({
'password': passwd,
'email': ret['login'],
'domain': ret['domain']
})
self.set_status(http.CREATED)
|
Change the notification object for an array | <?php
namespace App\Notifications;
use function array_key_exists;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
class RequestReview extends Notification
{
public $notification;
public $client;
/**
* Create a new notification instance.
* @param array $notification
*/
public function __construct($notification)
{
$this->client = new Client();
$this->notification = $notification;
}
/**
* Get the notification's delivery channels.
*
* @return array
*/
public function via()
{
return ['slack'];
}
public function toSlack()
{
$notification = $this->notification;
return (new SlackMessage)
->from("Dashi")
->image("http://icons.iconarchive.com/icons/thehoth/seo/256/seo-web-code-icon.png")
->success()
->content(":microscope: *{$notification['username']}* needs you to make a `Code Review` to this changes")
->attachment(function ($attachment) use ($notification) {
$fields = [
"Repository" => $notification["repository"],
"User" => $notification['username']
];
if (array_key_exists("changed_files", $notification)) {
$fields["File(s) changed"] = $notification["changed_files"];
}
$attachment->title($notification["title"], $notification["url"])
->content(":sleuth_or_spy: Make sure everything is in order before approve the Pull Request")
->fields($fields);
});
}
} | <?php
namespace App\Notifications;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
class RequestReview extends Notification
{
public $notification;
public $client;
/**
* Create a new notification instance.
* @param Request $notification
*/
public function __construct($notification)
{
$this->client = new Client();
$this->notification = $notification;
}
/**
* Get the notification's delivery channels.
*
* @return array
*/
public function via()
{
return ['slack'];
}
public function toSlack()
{
$notification = $this->notification;
$username = $notification["sender"]["login"];
return (new SlackMessage)
->from("Dashi")
->image("http://icons.iconarchive.com/icons/thehoth/seo/256/seo-web-code-icon.png")
->success()
->content(":microscope: {$username} needs you to make a Code Review to this changes")
->attachment(function ($attachment) use ($notification) {
$attachment->title($notification["pull_request"]["title"], $notification["pull_request"]["html_url"])
->content(":sleuth_or_spy: Make sure everything is in order before approve the Pull Request")
->fields([
"User" => $notification["sender"]["login"],
"Repository" => $notification["repository"]["name"],
"File(s) changed" => $notification["pull_request"]["changed_files"]
]);
});
}
} |
Change from local storage to chrome storage | import getWeatherInfo from './get-weather-info';
import fetchRandomPhoto from './fetch-random-photo';
import { lessThanOneHourAgo, lessThan24HoursAgo } from './helpers';
/*
* Load the next image and update the weather
*/
const loadNewData = () => {
chrome.storage.sync.get('photoFrequency', result => {
const { photoFrequency } = result;
if (photoFrequency === 'newtab') {
fetchRandomPhoto();
return;
}
chrome.storage.local.get('nextImage', r => {
const { nextImage } = r;
if (
photoFrequency === 'everyhour' &&
!lessThanOneHourAgo(nextImage.timestamp)
) {
fetchRandomPhoto();
return;
}
if (
photoFrequency === 'everyday' &&
!lessThan24HoursAgo(nextImage.timestamp)
) {
fetchRandomPhoto();
}
});
});
chrome.storage.local.get('forecast', result => {
const { forecast } = result;
chrome.storage.sync.get('coords', d => {
const { coords } = d;
if (!forecast && coords) {
getWeatherInfo();
return;
}
if (forecast) {
const { timestamp } = forecast;
if (timestamp) {
if (!lessThanOneHourAgo(timestamp)) {
getWeatherInfo();
}
}
}
});
});
};
export default loadNewData;
| import getWeatherInfo from './get-weather-info';
import fetchRandomPhoto from './fetch-random-photo';
import { lessThanOneHourAgo, lessThan24HoursAgo } from './helpers';
/*
* Load the next image and update the weather
*/
const loadNewData = () => {
chrome.storage.sync.get('photoFrequency', result => {
const { photoFrequency } = result;
if (photoFrequency === 'newtab') {
fetchRandomPhoto();
return;
}
const nextImage = JSON.parse(localStorage.getItem('nextImage'));
if (
photoFrequency === 'everyhour' &&
!lessThanOneHourAgo(nextImage.timestamp)
) {
fetchRandomPhoto();
return;
}
if (
photoFrequency === 'everyday' &&
!lessThan24HoursAgo(nextImage.timestamp)
) {
fetchRandomPhoto();
}
});
chrome.storage.local.get('forecast', result => {
const { forecast } = result;
chrome.storage.sync.get('coords', d => {
const { coords } = d;
if (!forecast && coords) {
getWeatherInfo();
return;
}
if (forecast) {
const { timestamp } = forecast;
if (timestamp) {
if (!lessThanOneHourAgo(timestamp)) {
getWeatherInfo();
}
}
}
});
});
};
export default loadNewData;
|
Make use of the events provided by chosen.
Make it work when using the search field. | /*
* Chosen jQuery plugin to add an image to the dropdown items.
*/
(function($) {
$.fn.chosenImage = function(options) {
return this.each(function() {
var $select = $(this);
var imgMap = {};
// 1. Retrieve img-src from data attribute and build object of image sources for each list item.
$select.find('option').filter(function(){
return $(this).text();
}).each(function(i) {
imgMap[i] = $(this).attr('data-img-src');
});
// 2. Execute chosen plugin and get the newly created chosen container.
$select.chosen(options);
var $chosen = $select.next('.chosen-container').addClass('chosenImage-container');
// 3. Style lis with image sources.
$chosen.on('mousedown.chosen, keyup.chosen', function(event){
$chosen.find('.chosen-results li').each(function() {
var imgIndex = $(this).attr('data-option-array-index');
$(this).css(cssObj(imgMap[imgIndex]));
});
});
// 4. Change image on chosen selected element when form changes.
$select.change(function() {
var imgSrc = $select.find('option:selected').attr('data-img-src') || '';
$chosen.find('.chosen-single span').css(cssObj(imgSrc));
});
$select.trigger('change');
// Utilties
function cssObj(imgSrc) {
var bgImg = (imgSrc) ? 'url(' + imgSrc + ')' : 'none';
return { 'background-image' : bgImg };
}
});
};
})(jQuery);
| /*
* Chosen jQuery plugin to add an image to the dropdown items.
*/
(function($) {
$.fn.chosenImage = function(options) {
return this.each(function() {
var $select = $(this);
var imgMap = {};
// 1. Retrieve img-src from data attribute and build object of image sources for each list item.
$select.find('option').filter(function(){
return $(this).text();
}).each(function(i) {
imgMap[i] = $(this).attr('data-img-src');
});
// 2. Execute chosen plugin and get the newly created chosen container.
$select.chosen(options);
var $chosen = $select.next('.chosen-container').addClass('chosenImage-container');
// 3. Style lis with image sources.
$chosen.mousedown(function(event) {
$chosen.find('.chosen-results li').each(function(i) {
$(this).css(cssObj(imgMap[i]));
});
});
// 4. Change image on chosen selected element when form changes.
$select.change(function() {
var imgSrc = $select.find('option:selected').attr('data-img-src') || '';
$chosen.find('.chosen-single span').css(cssObj(imgSrc));
});
$select.trigger('change');
// Utilties
function cssObj(imgSrc) {
var bgImg = (imgSrc) ? 'url(' + imgSrc + ')' : 'none';
return { 'background-image' : bgImg };
}
});
};
})(jQuery);
|
Make sure that 'stop' works from everywhere | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import asyncio
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(object, metaclass=Singleton):
def __init__(self):
self.loop = asyncio.get_event_loop()
self.do = self.sync_do
def sync_do(self, f, *args, **kwargs):
f(*args, **kwargs)
def thread_do(self, f, *args, **kwargs):
self.loop.call_soon_threadsafe(f, *args, **kwargs)
def schedule(self, target, event):
self.do(self.loop.call_soon, event)
def later(self, delay, event):
self.do(self.loop.call_later, delay, event)
def run(self):
self.do = self.sync_do
self.loop.run_forever()
def run_once(self):
self.stop_later()
self.run()
def run_in_thread(self):
self.do = self.thread_do
self.thread = threading.Thread(target=self.loop.run_forever,
name='asyncio_event_loop')
self.thread.daemon = True
self.thread.start()
def stop(self):
self.thread_do(self.loop.stop)
def stop_later(self):
self.do = self.sync_do
self.schedule(self, self.stop) | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import asyncio
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(object, metaclass=Singleton):
def __init__(self):
self.loop = asyncio.get_event_loop()
self.do = self.sync_do
def sync_do(self, f, *args, **kwargs):
f(*args, **kwargs)
def thread_do(self, f, *args, **kwargs):
self.loop.call_soon_threadsafe(f, *args, **kwargs)
def schedule(self, target, event):
self.do(self.loop.call_soon, event)
def later(self, delay, event):
self.do(self.loop.call_later, delay, event)
def run(self):
self.do = self.sync_do
self.loop.run_forever()
def run_once(self):
self.stop_later()
self.run()
def run_in_thread(self):
self.do = self.thread_do
self.thread = threading.Thread(target=self.loop.run_forever,
name='asyncio_event_loop')
self.thread.daemon = True
self.thread.start()
def stop(self):
self.loop.stop()
def stop_later(self):
self.do = self.sync_do
self.schedule(self, self.stop) |
Load content snippets conditionally and add pagination links | <?php get_header(); ?>
<div class="container">
<div id="primary" class="content-area">
<?php get_template_part(SNIPPETS_DIR . '/header/page', 'header'); ?>
<main id="main" class="site-main" role="main">
<?php
if (have_posts()) :
/* Start the Loop */
while (have_posts()) :
the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
if (is_page()):
get_template_part(SNIPPETS_DIR . '/content/content', 'page');
else:
get_template_part(SNIPPETS_DIR . '/content/content');
endif;
endwhile;
else :
get_template_part(SNIPPETS_DIR . '/content/content', 'none');
endif;
echo paginate_links(array(
'mid_size' => 4,
'type' => 'list'
));
?>
</main>
</div>
<?php get_sidebar(); ?>
</div>
<?php
get_footer();
| <?php get_header(); ?>
<div class="container">
<?php // get_template_part(SNIPPETS_DIR . '/header/page', 'header'); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if (have_posts()) :
/* Start the Loop */
while (have_posts()) :
the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part(SNIPPETS_DIR . '/content/content');
endwhile;
else :
get_template_part(SNIPPETS_DIR . '/content/content', 'none');
endif;
?>
</main>
</div>
<?php get_sidebar(); ?>
</div>
<?php
get_footer();
|
Make debug logging a bit more consistent | import os
from twisted.internet import reactor
from heufybot import HeufyBot, HeufyBotFactory
from config import Config
class BotHandler(object):
factories = {}
globalConfig = None
def __init__(self):
print "--- Loading configs..."
self.globalConfig = Config("globalconfig.yml")
self.globalConfig.loadConfig(None)
configList = self.getConfigList()
if len(configList) == 0:
print "WARNING: No server configs found. Using the global config instead."
else:
for filename in self.getConfigList():
config = Config(filename, globalConfig.settings)
def getConfigList(self):
root = os.path.join("config")
configs = []
for item in os.listdir(root):
if not os.path.isfile(os.path.join(root, item)):
continue
if not item.endswith(".yml"):
continue
if item == "globalconfig.yml":
continue
configs.append(item)
return configs
if __name__ == "__main__":
# Create folders
if not os.path.exists(os.path.join("config")):
os.makedirs("config")
handler = BotHandler()
| import os
from twisted.internet import reactor
from heufybot import HeufyBot, HeufyBotFactory
from config import Config
class BotHandler(object):
factories = {}
globalConfig = None
def __init__(self):
print "--- Loading configs..."
self.globalConfig = Config("globalconfig.yml")
self.globalConfig.loadConfig(None)
configList = self.getConfigList()
if len(configList) == 0:
print "*** WARNING: No server configs found. Using the global config instead."
else:
for filename in self.getConfigList():
config = Config(filename, globalConfig.settings)
def getConfigList(self):
root = os.path.join("config")
configs = []
for item in os.listdir(root):
if not os.path.isfile(os.path.join(root, item)):
continue
if not item.endswith(".yml"):
continue
if item == "globalconfig.yml":
continue
configs.append(item)
return configs
if __name__ == "__main__":
# Create folders
if not os.path.exists(os.path.join("config")):
os.makedirs("config")
handler = BotHandler() |
Remove comment about former functionality | // on click of a tag, it should be toggled - either added to or removed from an internal tracking
// array and its style changed.
//
// When the internal array changes, it should write out a new tag list to the hidden input
(function($) {
$(document).ready(function() {
$(".taggit-labels").closest("div").each(function(i) {
var inputs = $(this).find(".taggit-labels + input")[0];
var tagItems = $(this).find("ul.tags li");
var tagList = inputs.value.split(", ");
tagItems.click(function() {
var tagList = inputs.value.split(", ");
var tagName = $(this).attr("data-tag-name");
// Tag names need to be quotes if they contain commas or quotation marks
if(tagName.indexOf(",") != -1 || tagName.indexOf(" ") != -1) {
tagName = "\"" + tagName + "\"";
}
var index = $.inArray(tagName, tagList);
// Add the selected tag to the list of tags if it wasn't there previously
// and remove it if it was present.
if(index == -1) {
$(this).toggleClass("selected");
tagList.push(tagName);
} else {
$(this).toggleClass("selected");
tagList.splice(index, 1);
}
// Refresh the tag list
$(inputs).attr("value", tagList.join(", "));
});
});
});
})(django.jQuery);
| // on click of a tag, it should be toggled - either added to or removed from an internal tracking
// array and its style changed.
//
// When the internal array changes, it should write out a new tag list to the hidden input
(function($) {
$(document).ready(function() {
// TODO this line assumes one tag field and that it is named as 'tags' -
// this is too fragile
$(".taggit-labels").closest("div").each(function(i) {
var inputs = $(this).find(".taggit-labels + input")[0];
var tagItems = $(this).find("ul.tags li");
var tagList = inputs.value.split(", ");
tagItems.click(function() {
var tagList = inputs.value.split(", ");
var tagName = $(this).attr("data-tag-name");
// Tag names need to be quotes if they contain commas or quotation marks
if(tagName.indexOf(",") != -1 || tagName.indexOf(" ") != -1) {
tagName = "\"" + tagName + "\"";
}
var index = $.inArray(tagName, tagList);
// Add the selected tag to the list of tags if it wasn't there previously
// and remove it if it was present.
if(index == -1) {
$(this).toggleClass("selected");
tagList.push(tagName);
} else {
$(this).toggleClass("selected");
tagList.splice(index, 1);
}
// Refresh the tag list
$(inputs).attr("value", tagList.join(", "));
});
});
});
})(django.jQuery);
|
Fix para que los jugadores mantengan su posiciΓ³n | /**
* Created by ivan on 10/5/14.
*/
angular.module('Frosch')
.factory('ConfiguracionService', function ($http, $translate) {
var clase = function () {
var me = this;
this.equipos = true;
this.maxPorEquipo = 1;
this.puntos = 800;
this.numJugadores = 6;
this.blanqueada = -10;
var httpPromise = $http.get('config/config.json');
return httpPromise.then(function (httpResponse) {
me.configuracion = httpResponse.data;
return $translate.use(me.configuracion.idioma).then(function(){
return me;
}); //el cambio de idioma es promise
});
};
clase.prototype.setMaxPorEquipo = function (cantidad) {
this.maxPorEquipo = cantidad * 1;
this.equipos = this.maxPorEquipo > 1;
};
clase.prototype.creditosPorJugador = function () {
return this.configuracion.creditosPorPuntaje[this.puntos] * this.maxPorEquipo;
};
clase.prototype.setNumJugadores = function (numJugadores) {
if (numJugadores !== Math.round(numJugadores))
throw new Error("El nΓΊmero de jugadores debe ser exacto");
this.numJugadores = numJugadores;
};
return new clase();
}); | /**
* Created by ivan on 10/5/14.
*/
angular.module('Frosch')
.factory('ConfiguracionService', function ($http, $translate) {
var clase = function () {
var me = this;
this.equipos = true;
this.maxPorEquipo = 1;
this.puntos = 800;
this.numJugadores = 3;
this.blanqueada = -10;
var httpPromise = $http.get('config/config.json');
return httpPromise.then(function (httpResponse) {
me.configuracion = httpResponse.data;
return $translate.use(me.configuracion.idioma).then(function(){
return me;
}); //el cambio de idioma es promise
});
};
clase.prototype.setMaxPorEquipo = function (cantidad) {
this.maxPorEquipo = cantidad * 1;
this.equipos = this.maxPorEquipo > 1;
};
clase.prototype.creditosPorJugador = function () {
return this.configuracion.creditosPorPuntaje[this.puntos] * this.maxPorEquipo;
};
clase.prototype.setNumJugadores = function (numJugadores) {
if (numJugadores !== Math.round(numJugadores))
throw new Error("El nΓΊmero de jugadores debe ser exacto");
this.numJugadores = numJugadores;
};
return new clase();
}); |
Update archan provider for archan 3.0 | # -*- coding: utf-8 -*-
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
identifier = 'dependenpy.InternalDependencies'
name = 'Internal Dependencies'
description = 'Provide matrix data about internal dependencies ' \
'in a set of packages.'
argument_list = (
Argument('packages', list, 'The list of packages to check for.'),
Argument('enforce_init', bool, default=True,
description='Whether to assert presence of '
'__init__.py files in directories.'),
Argument('depth', int, 'The depth of the matrix to generate.'),
)
def get_data(self, packages, enforce_init=True, depth=None):
"""
Provide matrix data for internal dependencies in a set of packages.
Args:
*packages (list): the list of packages to check for.
enforce_init (bool):
whether to assert presence of __init__.py files
in directories.
depth (int): the depth of the matrix to generate.
Returns:
archan.DSM: instance of archan DSM.
"""
dsm = DependenpyDSM(*packages, enforce_init=enforce_init)
if depth is None:
depth = guess_depth(packages)
matrix = dsm.as_matrix(depth=depth)
return ArchanDSM(data=matrix.data, entities=matrix.keys)
except ImportError:
class InternalDependencies(object):
"""Empty dependenpy provider."""
| # -*- coding: utf-8 -*-
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DSM as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
identifier = 'dependenpy.InternalDependencies'
name = 'Internal Dependencies'
description = 'Provide matrix data about internal dependencies ' \
'in a set of packages.'
arguments = (
Argument('packages', list, 'The list of packages to check for.'),
Argument('enforce_init', bool, default=True,
description='Whether to assert presence of '
'__init__.py files in directories.'),
Argument('depth', int, 'The depth of the matrix to generate.'),
)
def get_dsm(self, packages, enforce_init=True, depth=None):
"""
Provide matrix data for internal dependencies in a set of packages.
Args:
*packages (list): the list of packages to check for.
enforce_init (bool):
whether to assert presence of __init__.py files
in directories.
depth (int): the depth of the matrix to generate.
Returns:
archan.DSM: instance of archan DSM.
"""
dsm = DependenpyDSM(*packages, enforce_init=enforce_init)
if depth is None:
depth = guess_depth(packages)
matrix = dsm.as_matrix(depth=depth)
return ArchanDSM(data=matrix.data, entities=matrix.keys)
except ImportError:
class InternalDependencies(object):
"""Empty dependenpy provider."""
|
Add apiErrorResponse to caught errors during login | <?php
namespace App\Api\Controllers\Auth;
use Validator;
use Illuminate\Http\Request;
use App\Api\Controllers\ApiController;
class LoginController extends ApiController
{
/**
* Get a validator for an incoming login request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email',
'password' => 'required',
]);
}
/**
* Check a users credentials and log them in.
*
* @param array $data
* @return response
*/
protected function login(Request $request)
{
$validator = $this->validator($request->input('data.attributes'));
if ($validator->fails()) {
$response = $this->apiErrorResponse($validator->errors());
return $response;
}
try {
if (!$token = \JWTAuth::attempt($request->input('data.attributes'))) {
$response = $this->apiErrorResponse('Invalid credentials');
return $response;
}
} catch (JWTException $e) {
return $this->apiErrorResponse($e->getMessage());
}
$response = $this->apiResponse($token);
return $response;
}
}
| <?php
namespace App\Api\Controllers\Auth;
use Validator;
use Illuminate\Http\Request;
use App\Api\Controllers\ApiController;
class LoginController extends ApiController
{
/**
* Get a validator for an incoming login request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email',
'password' => 'required',
]);
}
/**
* Check a users credentials and log them in.
*
* @param array $data
* @return response
*/
protected function login(Request $request)
{
$validator = $this->validator($request->input('data.attributes'));
if ($validator->fails()) {
$response = $this->apiErrorResponse($validator->errors());
return $response;
}
try {
if (!$token = \JWTAuth::attempt($request->input('data.attributes'))) {
$response = $this->apiErrorResponse('Invalid credentials');
return $response;
}
} catch (JWTException $e) {
return response()->json(['error' => 'Could not create token'], 500);
}
$response = $this->apiResponse($token);
return $response;
}
}
|
Create 1 temp directory if no number is given | import functools
import tempfile
import shutil
class makedirs(object):
def __init__(self, num=1):
self._num = num
def __call__(self, fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
def manager():
try:
dirs = [
tempfile.mkdtemp()
for i in xrange(self._num)
]
extra_args = list(args)
extra_args += dirs
fn(*extra_args, **kwargs)
finally:
for dir_ in dirs:
try:
shutil.rmtree(dir_)
except OSError, e:
# It's OK if dir doesn't exist
if e.errno != 2:
raise
return manager()
return wrapper
| import functools
import tempfile
import shutil
class makedirs(object):
def __init__(self, num):
self._num = num
def __call__(self, fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
def manager():
try:
dirs = [
tempfile.mkdtemp()
for i in xrange(self._num)
]
extra_args = list(args)
extra_args += dirs
fn(*extra_args, **kwargs)
finally:
for dir_ in dirs:
try:
shutil.rmtree(dir_)
except OSError, e:
# It's OK if dir doesn't exist
if e.errno != 2:
raise
return manager()
return wrapper
|
Enable retreiving of only latest event from fb. | import { SET_LATEST_EVENT, SET_EXISTING } from './constants'
import fbapi from 'toolbox/fbapi'
import moment from 'moment'
export function setLatestEvent(event) {
return {
type: SET_LATEST_EVENT,
payload: {
event: event
}
}
}
export function setExisting() {
return {
type: SET_EXISTING
}
}
export function pullLatestEvent() {
return (dispatch) => {
fbapi({
url: '/cusabor/events',
fields: 'name,description,start_time,end_time,place,cover',
additional: { since: Date.now() / 1000 | 0 },
callback: function(response) {
const event = response.data[0];
if (event) {
const { id, name, start_time, end_time, place, cover, description } = event;
const payload = {
exists: true,
title: name,
imgsrc: cover.source,
date: moment(start_time).format("dddd, MMM Do"),
start_time: moment(start_time).format("h:mma"),
end_time: moment(end_time).format("h:mma"),
place: place.name,
link: "https://www.facebook.com/" + id,
description: description
};
dispatch(setLatestEvent(payload));
dispatch(setExisting());
}
}
})
}
}
| import { SET_LATEST_EVENT, SET_EXISTING } from './constants'
import fbapi from 'toolbox/fbapi'
import moment from 'moment'
export function setLatestEvent(event) {
return {
type: SET_LATEST_EVENT,
payload: {
event: event
}
}
}
export function setExisting() {
return {
type: SET_EXISTING
}
}
export function pullLatestEvent() {
return (dispatch) => {
fbapi({
url: '/cusabor/events',
fields: 'name,description,start_time,end_time,place,cover',
// additional: { since: Date.now() / 1000 | 0 },
callback: function(response) {
const event = response.data[0];
if (event) {
const { id, name, start_time, end_time, place, cover, description } = event;
const payload = {
exists: true,
title: name,
imgsrc: cover.source,
date: moment(start_time).format("dddd, MMM Do"),
start_time: moment(start_time).format("h:mma"),
end_time: moment(end_time).format("h:mma"),
place: place.name,
link: "https://www.facebook.com/" + id,
description: description
};
dispatch(setLatestEvent(payload));
dispatch(setExisting());
}
}
})
}
}
|
Remove gorlin_glue from generated docs for now. It produces about 100 warnings during doc build.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@926 ead46cd0-7350-4e37-8683-fc4c6f79bf00 | #!/usr/bin/env python
"""Script to auto-generate our API docs.
"""
# stdlib imports
import os
import sys
# local imports
from apigen import ApiDocWriter
#*****************************************************************************
if __name__ == '__main__':
nipypepath = os.path.abspath('..')
sys.path.insert(1,nipypepath)
package = 'nipype'
outdir = os.path.join('api','generated')
docwriter = ApiDocWriter(package)
# Packages that should not be included in generated API docs.
docwriter.package_skip_patterns += ['\.externals$',
'\.utils$',
'\.interfaces\.gorlin_glue$',
]
# Modules that should not be included in generated API docs.
docwriter.module_skip_patterns += ['\.version$',
'\.interfaces\.afni$',
'\.pipeline\.alloy$',
'\.pipeline\.s3_node_wrapper$',
]
docwriter.write_api_docs(outdir)
docwriter.write_index(outdir, 'gen', relative_to='api')
print '%d files written' % len(docwriter.written_modules)
| #!/usr/bin/env python
"""Script to auto-generate our API docs.
"""
# stdlib imports
import os
import sys
# local imports
from apigen import ApiDocWriter
#*****************************************************************************
if __name__ == '__main__':
nipypepath = os.path.abspath('..')
sys.path.insert(1,nipypepath)
package = 'nipype'
outdir = os.path.join('api','generated')
docwriter = ApiDocWriter(package)
# Packages that should not be included in generated API docs.
docwriter.package_skip_patterns += ['\.externals$',
'\.utils$',
]
# Modules that should not be included in generated API docs.
docwriter.module_skip_patterns += ['\.version$',
'\.interfaces\.afni$',
'\.pipeline\.alloy$',
'\.pipeline\.s3_node_wrapper$',
]
docwriter.write_api_docs(outdir)
docwriter.write_index(outdir, 'gen', relative_to='api')
print '%d files written' % len(docwriter.written_modules)
|
Add ajax calls for sending emails | /**
* Created by nkmathew on 23/06/2016.
*/
$(document).ready(function () {
var source = $("#email-list-template").html();
var template = Handlebars.compile(source);
var html = template({email: '[email protected]'});
$('#email-list-section').append(html);
$("#email-input-box").keyup(function (e) {
if (e.keyCode == 13) {
var email = $('#email-input-box').val() + '@students.jkuat.ac.ke';
var html = template({email: email});
$('#email-list-section').append(html);
$('.email-delete-btn').click(function () {
$(this).closest('.email-line').remove();
});
$(this).val('');
}
});
$("#invite-button").click(function () {
var emailList = [];
$('.email-address').each(function () {
emailList.push($(this).html());
});
$.ajax({
type: 'POST',
url: '/site/send-signup-links',
data: {
'email-list': JSON.stringify(emailList),
},
success: function () {
$('.alert-box .msg').html('Signup links sent successfully');
$('.alert-box').addClass('alert-success fade in');
$('.alert-box').css('display', 'block');
// Clear list
console.log('Emails sent!!!')
$('.email-line').remove();
},
error: function (xhr, status, error) {
$('.alert-box .msg').html('<h4>' + error + '</h4><br/>' + xhr.responseText);
$('.alert-box').addClass('alert-danger fade in');
$('.alert-box').css('display', 'block');
},
});
});
});
| /**
* Created by nkmathew on 23/06/2016.
*/
$(document).ready(function () {
var source = $("#email-list-template").html();
var template = Handlebars.compile(source);
var html = template({email: '[email protected]'});
$('#email-list-section').append(html);
$("#email-input-box").keyup(function (e) {
if (e.keyCode == 13) {
var email = $('#email-input-box').val() + '@students.jkuat.ac.ke';
var html = template({email: email});
$('#email-list-section').append(html);
$('.email-delete-btn').click(function () {
$(this).closest('.email-line').remove();
});
$(this).val('');
}
});
$("#invite-button").click(function () {
var emailList = [];
$('.email-address').each(function () {
emailList.push($(this).html());
});
$.ajax({
type: 'POST',
url: '/site/send-signup-links',
data: {
'email-list': JSON.stringify(emailList),
},
error: function (msg) {
alert('Problem occurred while trying to send email...');
},
});
});
});
|
Check email address is not already used.
Signed-off-by: Chris Lamb <[email protected]> | from django import forms
from django.contrib.auth.models import User
from librement.profile.enums import AccountEnum
from librement.account.models import Email
from librement.profile.models import Profile
class RegistrationForm(forms.ModelForm):
email = forms.EmailField()
password = forms.CharField()
password_confirm = forms.CharField()
class Meta:
model = Profile
fields = (
'account_type',
'organisation',
'address_1',
'address_2',
'city',
'region',
'zipcode',
'country',
)
def clean_email(self):
val = self.cleaned_data['email']
if Email.objects.filter(email=val).exists():
raise forms.ValidationError("Email address already in use.")
return val
def clean_password_confirm(self):
password = self.cleaned_data.get('password', '')
password_confirm = self.cleaned_data['password_confirm']
if password != password_confirm:
raise forms.ValidationError("Passwords do not match.")
return password
def clean_organisation(self):
val = self.cleaned_data['organisation']
account_type = self.cleaned_data.get('account_type')
if account_type != AccountEnum.INDIVIDUAL and val == '':
raise forms.ValidationError(
"Required field for company/non-profit accounts"
)
return val
def save(self):
user = User.objects.create_user(
username='FIXME',
password=self.cleaned_data['password'],
)
return user
| from django import forms
from django.contrib.auth.models import User
from librement.profile.enums import AccountEnum
from librement.profile.models import Profile
class RegistrationForm(forms.ModelForm):
email = forms.EmailField()
password = forms.CharField()
password_confirm = forms.CharField()
class Meta:
model = Profile
fields = (
'account_type',
'organisation',
'address_1',
'address_2',
'city',
'region',
'zipcode',
'country',
)
def clean_password_confirm(self):
password = self.cleaned_data.get('password', '')
password_confirm = self.cleaned_data['password_confirm']
if password != password_confirm:
raise forms.ValidationError("Passwords do not match.")
return password
def clean_organisation(self):
val = self.cleaned_data['organisation']
account_type = self.cleaned_data.get('account_type')
if account_type != AccountEnum.INDIVIDUAL and val == '':
raise forms.ValidationError(
"Required field for company/non-profit accounts"
)
return val
def save(self):
user = User.objects.create_user(
username='FIXME',
password=self.cleaned_data['password'],
)
return user
|
Fix an error causing incorrect types | <?php
/**
* Front End Accounts
*
* @category WordPress
* @package FrontEndAcounts
* @since 0.1
* @author Christopher Davis <http://christopherdavis.me>
* @copyright 2013 Christopher Davis
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Chrisguitarguy\FrontEndAccounts\Form\Field;
!defined('ABSPATH') && exit;
/**
* Base class for anything that starts with '<input'
*
* @since 0.1
*/
abstract class InputBase extends FieldBase implements FieldInterface
{
/**
* {@inheritdoc}
* @see Chrisguitarguy\FrontEndAccounts\Form\Field\FieldInterface::render();
*/
public function render()
{
$t = $this->getType();
$attr = $this->getAdditionalAttributes();
printf(
'<input type="%1$s" id="%2$s" name="%2$s" value="%3$s" %4$s />',
$this->escAttr($t),
$this->escAttr($this->getName()),
'password' === $t ? '' : $this->escAttr($this->getValue()),
$this->arrayToAttr($attr)
);
}
/**
* Get the "type" of the field (eg. text, password, etc)
*
* @since 0.1
* @access protected
* @return string
*/
abstract protected function getType();
}
| <?php
/**
* Front End Accounts
*
* @category WordPress
* @package FrontEndAcounts
* @since 0.1
* @author Christopher Davis <http://christopherdavis.me>
* @copyright 2013 Christopher Davis
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Chrisguitarguy\FrontEndAccounts\Form\Field;
!defined('ABSPATH') && exit;
/**
* Base class for anything that starts with '<input'
*
* @since 0.1
*/
abstract class InputBase extends FieldBase implements FieldInterface
{
/**
* {@inheritdoc}
* @see Chrisguitarguy\FrontEndAccounts\Form\Field\FieldInterface::render();
*/
public function render()
{
$t = $this->getType();
$attr = $this->getAdditionalAttributes();
printf(
'<input type="%1%s" id="%2$s" name="%2$s" value="%3$s" %4$s />',
$this->escAttr($t),
$this->escAttr($this->getName()),
'password' === $t ? '' : $this->escAttr($this->getValue()),
$this->arrayToAttr($attr)
);
}
/**
* Get the "type" of the field (eg. text, password, etc)
*
* @since 0.1
* @access protected
* @return string
*/
abstract protected function getType();
}
|
Fix "Add your company" button | /**
* @jsx React.DOM
*/
const React = require('React');
const Site = require('Site');
const Container = require('Container');
const siteConfig = require('../../siteConfig.js');
class UserShowcase extends React.Component {
render() {
const showcase = siteConfig.users.map(user => {
return (
<a href={user.infoLink}>
<img src={user.image} title={user.caption}/>
</a>
);
});
return (
<Site>
<div className="mainContainer">
<Container padding={['bottom', 'top']}>
<div className="showcaseSection">
<div className="prose">
<h1>Who's using Jest?</h1>
<p>Jest is used by teams of all sizes to test websites, mobile
apps, and APIs.</p>
</div>
<div className="logos">
{showcase}
</div>
<p>Is your company using Jest?
</p>
<a href="https://github.com/facebook/jest/edit/master/website/siteConfig.js" className="button">Add your company</a>
</div>
</Container>
</div>
</Site>
);
}
}
module.exports = UserShowcase;
| /**
* @jsx React.DOM
*/
const React = require('React');
const Site = require('Site');
const Container = require('Container');
const siteConfig = require('../../siteConfig.js');
class UserShowcase extends React.Component {
render() {
const showcase = siteConfig.users.map(user => {
return (
<a href={user.infoLink}>
<img src={user.image} title={user.caption}/>
</a>
);
});
return (
<Site>
<div className="mainContainer">
<Container padding={['bottom', 'top']}>
<div className="showcaseSection">
<div className="prose">
<h1>Who's using Jest?</h1>
<p>Jest is used by teams of all sizes to test websites, mobile
apps, and APIs.</p>
</div>
<div className="logos">
{showcase}
</div>
<p>Is your company using Jest?
</p>
<a className="button">Add your company</a>
</div>
</Container>
</div>
</Site>
);
}
}
module.exports = UserShowcase;
|
Make global explicit in module scope
This is mainly because tests don't inferr that
global variables are just properties of the window
object, as browsers do, but it also makes this
more explicit. | (function(global) {
"use strict";
var queues = {};
var dd = new global.diffDOM();
var getRenderer = $component => response => dd.apply(
$component.get(0),
dd.diff($component.get(0), $(response[$component.data('key')]).get(0))
);
var getQueue = resource => (
queues[resource] = queues[resource] || []
);
var flushQueue = function(queue, response) {
while(queue.length) queue.shift()(response);
};
var clearQueue = queue => (queue.length = 0);
var poll = function(renderer, resource, queue, interval, form) {
if (document.visibilityState !== "hidden" && queue.push(renderer) === 1) $.ajax(
resource,
{
'method': form ? 'post' : 'get',
'data': form ? $('#' + form).serialize() : {}
}
).done(
response => {
flushQueue(queue, response);
if (response.stop === 1) {
poll = function(){};
}
}
).fail(
() => poll = function(){}
);
setTimeout(
() => poll.apply(window, arguments), interval
);
};
global.GOVUK.Modules.UpdateContent = function() {
this.start = component => poll(
getRenderer($(component)),
$(component).data('resource'),
getQueue($(component).data('resource')),
($(component).data('interval-seconds') || 1.5) * 1000,
$(component).data('form')
);
};
})(window);
| (function(Modules) {
"use strict";
var queues = {};
var dd = new diffDOM();
var getRenderer = $component => response => dd.apply(
$component.get(0),
dd.diff($component.get(0), $(response[$component.data('key')]).get(0))
);
var getQueue = resource => (
queues[resource] = queues[resource] || []
);
var flushQueue = function(queue, response) {
while(queue.length) queue.shift()(response);
};
var clearQueue = queue => (queue.length = 0);
var poll = function(renderer, resource, queue, interval, form) {
if (document.visibilityState !== "hidden" && queue.push(renderer) === 1) $.ajax(
resource,
{
'method': form ? 'post' : 'get',
'data': form ? $('#' + form).serialize() : {}
}
).done(
response => {
flushQueue(queue, response);
if (response.stop === 1) {
poll = function(){};
}
}
).fail(
() => poll = function(){}
);
setTimeout(
() => poll.apply(window, arguments), interval
);
};
Modules.UpdateContent = function() {
this.start = component => poll(
getRenderer($(component)),
$(component).data('resource'),
getQueue($(component).data('resource')),
($(component).data('interval-seconds') || 1.5) * 1000,
$(component).data('form')
);
};
})(window.GOVUK.Modules);
|
Add failure message when testing whether a string matches a regex | package com.insightfullogic.lambdabehave.expectations;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* .
*/
public final class StringExpectation extends BoundExpectation<String> {
public StringExpectation(final String str, final boolean positive) {
super(str, positive);
}
public StringExpectation isEmptyString() {
return matches(Matchers.isEmptyString());
}
public StringExpectation isEmptyOrNullString() {
return matches(Matchers.isEmptyOrNullString());
}
public StringExpectation equalToIgnoringCase(final String expectedString) {
return matches(Matchers.equalToIgnoringCase(expectedString));
}
public StringExpectation equalToIgnoringWhiteSpace(final String expectedString) {
return matches(Matchers.equalToIgnoringWhiteSpace(expectedString));
}
public StringExpectation containsString(final String substring) {
return matches(Matchers.containsString(substring));
}
public StringExpectation endsWith(final String suffix) {
return matches(Matchers.endsWith(suffix));
}
public StringExpectation startsWith(final String prefix) {
return matches(Matchers.startsWith(prefix));
}
private StringExpectation matches(final Matcher<String> matcher) {
assertThat(objectUnderTest, matcher);
return this;
}
public StringExpectation matches(String regex) {
assertTrue("String " + objectUnderTest + " does not match regex " + regex, objectUnderTest.matches(regex));
return this;
}
}
| package com.insightfullogic.lambdabehave.expectations;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* .
*/
public final class StringExpectation extends BoundExpectation<String> {
public StringExpectation(final String str, final boolean positive) {
super(str, positive);
}
public StringExpectation isEmptyString() {
return matches(Matchers.isEmptyString());
}
public StringExpectation isEmptyOrNullString() {
return matches(Matchers.isEmptyOrNullString());
}
public StringExpectation equalToIgnoringCase(final String expectedString) {
return matches(Matchers.equalToIgnoringCase(expectedString));
}
public StringExpectation equalToIgnoringWhiteSpace(final String expectedString) {
return matches(Matchers.equalToIgnoringWhiteSpace(expectedString));
}
public StringExpectation containsString(final String substring) {
return matches(Matchers.containsString(substring));
}
public StringExpectation endsWith(final String suffix) {
return matches(Matchers.endsWith(suffix));
}
public StringExpectation startsWith(final String prefix) {
return matches(Matchers.startsWith(prefix));
}
private StringExpectation matches(final Matcher<String> matcher) {
assertThat(objectUnderTest, matcher);
return this;
}
public StringExpectation matches(String regex) {
assertTrue(objectUnderTest.matches(regex));
return this;
}
}
|
[Command] Add property for bills repository | <?php
namespace HCLabs\Bills\Command\Scenario\CreateBillsForAccount;
use HCLabs\Bills\Command\Handler\AbstractCommandHandler;
use HCLabs\Bills\Model\Bill;
use HCLabs\Bills\Model\Repository\BillRepository;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class CreateBillsForAccountCommandHandler extends AbstractCommandHandler
{
/** @var BillRepository */
private $billRepository;
/**
* @param EventDispatcherInterface $dispatcher
* @param BillRepository $billRepository
*/
public function __construct(EventDispatcherInterface $dispatcher, BillRepository $billRepository)
{
parent::__construct($dispatcher);
$this->billRepository = $billRepository;
}
/**
* @param CreateBillsForAccountCommand $command
*/
public function handle($command)
{
$account = $command->getAccount();
$billingPeriod = new \DatePeriod($account->getBillingStartDate(),
$account->getBillingInterval(),
$account->dateToClose());
foreach ($billingPeriod as $billDate) {
$bill = Bill::create($account, $billDate);
$this->billRepository->save($bill);
}
}
} | <?php
namespace HCLabs\Bills\Command\Scenario\CreateBillsForAccount;
use HCLabs\Bills\Command\Handler\AbstractCommandHandler;
use HCLabs\Bills\Model\Bill;
use HCLabs\Bills\Model\Repository\BillRepository;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class CreateBillsForAccountCommandHandler extends AbstractCommandHandler
{
/**
* @param EventDispatcherInterface $dispatcher
* @param BillRepository $billRepository
*/
public function __construct(EventDispatcherInterface $dispatcher, BillRepository $billRepository)
{
parent::__construct($dispatcher);
$this->billRepository = $billRepository;
}
/**
* @param CreateBillsForAccountCommand $command
*/
public function handle($command)
{
$account = $command->getAccount();
$billingPeriod = new \DatePeriod($account->getBillingStartDate(),
$account->getBillingInterval(),
$account->dateToClose());
foreach ($billingPeriod as $billDate) {
$bill = Bill::create($account, $billDate);
$this->billRepository->save($bill);
}
}
} |
Add flushing for console logging | package com.proofpoint.log;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import static java.nio.charset.StandardCharsets.UTF_8;
final class OutputStreamHandler
extends Handler
{
private final StaticFormatter formatter = new StaticFormatter();
private final AtomicBoolean reported = new AtomicBoolean();
private final Writer writer;
public OutputStreamHandler(OutputStream out)
{
writer = new OutputStreamWriter(out, UTF_8);
}
@Override
public void publish(LogRecord record)
{
if (!isLoggable(record)) {
return;
}
try {
writer.write(formatter.format(record));
writer.flush();
}
catch (Exception e) {
// try to report the first error
if (!reported.getAndSet(true)) {
PrintWriter error = new PrintWriter(writer);
error.print("LOGGING FAILED: ");
e.printStackTrace(error);
error.flush();
}
}
}
@Override
public void flush() {}
@Override
public void close() {}
}
| package com.proofpoint.log;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.logging.ErrorManager.CLOSE_FAILURE;
import static java.util.logging.ErrorManager.FLUSH_FAILURE;
import static java.util.logging.ErrorManager.FORMAT_FAILURE;
import static java.util.logging.ErrorManager.WRITE_FAILURE;
final class OutputStreamHandler
extends Handler
{
private final Writer writer;
public OutputStreamHandler(OutputStream out)
{
writer = new OutputStreamWriter(out, UTF_8);
setFormatter(new StaticFormatter());
}
@Override
public void publish(LogRecord record)
{
if (!isLoggable(record)) {
return;
}
String message;
try {
message = getFormatter().format(record);
}
catch (Exception e) {
reportError(null, e, FORMAT_FAILURE);
return;
}
try {
writer.write(message);
}
catch (Exception e) {
reportError(null, e, WRITE_FAILURE);
}
}
@Override
public void flush()
{
try {
writer.flush();
}
catch (Exception e) {
reportError(null, e, FLUSH_FAILURE);
}
}
@Override
public void close()
{
try {
writer.flush();
}
catch (Exception e) {
reportError(null, e, CLOSE_FAILURE);
}
}
}
|
Add promise version of copy method | const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get copyFile() {
return util.promisify(fs.copyFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get writeFile() {
return util.promisify(fs.writeFile)
}
static get mkdir() {
return util.promisify(fs.mkdir)
}
static fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
static mkdirp(pathname = '') {
const pathParts = pathname.split('/')
return pathParts.reduce((promise, part) => promise
.then(previousPath => {
const newPath = path.join(previousPath, part)
if (FsUtils.fileExist(newPath)) {
return newPath
}
return FsUtils.mkdir(newPath)
.catch(error => {
if (error.code !== 'EEXIST') {
throw new Error('dir_create_failed')
}
})
.then(() => newPath)
}), Promise.resolve(pathname[0] === '/' ? '/' : ''))
}
}
module.exports = exports = { FsUtils }
| const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get writeFile() {
return util.promisify(fs.writeFile)
}
static get mkdir() {
return util.promisify(fs.mkdir)
}
static fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
static mkdirp(pathname = '') {
const pathParts = pathname.split('/')
return pathParts.reduce((promise, part) => promise
.then(previousPath => {
const newPath = path.join(previousPath, part)
if (FsUtils.fileExist(newPath)) {
return newPath
}
return FsUtils.mkdir(newPath)
.catch(error => {
if (error.code !== 'EEXIST') {
throw new Error('dir_create_failed')
}
})
.then(() => newPath)
}), Promise.resolve(pathname[0] === '/' ? '/' : ''))
}
}
module.exports = exports = { FsUtils }
|
Update the idProperty and labelProperty of the store properly based on what the picklist is using. | /*
* Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
*/
/**
* @class Mobile.SalesLogix.Views.PickList
*
*
* @extends Sage.Platform.Mobile.List
*
*/
define('Mobile/SalesLogix/Views/PickList', [
'dojo/_base/declare',
'dojo/string',
'Sage/Platform/Mobile/List'
], function(
declare,
string,
List
) {
return declare('Mobile.SalesLogix.Views.PickList', [List], {
//Templates
itemTemplate: new Simplate([
'<h3>{%: $.text %}</h3>'
]),
//View Properties
id: 'pick_list',
expose: false,
resourceKind: 'picklists',
resourceProperty: 'items',
contractName: 'system',
activateEntry: function(params) {
if (this.options.keyProperty === 'text' && !this.options.singleSelect) {
params.key = params.descriptor;
}
this.inherited(arguments);
},
show: function(options) {
this.set('title', options && options.title || this.title);
if (options.keyProperty) {
this.idProperty = options.keyProperty;
}
if (options.textProperty) {
this.labelProperty = options.textProperty;
}
this.inherited(arguments);
},
formatSearchQuery: function(searchQuery) {
return string.substitute('upper(text) like "${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
}
});
});
| /*
* Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
*/
/**
* @class Mobile.SalesLogix.Views.PickList
*
*
* @extends Sage.Platform.Mobile.List
*
*/
define('Mobile/SalesLogix/Views/PickList', [
'dojo/_base/declare',
'dojo/string',
'Sage/Platform/Mobile/List'
], function(
declare,
string,
List
) {
return declare('Mobile.SalesLogix.Views.PickList', [List], {
//Templates
itemTemplate: new Simplate([
'<h3>{%: $.text %}</h3>'
]),
//View Properties
id: 'pick_list',
expose: false,
resourceKind: 'picklists',
resourceProperty: 'items',
contractName: 'system',
activateEntry: function(params) {
if (this.options.keyProperty === 'text' && !this.options.singleSelect) {
params.key = params.descriptor;
}
this.inherited(arguments);
},
show: function(options) {
this.set('title', options && options.title || this.title);
this.inherited(arguments);
},
formatSearchQuery: function(searchQuery) {
return string.substitute('upper(text) like "${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
}
});
});
|
Initialize earlier the Everlive instance. | (function (global) {
'use strict';
var app = global.app = global.app || {};
app.everlive = new Everlive({
apiKey: app.config.everlive.apiKey,
scheme: app.config.everlive.scheme
});
var fixViewResize = function () {
if (device.platform === 'iOS') {
setTimeout(function() {
$(document.body).height(window.innerHeight);
}, 10);
}
};
var onDeviceReady = function() {
navigator.splashscreen.hide();
if (!app.isKeySet(app.config.everlive.apiKey)) {
$(app.config.views.init).hide();
$('#pushApp').addClass('noapikey-scrn').html(app.constants.NO_API_KEY_MESSAGE);
return;
}
fixViewResize();
var os = kendo.support.mobileOS,
statusBarStyle = os.ios && os.flatVersion >= 700 ? 'black-translucent' : 'black';
app.mobile = new kendo.mobile.Application(document.body, {
transition: 'slide',
statusBarStyle: statusBarStyle,
skin: 'flat'
});
};
document.addEventListener('deviceready', onDeviceReady, false);
document.addEventListener('orientationchange', fixViewResize);
}(window));
| (function (global) {
'use strict';
var app = global.app = global.app || {};
var fixViewResize = function () {
if (device.platform === 'iOS') {
setTimeout(function() {
$(document.body).height(window.innerHeight);
}, 10);
}
};
var onDeviceReady = function() {
navigator.splashscreen.hide();
if (!app.isKeySet(app.config.everlive.apiKey)) {
$(app.config.views.init).hide();
$('#pushApp').addClass('noapikey-scrn').html(app.constants.NO_API_KEY_MESSAGE);
return;
}
fixViewResize();
var os = kendo.support.mobileOS,
statusBarStyle = os.ios && os.flatVersion >= 700 ? 'black-translucent' : 'black';
app.mobile = new kendo.mobile.Application(document.body, {
transition: 'slide',
statusBarStyle: statusBarStyle,
skin: 'flat'
});
app.everlive = new Everlive({
apiKey: app.config.everlive.apiKey,
scheme: app.config.everlive.scheme
});
};
document.addEventListener('deviceready', onDeviceReady, false);
document.addEventListener('orientationchange', fixViewResize);
}(window));
|
Set log with small message | # -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.convert import force_string
from ines.middlewares import Middleware
from ines.utils import format_error_to_json
class LoggingMiddleware(Middleware):
name = 'logging'
@property
def request_factory(self):
return self.config.registry.queryUtility(IRequestFactory)
@reify
def api_name(self):
return self.settings.get('logging_api_name') or 'logging'
def __call__(self, environ, start_response):
try:
for chunk in self.application(environ, start_response):
yield chunk
except (BaseException, Exception) as error:
type_, value, tb = sys.exc_info()
message = ''.join(format_exception(type_, value, tb))
# Save / log error
request = self.request_factory(environ)
request.registry = self.config.registry
try:
small_message = '%s: %s' % (error.__class__.__name__, force_string(error))
except (BaseException, Exception):
small_message = error
try:
getattr(request.api, self.api_name).log_critical(
'internal_server_error',
str(small_message))
except (BaseException, Exception):
print message
internal_server_error = HTTPInternalServerError()
headers = [('Content-type', 'application/json')]
start_response(internal_server_error.status, headers)
yield format_error_to_json(internal_server_error, request=request)
| # -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.middlewares import Middleware
from ines.utils import format_error_to_json
class LoggingMiddleware(Middleware):
name = 'logging'
@property
def request_factory(self):
return self.config.registry.queryUtility(IRequestFactory)
@reify
def api_name(self):
return self.settings.get('logging_api_name') or 'logging'
def __call__(self, environ, start_response):
try:
for chunk in self.application(environ, start_response):
yield chunk
except (BaseException, Exception):
type_, value, tb = sys.exc_info()
error = ''.join(format_exception(type_, value, tb))
# Save / log error
request = self.request_factory(environ)
request.registry = self.config.registry
try:
message = error.split()[-1]
getattr(request.api, self.api_name).log_critical('internal_server_error', message)
except (BaseException, Exception):
print error
internal_server_error = HTTPInternalServerError()
headers = [('Content-type', 'application/json')]
start_response(internal_server_error.status, headers)
yield format_error_to_json(internal_server_error, request=request)
|
Fix Chrome headless when root on Linux
Fix Chrome headless when running as root by adding --no-sandbox. | // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
const puppeteer = require("puppeteer");
process.env.CHROME_BIN = puppeteer.executablePath();
module.exports = function (config) {
config.set({
autoWatch: false,
concurrency: Infinity,
browsers: ["ChromeHeadlessNoSandbox"],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",
flags: ["--no-sandbox"]
}
},
frameworks: ["jasmine", "karma-typescript"],
files: [
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.1/clipboard.min.js",
"assets/scripts/**/*.ts"
],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
karmaTypescriptConfig: {
tsconfig: "tsconfig.json"
},
htmlDetailed: {
splitResults: false
},
plugins: [
"karma-appveyor-reporter",
"karma-chrome-launcher",
"karma-html-detailed-reporter",
"karma-jasmine",
"karma-typescript"
],
reporters: [
"progress",
"appveyor",
"karma-typescript"
]
});
};
| // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
const puppeteer = require("puppeteer");
process.env.CHROME_BIN = puppeteer.executablePath();
module.exports = function (config) {
config.set({
autoWatch: false,
concurrency: Infinity,
browsers: ["ChromeHeadless"],
frameworks: ["jasmine", "karma-typescript"],
files: [
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.1/clipboard.min.js",
"assets/scripts/**/*.ts"
],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
karmaTypescriptConfig: {
tsconfig: "tsconfig.json"
},
htmlDetailed: {
splitResults: false
},
plugins: [
"karma-appveyor-reporter",
"karma-chrome-launcher",
"karma-html-detailed-reporter",
"karma-jasmine",
"karma-typescript"
],
reporters: [
"progress",
"appveyor",
"karma-typescript"
]
});
};
|
Remove "1" from possible $alphabet
Remove "1" from possible $alphabet. Fixes #1 | <?php
namespace Allty\Utils;
class Base58 {
static $alphabet = '23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
const BASE = 58;
public static function encode($int) {
if(!is_integer($int)) {
throw new \InvalidArgumentException('$int must be an integer. Got a '.gettype($int).'!');
}
$encoded = '';
while($int) {
$remainder = $int % self::BASE;
$int = floor($int / self::BASE);
$encoded = self::$alphabet{$remainder} . $encoded;
}
return $encoded;
}
public static function decode($str) {
if(!is_string($str)) {
throw new \InvalidArgumentException('$str must be a string. Got a '.gettype($str).'!');
}
$decoded = 0;
while($str) {
if(($alphabetPosition = strpos(self::$alphabet, $str[0])) === false) {
throw new \RuntimeException('decode() cannot find "'.$str[0].'" in alphabet.');
}
$decoded += $alphabetPosition * (pow(self::BASE, strlen($str) - 1));
$str = substr($str, 1);
}
return $decoded;
}
}
| <?php
namespace Allty\Utils;
class Base58 {
static $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
const BASE = 58;
public static function encode($int) {
if(!is_integer($int)) {
throw new \InvalidArgumentException('$int must be an integer. Got a '.gettype($int).'!');
}
$encoded = '';
while($int) {
$remainder = $int % self::BASE;
$int = floor($int / self::BASE);
$encoded = self::$alphabet{$remainder} . $encoded;
}
return $encoded;
}
public static function decode($str) {
if(!is_string($str)) {
throw new \InvalidArgumentException('$str must be a string. Got a '.gettype($str).'!');
}
$decoded = 0;
while($str) {
if(($alphabetPosition = strpos(self::$alphabet, $str[0])) === false) {
throw new \RuntimeException('decode() cannot find "'.$str[0].'" in alphabet.');
}
$decoded += $alphabetPosition * (pow(self::BASE, strlen($str) - 1));
$str = substr($str, 1);
}
return $decoded;
}
}
|
Fix selectedLabels selected$ merge function
As we did for localStorage, we should also consider that values can
change over time and so newSelected may not be part of it anymore.
Fallback onto props.select() method in such case β which will here deal
with localStorage values⦠or take the first/last value as the last fallback. | import { div, select, option, label } from '@cycle/dom';
import { Observable } from 'rx';
import R from 'ramda';
function LabeledSelect({ DOM, props$, values$ }) {
const newSelected$ = DOM
.select('.select')
.events('input')
.map(ev => ev.target.value)
.startWith(null);
const selected$ = Observable.combineLatest(
props$,
values$,
newSelected$,
(props, values, newSelected) => R.cond([
[R.contains(newSelected), R.always(newSelected)],
[R.T, props.select],
])(values)
);
const propsDefaults = { render: R.identity };
const vtree$ = Observable.combineLatest(
props$.map(R.merge(propsDefaults)),
selected$,
values$,
(props, selected, values) => div([
label({ htmlFor: props.name }, props.label),
select(
{
className: R.join(' ', R.concat(['select'], props.classNames)),
name: props.name,
},
[R.map(value => R.cond([
[
R.equals(selected),
R.always(option({ value, selected: true }, props.render(value))),
],
[R.T, R.always(option({ value }, props.render(value)))],
])(value), values)]
),
])
);
return {
DOM: vtree$,
selected$,
};
}
export default LabeledSelect;
| import { div, select, option, label } from '@cycle/dom';
import { Observable } from 'rx';
import R from 'ramda';
function LabeledSelect({ DOM, props$, values$ }) {
const newSelected$ = DOM
.select('.select')
.events('input')
.map(ev => ev.target.value)
.startWith(null);
const selected$ = Observable.combineLatest(
props$,
values$,
newSelected$,
(props, values, newSelected) => R.defaultTo(
props.select(values),
newSelected
)
);
const propsDefaults = { render: R.identity };
const vtree$ = Observable.combineLatest(
props$.map(R.merge(propsDefaults)),
selected$,
values$,
(props, selected, values) => div([
label({ htmlFor: props.name }, props.label),
select(
{
className: R.join(' ', R.concat(['select'], props.classNames)),
name: props.name,
},
[R.map(value => R.cond([
[
R.equals(selected),
R.always(option({ value, selected: true }, props.render(value))),
],
[R.T, R.always(option({ value }, props.render(value)))],
])(value), values)]
),
])
);
return {
DOM: vtree$,
selected$,
};
}
export default LabeledSelect;
|
Make sure that the select queries return records otherwise, bail | 'use strict';
exports.up = function (knex, Promise) {
return knex('publishedProjects')
.whereNull('date_created')
.orWhereNull('date_updated')
.select('id', 'date_created', 'date_updated')
.then(function(publishedProjects) {
if (!publishedProjects) {
return;
}
return Promise.map(publishedProjects, function(publishedProject) {
var publishedProjectId = publishedProject.id;
var dateUpdated = publishedProject.date_updated;
// For existing published projects that have been updated since
// date tracking has been added, they will have a date_updated
// but not a date_created. Set the date_created to the date_updated
if (dateUpdated) {
return knex('publishedProjects').update('date_created', dateUpdated)
.where('id', publishedProjectId);
}
// For existing published projects that have not been updated
// since date tracking has been added - set both the dates
// to the date_updated of the corresponding project
return knex('projects')
.where('published_id', publishedProjectId).select('date_updated')
.then(function(projects) {
if (!projects || !projects[0]) {
return;
}
var date = projects[0].date_updated;
// Update the date_created and date_updated fields in the
// publishedProjects table
return knex('publishedProjects')
.where('id', publishedProjectId)
.update({
date_created: date,
date_updated: date
});
});
});
});
};
exports.down = function (knex, Promise) {
// This is an "update once" migration so that we do not lose data
return Promise.resolve();
};
| 'use strict';
exports.up = function (knex, Promise) {
return knex('publishedProjects')
.whereNull('date_created')
.orWhereNull('date_updated')
.select('id', 'date_created', 'date_updated')
.then(function(publishedProjects) {
return Promise.map(publishedProjects, function(publishedProject) {
var publishedProjectId = publishedProject.id;
var dateUpdated = publishedProject.date_updated;
// For existing published projects that have been updated since
// date tracking has been added, they will have a date_updated
// but not a date_created. Set the date_created to the date_updated
if (dateUpdated) {
return knex('publishedProjects').update('date_created', dateUpdated)
.where('id', publishedProjectId);
}
// For existing published projects that have not been updated
// since date tracking has been added - set both the dates
// to the date_updated of the corresponding project
return knex('projects')
.where('published_id', publishedProjectId).select('date_updated')
.then(function(projects) {
var date = projects[0].date_updated;
// Update the date_created and date_updated fields in the
// publishedProjects table
return knex('publishedProjects')
.where('id', publishedProjectId)
.update({
date_created: date,
date_updated: date
});
});
});
});
};
exports.down = function (knex, Promise) {
// This is an "update once" migration so that we do not lose data
return Promise.resolve();
};
|
Fix logic error with searching of composer loader | <?php
/**
* Parser Reflection API
*
* @copyright Copyright 2015, Lisachenko Alexander <[email protected]>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace ParserReflection\Locator;
use Composer\Autoload\ClassLoader;
use ParserReflection\LocatorInterface;
use ParserReflection\ReflectionException;
/**
* Locator, that can find a file for the given class name by asking composer
*/
class ComposerLocator implements LocatorInterface
{
/**
* @var ClassLoader
*/
private $loader;
public function __construct(ClassLoader $loader = null)
{
if (!$loader) {
$loaders = spl_autoload_functions();
foreach ($loaders as $loader) {
if (is_array($loader) && $loader[0] instanceof ClassLoader) {
$loader = $loader[0];
break;
}
}
if (!$loader) {
throw new ReflectionException("Can not found a correct composer loader");
}
}
$this->loader = $loader;
}
/**
* Returns a path to the file for given class name
*
* @param string $className Name of the class
*
* @return string|false Path to the file with given class or false if not found
*/
public function locateClass($className)
{
return $this->loader->findFile($className);
}
} | <?php
/**
* Parser Reflection API
*
* @copyright Copyright 2015, Lisachenko Alexander <[email protected]>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace ParserReflection\Locator;
use Composer\Autoload\ClassLoader;
use ParserReflection\LocatorInterface;
use ParserReflection\ReflectionException;
/**
* Locator, that can find a file for the given class name by asking composer
*/
class ComposerLocator implements LocatorInterface
{
/**
* @var ClassLoader
*/
private $loader;
public function __construct(ClassLoader $loader = null)
{
if (!$loader) {
$loaders = spl_autoload_functions();
foreach ($loaders as $loader) {
if (is_array($loader) && $loader[0] instanceof ClassLoader) {
$loader = $loader[0];
}
}
if (!$loader) {
throw new ReflectionException("Can not found a correct composer loader");
}
}
$this->loader = $loader;
}
/**
* Returns a path to the file for given class name
*
* @param string $className Name of the class
*
* @return string|false Path to the file with given class or false if not found
*/
public function locateClass($className)
{
return $this->loader->findFile($className);
}
} |
Convert Trans::trans() to use __() instead | <?php
namespace Bolt\Nut;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Bolt\Translation\Translator as Trans;
class ExtensionsEnable extends BaseCommand
{
protected function configure()
{
$this
->setName('extensions:enable')
->setAliases(array('extensions:install'))
->setDescription('Installs an extension by name and version.')
->addArgument('name', InputArgument::REQUIRED, 'Name of the extension to enable')
->addArgument('version', InputArgument::REQUIRED, 'Version of the extension to enable');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
$version = $input->getArgument('version');
if (!isset($name) || !isset($version)) {
$output->writeln(
'<error>' .
Trans::__('You must specify both a name and a version to install!') .
'</error>'
);
return;
}
$result = $this->app['extend.runner']->install($name, $version);
$output->writeln("<info>[Done]</info> ");
$output->writeln($result, OutputInterface::OUTPUT_PLAIN);
}
}
| <?php
namespace Bolt\Nut;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Bolt\Translation\Translator as Trans;
class ExtensionsEnable extends BaseCommand
{
protected function configure()
{
$this
->setName('extensions:enable')
->setAliases(array('extensions:install'))
->setDescription('Installs an extension by name and version.')
->addArgument('name', InputArgument::REQUIRED, 'Name of the extension to enable')
->addArgument('version', InputArgument::REQUIRED, 'Version of the extension to enable');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
$version = $input->getArgument('version');
if (!isset($name) || !isset($version)) {
$output->writeln(
'<error>' .
Trans::trans('You must specify both a name and a version to install!') .
'</error>'
);
return;
}
$result = $this->app['extend.runner']->install($name, $version);
$output->writeln("<info>[Done]</info> ");
$output->writeln($result, OutputInterface::OUTPUT_PLAIN);
}
}
|
Hide for your own account. | import React from 'react';
import steem from 'steem'
import { Button } from 'semantic-ui-react'
export default class AccountFollow extends React.Component {
constructor(props) {
super(props)
this.state = {
processing: false,
following: props.account.following || []
}
}
componentWillReceiveProps(nextProps) {
if(this.state.processing && nextProps.length !== this.state.following.length) {
this.setState({processing: false})
}
}
follow = (e) => {
this.setState({processing: true})
this.props.actions.follow({
account: this.props.account,
action: "follow",
who: this.props.who
})
}
unfollow = (e) => {
this.setState({processing: true})
this.props.actions.follow({
account: this.props.account,
action: "unfollow",
who: this.props.who
})
}
render() {
if(this.props.account.name === this.props.who) return false
const loading = (this.state.processing || !this.props.account || !this.props.account.following)
const following = (this.props.account.following && this.props.account.following.indexOf(this.props.who) !== -1)
return (
<Button
color={(loading) ? 'grey' : (following) ? 'orange' : 'green' }
content={(following) ? 'Unfollow' : 'Follow'}
loading={loading}
onClick={(loading) ? () => {} : (following) ? this.unfollow : this.follow}
/>
)
}
}
| import React from 'react';
import steem from 'steem'
import { Button } from 'semantic-ui-react'
export default class AccountFollow extends React.Component {
constructor(props) {
super(props)
this.state = {
processing: false,
following: props.account.following || []
}
}
componentWillReceiveProps(nextProps) {
if(this.state.processing && nextProps.length !== this.state.following.length) {
this.setState({processing: false})
}
}
follow = (e) => {
this.setState({processing: true})
this.props.actions.follow({
account: this.props.account,
action: "follow",
who: this.props.who
})
}
unfollow = (e) => {
this.setState({processing: true})
this.props.actions.follow({
account: this.props.account,
action: "unfollow",
who: this.props.who
})
}
render() {
const loading = (this.state.processing || !this.props.account || !this.props.account.following)
const following = (this.props.account.following && this.props.account.following.indexOf(this.props.who) !== -1)
return (
<Button
color={(loading) ? 'grey' : (following) ? 'orange' : 'green' }
content={(following) ? 'Unfollow' : 'Follow'}
loading={loading}
onClick={(loading) ? () => {} : (following) ? this.unfollow : this.follow}
/>
)
}
}
|
Disable POST approved invoice for now
Need to rethink this. Looks like some dependency change (swagger-tools)
broke this. Anyway, there should be a way to transform drafts into
approved into paid. Maybe single endpoint would do. | 'use strict';
module.exports = {
'get': {
'description': 'This endpoint returns information about invoices that have been approved. The response includes basic details of each invoice, such as sender and receiver information.',
'responses': {
'200': {
'description': 'An array of approved invoices',
'schema': {
'$ref': '#/definitions/InvoiceApproved'
}
},
'default': {
'description': 'Unexpected error',
'schema': {
'$ref': '#/definitions/Error'
}
}
}
},
// XXXXX: figure out proper semantics for approving (separate resource?)
/*
'post': {
'description': 'This endpoint allows you to send approved invoices.',
'parameters': [
{
'name': 'body',
'in': 'body',
'description': 'The Invoice JSON you want to POST',
'schema': {
'approvedInvoices': {
'type': 'array',
'items': {
'$ref': '#/definitions/Id'
}
}
},
'required': true
}
],
'responses': {
'200': {
'description': 'Ids of the approved invoices',
'schema': {
'type': 'array',
'items': {
'$ref': '#/definitions/Id'
}
}
},
'default': {
'description': 'Unexpected error',
'schema': {
'$ref': '#/definitions/Error'
}
}
}
}
*/
};
| 'use strict';
module.exports = {
'get': {
'description': 'This endpoint returns information about invoices that have been approved. The response includes basic details of each invoice, such as sender and receiver information.',
'responses': {
'200': {
'description': 'An array of approved invoices',
'schema': {
'$ref': '#/definitions/InvoiceApproved'
}
},
'default': {
'description': 'Unexpected error',
'schema': {
'$ref': '#/definitions/Error'
}
}
}
},
'post': {
'description': 'This endpoint allows you to send approved invoices.',
'parameters': [
{
'name': 'body',
'in': 'body',
'description': 'The Invoice JSON you want to POST',
'schema': {
'pendingInvoices': {
'type': 'array',
'items': {
'$ref': '#/definitions/Id'
}
}
},
'required': true
}
],
'responses': {
'200': {
'description': 'Ids of the approved invoices',
'schema': {
'type': 'array',
'items': {
'$ref': '#/definitions/Id'
}
}
},
'default': {
'description': 'Unexpected error',
'schema': {
'$ref': '#/definitions/Error'
}
}
}
}
};
|
Use literal function for citext array default value, not string | 'use strict'
module.exports = function (sequelize, DataTypes) {
let User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING(1024),
allowNull: false
},
salt: {
type: DataTypes.STRING,
allowNull: true
},
nicknames: {
type: 'citext[]',
allowNull: true,
defaultValue: sequelize.literal('ARRAY[]::citext[]')
},
drilled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
drilledDispatch: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
group: {
type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'),
allowNull: false,
defaultValue: 'normal'
},
dispatch: {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: null,
unique: true
}
}, {
paranoid: true,
classMethods: {
associate: function (models) {
User.hasMany(models.Rat, { as: 'rats' })
}
}
})
return User
}
| 'use strict'
module.exports = function (sequelize, DataTypes) {
let User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING(1024),
allowNull: false
},
salt: {
type: DataTypes.STRING,
allowNull: true
},
nicknames: {
type: 'citext[]',
allowNull: true,
defaultValue: 'ARRAY[]::citext[]'
},
drilled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
drilledDispatch: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
group: {
type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'),
allowNull: false,
defaultValue: 'normal'
},
dispatch: {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: null,
unique: true
}
}, {
paranoid: true,
classMethods: {
associate: function (models) {
User.hasMany(models.Rat, { as: 'rats' })
}
}
})
return User
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.