text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix error type for Python 2 | import argparse
import os
from six.moves.urllib import request
import zipfile
"""Download the MSCOCO dataset (images and captions)."""
urls = [
'http://images.cocodataset.org/zips/train2014.zip',
'http://images.cocodataset.org/zips/val2014.zip',
'http://images.cocodataset.org/annotations/annotations_trainval2014.zip'
]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--out', type=str, default='data')
args = parser.parse_args()
try:
os.makedirs(args.out)
except OSError:
raise OSError(
"'{}' already exists, delete it and try again".format(args.out))
for url in urls:
print('Downloading {}...'.format(url))
# Download the zip file
file_name = os.path.basename(url)
dst_file_path = os.path.join(args.out, file_name)
request.urlretrieve(url, dst_file_path)
# Unzip the file
zf = zipfile.ZipFile(dst_file_path)
for name in zf.namelist():
dirname, filename = os.path.split(name)
if not filename == '':
zf.extract(name, args.out)
# Remove the zip file since it has been extracted
os.remove(dst_file_path)
| import argparse
import os
from six.moves.urllib import request
import zipfile
"""Download the MSCOCO dataset (images and captions)."""
urls = [
'http://images.cocodataset.org/zips/train2014.zip',
'http://images.cocodataset.org/zips/val2014.zip',
'http://images.cocodataset.org/annotations/annotations_trainval2014.zip'
]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--out', type=str, default='data')
args = parser.parse_args()
try:
os.makedirs(args.out)
except FileExistsError:
raise FileExistsError(
"'{}' already exists, delete it and try again".format(args.out))
for url in urls:
print('Downloading {}...'.format(url))
# Download the zip file
file_name = os.path.basename(url)
dst_file_path = os.path.join(args.out, file_name)
request.urlretrieve(url, dst_file_path)
# Unzip the file
zf = zipfile.ZipFile(dst_file_path)
for name in zf.namelist():
dirname, filename = os.path.split(name)
if not filename == '':
zf.extract(name, args.out)
# Remove the zip file since it has been extracted
os.remove(dst_file_path)
|
Use the autocomplete lookup instead of traversing DOM elements | //= require jquery.autocomplete
(function ($) {
$.fn.ministerSelect = function (options) {
var settings = $.extend({
inputClass: 'minister-select-input'
}, options);
return this.each(function () {
var $select = $(this),
$input = $('<input type="text" value="" class="' + settings['inputClass'] + '" />'),
lookup = [];
// compile the list of auto suggestions from the select and pre-fill the input field
$select.find('option').each(function () {
var $option = $(this);
lookup.push($option.text());
if ($option.is(':selected')) {
$input.val($option.text());
}
});
// construct the auto complete and only trigger change method on the input when user selects an option
$input.autocomplete({
lookup: lookup,
onSelect: function () {
$(this).trigger('change');
}
});
// when the input changes, the relevant select option has to be chosen
$input.on('change', function () {
var textToCompare = $(this).val().toLowerCase(),
matching_options = $.grep(lookup, function(suggestion) {
return suggestion.toLowerCase().indexOf(textToCompare) !== -1
});
if (matching_options.length == 1) {
var $option = $select.find('option:contains("' + matching_options[0] + '")').first();
$select.val($option.val());
$input.val($option.text());
} else {
$select.val('');
$input.val('');
}
});
$select.hide();
$select.before($input);
});
}
}(jQuery)); | //= require jquery.autocomplete
(function ($) {
$.fn.ministerSelect = function (options) {
var settings = $.extend({
inputClass: 'minister-select-input'
}, options);
return this.each(function () {
var $select = $(this),
$input = $('<input type="text" value="" class="' + settings['inputClass'] + '" />'),
lookup = [];
// compile the list of auto suggestions from the select and pre-fill the input field
$select.find('option').each(function () {
var $option = $(this);
lookup.push($option.text());
if ($option.is(':selected')) {
$input.val($option.text());
}
});
// construct the auto complete and only trigger change method on the input when user selects an option
$input.autocomplete({
lookup: lookup,
onSelect: function () {
$(this).trigger('change');
}
});
// when the input changes, the relevant select option has to be chosen
$input.on('change', function () {
var text = $(this).val(),
options = $select.find('option').filter(function () {
return $(this).text().toLowerCase().indexOf(text.toLowerCase()) !== -1;
});
if (options.length == 1) {
var $option = $(options[0]);
$select.val($option.val());
$input.val($option.text());
} else {
$select.val('');
$input.val('');
}
});
$select.hide();
$select.before($input);
});
}
}(jQuery)); |
Remove some required arguments in post function context | from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the user id (uid) for security reasons.
Two key parameters are required in the context to do so:
- 'post_function_obj': the osv model where the function is defined,
- 'post_function_name': the name of the function to call,
And two optional key parameters:
- 'post_function_args': an iterable object listing the required
arguments to pass after 'cr, uid',
- 'post_function_kwargs': a dictionary object listing the
optionnal keyword args to pass.
"""
if 'post_function_obj' in context:
# We get the function addr by its name,
# and call it with (cr, uid, *args, **kwargs)
getattr(
pooler.get_pool(cr.dbname)[context['post_function_obj']],
context['post_function_name']
)(
cr, uid,
*context.get('post_function_args', []),
**context.get('post_function_kwargs', {})
)
# We clean the context to avoid multiple calls of the function.
context.pop('post_function_obj')
context.pop('post_function_name')
context.pop('post_function_args')
context.pop('post_function_kwargs')
| from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the user id (uid) for security reasons.
Two key parameters are required in the context to do so:
- 'post_function_obj': the osv model where the function is defined,
- 'post_function_name': the name of the function to call,
And two optional key parameters:
- 'post_function_args': an iterable object listing the required
arguments to pass after 'cr, uid',
- 'post_function_kwargs': a dictionary object listing the
optionnal keyword args to pass.
"""
if 'post_function_obj' in context:
# We get the function addr by its name,
# and call it with (cr, uid, *args, **kwargs)
getattr(
pooler.get_pool(cr.dbname)[context['post_function_obj']],
context['post_function_name']
)(
cr, uid,
*context['post_function_args'],
**context['post_function_kwargs']
)
# We clean the context to avoid multiple calls of the function.
context.pop('post_function_obj')
context.pop('post_function_name')
context.pop('post_function_args')
context.pop('post_function_kwargs')
|
Remove check for matching base domain and update host string concatenation to *append* the port rather than reconstructing the whole string | class UrlBuilder {
constructor(name, absolute, ziggyObject) {
this.name = name;
this.ziggy = ziggyObject;
this.route = this.ziggy.namedRoutes[this.name];
if (typeof this.name === 'undefined') {
throw new Error('Ziggy Error: You must provide a route name');
} else if (typeof this.route === 'undefined') {
throw new Error(`Ziggy Error: route '${this.name}' is not found in the route list`);
}
this.absolute = typeof absolute === 'undefined' ? true : absolute;
this.domain = this.setDomain();
this.path = this.route.uri.replace(/^\//, '');
}
setDomain() {
if (!this.absolute)
return '/';
if (!this.route.domain)
return this.ziggy.baseUrl.replace(/\/?$/, '/');
let host = (this.route.domain || this.ziggy.baseDomain).replace(/\/+$/, '');
if (this.ziggy.basePort) {
host = `${host}:${this.ziggy.basePort}`;
}
return this.ziggy.baseProtocol + '://' + host + '/';
}
construct() {
return this.domain + this.path
}
}
export default UrlBuilder;
| class UrlBuilder {
constructor(name, absolute, ziggyObject) {
this.name = name;
this.ziggy = ziggyObject;
this.route = this.ziggy.namedRoutes[this.name];
if (typeof this.name === 'undefined') {
throw new Error('Ziggy Error: You must provide a route name');
} else if (typeof this.route === 'undefined') {
throw new Error(`Ziggy Error: route '${this.name}' is not found in the route list`);
}
this.absolute = typeof absolute === 'undefined' ? true : absolute;
this.domain = this.setDomain();
this.path = this.route.uri.replace(/^\//, '');
}
setDomain() {
if (!this.absolute)
return '/';
if (!this.route.domain)
return this.ziggy.baseUrl.replace(/\/?$/, '/');
let host = (this.route.domain || this.ziggy.baseDomain).replace(/\/+$/, '');
if (this.ziggy.basePort && (host.replace(/\/+$/, '') === this.ziggy.baseDomain.replace(/\/+$/, '')))
host = this.ziggy.baseDomain + ':' + this.ziggy.basePort;
return this.ziggy.baseProtocol + '://' + host + '/';
}
construct() {
return this.domain + this.path
}
}
export default UrlBuilder;
|
Update path fonts gulp task | // imports
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
// build src
gulp.task('browserify', function(cb){
return browserify('./src/app.js', {
debug: true
})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./www/'));
cb();
});
// build in release mode
gulp.task('browserify:release', function(cb){
return browserify('./src/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./www/'));
cb();
});
// copy fonts
gulp.task('fonts', function(cb){
return gulp.src('node_modules/ionic-npm/fonts/**')
.pipe(gulp.dest('./www/fonts/'));
cb();
});
// copy assets
gulp.task('assets', function(cb){
return gulp.src('./assets/**')
.pipe(gulp.dest('./www/'));
cb();
});
// copy templates
gulp.task('templates', function(cb){
return gulp.src('./src/**/*.html')
.pipe(gulp.dest('./www/'));
cb();
});
| // imports
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
// build src
gulp.task('browserify', function(cb){
return browserify('./src/app.js', {
debug: true
})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./www/'));
cb();
});
// build in release mode
gulp.task('browserify:release', function(cb){
return browserify('./src/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./www/'));
cb();
});
// copy fonts
gulp.task('fonts', function(cb){
return gulp.src('node_modules/ionic-framework/release/fonts/**')
.pipe(gulp.dest('./www/fonts/'));
cb();
});
// copy assets
gulp.task('assets', function(cb){
return gulp.src('./assets/**')
.pipe(gulp.dest('./www/'));
cb();
});
// copy templates
gulp.task('templates', function(cb){
return gulp.src('./src/**/*.html')
.pipe(gulp.dest('./www/'));
cb();
}); |
Fix CSS state when a vote is cancelled. | /**
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
(function($) {
$('.upvote').on('click', function(e) {
var url = '/links/upvote/{id}'.replace('{id}', $(this).data('id'));
var $link = $(this);
var hasBeenVoted = $link.hasClass('link-voted');
var $vote = $link.parent();
var $downvote = $vote.find('.downvote');
var $votes = $(this).parent().find('.votes-count');
e.preventDefault();
$.ajax({
url: url,
dataType: 'json',
success: function(link) {
$votes.text(link.votes);
$downvote.removeClass('link-voted');
if (hasBeenVoted) {
$link.removeClass('link-voted');
} else {
$link.addClass('link-voted');
}
}
});
});
$('.downvote').on('click', function(e) {
var url = '/links/downvote/{id}'.replace('{id}', $(this).data('id'));
var $link = $(this);
var hasBeenVoted = $link.hasClass('link-voted');
var $vote = $link.parent();
var $upvote = $vote.find('.upvote');
var $votes = $vote.find('.votes-count');
e.preventDefault();
$.ajax({
url: url,
dataType: 'json',
success: function(link) {
$votes.text(link.votes);
$upvote.removeClass('link-voted');
if (hasBeenVoted) {
$link.removeClass('link-voted');
} else {
$link.addClass('link-voted');
}
}
});
});
})(jQuery); | /**
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
(function($) {
$('.upvote').on('click', function(e) {
var url = '/links/upvote/{id}'.replace('{id}', $(this).data('id'));
var $link = $(this);
var $vote = $link.parent();
var $downvote = $vote.find('.downvote');
var $votes = $(this).parent().find('.votes-count');
e.preventDefault();
$.ajax({
url: url,
dataType: 'json',
success: function(link) {
$votes.text(link.votes);
$link.addClass('link-voted');
$downvote.removeClass('link-voted');
}
});
});
$('.downvote').on('click', function(e) {
var url = '/links/downvote/{id}'.replace('{id}', $(this).data('id'));
var $link = $(this);
var $vote = $link.parent();
var $upvote = $vote.find('.upvote');
var $votes = $vote.find('.votes-count');
e.preventDefault();
$.ajax({
url: url,
dataType: 'json',
success: function(link) {
$votes.text(link.votes);
$link.addClass('link-voted');
$upvote.removeClass('link-voted');
}
});
});
})(jQuery); |
Add support for IE11 (msCrypto) | var almost = (function() {
function lookupWord(id)
{
// TODO: Return the specified entry from our words list.
return 'word' + id;
}
return {
getWords : function(howMany) {
var c = window.crypto || window.msCrypto;
if (c && c.getRandomValues) {
// Get random values using a (believed to be) cryptographically secure method.
// See http://stackoverflow.com/questions/5651789/is-math-random-cryptographically-secure
var array = new Uint32Array(/*edge requires explicit type conversion*/Number(howMany));
c.getRandomValues(array);
// Build our passphrase. The words are space delimited.
var p = '';
for (var i = 0; i < array.length; i++) {
// Choose a corresponding entry from our words list.
var word = lookupWord(array[i]);
p += ' ' + word;
}
// trim() is native to String only in browsers that support ECMAScript 5
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
};
}
return p.trim();
}
else {
return "Error: Cannot find a cryptographically secure source of randomness."
}
}
};
})();
| var almost = (function() {
function lookupWord(id)
{
// TODO: Return the specified entry from our words list.
return 'word' + id;
}
return {
getWords : function(howMany) {
if (window.crypto && window.crypto.getRandomValues) {
// Get random values using a (believed to be) cryptographically secure method.
// See http://stackoverflow.com/questions/5651789/is-math-random-cryptographically-secure
var array = new Uint32Array(/*edge requires explicit type conversion*/Number(howMany));
window.crypto.getRandomValues(array);
// Build our passphrase. The words are space delimited.
var p = '';
for (var i = 0; i < array.length; i++) {
// Choose a corresponding entry from our words list.
var word = lookupWord(array[i]);
p += ' ' + word;
}
// trim() is native to String only in browsers that support ECMAScript 5
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
};
}
return p.trim();
}
else {
return "Error: Cannot find a cryptographically secure source of randomness."
}
}
};
})();
|
Refactor populate_db pyinvoke task to use it in tests | import json
from pathlib import Path
import sys
import sqlalchemy as sa
from invoke import task
FANTASY_DATA_FOLDER = Path(__file__).parent / 'fantasy-database'
@task
def populate_db(ctx, data_folder=FANTASY_DATA_FOLDER, dsn=None):
from examples.fantasy import tables
data_file = data_folder / 'data.json'
if not Path(data_file).exists():
sys.exit(f'Invalid data file: {data_file}')
with data_file.open() as f:
data = json.load(f)
create_sql = (data_folder / 'schema.sql').read_text()
if dsn is None:
dsn = 'postgresql://example:somepassword@localhost/example'
engine = sa.create_engine(dsn, echo=True)
conn = engine.connect()
trans = conn.begin()
conn.execute(sa.text(create_sql))
tables_in_order = ('photos', 'stores', 'authors', 'series', 'books',
'chapters', 'books_stores')
try:
for table_name in tables_in_order:
table = getattr(tables, table_name)
values = data[table_name]
for value in values:
query = table.insert().values(value)
conn.execute(query)
trans.commit()
except Exception as exc:
trans.rollback()
raise
print('\nDatabase is successfully populated!')
| import json
from pathlib import Path
import sys
import sqlalchemy as sa
from invoke import task
FANTASY_DB_SQL = Path.cwd() / 'fantasy-database' / 'schema.sql'
FANTASY_DB_DATA = Path.cwd() / 'fantasy-database' / 'data.json'
@task
def populate_db(ctx, data_file=FANTASY_DB_DATA):
from examples.fantasy import tables
if not Path(data_file).exists():
sys.exit(f'Invalid data file: {data_file}')
with data_file.open() as f:
data = json.load(f)
create_sql = FANTASY_DB_SQL.read_text()
engine = \
sa.create_engine('postgresql://example:somepassword@localhost/example',
echo=True)
conn = engine.connect()
trans = conn.begin()
conn.execute(sa.text(create_sql))
tables_in_order = ('photos', 'stores', 'authors', 'series', 'books',
'chapters', 'books_stores')
try:
for table_name in tables_in_order:
table = getattr(tables, table_name)
values = data[table_name]
for value in values:
query = table.insert().values(value)
conn.execute(query)
trans.commit()
except Exception as exc:
trans.rollback()
raise
print('\nDatabase is successfully populated!')
|
Use exception renderable instead of uses of instanceof | <?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (ValidationException $e, $request) {
return response()->json([
'message' => trans('error.validation'),
'errors' => $e->errors(),
], 422);
});
$this->renderable(function (InvalidSignatureException $e, $request) {
return response()->json([
'message' => trans('error.signature'),
], 500);
});
return parent::render($request, $exception);
}
}
| <?php
namespace App\Exceptions;
use App\Exceptions\SolverException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Throwable $exception)
{
if ($exception instanceof ValidationException) {
return response()->json([
'message' => trans('error.validation'),
'errors' => $exception->errors(),
], 422);
}
if ($exception instanceof SolverException) {
return response()->json([
'message' => trans('error.solution'),
], 422);
}
if ($exception instanceof InvalidSignatureException) {
return response()->json([
'message' => trans('error.signature'),
], 500);
}
return parent::render($request, $exception);
}
}
|
Add default headers, fix output | #!/usr/bin/env python3
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
}
def __init__(self):
pass
def find(self):
page = requests.get(self._page, headers=self._headers)
if page.status_code != 200:
print("Bad status code:", page.status_code)
from sys import exit
exit(1)
tree = lxml.html.fromstring(page.text)
sel = CSSSelector('div[class="toc"] > ul > li > ul > li')
results = sel(tree)
sections = {}
for result in results:
scope = result.find('a').text_content()
if not scope:
scope = self._no_scope
endpointlist = []
endpoints = result.cssselect('li > a')
for endpoint in endpoints[1:]:
descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/')
endpointlist.append(descriptor)
sections[scope] = endpointlist
return sections
if __name__ == "__main__":
print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True))
| #!/usr/bin/env python3
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
def __init__(self):
pass
def find(self):
page = requests.get(self._page)
if page.status_code != 200:
print("Bad status code:", page.status_code)
from sys import exit
exit(1)
tree = lxml.html.fromstring(page.text)
sel = CSSSelector('div[class="toc"] > ul > li > ul > li')
results = sel(tree)
sections = {}
for result in results:
scope = result.find('a').text_content()
if not scope:
scope = self._no_scope
endpointlist = []
endpoints = result.cssselect('li > a')
for endpoint in endpoints[1:]:
descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/')
endpointlist.append(descriptor)
sections[scope] = endpointlist
from pprint import pprint
pprint(sections)
return sections
if __name__ == "__main__":
json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True)
|
feat(form): Add class id to form dropdown container | import React, {PropTypes, Component} from 'react'
import { Form, FormGroup, FormControl, Row, Col } from 'react-bootstrap'
import { connect } from 'react-redux'
import { setQueryParam } from '../../actions/form'
class DropdownSelector extends Component {
static propTypes = {
name: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
label: PropTypes.string,
options: PropTypes.array,
setQueryParam: PropTypes.func
}
_onQueryParamChange = (evt) => {
const val = evt.target.value
this.props.setQueryParam({
[this.props.name]: isNaN(val) ? val : parseFloat(val)
})
}
render () {
const { value, label, options } = this.props
return (
<Row>
<Col xs={6} className='setting-label'>{label}</Col>
<Col xs={6}>
<Form>
<FormGroup className='dropdown-selector-container'>
<FormControl
className='dropdown-selector'
componentClass='select'
value={value}
onChange={this._onQueryParamChange}
>
{options.map((o, i) => (
<option key={i} value={o.value}>{o.text}</option>
))}
</FormControl>
</FormGroup>
</Form>
</Col>
</Row>
)
}
}
const mapStateToProps = (state, ownProps) => {
return { }
}
const mapDispatchToProps = { setQueryParam }
export default connect(mapStateToProps, mapDispatchToProps)(DropdownSelector)
| import React, {PropTypes, Component} from 'react'
import { Form, FormGroup, FormControl, Row, Col } from 'react-bootstrap'
import { connect } from 'react-redux'
import { setQueryParam } from '../../actions/form'
class DropdownSelector extends Component {
static propTypes = {
name: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
label: PropTypes.string,
options: PropTypes.array,
setQueryParam: PropTypes.func
}
_onQueryParamChange = (evt) => {
const val = evt.target.value
this.props.setQueryParam({
[this.props.name]: isNaN(val) ? val : parseFloat(val)
})
}
render () {
const { value, label, options } = this.props
return (
<Row>
<Col xs={6} className='setting-label'>{label}</Col>
<Col xs={6}>
<Form>
<FormGroup>
<FormControl
className='dropdown-selector'
componentClass='select'
value={value}
onChange={this._onQueryParamChange}
>
{options.map((o, i) => (
<option key={i} value={o.value}>{o.text}</option>
))}
</FormControl>
</FormGroup>
</Form>
</Col>
</Row>
)
}
}
const mapStateToProps = (state, ownProps) => {
return { }
}
const mapDispatchToProps = { setQueryParam }
export default connect(mapStateToProps, mapDispatchToProps)(DropdownSelector)
|
Fix numberOfPages when nItems is null | /**
* Created by FG0003 on 09/02/2017.
*/
import Template from './pagination.tpl.html';
import previous from './../../../icons/previous.svg';
import next from './../../../icons/next.svg';
import first from './../../../icons/first.svg';
import last from './../../../icons/last.svg';
class PaginationController{
constructor(AngularUtilService){
this.util = AngularUtilService;
this.previous = previous;
this.next = next;
this.first = first;
this.last = last;
}
get page(){
if(this.currentPage != null && this.currentPage != 0)
return this.currentPage;
return 1;
}
set page(value){
this.currentPage = value;
}
$onChanges(){
if(this.currentPage > this.numberOfPages){
this.currentPage = this.numberOfPages;
}
}
$onInit(){
if(this.util.isUndefined(this.currentPage)) this.currentPage = 1;
}
get numberOfPages(){
if(this.nItems == 0 || this.nItems == null)
return 1;
return Math.ceil(this.nItems/this.itemsPerPage);
}
}
PaginationController.$inject = ['AngularUtilService'];
export let PaginationComponent = {
selector:'mdPagination',
bindings:{
itemsPerPage:'=',
currentPage:'=',
nItems: '<',
isDisabled: '<'
},
controller:PaginationController,
controllerAs:'$pagination',
template: Template
};
| /**
* Created by FG0003 on 09/02/2017.
*/
import Template from './pagination.tpl.html';
import previous from './../../../icons/previous.svg';
import next from './../../../icons/next.svg';
import first from './../../../icons/first.svg';
import last from './../../../icons/last.svg';
class PaginationController{
constructor(AngularUtilService){
this.util = AngularUtilService;
this.previous = previous;
this.next = next;
this.first = first;
this.last = last;
}
get page(){
if(this.currentPage != null && this.currentPage != 0)
return this.currentPage;
return 1;
}
set page(value){
this.currentPage = value;
}
$onChanges(){
if(this.currentPage > this.numberOfPages){
this.currentPage = this.numberOfPages;
}
}
$onInit(){
}
get numberOfPages(){
if(this.nItems == 0)
return 1;
return Math.ceil(this.nItems/this.itemsPerPage);
}
}
PaginationController.$inject = ['AngularUtilService'];
export let PaginationComponent = {
selector:'mdPagination',
bindings:{
itemsPerPage:'=',
currentPage:'=',
nItems: '<',
isDisabled: '<'
},
controller:PaginationController,
controllerAs:'$pagination',
template: Template
};
|
Fix integer formatter to accept zero value | <?php
declare(strict_types = 1);
namespace DASPRiD\Formidable\Mapping\Formatter;
use Assert\Assertion;
use DASPRiD\Formidable\Data;
use DASPRiD\Formidable\FormError\FormError;
use DASPRiD\Formidable\Mapping\BindResult;
final class IntegerFormatter implements FormatterInterface
{
/**
* {@inheritdoc}
*/
public function bind(string $key, Data $data) : BindResult
{
if (!$data->hasKey($key)) {
return BindResult::fromFormErrors(new FormError(
$key,
'error.required'
));
}
$value = $data->getValue($key);
if (!preg_match('(^-?[1-9]*\d+$)', $value)) {
return BindResult::fromFormErrors(new FormError(
$key,
'error.integer'
));
}
return BindResult::fromValue((int) $data->getValue($key));
}
/**
* {@inheritdoc}
*/
public function unbind(string $key, $value) : Data
{
Assertion::integer($value);
return Data::fromFlatArray([$key => (string) $value]);
}
}
| <?php
declare(strict_types = 1);
namespace DASPRiD\Formidable\Mapping\Formatter;
use Assert\Assertion;
use DASPRiD\Formidable\Data;
use DASPRiD\Formidable\FormError\FormError;
use DASPRiD\Formidable\Mapping\BindResult;
final class IntegerFormatter implements FormatterInterface
{
/**
* {@inheritdoc}
*/
public function bind(string $key, Data $data) : BindResult
{
if (!$data->hasKey($key)) {
return BindResult::fromFormErrors(new FormError(
$key,
'error.required'
));
}
$value = $data->getValue($key);
if (!preg_match('(^-?[1-9]\d*$)', $value)) {
return BindResult::fromFormErrors(new FormError(
$key,
'error.integer'
));
}
return BindResult::fromValue((int) $data->getValue($key));
}
/**
* {@inheritdoc}
*/
public function unbind(string $key, $value) : Data
{
Assertion::integer($value);
return Data::fromFlatArray([$key => (string) $value]);
}
}
|
Fix installation on Python < 2.7
When the install_requires array was moved, a erroneous trailing comma
was left, turning it into a tuple which cannot be appended to. Removing
the comma allows installation on Python 2.6 which is what CloudFormation
uses. | """ Setup script for PyPI """
import os
import sys
from setuptools import setup
from ConfigParser import SafeConfigParser
settings = SafeConfigParser()
settings.read(os.path.realpath('dynamic_dynamodb/dynamic-dynamodb.conf'))
def return_requires():
install_requires = [
'boto >= 2.29.1',
'requests >= 0.14.1',
'logutils >= 0.3.3',
'retrying >= 1.3.3'
]
if sys.version_info < (2, 7):
install_requires.append('ordereddict >= 1.1')
return install_requires
setup(
name='dynamic-dynamodb',
version=settings.get('general', 'version'),
license='Apache License, Version 2.0',
description='Automatic provisioning for AWS DynamoDB tables',
author='Sebastian Dahlgren',
author_email='[email protected]',
url='http://sebdah.github.com/dynamic-dynamodb/',
keywords="dynamodb aws provisioning amazon web services",
platforms=['Any'],
packages=['dynamic_dynamodb'],
scripts=['dynamic-dynamodb'],
include_package_data=True,
zip_safe=False,
install_requires=return_requires(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python'
]
)
| """ Setup script for PyPI """
import os
import sys
from setuptools import setup
from ConfigParser import SafeConfigParser
settings = SafeConfigParser()
settings.read(os.path.realpath('dynamic_dynamodb/dynamic-dynamodb.conf'))
def return_requires():
install_requires = [
'boto >= 2.29.1',
'requests >= 0.14.1',
'logutils >= 0.3.3',
'retrying >= 1.3.3'
],
if sys.version_info < (2, 7):
install_requires.append('ordereddict >= 1.1')
return install_requires
setup(
name='dynamic-dynamodb',
version=settings.get('general', 'version'),
license='Apache License, Version 2.0',
description='Automatic provisioning for AWS DynamoDB tables',
author='Sebastian Dahlgren',
author_email='[email protected]',
url='http://sebdah.github.com/dynamic-dynamodb/',
keywords="dynamodb aws provisioning amazon web services",
platforms=['Any'],
packages=['dynamic_dynamodb'],
scripts=['dynamic-dynamodb'],
include_package_data=True,
zip_safe=False,
install_requires=return_requires(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python'
]
)
|
Fix decoding of empty responses.
When an empty response was given by the web server, we were
decoding to '{}', which is problematic when you are expecting
an empty response for things like empty text/plain files. This
fixes the problematic assumption we were making.
Reviewed at http://reviews.reviewboard.org/r/3680/ | import json
from rbtools.api.utils import parse_mimetype
DECODER_MAP = {}
def DefaultDecoder(payload):
"""Default decoder for API payloads.
The default decoder is used when a decoder is not found in the
DECODER_MAP. This is a last resort which should only be used when
something has gone wrong.
"""
return {
'resource': {
'data': payload,
},
}
DEFAULT_DECODER = DefaultDecoder
def JsonDecoder(payload):
return json.loads(payload)
DECODER_MAP['application/json'] = JsonDecoder
def PlainTextDecoder(payload):
return {
'resource': {
'text': payload,
},
}
DECODER_MAP['text/plain'] = PlainTextDecoder
def PatchDecoder(payload):
return {
'resource': {
'diff': payload,
},
}
DECODER_MAP['text/x-patch'] = PatchDecoder
def decode_response(payload, mime_type):
"""Decode a Web API response.
The body of a Web API response will be decoded into a dictionary,
according to the provided mime_type.
"""
mime = parse_mimetype(mime_type)
format = '%s/%s' % (mime['main_type'], mime['format'])
if format in DECODER_MAP:
decoder = DECODER_MAP[format]
else:
decoder = DEFAULT_DECODER
return decoder(payload)
| import json
from rbtools.api.utils import parse_mimetype
DECODER_MAP = {}
def DefaultDecoder(payload):
"""Default decoder for API payloads.
The default decoder is used when a decoder is not found in the
DECODER_MAP. This is a last resort which should only be used when
something has gone wrong.
"""
return {
'resource': {
'data': payload,
},
}
DEFAULT_DECODER = DefaultDecoder
def JsonDecoder(payload):
return json.loads(payload)
DECODER_MAP['application/json'] = JsonDecoder
def PlainTextDecoder(payload):
return {
'resource': {
'text': payload,
},
}
DECODER_MAP['text/plain'] = PlainTextDecoder
def PatchDecoder(payload):
return {
'resource': {
'diff': payload,
},
}
DECODER_MAP['text/x-patch'] = PatchDecoder
def decode_response(payload, mime_type):
"""Decode a Web API response.
The body of a Web API response will be decoded into a dictionary,
according to the provided mime_type.
"""
if not payload:
return {}
mime = parse_mimetype(mime_type)
format = '%s/%s' % (mime['main_type'], mime['format'])
if format in DECODER_MAP:
decoder = DECODER_MAP[format]
else:
decoder = DEFAULT_DECODER
return decoder(payload)
|
Prepare to send 'ready' message when all setup is done
Signed-off-by: Tomas Neme <[email protected]> | /*******************
* This is the pubsub driver that should tell caspa about the melted status
*
*******************/
events = require('events');
utils = require('utils');
_ = require('underscore');
mbc = require('mbc-common');
defaults = { // copied from caspa/models.App.Status
_id: 1,
piece: {
previous: null,
curent: null,
next: null
},
show: {
previous: null,
current: null,
next: null,
},
source: null,
no_air: false
};
function CaspaDriver() {
events.EventEmitter.call(this);
var self = this;
this.status = _.clone(defaults);
this.channel = "mostoStatus";
this.publisher = mbc.pubsub();
var setups = [
];
var sendReady = _.times(setups.length, function() {
self.emit('ready');
});
setups.forEach(function(setup){
setup(sendReady);
});
CaspaDriver.prototype.setStatus = function(status) {
// this overrides this.status with the values passed by status
this.status = _.extend(this.status, status);
this.publish(status);
};
CaspaDriver.prototype.publish = function(status) {
this.publisher.publish({backend: this.channel, model: status});
};
CaspaDriver.prototype.publishStatus = function(status) {
this.publisher.publish({backend: "mostoStatus", model: status})
};
}
util.inherits(CaspaDriver, events.EventEmitter);
exports = module.exports = function() {
driver = new CaspaDriver();
return driver;
};
| /*******************
* This is the pubsub driver that should tell caspa about the melted status
*
*******************/
events = require('events');
utils = require('utils');
_ = require('underscore');
mbc = require('mbc-common');
defaults = { // copied from caspa/models.App.Status
_id: 1,
piece: {
previous: null,
curent: null,
next: null
},
show: {
previous: null,
current: null,
next: null,
},
source: null,
no_air: false
};
function CaspaDriver() {
events.EventEmitter.call(this);
var self = this;
this.status = _.clone(defaults);
this.channel = "mostoStatus";
this.publisher = mbc.pubsub();
CaspaDriver.prototype.setStatus = function(status) {
// this overrides this.status with the values passed by status
this.status = _.extend(this.status, status);
this.publish(status);
};
CaspaDriver.prototype.publish = function(status) {
this.publisher.publish({backend: this.channel, model: status});
};
CaspaDriver.prototype.publishStatus = function(status) {
this.publisher.publish({backend: "mostoStatus", model: status})
};
}
util.inherits(CaspaDriver, events.EventEmitter);
exports = module.exports = function() {
driver = new CaspaDriver();
return driver;
};
|
[JUnit] Use explicit encoding when getting bytes from String | package cucumber.runtime.junit;
import cucumber.runtime.io.Resource;
import cucumber.runtime.model.CucumberFeature;
import cucumber.runtime.model.FeatureParser;
import gherkin.events.PickleEvent;
import gherkin.pickles.Compiler;
import gherkin.pickles.Pickle;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
class TestPickleBuilder {
private TestPickleBuilder() {
}
static List<PickleEvent> pickleEventsFromFeature(final String path, final String source) {
List<PickleEvent> pickleEvents = new ArrayList<PickleEvent>();
Compiler compiler = new Compiler();
CucumberFeature feature = parseFeature(path, source);
for (Pickle pickle : compiler.compile(feature.getGherkinFeature())) {
pickleEvents.add(new PickleEvent(feature.getUri().toString(), pickle));
}
return pickleEvents;
}
static CucumberFeature parseFeature(final String path, final String source) {
return parseFeature(URI.create(path), source);
}
static CucumberFeature parseFeature(final URI path, final String source) {
return FeatureParser.parseResource(new Resource() {
@Override
public URI getPath() {
return path;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
}
});
}
}
| package cucumber.runtime.junit;
import cucumber.runtime.io.Resource;
import cucumber.runtime.model.CucumberFeature;
import cucumber.runtime.model.FeatureParser;
import gherkin.events.PickleEvent;
import gherkin.pickles.Compiler;
import gherkin.pickles.Pickle;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
class TestPickleBuilder {
private TestPickleBuilder() {
}
static List<PickleEvent> pickleEventsFromFeature(final String path, final String source) {
List<PickleEvent> pickleEvents = new ArrayList<PickleEvent>();
Compiler compiler = new Compiler();
CucumberFeature feature = parseFeature(path, source);
for (Pickle pickle : compiler.compile(feature.getGherkinFeature())) {
pickleEvents.add(new PickleEvent(feature.getUri().toString(), pickle));
}
return pickleEvents;
}
static CucumberFeature parseFeature(final String path, final String source) {
return parseFeature(URI.create(path), source);
}
static CucumberFeature parseFeature(final URI path, final String source) {
return FeatureParser.parseResource(new Resource() {
@Override
public URI getPath() {
return path;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(source.getBytes());
}
});
}
}
|
Revert optimization: it didn't help | <?php
declare(strict_types=1);
namespace WoohooLabs\Zen;
use Closure;
use Psr\Container\ContainerInterface;
use WoohooLabs\Zen\Exception\NotFoundException;
use function array_key_exists;
abstract class AbstractCompiledContainer implements ContainerInterface
{
/**
* @var array
*/
protected $singletonEntries = [];
/**
* @var string[]
*/
protected static $entryPoints = [];
/**
* @param string $id
*/
public function has($id): bool
{
return array_key_exists($id, static::$entryPoints);
}
/**
* @param string $id
* @return mixed
* @throws NotFoundException
*/
public function get($id)
{
return $this->singletonEntries[$id] ?? $this->{static::$entryPoints[$id] ?? "throwNotFoundException"}($id);
}
/**
* @return mixed
*/
protected function throwNotFoundException(string $id)
{
throw new NotFoundException($id);
}
/**
* @param object $object
* @return object
*/
protected function setClassProperties($object, array $properties)
{
Closure::bind(
static function () use ($object, $properties) {
foreach ($properties as $name => $value) {
$object->$name = $value;
}
},
null,
$object
)->__invoke();
return $object;
}
}
| <?php
declare(strict_types=1);
namespace WoohooLabs\Zen;
use Closure;
use Psr\Container\ContainerInterface;
use WoohooLabs\Zen\Exception\NotFoundException;
use function array_key_exists;
abstract class AbstractCompiledContainer implements ContainerInterface
{
/**
* @var array
*/
protected $singletonEntries = [];
/**
* @var string[]
*/
protected static $entryPoints = [];
/**
* @param string $id
*/
public function has($id): bool
{
return array_key_exists($id, static::$entryPoints);
}
/**
* @param string $id
* @return mixed
* @throws NotFoundException
*/
public function get($id)
{
return $this->singletonEntries[$id] ?? (array_key_exists($id, static::$entryPoints) ? $this->{static::$entryPoints[$id]}() : $this->throwNotFoundException($id));
}
/**
* @return mixed
*/
protected function throwNotFoundException(string $id)
{
throw new NotFoundException($id);
}
/**
* @param object $object
* @return object
*/
protected function setClassProperties($object, array $properties)
{
Closure::bind(
static function () use ($object, $properties) {
foreach ($properties as $name => $value) {
$object->$name = $value;
}
},
null,
$object
)->__invoke();
return $object;
}
}
|
Update minifier to write to build file more smartly
This handles cases where the main stylesheet is referenced from a
subdir or different directory from the root of index.html, but
still allow the minifier to write to the file using a different path
(for example outside of the webroot). | <?php
/**
* Minify CSS Preprocessor class file
*
* @package Holograph
*/
namespace Holograph\Preprocessor\Css;
use Holograph\Preprocessor\PreprocessorAbstract;
use Holograph\FileOps;
/**
* Class to minify and combine Css files
*
* @package Holograph
* @author Jansen Price <[email protected]>
* @version $Id$
*/
class Minify extends PreprocessorAbstract
{
/**
* Execute preprocessor
*
* This will take all CSS files from the source dir, minify each one and
* then combine them into one file.
*
* @param array $options Options for execution
* @return void
*/
public function execute($options = array())
{
$cssFiles = FileOps::rglob("*.css", 0, $this->getSourceDir());
if (empty($cssFiles)) {
return false;
}
FileOps::ensurePathExists($this->getDestinationDir());
// Just get the basename of the main style sheet, this will be written
// to the destination dir
$mainStylesheet = basename($options['main_stylesheet']);
$mainStylesheet = $this->getDestinationDir() . DIRECTORY_SEPARATOR . $mainStylesheet;
$buffer = array();
foreach ($cssFiles as $file) {
$content = file_get_contents($file);
$newContent = \Minify_CSS_Compressor::process($content);
$buffer[] = $newContent;
}
if ($buffer) {
file_put_contents($mainStylesheet, implode("\n", $buffer));
}
}
}
| <?php
/**
* Minify CSS Preprocessor class file
*
* @package Holograph
*/
namespace Holograph\Preprocessor\Css;
use Holograph\Preprocessor\PreprocessorAbstract;
use Holograph\FileOps;
/**
* Class to minify and combine Css files
*
* @package Holograph
* @author Jansen Price <[email protected]>
* @version $Id$
*/
class Minify extends PreprocessorAbstract
{
/**
* Execute preprocessor
*
* This will take all CSS files from the source dir, minify each one and
* then combine them into one file.
*
* @param array $options Options for execution
* @return void
*/
public function execute($options = array())
{
$cssFiles = FileOps::rglob("*.css", 0, $this->getSourceDir());
if (empty($cssFiles)) {
return false;
}
FileOps::ensurePathExists($this->getDestinationDir());
$mainStylesheet = $options['main_stylesheet'];
$buffer = array();
foreach ($cssFiles as $file) {
$content = file_get_contents($file);
$newContent = \Minify_CSS_Compressor::process($content);
$newfile = str_replace(
$this->getSourceDir(),
$this->getDestinationDir(),
$file
);
$buffer[] = $newContent;
}
if ($buffer) {
file_put_contents($mainStylesheet, implode("\n", $buffer));
}
}
}
|
Rename to better method names | <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Test / Unit / Framework / Mvc/ Request
*/
namespace PH7\Test\Unit\Framework\Mvc\Request;
use PH7\Framework\Mvc\Request\Http as HttpRequest;
use PHPUnit_Framework_TestCase;
class HttpTest extends PHPUnit_Framework_TestCase
{
/** @var HttpRequest */
private $oHttpRequest;
protected function setUp()
{
$this->oHttpRequest = new HttpRequest;
}
public function testGetRequestCastedToInt()
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET['string_id'] = '123';
$sActual = $this->oHttpRequest->get('string_id', 'int');
$this->assertSame(123, $sActual);
}
public function testPostRequestCastedToInt()
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST['string_id'] = '123';
$sActual = $this->oHttpRequest->post('string_id', 'int');
$this->assertSame(123, $sActual);
}
protected function tearDown()
{
unset($_GET, $_POST, $_SERVER);
}
}
| <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Test / Unit / Framework / Mvc/ Request
*/
namespace PH7\Test\Unit\Framework\Mvc\Request;
use PH7\Framework\Mvc\Request\Http as HttpRequest;
use PHPUnit_Framework_TestCase;
class HttpTest extends PHPUnit_Framework_TestCase
{
/** @var HttpRequest */
private $oHttpRequest;
protected function setUp()
{
$this->oHttpRequest = new HttpRequest;
}
public function testGetRequestWithIntCast()
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET['string_id'] = '123';
$sActual = $this->oHttpRequest->get('string_id', 'int');
$this->assertSame(123, $sActual);
}
public function testPostRequestWithIntCast()
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST['string_id'] = '123';
$sActual = $this->oHttpRequest->post('string_id', 'int');
$this->assertSame(123, $sActual);
}
protected function tearDown()
{
unset($_GET, $_POST, $_SERVER);
}
}
|
Apply a couple refinements to object name strategy.
Zero length names are invalid.
So are names beginning or ending with -. | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Hypothesis strategies useful for testing ``pykube``.
"""
from string import ascii_lowercase, digits
from pyrsistent import pmap
from hypothesis.strategies import builds, fixed_dictionaries, text, lists, sampled_from
from .. import NamespacedObjectMetadata, Namespace, ConfigMap
def object_name():
# https://kubernetes.io/docs/user-guide/identifiers/#names
# [a-z0-9]([-a-z0-9]*[a-z0-9])?
alphabet = ascii_lowercase + digits + b"-"
return builds(
lambda parts: b"".join(parts).decode("ascii"),
lists(sampled_from(alphabet), min_size=1, average_size=10),
).filter(
lambda value: not (value.startswith(b"-") or value.endswith(b"-"))
)
def object_metadatas():
return builds(
NamespacedObjectMetadata,
items=fixed_dictionaries({
u"name": object_name(),
}).map(pmap),
)
def namespaced_object_metadatas():
return builds(
lambda metadata, namespace: metadata.transform(
["items"], lambda items: items.set(u"namespace", namespace),
),
metadata=object_metadatas(),
namespace=object_name(),
)
def namespaces():
return builds(
Namespace,
metadata=object_metadatas(),
)
def configmaps():
"""
Strategy for creating ``ConfigMap`` Kubernetes objects.
"""
return builds(
ConfigMap,
metadata=namespaced_object_metadatas(),
)
| # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Hypothesis strategies useful for testing ``pykube``.
"""
from string import ascii_lowercase, digits
from pyrsistent import pmap
from hypothesis.strategies import builds, fixed_dictionaries, text, lists, sampled_from
from .. import NamespacedObjectMetadata, Namespace, ConfigMap
def object_name():
# https://kubernetes.io/docs/user-guide/identifiers/#names
# [a-z0-9]([-a-z0-9]*[a-z0-9])?
alphabet = ascii_lowercase + digits + b"-"
return builds(
lambda parts: b"".join(parts).decode("ascii"),
lists(sampled_from(alphabet), average_size=10),
)
def object_metadatas():
return builds(
NamespacedObjectMetadata,
items=fixed_dictionaries({
u"name": object_name(),
}).map(pmap),
)
def namespaced_object_metadatas():
return builds(
lambda metadata, namespace: metadata.transform(
["items"], lambda items: items.set(u"namespace", namespace),
),
metadata=object_metadatas(),
namespace=object_name(),
)
def namespaces():
return builds(
Namespace,
metadata=object_metadatas(),
)
def configmaps():
"""
Strategy for creating ``ConfigMap`` Kubernetes objects.
"""
return builds(
ConfigMap,
metadata=namespaced_object_metadatas(),
)
|
Add watcher for jsx files. | var gulp = require('gulp'),
react = require('gulp-react'),
gulpIf = require('gulp-if'),
uglify = require('gulp-uglify'),
_ = require('underscore'),
elixir = require('laravel-elixir'),
utilities = require('laravel-elixir/ingredients/commands/Utilities'),
notification = require('laravel-elixir/ingredients/commands/Notification');
elixir.extend('react', function (src, options) {
var config = this,
defaultOptions = {
debug: ! config.production,
srcDir: config.assetsDir + 'js',
output: config.jsOutput
};
options = _.extend(defaultOptions, options);
src = "./" + utilities.buildGulpSrc(src, options.srcDir);
options = _.extend(defaultOptions, options);
gulp.task('react', function () {
var onError = function(e) {
new notification().error(e, 'React Compilation Failed!');
this.emit('end');
};
return gulp.src(src)
.pipe(react(options)).on('error', onError)
.pipe(gulpIf(! options.debug, uglify()))
.pipe(gulp.dest(options.output))
.pipe(new notification().message('React Compiled!'));
});
this.registerWatcher('react', options.srcDir + '/**/*.js');
this.registerWatcher('react', options.srcDir + '/**/*.jsx');
return this.queueTask('react');
});
| var gulp = require('gulp'),
react = require('gulp-react'),
gulpIf = require('gulp-if'),
uglify = require('gulp-uglify'),
_ = require('underscore'),
elixir = require('laravel-elixir'),
utilities = require('laravel-elixir/ingredients/commands/Utilities'),
notification = require('laravel-elixir/ingredients/commands/Notification');
elixir.extend('react', function (src, options) {
var config = this,
defaultOptions = {
debug: ! config.production,
srcDir: config.assetsDir + 'js',
output: config.jsOutput
};
options = _.extend(defaultOptions, options);
src = "./" + utilities.buildGulpSrc(src, options.srcDir);
options = _.extend(defaultOptions, options);
gulp.task('react', function () {
var onError = function(e) {
new notification().error(e, 'React Compilation Failed!');
this.emit('end');
};
return gulp.src(src)
.pipe(react(options)).on('error', onError)
.pipe(gulpIf(! options.debug, uglify()))
.pipe(gulp.dest(options.output))
.pipe(new notification().message('React Compiled!'));
});
this.registerWatcher('react', options.srcDir + '/**/*.js');
return this.queueTask('react');
});
|
Use one query with group_by for service status | from flask import jsonify
from sqlalchemy.types import String
from sqlalchemy import func
import datetime
from .. import main
from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent
@main.route('/frameworks', methods=['GET'])
def list_frameworks():
frameworks = Framework.query.all()
return jsonify(
frameworks=[f.serialize() for f in frameworks]
)
@main.route('/frameworks/g-cloud-7/stats', methods=['GET'])
def get_framework_stats():
seven_days_ago = datetime.datetime.utcnow() + datetime.timedelta(-7)
lot_column = DraftService.data['lot'].cast(String).label('lot')
return str({
'services_by_status': dict(db.session.query(
DraftService.status, func.count(DraftService.status)
).group_by(DraftService.status)),
'services_by_lot': dict(db.session.query(
lot_column, func.count(lot_column)
).group_by(lot_column).all()),
'users': User.query.count(),
'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(),
'suppliers': Supplier.query.count(),
'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(),
'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count()
})
| from flask import jsonify
from sqlalchemy.types import String
from sqlalchemy import func
import datetime
from .. import main
from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent
@main.route('/frameworks', methods=['GET'])
def list_frameworks():
frameworks = Framework.query.all()
return jsonify(
frameworks=[f.serialize() for f in frameworks]
)
@main.route('/frameworks/g-cloud-7/stats', methods=['GET'])
def get_framework_stats():
seven_days_ago = datetime.datetime.utcnow() + datetime.timedelta(-7)
lot_column = DraftService.data['lot'].cast(String).label('lot')
return str({
'services_drafts': DraftService.query.filter(
DraftService.status == "not-submitted"
).count(),
'services_complete': DraftService.query.filter(
DraftService.status == "submitted"
).count(),
'services_by_lot': dict(db.session.query(
lot_column, func.count(lot_column)
).group_by(lot_column).all()),
'users': User.query.count(),
'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(),
'suppliers': Supplier.query.count(),
'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(),
'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count()
})
|
Correct test setter for email | <?php
/*
* (c) Nimbles b.v. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nimbles\OnlineBetaalPlatform\Model;
use PHPUnit\Framework\TestCase;
/**
* Class PaymentTest
*/
class PaymentTest extends TestCase
{
public function testPayment()
{
$payment = new Payment('https://nimbles.com/return/url', 1050);
$this->assertEquals(1050, $payment->getAmount());
$this->assertEquals('https://nimbles.com/return/url', $payment->getReturnUrl());
$payment->setUid('secret-uuid');
$this->assertEquals('secret-uuid', $payment->getUid());
$payment->setStatus('created');
$this->assertEquals('created', $payment->getStatus());
$payment->setBuyerLastName('jenkins');
$this->assertEquals('jenkins', $payment->getBuyerLastName());
$payment->setBuyerFirstName('peter');
$this->assertEquals('peter', $payment->getBuyerFirstName());
$payment->setBuyerEmail('[email protected]');
$this->assertEquals('[email protected]', $payment->getBuyerEmail());
$payment->setRedirectUrl('https://nimbles.com/redirect/url');
$this->assertEquals('https://nimbles.com/redirect/url', $payment->getRedirectUrl());
$payment->setShippingCosts(500);
$this->assertEquals(500, $payment->getShippingCosts());
}
}
| <?php
/*
* (c) Nimbles b.v. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nimbles\OnlineBetaalPlatform\Model;
use PHPUnit\Framework\TestCase;
/**
* Class PaymentTest
*/
class PaymentTest extends TestCase
{
public function testPayment()
{
$payment = new Payment('https://nimbles.com/return/url', 1050);
$this->assertEquals(1050, $payment->getAmount());
$this->assertEquals('https://nimbles.com/return/url', $payment->getReturnUrl());
$payment->setUid('secret-uuid');
$this->assertEquals('secret-uuid', $payment->getUid());
$payment->setStatus('created');
$this->assertEquals('created', $payment->getStatus());
$payment->setBuyerLastName('jenkins');
$this->assertEquals('jenkins', $payment->getBuyerLastName());
$payment->setBuyerFirstName('peter');
$this->assertEquals('peter', $payment->getBuyerFirstName());
$payment->setBuyerLastName('[email protected]');
$this->assertEquals('[email protected]', $payment->getBuyerEmail());
$payment->setRedirectUrl('https://nimbles.com/redirect/url');
$this->assertEquals('https://nimbles.com/redirect/url', $payment->getRedirectUrl());
$payment->setShippingCosts(500);
$this->assertEquals(500, $payment->getShippingCosts());
}
}
|
Create a instance for AudioContext | (function (exports) {
'use strict';
/**
* @constructor
*/
function BrowserMusicPlayer () {
this.ctx = new (window.AudioContext || window.webkitAudioContext)();
}
/**
* ファイルをFileReader.readAsDataURL()を使って読み込み、FileReaderオブジェクトを返します
* @param {File} file
* @returns {FileReader}
*/
BrowserMusicPlayer.prototype.loadMusic = function (file) {
if (!this.isMusicFile(file)) {
throw new Error('Not a music file');
}
var reader = new FileReader();
reader.readAsDataURL(file);
return reader;
};
/**
* 指定されたファイルが音楽ファイルかどうか調べ、その結果を真偽値で返します
* @param {File} file
* @returns {boolean}
*/
BrowserMusicPlayer.prototype.isMusicFile = function (file) {
var type = file.type.substring(6, 9);
return /(mp3|wav|ogg|wma|m4a)/.test(type);
};
/**
* audio要素を作ります
* @param {String} src
* @returns {HTMLElement}
*/
BrowserMusicPlayer.prototype.createAudioElement = function (src) {
var audio = document.createElement('audio');
audio.src = src;
return audio;
};
BrowserMusicPlayer.prototype.play = function () {
};
BrowserMusicPlayer.prototype.stop = function () {
};
BrowserMusicPlayer.prototype.rewind = function () {
};
BrowserMusicPlayer.prototype.forward = function () {
};
exports.BrowserMusicPlayer = BrowserMusicPlayer;
})(window);
| (function (exports) {
'use strict';
/**
* @constructor
*/
function BrowserMusicPlayer () {}
/**
* ファイルをFileReader.readAsDataURL()を使って読み込み、FileReaderオブジェクトを返します
* @param {File} file
* @returns {FileReader}
*/
BrowserMusicPlayer.prototype.loadMusic = function (file) {
if (!this.isMusicFile(file)) {
throw new Error('Not a music file');
}
var reader = new FileReader();
reader.readAsDataURL(file);
return reader;
};
/**
* 指定されたファイルが音楽ファイルかどうか調べ、その結果を真偽値で返します
* @param {File} file
* @returns {boolean}
*/
BrowserMusicPlayer.prototype.isMusicFile = function (file) {
var type = file.type.substring(6, 9);
return /(mp3|wav|ogg|wma|m4a)/.test(type);
};
/**
* audio要素を作ります
* @param {String} src
* @returns {HTMLElement}
*/
BrowserMusicPlayer.prototype.createAudioElement = function (src) {
var audio = document.createElement('audio');
audio.src = src;
return audio;
};
BrowserMusicPlayer.prototype.play = function () {
};
BrowserMusicPlayer.prototype.stop = function () {
};
BrowserMusicPlayer.prototype.rewind = function () {
};
BrowserMusicPlayer.prototype.forward = function () {
};
exports.BrowserMusicPlayer = BrowserMusicPlayer;
})(window);
|
Fix select values for stars | (function () {
'use strict';
var React = require('react');
var $ = require('jquery');
var RatingForm = React.createClass({
handleSubmit: function (event) {
event.preventDefault();
var $form = $(event.target);
var rating = {
text: $form.find('#text').val(),
stars: $form.find('#stars').val()
};
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: rating,
success: function(data) {
this.props.ratingSent();
// notify container
}.bind(this),
error: function(xhr, status, err) {
console.error(xhr, status, err.toString());
}.bind(this)
});
},
render: function () {
return(
<form onSubmit={ this.handleSubmit }>
<label htmlFor="stars">Stars</label> <select id="stars" name="stars">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select><br /><br />
<label htmlFor="text">Text</label> <input id="text" type="text" name="text" /><br /><br />
<input type="submit" value="Send comment" />
</form>
);
}
});
module.exports = RatingForm;
})();
| (function () {
'use strict';
var React = require('react');
var $ = require('jquery');
var RatingForm = React.createClass({
handleSubmit: function (event) {
event.preventDefault();
var $form = $(event.target);
var rating = {
text: $form.find('#text').val(),
stars: $form.find('#stars').val()
};
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: rating,
success: function(data) {
this.props.ratingSent();
// notify container
}.bind(this),
error: function(xhr, status, err) {
console.error(xhr, status, err.toString());
}.bind(this)
});
},
render: function () {
return(
<form onSubmit={ this.handleSubmit }>
<label htmlFor="stars">Stars</label> <select id="stars" name="stars">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="1">5</option>
</select><br /><br />
<label htmlFor="text">Text</label> <input id="text" type="text" name="text" /><br /><br />
<input type="submit" value="Send comment" />
</form>
);
}
});
module.exports = RatingForm;
})();
|
Client: Remove global variable used for debugging | var Backbone = require("lib").Backbone;
var utils = require("utils");
var View = Backbone.View.extend({
el: "#top-progress-bar",
initialize: function() {
this.progress = this.$el.find(".determinate");
this._timer = null;
},
setProgress: function(fraction) {
if(this._timer) {
clearTimeout(this._timer);
}
this.$el.css({
visibility: "visible"
});
this.progress.css({
width: (fraction * 100) + "%"
});
if(fraction === 1) {
var self = this;
this._timer = setTimeout(function() {
self.reset();
}, 320);
}
return this;
},
reset: function() {
this._resetTimer();
this.$el.css({
visibility: "hidden"
});
this.progress.css({
width: "0%"
});
},
_resetTimer: function() {
if(this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
}
});
// singleton
var view = null;
var init = function() {
if(view === null) {
view = new View();
}
};
var setProgress = function(fraction ) {
utils.assert(fraction >= 0 && fraction <= 1);
view.setProgress(fraction);
};
var reset = function() {
view.reset();
}
module.exports = {
init: init,
setProgress: setProgress,
reset: reset
}; | var Backbone = require("lib").Backbone;
var utils = require("utils");
var View = Backbone.View.extend({
el: "#top-progress-bar",
initialize: function() {
this.progress = this.$el.find(".determinate");
this._timer = null;
},
setProgress: function(fraction) {
if(this._timer) {
clearTimeout(this._timer);
}
this.$el.css({
visibility: "visible"
});
this.progress.css({
width: (fraction * 100) + "%"
});
if(fraction === 1) {
var self = this;
this._timer = setTimeout(function() {
self.reset();
}, 320);
}
return this;
},
reset: function() {
this._resetTimer();
this.$el.css({
visibility: "hidden"
});
this.progress.css({
width: "0%"
});
},
_resetTimer: function() {
if(this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
}
});
var view = null;
var init = function() {
if(view === null) {
view = new View();
window.p = view;
}
};
var setProgress = function(fraction ) {
utils.assert(fraction >= 0 && fraction <= 1);
view.setProgress(fraction);
};
var reset = function() {
view.reset();
}
module.exports = {
init: init,
setProgress: setProgress,
reset: reset
}; |
Add character replacements for RT search | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if formatted_title.startswith('A '):
formatted_title = formatted_title.replace('A ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
formatted_title = formatted_title.replace(':', '')
formatted_title = formatted_title.replace(',', '')
formatted_title = formatted_title.replace('.', '')
formatted_title = formatted_title.replace('&', 'and')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
| import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if formatted_title.startswith('A '):
formatted_title = formatted_title.replace('A ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
formatted_title = formatted_title.replace(':', '')
formatted_title = formatted_title.replace(',', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
|
philadelphia-client: Simplify command name length calculation | package com.paritytrading.philadelphia.client.command;
import com.paritytrading.philadelphia.client.TerminalClient;
import java.util.Scanner;
class HelpCommand implements Command {
@Override
public void execute(TerminalClient client, Scanner arguments) throws CommandException {
if (arguments.hasNext()) {
Command command = Commands.find(arguments.next());
if (arguments.hasNext())
throw new CommandException();
if (command != null)
displayCommandHelp(client, command);
else
displayGeneralHelp(client);
} else {
displayGeneralHelp(client);
}
}
private void displayGeneralHelp(TerminalClient client) {
client.printf("Commands:\n");
int maxCommandNameLength = calculateMaxCommandNameLength();
for (Command command : Commands.all())
client.printf(" %-" + maxCommandNameLength + "s %s\n", command.getName(), command.getDescription());
client.printf("\nType 'help <command>' for command specific help.\n");
}
private void displayCommandHelp(TerminalClient client, Command command) {
client.printf("Usage: %s\n\n %s\n\n", command.getUsage(), command.getDescription());
}
private int calculateMaxCommandNameLength() {
return Commands.names().collectInt(String::length).max();
}
@Override
public String getName() {
return "help";
}
@Override
public String getDescription() {
return "Display the help";
}
@Override
public String getUsage() {
return "help [command]";
}
}
| package com.paritytrading.philadelphia.client.command;
import com.paritytrading.philadelphia.client.TerminalClient;
import java.util.Scanner;
class HelpCommand implements Command {
@Override
public void execute(TerminalClient client, Scanner arguments) throws CommandException {
if (arguments.hasNext()) {
Command command = Commands.find(arguments.next());
if (arguments.hasNext())
throw new CommandException();
if (command != null)
displayCommandHelp(client, command);
else
displayGeneralHelp(client);
} else {
displayGeneralHelp(client);
}
}
private void displayGeneralHelp(TerminalClient client) {
client.printf("Commands:\n");
int maxCommandNameLength = calculateMaxCommandNameLength();
for (Command command : Commands.all())
client.printf(" %-" + maxCommandNameLength + "s %s\n", command.getName(), command.getDescription());
client.printf("\nType 'help <command>' for command specific help.\n");
}
private void displayCommandHelp(TerminalClient client, Command command) {
client.printf("Usage: %s\n\n %s\n\n", command.getUsage(), command.getDescription());
}
private int calculateMaxCommandNameLength() {
return Commands.all().collectInt(c -> c.getName().length()).max();
}
@Override
public String getName() {
return "help";
}
@Override
public String getDescription() {
return "Display the help";
}
@Override
public String getUsage() {
return "help [command]";
}
}
|
Fix to Modal displaying off the page. | /**
* Copyright 2015 Ian Davies
*
* 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.
*/
define([], function() {
return ['$compile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var rawClone = element.clone();
scope.modals = scope.modals || {};
scope.modals[attrs.isaacModal] = {
show: function() {
$("#isaacModal").empty().append($compile(rawClone)(scope));
$("#isaacModal").foundation("reveal", "open");
var windowHeight = $(window).height(),
modalHeight = $("#isaacModal").height(),
modalPosition = (33/100*windowHeight) - (modalHeight/2);
$("#isaacModal").css("top", modalPosition > 0 ? modalPosition+'px' : 0);
},
hide: function() {
$("#isaacModal").foundation("reveal", "close");
},
}
}
}
}];
}); | /**
* Copyright 2015 Ian Davies
*
* 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.
*/
define([], function() {
return ['$compile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var rawClone = element.clone();
scope.modals = scope.modals || {};
scope.modals[attrs.isaacModal] = {
show: function() {
$("#isaacModal").empty().append($compile(rawClone)(scope));
$("#isaacModal").foundation("reveal", "open");
var modalHeight = $("#isaacModal").height();
$("#isaacModal").css("top", "calc(33% - " + modalHeight + "px /2)");
},
hide: function() {
$("#isaacModal").foundation("reveal", "close");
},
}
}
}
}];
}); |
Add a slot for legislator role | """ these are helper classes for object creation during the scrape """
from pupa.models.person import Person
from pupa.models.organization import Organization
from pupa.models.membership import Membership
class Legislator(Person):
_is_legislator = True
__slots__ = ('post_id', 'party', 'chamber', '_contact_details', 'role')
def __init__(self, name, post_id, party=None, chamber=None, **kwargs):
super(Legislator, self).__init__(name, **kwargs)
self.post_id = post_id
self.party = party
self.chamber = chamber
self._contact_details = []
def add_contact(self, type, value, note):
self._contact_details.append({'type': type, 'value': value,
'note': note})
def add_committee_membership(self, com_name, role='member'):
org = Organization(com_name, classification='committee')
self.add_membership(org, role=role)
org.sources = self.sources
self._related.append(org)
class Committee(Organization):
def __init__(self, *args, **kwargs):
super(Committee, self).__init__(*args, **kwargs)
def add_member(self, name, role='member', **kwargs):
membership = Membership(None, self._id, role=role,
unmatched_legislator={'name': name},
**kwargs)
self._related.append(membership)
| """ these are helper classes for object creation during the scrape """
from pupa.models.person import Person
from pupa.models.organization import Organization
from pupa.models.membership import Membership
class Legislator(Person):
_is_legislator = True
__slots__ = ('post_id', 'party', 'chamber', '_contact_details')
def __init__(self, name, post_id, party=None, chamber=None, **kwargs):
super(Legislator, self).__init__(name, **kwargs)
self.post_id = post_id
self.party = party
self.chamber = chamber
self._contact_details = []
def add_contact(self, type, value, note):
self._contact_details.append({'type': type, 'value': value,
'note': note})
def add_committee_membership(self, com_name, role='member'):
org = Organization(com_name, classification='committee')
self.add_membership(org, role=role)
org.sources = self.sources
self._related.append(org)
class Committee(Organization):
def __init__(self, *args, **kwargs):
super(Committee, self).__init__(*args, **kwargs)
def add_member(self, name, role='member', **kwargs):
membership = Membership(None, self._id, role=role,
unmatched_legislator={'name': name},
**kwargs)
self._related.append(membership)
|
Reset learners password when user is unGDPRed/unretired via django admin. | """
Django forms for accounts
"""
from django import forms
from django.core.exceptions import ValidationError
from openedx.core.djangoapps.user_api.accounts.utils import generate_password
class RetirementQueueDeletionForm(forms.Form):
"""
Admin form to facilitate learner retirement cancellation
"""
cancel_retirement = forms.BooleanField(required=True)
def save(self, retirement):
"""
When the form is POSTed we double-check the retirment status
and perform the necessary steps to cancel the retirement
request.
"""
if retirement.current_state.state_name != 'PENDING':
self.add_error(
None,
# Translators: 'current_state' is a string from an enumerated list indicating the learner's retirement
# state. Example: FORUMS_COMPLETE
"Retirement requests can only be cancelled for users in the PENDING state."
" Current request state for '{original_username}': {current_state}".format(
original_username=retirement.original_username,
current_state=retirement.current_state.state_name
)
)
raise ValidationError('Retirement is in the wrong state!')
# Load the user record using the retired email address -and- change the email address back.
retirement.user.email = retirement.original_email
# Reset users password so they can request a password reset and log in again.
retirement.user.set_password(generate_password(length=25))
retirement.user.save()
# Delete the user retirement status record.
# No need to delete the accompanying "permanent" retirement request record - it gets done via Django signal.
retirement.delete()
| """
Django forms for accounts
"""
from django import forms
from django.core.exceptions import ValidationError
class RetirementQueueDeletionForm(forms.Form):
"""
Admin form to facilitate learner retirement cancellation
"""
cancel_retirement = forms.BooleanField(required=True)
def save(self, retirement):
"""
When the form is POSTed we double-check the retirment status
and perform the necessary steps to cancel the retirement
request.
"""
if retirement.current_state.state_name != 'PENDING':
self.add_error(
None,
# Translators: 'current_state' is a string from an enumerated list indicating the learner's retirement
# state. Example: FORUMS_COMPLETE
"Retirement requests can only be cancelled for users in the PENDING state."
" Current request state for '{original_username}': {current_state}".format(
original_username=retirement.original_username,
current_state=retirement.current_state.state_name
)
)
raise ValidationError('Retirement is in the wrong state!')
# Load the user record using the retired email address -and- change the email address back.
retirement.user.email = retirement.original_email
retirement.user.save()
# Delete the user retirement status record.
# No need to delete the accompanying "permanent" retirement request record - it gets done via Django signal.
retirement.delete()
|
BAP-10654: Prepare existing code for new Localization Entity
- reverted back parentLocalization and childLocalization names | <?php
namespace Oro\Bundle\LocaleBundle\Tests\Functional\DataFixtures;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Oro\Bundle\LocaleBundle\Entity\Localization;
class LoadLocalizationData extends AbstractFixture
{
/**
* @var array
*/
protected $localizations = [
[
'language' => 'en_US',
'formatting' => 'en_US',
'parent' => null,
'title' => 'English (United States)',
],
[
'language' => 'en_CA',
'formatting' => 'en_CA',
'parent' => 'en_US',
'title' => 'English (Canada)',
],
];
/**
* @param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
$registry = [];
foreach ($this->localizations as $item) {
$code = $item['language'];
$localization = new Localization();
$localization
->setLanguageCode($item['language'])
->setFormattingCode($item['formatting'])
->setName($item['title']);
if ($item['parent']) {
$localization->setParentLocalization($registry[$item['parent']]);
}
$registry[$code] = $localization;
$manager->persist($localization);
$this->addReference($code, $localization);
}
$manager->flush();
$manager->clear();
}
}
| <?php
namespace Oro\Bundle\LocaleBundle\Tests\Functional\DataFixtures;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Oro\Bundle\LocaleBundle\Entity\Localization;
class LoadLocalizationData extends AbstractFixture
{
/**
* @var array
*/
protected $localizations = [
[
'language' => 'en_US',
'formatting' => 'en_US',
'parent' => null,
'title' => 'English (United States)',
],
[
'language' => 'en_CA',
'formatting' => 'en_CA',
'parent' => 'en_US',
'title' => 'English (Canada)',
],
];
/**
* @param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
$registry = [];
foreach ($this->localizations as $item) {
$code = $item['language'];
$localization = new Localization();
$localization
->setLanguageCode($item['language'])
->setFormattingCode($item['formatting'])
->setName($item['title']);
if ($item['parent']) {
$localization->setParent($registry[$item['parent']]);
}
$registry[$code] = $localization;
$manager->persist($localization);
$this->addReference($code, $localization);
}
$manager->flush();
$manager->clear();
}
}
|
Replace jQuery `each` method with for loop | window.GOVUK = window.GOVUK || {}
window.GOVUK.Modules = window.GOVUK.Modules || {};
(function (global, GOVUK) {
'use strict'
GOVUK.Modules.TrackBrexitQaChoices = function () {
this.start = function (element) {
track(element)
}
function track (element) {
element.on('submit', function (event) {
var eventLabel, options
var $submittedForm = event.target
var $checkedOptions = $submittedForm.querySelectorAll('input:checked')
var questionKey = $submittedForm.data('question-key')
if ($checkedOptions.length) {
for (var i = 0; i < $checkedOptions.length; i++) {
var checkedOptionId = $checkedOptions[i].getAttribute('id')
var checkedOptionLabel = $submittedForm.find('label[for="' + checkedOptionId + '"]').text().trim()
eventLabel = checkedOptionLabel.length
? checkedOptionLabel
: $checkedOptions[i].val()
options = { transport: 'beacon', label: eventLabel }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
}
} else {
// Skipped questions
options = { transport: 'beacon', label: 'no choice' }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
}
})
}
}
})(window, window.GOVUK)
| window.GOVUK = window.GOVUK || {}
window.GOVUK.Modules = window.GOVUK.Modules || {};
(function (global, GOVUK) {
'use strict'
GOVUK.Modules.TrackBrexitQaChoices = function () {
this.start = function (element) {
track(element)
}
function track (element) {
element.on('submit', function (event) {
var $checkedOption, eventLabel, options
var $submittedForm = event.target
var $checkedOptions = $submittedForm.querySelectorAll('input:checked')
var questionKey = $submittedForm.data('question-key')
if ($checkedOptions.length) {
$checkedOptions.each(function (index) {
$checkedOption = $(this)
var checkedOptionId = $checkedOption.attr('id')
var checkedOptionLabel = $submittedForm.find('label[for="' + checkedOptionId + '"]').text().trim()
eventLabel = checkedOptionLabel.length
? checkedOptionLabel
: $checkedOption.val()
options = { transport: 'beacon', label: eventLabel }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
})
} else {
// Skipped questions
options = { transport: 'beacon', label: 'no choice' }
GOVUK.SearchAnalytics.trackEvent('brexit-checker-qa', questionKey, options)
}
})
}
}
})(window, window.GOVUK)
|
Fix "Axis Tick Styling" example. | var options = {
container: document.getElementById('myChart'),
data: generateSpiralData(),
series: [{
type: 'line',
xKey: 'x',
yKey: 'y',
marker: {
enabled: false
}
}],
axes: [
{
type: 'number',
position: 'bottom',
tick: {
count: 10,
},
}, {
type: 'number',
position: 'left',
tick: {
count: 10,
},
}
],
legend: {
enabled: false
}
};
var chart = agCharts.AgChart.create(options);
function setTickCountTo5() {
options.axes[0].tick.count = 5;
options.axes[1].tick.count = 5;
agCharts.AgChart.update(chart, options);
}
function setTickCountTo10() {
options.axes[0].tick.count = 10;
options.axes[1].tick.count = 10;
agCharts.AgChart.update(chart, options);
}
function generateSpiralData() {
var a = 1;
var b = 1;
var data = [];
var step = 0.1;
for (var th = 1; th < 50; th += step) {
var r = a + b * th;
var datum = {
x: r * Math.cos(th),
y: r * Math.sin(th)
};
data.push(datum);
}
return data;
} | var options = {
container: document.getElementById('myChart'),
data: generateSpiralData(),
series: [{
type: 'line',
xKey: 'x',
yKey: 'y',
marker: {
enabled: false
}
}],
axes: [
{
type: 'number',
position: 'bottom',
tick: {
count: 10,
},
}, {
type: 'number',
position: 'left',
tick: {
count: 10,
},
}
],
legend: {
enabled: false
}
};
var chart = agCharts.AgChart.create(options);
function setTickCountTo5() {
chart.axes[0].tick.count = 5;
chart.axes[1].tick.count = 5;
chart.performLayout();
}
function setTickCountTo10() {
chart.axes[0].tick.count = 10;
chart.axes[1].tick.count = 10;
chart.performLayout();
}
function generateSpiralData() {
var a = 1;
var b = 1;
var data = [];
var step = 0.1;
for (var th = 1; th < 50; th += step) {
var r = a + b * th;
var datum = {
x: r * Math.cos(th),
y: r * Math.sin(th)
};
data.push(datum);
}
return data;
} |
Return None if key is not found | import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if keys is not None:
params['keys'] = True
r = requests.get(url, params=params)
if r.ok:
return json.loads(r.text)
elif r.status_code == 404:
return None
else:
r.raise_for_status()
def get(self, key, recurse=None):
return self._get(key, recurse=recurse)
def list_keys(self, key=''):
return self._get(key, keys=True)
def set(self, key, value, cas=None):
params = dict()
if cas is not None:
params['cas'] = cas
r = requests.put(self._url + '/' + key, data=value, params=params)
if r.ok:
if re.match(r"true", r.text) is not None:
return True
elif re.match(r"false", r.text) is not None:
return False
else:
r.raise_for_status()
def delete(self, key, recurse=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
r = requests.delete(url, params=params)
r.raise_for_status()
| import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if keys is not None:
params['keys'] = True
r = requests.get(url, params=params)
if r.ok:
return json.loads(r.text)
else:
r.raise_for_status()
def get(self, key, recurse=None):
return self._get(key, recurse=recurse)
def list(self, key=''):
return self._get(key, keys=True)
def set(self, key, value, cas=None):
params = dict()
if cas is not None:
params['cas'] = cas
r = requests.put(self._url + '/' + key, data=value, params=params)
if r.ok:
if re.match(r"true", r.text) is not None:
return True
elif re.match(r"false", r.text) is not None:
return False
else:
r.raise_for_status()
def delete(self, key, recurse=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
r = requests.delete(url, params=params)
r.raise_for_status()
|
Fix accidental global variable assignment | 'use strict';
var Kefir = require('kefir');
module.exports = Stream;
function Stream(value) {
if (typeof value === 'function') {
var subscribe = value;
this._observable = Kefir.fromBinder(function (sink) {
return subscribe({
push: sink,
close: function (value) {
if (typeof value !== 'undefined') {
sink(value);
}
sink(Kefir.END);
}
});
}, this);
} else {
this._observable = value;
}
this._consumers = 0;
process.nextTick(function () {
if (this._consumers === 0) {
this._consumers++;
this._observable.onValue(function () {});
}
}.bind(this));
}
Stream.prototype.pipe = function (sink) {
this._consumers++;
return new Stream(this._observable.flatMap(function (input) {
var output = sink(input);
if (output instanceof Stream) {
return output._observable;
} else {
return Kefir.once(output);
}
}));
};
| 'use strict';
var Kefir = require('kefir');
module.exports = Stream;
function Stream(value) {
if (typeof value === 'function') {
var subscribe = value;
this._observable = Kefir.fromBinder(function (sink) {
return subscribe({
push: sink,
close: function (value) {
if (typeof value !== 'undefined') {
sink(value);
}
sink(Kefir.END);
}
});
}, this);
} else {
this._observable = value;
}
this._consumers = 0;
process.nextTick(function () {
if (this._consumers === 0) {
this._consumers++;
this._observable.onValue(function () {});
}
}.bind(this));
}
Stream.prototype.pipe = function (sink) {
this._consumers++;
return new Stream(this._observable.flatMap(function (input) {
output = sink(input);
if (output instanceof Stream) {
return output._observable;
} else {
return Kefir.once(output);
}
}));
};
|
Remove empty values when fetching credentials from session | <?php
namespace App\Services;
use Illuminate\Http\Request;
abstract class Authentication
{
/**
* Retrieves array of currently configured clients.
*
* @return array
*/
abstract public function getSupportedClientKeys();
/**
* Engage in login flow.
*
* @param string $provider
* @param Request $request
*
* @return RedirectResponse|Identity
* @throws Exception
*/
abstract public function login($provider, Request $request);
/**
* Get value from session by key.
*
* @param string $key
* @param mixed $value
*
* @return boolean
*/
protected function addToSession($key, $value)
{
$success = session([$key => $value]);
session()->save();
return $success;
}
/**
* Get value from session by key.
*
* @param string $key
* @param boolean $remove Optional
*
* @return mixed|null
*/
protected function getFromSession($key, $remove = true)
{
if ($remove) {
$value = session()->pull($key);
} else {
$value = session($key);
}
session()->save();
if (is_array($value)) {
$value = array_filter($value);
}
return $value;
}
}
| <?php
namespace App\Services;
use Illuminate\Http\Request;
abstract class Authentication
{
/**
* Retrieves array of currently configured clients.
*
* @return array
*/
abstract public function getSupportedClientKeys();
/**
* Engage in login flow.
*
* @param string $provider
* @param Request $request
*
* @return RedirectResponse|Identity
* @throws Exception
*/
abstract public function login($provider, Request $request);
/**
* Get value from session by key.
*
* @param string $key
* @param mixed $value
*
* @return boolean
*/
protected function addToSession($key, $value)
{
$success = session([$key => $value]);
session()->save();
return $success;
}
/**
* Get value from session by key.
*
* @param string $key
* @param boolean $remove Optional
*
* @return mixed|null
*/
protected function getFromSession($key, $remove = true)
{
if ($remove) {
$value = session()->pull($key);
} else {
$value = session($key);
}
session()->save();
return $value;
}
}
|
Allow blanking array properties on users | <?php
namespace Auth;
trait LDAPSettableObject
{
protected function setCachedOnlyProp($propName, $value)
{
if(in_array($propName, $this->cachedOnlyProps))
{
if(!is_object($this->ldapObj))
{
$this->setFieldLocal($propName, $value);
return true;
}
throw new \Exception('Unsupported!');
}
return false;
}
protected function setMultiValueProp($propName, $value)
{
if(in_array($propName, $this->multiValueProps) && !is_array($value))
{
if($value === null)
{
$this->setField($propName, $value);
}
else
{
$this->setField($propName, array($value));
}
return true;
}
return false;
}
public function __set($propName, $value)
{
if($this->setCachedOnlyProp($propName, $value) === true)
{
return;
}
if($this->setMultiValueProp($propName, $value) === true)
{
return;
}
$this->setField($propName, $value);
}
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
| <?php
namespace Auth;
trait LDAPSettableObject
{
protected function setCachedOnlyProp($propName, $value)
{
if(in_array($propName, $this->cachedOnlyProps))
{
if(!is_object($this->ldapObj))
{
$this->setFieldLocal($propName, $value);
return true;
}
throw new \Exception('Unsupported!');
}
return false;
}
protected function setMultiValueProp($propName, $value)
{
if(in_array($propName, $this->multiValueProps) && !is_array($value))
{
$this->setField($propName, array($value));
return true;
}
return false;
}
public function __set($propName, $value)
{
if($this->setCachedOnlyProp($propName, $value) === true)
{
return;
}
if($this->setMultiValueProp($propName, $value) === true)
{
return;
}
$this->setField($propName, $value);
}
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
|
Fix ServiceProvider registerCommands method compatibility | <?php
declare(strict_types=1);
namespace Rinvex\Auth\Providers;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Rinvex\Support\Traits\ConsoleTools;
use Rinvex\Auth\Console\Commands\PublishCommand;
use Rinvex\Auth\Services\PasswordResetBrokerManager;
use Rinvex\Auth\Services\EmailVerificationBrokerManager;
class AuthServiceProvider extends ServiceProvider
{
use ConsoleTools;
/**
* The commands to be registered.
*
* @var array
*/
protected $commands = [
PublishCommand::class => 'command.rinvex.auth.publish',
];
/**
* {@inheritdoc}
*/
public function register()
{
// Merge config
$this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex.auth');
// Register console commands
$this->registerCommands($this->commands);
// Register the password reset broker manager
$this->app->singleton('auth.password', function ($app) {
return new PasswordResetBrokerManager($app);
});
// Register the verification broker manager
$this->app->singleton('rinvex.auth.emailverification', function ($app) {
return new EmailVerificationBrokerManager($app);
});
}
/**
* {@inheritdoc}
*/
public function boot(Router $router)
{
// Publish resources
$this->publishesConfig('rinvex/laravel-auth');
}
}
| <?php
declare(strict_types=1);
namespace Rinvex\Auth\Providers;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Rinvex\Support\Traits\ConsoleTools;
use Rinvex\Auth\Console\Commands\PublishCommand;
use Rinvex\Auth\Services\PasswordResetBrokerManager;
use Rinvex\Auth\Services\EmailVerificationBrokerManager;
class AuthServiceProvider extends ServiceProvider
{
use ConsoleTools;
/**
* The commands to be registered.
*
* @var array
*/
protected $commands = [
PublishCommand::class => 'command.rinvex.auth.publish',
];
/**
* {@inheritdoc}
*/
public function register()
{
// Merge config
$this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex.auth');
// Register console commands
$this->registerCommands();
// Register the password reset broker manager
$this->app->singleton('auth.password', function ($app) {
return new PasswordResetBrokerManager($app);
});
// Register the verification broker manager
$this->app->singleton('rinvex.auth.emailverification', function ($app) {
return new EmailVerificationBrokerManager($app);
});
}
/**
* {@inheritdoc}
*/
public function boot(Router $router)
{
// Publish resources
$this->publishesConfig('rinvex/laravel-auth');
}
}
|
Fix this code so it works | from django.db import models
class DenormalizeManagerMixin(object):
def update_cohort(self, cohort, **kwargs):
stats, created = self.get_or_create(**kwargs)
stats.highest_paid = cohort.order_by('-compensation')[0]
stats.lowest_paid = cohort.order_by('compensation')[0]
stats.save()
class OrganizationStatsManager(DenormalizeManagerMixin, models.Manager):
use_for_related_manager = True
def denormalize(self, obj):
Employee = obj._meta.concrete_model
use_children = False
organization = obj.position.organization
# TODO: Allow organization to break and say it is top-level
# Example: El Paso County Sheriff's Department instead
# of going all the way to El Paso County.
if organization.parent:
use_children = True
organization = organization.parent
if use_children:
kwargs = {'position__organization__parent': organization, }
else:
kwargs = {'position__organization': organization, }
cohort = Employee.objects.filter(**kwargs)
self.update_cohort(cohort, organization=organization)
class PositionStatsManager(DenormalizeManagerMixin, models.Manager):
use_for_related_manager = True
def denormalize(self, obj):
Employee = obj._meta.concrete_model
position_cohort = Employee.objects.filter(
position__organization=obj.position.organization)
self.update_cohort(position_cohort, position=obj.position.post)
| from django.db import models
class DenormalizeManagerMixin(object):
def update_cohort(self, cohort, **kwargs):
stats, created = self.get_or_create(**kwargs)
stats.highest_paid = cohort.order_by('-compensation')[0]
stats.lowest_paid = cohort.order_by('compensation')[0]
stats.save()
class OrganizationStatsManager(models.Manager):
use_for_related_manager = True
def denormalize(self, obj):
Employee = obj._meta.concrete_model
use_children = False
organization = obj.position.organization
# TODO: Allow organization to break and say it is top-level
# Example: El Paso County Sheriff's Department instead
# of going all the way to El Paso County.
if organization.parent:
use_children = True
organization = organization.parent
if use_children:
kwargs = {
'parent': None,
'children__members__employee': obj,
}
else:
kwargs = {'members__employee': obj, }
cohort = Employee.objects.filter(**kwargs)
self.update_cohort(cohort, organization=organization)
class PositionStatsManager(models.Manager):
use_for_related_manager = True
def denormalize(self, obj):
Employee = obj._meta.concrete_model
position_cohort = Employee.objects.filter(
position__organization=obj.position.organization)
self.update_cohort(position_cohort, position=obj.position.post)
|
refactor: Remove materializecss select field render function
Using it now in controller when required | import Ember from 'ember';
import $ from 'jquery';
export default Ember.Controller.extend({
indexedDbPromised: Ember.inject.service('indexed-db'),
init () {
window.addEventListener('offline', () => {
/* global Materialize */
Materialize.toast('Conection lost. Trying to reconect...');
});
window.addEventListener('online', () => {
$('.toast').fadeOut('fast');
Ember.run.later(() => {
/* global location */
location.reload();
}, 500);
});
// Create or open Database before default route is loaded
Ember.run.once(() => {
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-favorites',
$dbStore: 'favorites',
$dbVersion: 1,
$keyPath: 'favId'
});
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-recent',
$dbStore: 'recent',
$dbVersion: 1,
$keyPath: 'fromTo',
$index: ['by-date', 'request_time']
});
});
},
currentPathDidChange: function () {
Ember.run.schedule('afterRender', () => {
if (this.get('currentPath') === 'trains') {
// $('select').material_select();
Materialize.updateTextFields();
}
});
}.observes('currentPath')
});
| import Ember from 'ember';
import $ from 'jquery';
export default Ember.Controller.extend({
indexedDbPromised: Ember.inject.service('indexed-db'),
init () {
window.addEventListener('offline', () => {
/* global Materialize */
Materialize.toast('Conection lost. Trying to reconect...');
});
window.addEventListener('online', () => {
$('.toast').fadeOut('fast');
Ember.run.later(() => {
/* global location */
location.reload();
}, 500);
});
// Create or open Database before default route is loaded
Ember.run.once(() => {
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-favorites',
$dbStore: 'favorites',
$dbVersion: 1,
$keyPath: 'favId'
});
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-recent',
$dbStore: 'recent',
$dbVersion: 1,
$keyPath: 'fromTo',
$index: ['by-date', 'request_time']
});
});
},
currentPathDidChange: function () {
Ember.run.schedule('afterRender', () => {
if (this.get('currentPath') === 'trains') {
$('select').material_select();
Materialize.updateTextFields();
}
});
}.observes('currentPath')
});
|
Remove slug from view. Useless by now. | @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('manager.services.index.title') }}</div>
<div class="panel-body">
<table class="table table-condensed">
<tr>
<th>{{ trans('manager.services.index.th.name') }}</th>
</tr>
@foreach ($services as $service)
<tr>
<td title="{{ $service->description }}">
<div class="btn-group">
{!! Button::normal()->withIcon(Icon::edit())->asLinkTo( route('manager.business.service.edit', [$business->id, $service->id]) ) !!}
{!! Button::normal($service->name)->asLinkTo( route('manager.business.service.show', [$business->id, $service->id]) ) !!}
</div>
</td>
</tr>
@endforeach
</table>
<div class="panel-footer">
{!! Button::primary(trans('manager.services.btn.create'))->withIcon(Icon::plus())->asLinkTo( route('manager.business.service.create', [$business->id]) )->block() !!}
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
| @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('manager.services.index.title') }}</div>
<div class="panel-body">
<table class="table table-condensed">
<tr>
<th>{{ trans('manager.services.index.th.name') }}</th>
<th>{{ trans('manager.services.index.th.slug') }}</th>
</tr>
@foreach ($services as $service)
<tr>
<td title="{{ $service->description }}">
<div class="btn-group">
{!! Button::normal()->withIcon(Icon::edit())->asLinkTo( route('manager.business.service.edit', [$business->id, $service->id]) ) !!}
{!! Button::normal($service->name)->asLinkTo( route('manager.business.service.show', [$business->id, $service->id]) ) !!}
</div>
</td>
<td>{{ $service->slug }}</td>
</tr>
@endforeach
</table>
<div class="panel-footer">
{!! Button::primary(trans('manager.services.btn.create'))->withIcon(Icon::plus())->asLinkTo( route('manager.business.service.create', [$business->id]) )->block() !!}
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
|
Improve the spec descriptions in ContextSpecification. | describe('jasmine.grammar.ContextSpecification', function() {
var ContextSpecification = jasmine.grammar.ContextSpecification;
var env;
beforeEach(function() {
env = new jasmine.Env();
jasmine.grammar._currentEnv = env;
});
describe('concern', function() {
it('creates a suite tagged with "concern"', function() {
var suite = ContextSpecification.concern('A specific feature of the system', function() {});
expect(suite.description).toBe('A specific feature of the system');
expect(suite.tags).toEqual(['concern']);
});
});
describe('context', function() {
it('creates a suite with tagged with "context"', function() {
var suite = ContextSpecification.context('Context within which certain specifications will be valid.', function() {});
expect(suite.description).toBe('Context within which certain specifications will be valid.');
expect(suite.tags).toEqual(['context']);
});
});
describe('spec', function() {
it('creates a spec in the current suite', function() {
var parentSuite = ContextSpecification.context('Dummy context', function() {});
jasmine.grammar.getEnv().currentSuite = parentSuite;
var spec = ContextSpecification.spec('Observe this outcome', function() {});
expect(spec.description).toBe('Observe this outcome');
expect(spec.suite).toBe(parentSuite);
});
});
});
| describe('jasmine.grammar.ContextSpecification', function() {
var ContextSpecification = jasmine.grammar.ContextSpecification;
var env;
beforeEach(function() {
env = new jasmine.Env();
jasmine.grammar._currentEnv = env;
});
describe('concern', function() {
it('should create a suite with extended attributes', function() {
var suite = ContextSpecification.concern('A specific feature of the system', function() {});
expect(suite.description).toBe('A specific feature of the system');
expect(suite.tags).toEqual(['concern']);
});
});
describe('context', function() {
it('should create a suite with extended attributes', function() {
var suite = ContextSpecification.context('Context within which certain specifications will be valid.', function() {});
expect(suite.description).toBe('Context within which certain specifications will be valid.');
expect(suite.tags).toEqual(['context']);
});
});
describe('spec', function() {
it('should create an end result specification item', function() {
// we need a suite before a spec
var parentSuite = ContextSpecification.context('Dummy context', function() {});
jasmine.grammar.getEnv().currentSuite = parentSuite;
var spec = ContextSpecification.spec('Observe this outcome', function() {});
expect(spec.description).toBe('Observe this outcome');
expect(spec.suite).toBe(parentSuite);
});
});
});
|
fix(webpack): Use external `react` and `react-dom`
Prevent bundling React and ReactDOM to use a single version of React if one is already included.
Refs https://github.com/scup/atellier/issues/33 | var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'react-atellier.js',
library: 'ReactAtellier',
libraryTarget: 'umd',
},
externals: {
// Use external version of React
'react': 'react',
'react-dom': 'react-dom'
},
module: {
loaders: [
{
test: /\.less$/,
loader: 'style!css!less?outputStyle=expanded&' +
'includePaths[]=' + (path.resolve(__dirname, './bower_components')) + '&' +
'includePaths[]=' + (path.resolve(__dirname, './node_modules'))
},
{
test: /\.less$/,
loader: 'autoprefixer'
},
{
test: /\.(otf|ttf)$/,
loader: 'url?limit=100000'
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=45000'
},
{
test: /(\.js)$/,
exclude: [path.resolve(__dirname, 'node_modules')],
loader: 'babel',
include: path.join(__dirname, 'src')
},
],
},
devServer: {
contentBase: './example',
host: 'localhost',
inline: true,
info: false,
},
};
| var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'react-atellier.js',
library: 'ReactAtellier',
libraryTarget: 'umd',
},
externals: {
// Use external version of React
"react": "React"
},
module: {
loaders: [
{
test: /\.less$/,
loader: 'style!css!less?outputStyle=expanded&' +
'includePaths[]=' + (path.resolve(__dirname, './bower_components')) + '&' +
'includePaths[]=' + (path.resolve(__dirname, './node_modules'))
},
{
test: /\.less$/,
loader: 'autoprefixer'
},
{
test: /\.(otf|ttf)$/,
loader: 'url?limit=100000'
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=45000'
},
{
test: /(\.js)$/,
exclude: [path.resolve(__dirname, 'node_modules')],
loader: 'babel',
include: path.join(__dirname, 'src')
},
],
},
devServer: {
contentBase: './example',
host: 'localhost',
inline: true,
info: false,
},
};
|
Add debug flag to nodemon to allow debugging via node-inspect et. al. | module.exports = function(grunt) {
// Load tasks
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-concurrent');
grunt.initConfig({
less: {
development: {
options: {
paths: ["assets/css"]
},
files: {
"client/css/app.css": "client/css/app.less"
}
}
},
watch: {
styles: {
// Which files to watch (all .less files recursively in the less directory)
files: ['client/css/**/*.less'],
tasks: ['less'],
options: {
nospawn: true
}
}
},
concurrent: {
dev: ['nodemon:dev', 'watch'],
options: {
logConcurrentOutput: true
}
},
nodemon: {
dev: {
script: './server/main.js'
},
options: {
nodeArgs: ['--debug']
}
},
clean: ["node_modules", "client/components"]
});
grunt.registerTask('dev', ['less', 'concurrent:dev']);
}; | module.exports = function(grunt) {
// Load tasks
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-concurrent');
grunt.initConfig({
less: {
development: {
options: {
paths: ["assets/css"]
},
files: {
"client/css/app.css": "client/css/app.less"
}
}
},
watch: {
styles: {
// Which files to watch (all .less files recursively in the less directory)
files: ['client/css/**/*.less'],
tasks: ['less'],
options: {
nospawn: true
}
}
},
concurrent: {
dev: ['nodemon:dev', 'watch'],
options: {
logConcurrentOutput: true
}
},
nodemon: {
dev: {
script: './server/main.js'
}
},
clean: ["node_modules", "client/components"]
});
grunt.registerTask('dev', ['less', 'concurrent:dev']);
}; |
fix(PropertyPanel): Add support of show function on prop group | import React from 'react';
import PropTypes from 'prop-types';
import style from 'PVWStyle/ReactProperties/PropertyPanel.mcss';
import factory from '../PropertyFactory';
function alwaysShow() {
return true;
}
export default class PropertyPanel extends React.Component {
constructor(props) {
super(props);
// Bind callback
this.valueChange = this.valueChange.bind(this);
}
valueChange(newVal) {
if (this.props.onChange) {
this.props.onChange(newVal);
}
}
render() {
const viewData = this.props.viewData;
const uiContents = (content) =>
factory(
content,
viewData,
this.props.onChange ? this.valueChange : undefined
);
const uiContainer = (property) => (
<div
key={property.title}
style={{
display: (property.show || alwaysShow)(viewData) ? 'block' : 'none',
}}
>
<div className={style.propertyHeader}>
<strong>{property.title}</strong>
</div>
{property.contents.map(uiContents)}
</div>
);
return (
<section
className={[this.props.className, style.propertyPanel].join(' ')}
>
{this.props.input.map(uiContainer)}
</section>
);
}
}
PropertyPanel.propTypes = {
className: PropTypes.string,
input: PropTypes.array,
onChange: PropTypes.func,
viewData: PropTypes.object,
};
PropertyPanel.defaultProps = {
className: '',
input: [],
viewData: {},
onChange: undefined,
};
| import React from 'react';
import PropTypes from 'prop-types';
import style from 'PVWStyle/ReactProperties/PropertyPanel.mcss';
import factory from '../PropertyFactory';
export default class PropertyPanel extends React.Component {
constructor(props) {
super(props);
// Bind callback
this.valueChange = this.valueChange.bind(this);
}
valueChange(newVal) {
if (this.props.onChange) {
this.props.onChange(newVal);
}
}
render() {
const viewData = this.props.viewData;
const uiContents = (content) =>
factory(
content,
viewData,
this.props.onChange ? this.valueChange : undefined
);
const uiContainer = (property) => (
<div key={property.title}>
<div className={style.propertyHeader}>
<strong>{property.title}</strong>
</div>
{property.contents.map(uiContents)}
</div>
);
return (
<section
className={[this.props.className, style.propertyPanel].join(' ')}
>
{this.props.input.map(uiContainer)}
</section>
);
}
}
PropertyPanel.propTypes = {
className: PropTypes.string,
input: PropTypes.array,
onChange: PropTypes.func,
viewData: PropTypes.object,
};
PropertyPanel.defaultProps = {
className: '',
input: [],
viewData: {},
onChange: undefined,
};
|
Maintain scroll position in data source/sink list in Enabler.
Instead of blowing away the adapter each time we update, keep the same adapter
and just update the list.
Thanks to
http://vikinghammer.com/2011/06/17/android-listview-maintain-your-scroll-position-when-you-refresh/ | package com.openxc.enabler;
import java.util.TimerTask;
import android.app.Activity;
import com.openxc.VehicleManager;
import android.widget.ListView;
import android.widget.ArrayAdapter;
public class PipelineStatusUpdateTask extends TimerTask {
private VehicleManager mVehicleManager;
private Activity mActivity;
private ListView mSourceListView;
private ListView mSinkListView;
private ArrayAdapter<Object> mSourceListAdapter;
private ArrayAdapter<Object> mSinkListAdapter;
public PipelineStatusUpdateTask(VehicleManager vehicleService,
Activity activity, ListView sourceListView, ListView sinkListView) {
mVehicleManager = vehicleService;
mActivity = activity;
mSourceListView = sourceListView;
mSinkListView = sinkListView;
mSourceListAdapter = new ArrayAdapter<Object>(mActivity,
android.R.layout.simple_list_item_1);
mSourceListView.setAdapter(mSourceListAdapter);
mSinkListAdapter = new ArrayAdapter<Object>(mActivity,
android.R.layout.simple_list_item_1);
mSinkListView.setAdapter(mSinkListAdapter);
}
public void run() {
mActivity.runOnUiThread(new Runnable() {
public void run() {
mSourceListAdapter.clear();
mSourceListAdapter.addAll(
mVehicleManager.getSourceSummaries().toArray());
mSourceListAdapter.notifyDataSetChanged();
mSinkListAdapter.clear();
mSinkListAdapter.addAll(
mVehicleManager.getSinkSummaries().toArray());
mSinkListAdapter.notifyDataSetChanged();
}
});
}
}
| package com.openxc.enabler;
import java.util.TimerTask;
import android.app.Activity;
import com.openxc.VehicleManager;
import android.widget.ListView;
import android.widget.ArrayAdapter;
public class PipelineStatusUpdateTask extends TimerTask {
private VehicleManager mVehicleManager;
private Activity mActivity;
private ListView mSourceListView;
private ListView mSinkListView;
public PipelineStatusUpdateTask(VehicleManager vehicleService,
Activity activity, ListView sourceListView, ListView sinkListView) {
mVehicleManager = vehicleService;
mActivity = activity;
mSourceListView = sourceListView;
mSinkListView = sinkListView;
}
public void run() {
mActivity.runOnUiThread(new Runnable() {
public void run() {
mSourceListView.setAdapter(new ArrayAdapter<Object>(mActivity,
android.R.layout.simple_list_item_1,
mVehicleManager.getSourceSummaries().toArray()));
mSinkListView.setAdapter(new ArrayAdapter<Object>(mActivity,
android.R.layout.simple_list_item_1,
mVehicleManager.getSinkSummaries().toArray()));
}
});
}
}
|
Update reverse a linked list code | public class Program {
public static void main(String[] args) {
LinkedList head = new LinkedList(new int[] {1, 2, 3, 4}, LinkedList.Type.Singly);
head = reverseSingly(head);
head.assertEquals(new int[] {4, 3, 2, 1}, LinkedList.Type.Singly);
head = new LinkedList(new int[] {1, 2, 3, 4}, LinkedList.Type.Doubly);
head = reverseDoubly(head);
head.assertEquals(new int[] {4, 3, 2, 1}, LinkedList.Type.Doubly);
System.out.println("Tests passed");
}
public static LinkedList reverseSingly(LinkedList head) {
if (head != null) {
LinkedList prev = null;
while (head.next != null) {
LinkedList next = head.next;
head.next = prev;
prev = head;
head = next;
}
head.next = prev;
}
return head;
}
public static LinkedList reverseDoubly(LinkedList head) {
while (head != null) {
LinkedList temp = head.next;
head.next = head.prev;
head.prev = temp;
if (temp == null)
break;
head = temp;
}
return head;
}
}
| public class Program {
public static void main(String[] args) {
LinkedList head = new LinkedList(new int[] {1, 2, 3, 4}, LinkedList.Type.Singly);
head = reverseSingly(head);
head.assertEquals(new int[] {4, 3, 2, 1}, LinkedList.Type.Singly);
head = new LinkedList(new int[] {1, 2, 3, 4}, LinkedList.Type.Doubly);
head = reverseDoubly(head);
head.assertEquals(new int[] {4, 3, 2, 1}, LinkedList.Type.Doubly);
System.out.println("Tests passed");
}
public static LinkedList reverseSingly(LinkedList head) {
if (head != null) {
LinkedList prev = null;
while (head.next != null) {
LinkedList next = head.next;
head.next = prev;
prev = head;
head = next;
}
head.next = prev;
}
return head;
}
public static LinkedList reverseDoubly(LinkedList head) {
while (head != null) {
LinkedList temp = head.next;
head.next = head.prev;
head.prev = temp;
if (temp == null)
return head;
head = temp;
}
return head;
}
}
|
Define type of `props.tag` as a string | import React from "react";
export default class ResponsiveComponent extends React.Component {
constructor(props) {
super(props);
this.state = { canRender: false };
this._mediaQueryList = null;
this._updateState = this._updateState.bind(this);
}
componentWillMount() {
this._tryToRender();
}
componentWillUnmount() {
this._dispose();
}
componentWillReceiveProps(nextProps) {
this._tryToRender(nextProps);
}
_tryToRender(props = this.props) {
if (!props.query) {
throw new Error("ResponsiveComponent: `query` is a required prop!");
}
this._dispose();
this._mediaQueryList = global.matchMedia(props.query);
this._mediaQueryList.addListener(this._updateState);
this._updateState();
}
_dispose() {
if (this._mediaQueryList) {
this._mediaQueryList.removeListener(this._updateState);
this._mediaQueryList = null;
}
}
_updateState() {
if (this._mediaQueryList.matches !== this.state.canRender) {
this.setState({ canRender: this._mediaQueryList.matches });
}
}
get _display() {
return React.createElement(this.props.tag || "div",
{ className: "responsive-component" },
this.props.children);
}
render() {
return this.state.canRender ? this._display : null;
}
}
ResponsiveComponent.propTypes = {
query: React.PropTypes.string.isRequired,
tag: React.PropTypes.string
};
| import React from "react";
export default class ResponsiveComponent extends React.Component {
constructor(props) {
super(props);
this.state = { canRender: false };
this._mediaQueryList = null;
this._updateState = this._updateState.bind(this);
}
componentWillMount() {
this._tryToRender();
}
componentWillUnmount() {
this._dispose();
}
componentWillReceiveProps(nextProps) {
this._tryToRender(nextProps);
}
_tryToRender(props = this.props) {
if (!props.query) {
throw new Error("ResponsiveComponent: `query` is a required prop!");
}
this._dispose();
this._mediaQueryList = global.matchMedia(props.query);
this._mediaQueryList.addListener(this._updateState);
this._updateState();
}
_dispose() {
if (this._mediaQueryList) {
this._mediaQueryList.removeListener(this._updateState);
this._mediaQueryList = null;
}
}
_updateState() {
if (this._mediaQueryList.matches !== this.state.canRender) {
this.setState({ canRender: this._mediaQueryList.matches });
}
}
get _display() {
return React.createElement(this.props.tag || "div",
{ className: "responsive-component" },
this.props.children);
}
render() {
return this.state.canRender ? this._display : null;
}
}
ResponsiveComponent.propTypes = { query: React.PropTypes.string.isRequired };
|
Add FF, Safari and Chrome to tests | module.exports = function(grunt) {
var browsers = [
{
browserName: 'internet explorer',
platform: 'Windows 10',
version: '11.285'
},
{
browserName: 'chrome',
platform: 'Linux'
},
{
browserName: 'firefox',
platform: 'Linux'
},
{
browserName: 'safari',
platform: 'Linux'
}
];
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: {
options: {
base: '',
port: 9999
}
}
},
'saucelabs-jasmine': {
all: {
options: {
urls: ['http://127.0.0.1:9999/test'],
browsers: browsers,
build: process.env.TRAVIS_JOB_ID,
testname: 'JSON-Patch test',
throttled: 3,
sauceConfig: {
'video-upload-on-pass': false
}
}
}
},
watch: {}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.registerTask('default', ['connect', 'saucelabs-jasmine']);
};
| module.exports = function(grunt) {
var browsers = [
{
browserName: 'internet explorer',
platform: 'Windows 10',
version: '11.285'
}
];
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: {
options: {
base: '',
port: 9999
}
}
},
'saucelabs-jasmine': {
all: {
options: {
urls: ['http://127.0.0.1:9999/test'],
browsers: browsers,
build: process.env.TRAVIS_JOB_ID,
testname: 'JSON-Patch test',
throttled: 3,
sauceConfig: {
'video-upload-on-pass': false
}
}
}
},
watch: {}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.registerTask('default', ['connect', 'saucelabs-jasmine']);
};
|
Fix bug with csrf token | /**
* @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC
* @link http://2amigos.us
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
if (typeof dosamigos == "undefined" || !dosamigos) {
var dosamigos = {};
}
dosamigos.ckEditorWidget = (function ($) {
var pub = {
registerOnChangeHandler: function (id) {
CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () {
CKEDITOR.instances[id].updateElement();
$('#' + id).trigger('change');
return false;
});
},
registerCsrfImageUploadHandler: function () {
yii & $(document).off('click', '.cke_dialog_tabs a:eq(1), .cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(1), .cke_dialog_tabs a:eq(2)', function () {
var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
if (!$form.find('input[name=' + csrfName + ']').length) {
var csrfTokenInput = $('<input/>').attr({
'type': 'hidden',
'name': csrfName
}).val(yii.getCsrfToken());
$form.append(csrfTokenInput);
}
});
}
};
return pub;
})(jQuery);
| /**
* @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC
* @link http://2amigos.us
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
if (typeof dosamigos == "undefined" || !dosamigos) {
var dosamigos = {};
}
dosamigos.ckEditorWidget = (function ($) {
var pub = {
registerOnChangeHandler: function (id) {
CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () {
CKEDITOR.instances[id].updateElement();
$('#' + id).trigger('change');
return false;
});
},
registerCsrfImageUploadHandler: function () {
yii & $(document).off('click', '.cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(2)', function () {
var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
if (!$form.find('input[name=' + csrfName + ']').length) {
var csrfTokenInput = $('<input/>').attr({
'type': 'hidden',
'name': csrfName
}).val(yii.getCsrfToken());
$form.append(csrfTokenInput);
}
});
}
};
return pub;
})(jQuery);
|
Replace the test data set with this one. | import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data('small_64D')
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals)
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
for sh_order in [4, 6]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
op.join(tmpdir, 'bvecs.txt'),
out_dir=tmpdir, sh_order=sh_order)
npt.assert_(op.exists(fname))
sh_coeffs_img = nib.load(fname)
npt.assert_equal(sh_order,
calculate_max_order(sh_coeffs_img.shape[-1]))
| import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data()
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals)
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
for sh_order in [4, 8]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
op.join(tmpdir, 'bvecs.txt'),
out_dir=tmpdir, sh_order=sh_order)
npt.assert_(op.exists(fname))
sh_coeffs_img = nib.load(fname)
npt.assert_equal(sh_order,
calculate_max_order(sh_coeffs_img.shape[-1]))
|
Set produced Logger as DefaultBean | package io.quarkus.arc.runtime;
import java.lang.annotation.Annotation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.PreDestroy;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Singleton;
import org.jboss.logging.Logger;
import io.quarkus.arc.DefaultBean;
import io.quarkus.arc.log.LoggerName;
@Singleton
public class LoggerProducer {
private final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>();
@Dependent
@Produces
@DefaultBean
Logger getSimpleLogger(InjectionPoint injectionPoint) {
return loggers.computeIfAbsent(injectionPoint.getMember().getDeclaringClass().getName(), Logger::getLogger);
}
@LoggerName("")
@Dependent
@Produces
@DefaultBean
Logger getLoggerWithCustomName(InjectionPoint injectionPoint) {
String name = null;
for (Annotation qualifier : injectionPoint.getQualifiers()) {
if (qualifier.annotationType().equals(LoggerName.class)) {
name = ((LoggerName) qualifier).value();
}
}
if (name == null || name.isEmpty()) {
throw new IllegalStateException("Unable to derive the logger name at " + injectionPoint);
}
return loggers.computeIfAbsent(name, Logger::getLogger);
}
@PreDestroy
void destroy() {
loggers.clear();
}
}
| package io.quarkus.arc.runtime;
import java.lang.annotation.Annotation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.PreDestroy;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Singleton;
import org.jboss.logging.Logger;
import io.quarkus.arc.log.LoggerName;
@Singleton
public class LoggerProducer {
private final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>();
@Dependent
@Produces
Logger getSimpleLogger(InjectionPoint injectionPoint) {
return loggers.computeIfAbsent(injectionPoint.getMember().getDeclaringClass().getName(), Logger::getLogger);
}
@LoggerName("")
@Dependent
@Produces
Logger getLoggerWithCustomName(InjectionPoint injectionPoint) {
String name = null;
for (Annotation qualifier : injectionPoint.getQualifiers()) {
if (qualifier.annotationType().equals(LoggerName.class)) {
name = ((LoggerName) qualifier).value();
}
}
if (name == null || name.isEmpty()) {
throw new IllegalStateException("Unable to derive the logger name at " + injectionPoint);
}
return loggers.computeIfAbsent(name, Logger::getLogger);
}
@PreDestroy
void destroy() {
loggers.clear();
}
}
|
tests: Fix error in test_preprocessor_cur (xrange -> range) | import unittest
from Orange.data import Table
from Orange.preprocess import ProjectCUR
class TestCURProjector(unittest.TestCase):
def test_project_cur_default(self):
data = Table("ionosphere")
projector = ProjectCUR()
data_cur = projector(data)
for i in range(data_cur.X.shape[1]):
sbtr = (data.X - data_cur.X[:, i][:, None]) == 0
self.assertTrue(((sbtr.sum(0) == data.X.shape[0])).any())
self.assertTrue(data_cur.X.shape[1] <= data.X.shape[1])
self.assertTrue((data.metas == data_cur.metas).all())
self.assertTrue((data.Y == data_cur.Y).any())
def test_project_cur(self):
data = Table("ionosphere")
projector = ProjectCUR(rank=3, max_error=1)
data_cur = projector(data)
for i in range(data_cur.X.shape[1]):
sbtr = (data.X - data_cur.X[:, i][:, None]) == 0
self.assertTrue(((sbtr.sum(0) == data.X.shape[0])).any())
self.assertTrue(data_cur.X.shape[1] <= data.X.shape[1])
self.assertTrue((data.metas == data_cur.metas).all())
self.assertTrue((data.Y == data_cur.Y).any())
| import unittest
from Orange.data import Table
from Orange.preprocess import ProjectCUR
class TestCURProjector(unittest.TestCase):
def test_project_cur_default(self):
data = Table("ionosphere")
projector = ProjectCUR()
data_cur = projector(data)
for i in xrange(data_cur.X.shape[1]):
sbtr = (data.X - data_cur.X[:, i][:, None]) == 0
self.assertTrue(((sbtr.sum(0) == data.X.shape[0])).any())
self.assertTrue(data_cur.X.shape[1] <= data.X.shape[1])
self.assertTrue((data.metas == data_cur.metas).all())
self.assertTrue((data.Y == data_cur.Y).any())
def test_project_cur(self):
data = Table("ionosphere")
projector = ProjectCUR(rank=3, max_error=1)
data_cur = projector(data)
for i in xrange(data_cur.X.shape[1]):
sbtr = (data.X - data_cur.X[:, i][:, None]) == 0
self.assertTrue(((sbtr.sum(0) == data.X.shape[0])).any())
self.assertTrue(data_cur.X.shape[1] <= data.X.shape[1])
self.assertTrue((data.metas == data_cur.metas).all())
self.assertTrue((data.Y == data_cur.Y).any())
|
conan: Copy find modules to root of module path | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ClangTidyTargetCMakeConan(ConanFile):
name = "clang-tidy-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/clang-tidy-target-cmake"
license = "MIT"
def source(self):
zip_name = "clang-tidy-target-cmake.zip"
download("https://github.com/polysquare/"
"clang-tidy-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="Find*.cmake",
dst="",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/clang-tidy-target-cmake",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
| from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ClangTidyTargetCMakeConan(ConanFile):
name = "clang-tidy-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/clang-tidy-target-cmake"
license = "MIT"
def source(self):
zip_name = "clang-tidy-target-cmake.zip"
download("https://github.com/polysquare/"
"clang-tidy-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/clang-tidy-target-cmake",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
|
Use the generic names for these as well. | #!python3
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup (
name = 'PyDoom rendering module',
ext_modules = cythonize (
[
Extension (
"pydoom.extensions.video",
["pydoom/extensions/video.pyx", "pydoom/extensions/cvideo.c"],
include_dirs = [
"extern/glew-1.11.0/include",
"extern/SDL2-2.0.3/include",
],
libraries = [
"GL",
"GLEW",
"SDL2",
"SDL2main",
]
),
Extension (
"pydoom.extensions.utility",
["pydoom/extensions/utility.pyx", "pydoom/extensions/cutility.c"],
include_dirs = [
"extern/SDL2-2.0.3/include"
],
libraries = [
"extern/SDL2-2.0.3/lib/x64/SDL2",
"extern/SDL2-2.0.3/lib/x64/SDL2main",
"extern/SDL2-2.0.3/lib/x64/SDL2test",
]
)
]
)
)
| #!python3
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup (
name = 'PyDoom rendering module',
ext_modules = cythonize (
[
Extension (
"pydoom.extensions.video",
["pydoom/extensions/video.pyx", "pydoom/extensions/cvideo.c"],
include_dirs = [
"extern/glew-1.11.0/include",
"extern/SDL2-2.0.3/include",
],
libraries = [
"GL",
"extern/glew-1.11.0/lib/Release/x64/glew32",
"extern/SDL2-2.0.3/lib/x64/SDL2",
"extern/SDL2-2.0.3/lib/x64/SDL2main",
"extern/SDL2-2.0.3/lib/x64/SDL2test",
]
),
Extension (
"pydoom.extensions.utility",
["pydoom/extensions/utility.pyx", "pydoom/extensions/cutility.c"],
include_dirs = [
"extern/SDL2-2.0.3/include"
],
libraries = [
"extern/SDL2-2.0.3/lib/x64/SDL2",
"extern/SDL2-2.0.3/lib/x64/SDL2main",
"extern/SDL2-2.0.3/lib/x64/SDL2test",
]
)
]
)
)
|
Set access_policy for messaging's dispatcher
oslo.messaging allow dispatcher to restrict endpoint methods since
5.11.0 in d3a8f280ebd6fd12865fd20c4d772774e39aefa2, set with
DefaultRPCAccessPolicy to fix FutureWarning like:
"The access_policy argument is changing its default value to <class
'oslo_messaging.rpc.dispatcher.DefaultRPCAccessPolicy'> in version '?',
please update the code to explicitly set None as the value:
access_policy defaults to LegacyRPCAccessPolicy which exposes private
methods. Explicitly set access_policy to DefaultRPCAccessPolicy or
ExplicitRPCAccessPolicy.
Change-Id: Ib90013909237816cf906d584778f5e0ce7152fab | # Copyright 2015 - Alcatel-Lucent
# Copyright 2016 - Nokia
#
# 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 oslo_config import cfg
import oslo_messaging as messaging
from oslo_messaging.rpc import dispatcher
OPTS = [
cfg.StrOpt('rpc_topic',
default='rpcapiv1',
help='The topic vitrage listens on'),
]
def set_defaults(control_exchange):
messaging.set_transport_defaults(control_exchange)
def get_client(transport, target, version_cap=None, serializer=None):
assert transport is not None
return messaging.RPCClient(transport,
target,
version_cap=version_cap,
serializer=serializer)
def get_server(target, endpoints, transport, serializer=None):
assert transport is not None
access_policy = dispatcher.DefaultRPCAccessPolicy
return messaging.get_rpc_server(transport,
target,
endpoints,
executor='eventlet',
serializer=serializer,
access_policy=access_policy)
| # Copyright 2015 - Alcatel-Lucent
# Copyright 2016 - Nokia
#
# 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 oslo_config import cfg
import oslo_messaging as messaging
OPTS = [
cfg.StrOpt('rpc_topic',
default='rpcapiv1',
help='The topic vitrage listens on'),
]
def set_defaults(control_exchange):
messaging.set_transport_defaults(control_exchange)
def get_client(transport, target, version_cap=None, serializer=None):
assert transport is not None
return messaging.RPCClient(transport,
target,
version_cap=version_cap,
serializer=serializer)
def get_server(target, endpoints, transport, serializer=None):
assert transport is not None
return messaging.get_rpc_server(transport,
target,
endpoints,
executor='eventlet',
serializer=serializer)
|
Use $document instead of document for on fn
Signed-off-by: gconsidine <[email protected]> | const templateUrl = require('~components/layout/side-nav.partial.html');
let $document;
function atSideNavLink (scope, element, attrs, ctrl) {
scope.layoutVm = ctrl;
$document.on('click', (e) => {
if ($(e.target).parents('.at-Layout-side').length === 0) {
scope.$emit('clickOutsideSideNav');
}
});
}
function AtSideNavController ($scope, $window) {
const vm = this || {};
const breakpoint = 700;
vm.isExpanded = false;
vm.toggleExpansion = () => {
vm.isExpanded = !vm.isExpanded;
};
$scope.$watch('layoutVm.currentState', () => {
if ($window.innerWidth <= breakpoint) {
vm.isExpanded = false;
}
});
$scope.$on('clickOutsideSideNav', () => {
if ($window.innerWidth <= breakpoint) {
vm.isExpanded = false;
}
});
}
AtSideNavController.$inject = ['$scope', '$window'];
function atSideNav (_$document_) {
$document = _$document_;
return {
restrict: 'E',
replace: true,
require: '^^atLayout',
controller: AtSideNavController,
controllerAs: 'vm',
link: atSideNavLink,
transclude: true,
templateUrl,
scope: {
}
};
}
atSideNav.$inject = ['$document'];
export default atSideNav;
| const templateUrl = require('~components/layout/side-nav.partial.html');
function atSideNavLink (scope, element, attrs, ctrl) {
scope.layoutVm = ctrl;
document.on('click', (e) => {
if ($(e.target).parents('.at-Layout-side').length === 0) {
scope.$emit('clickOutsideSideNav');
}
});
}
function AtSideNavController ($scope, $window) {
const vm = this || {};
const breakpoint = 700;
vm.isExpanded = false;
vm.toggleExpansion = () => {
vm.isExpanded = !vm.isExpanded;
};
$scope.$watch('layoutVm.currentState', () => {
if ($window.innerWidth <= breakpoint) {
vm.isExpanded = false;
}
});
$scope.$on('clickOutsideSideNav', () => {
if ($window.innerWidth <= breakpoint) {
vm.isExpanded = false;
}
});
}
AtSideNavController.$inject = ['$scope', '$window'];
function atSideNav () {
return {
restrict: 'E',
replace: true,
require: '^^atLayout',
controller: AtSideNavController,
controllerAs: 'vm',
link: atSideNavLink,
transclude: true,
templateUrl,
scope: {
}
};
}
export default atSideNav;
|
Add Type attribute to password (security header) | <?php
/**
* Created by PhpStorm.
* User: Giansalex
* Date: 15/07/2017
* Time: 22:54.
*/
namespace Greenter\Ws\Header;
use SoapHeader;
use SoapVar;
/**
* Class WSSESecurityHeader.
*/
class WSSESecurityHeader extends SoapHeader
{
const WSS_NAMESPACE = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
const PASSWORD_TYPE = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText';
const PASSWORD_FORMAT = '<o:Password xmlns:o="%s" Type="%s">%s</o:Password>';
public function __construct($username, $password)
{
$passwordXml = sprintf(self::PASSWORD_FORMAT, self::WSS_NAMESPACE, self::PASSWORD_TYPE, $password);
$security = new SoapVar(
[new SoapVar(
[
new SoapVar($username, XSD_STRING, null, null, 'Username', self::WSS_NAMESPACE),
new SoapVar($passwordXml, XSD_ANYXML),
],
SOAP_ENC_OBJECT,
null,
null,
'UsernameToken',
self::WSS_NAMESPACE
)],
SOAP_ENC_OBJECT
);
$this->SoapHeader(self::WSS_NAMESPACE, 'Security', $security, false);
}
}
| <?php
/**
* Created by PhpStorm.
* User: Giansalex
* Date: 15/07/2017
* Time: 22:54.
*/
namespace Greenter\Ws\Header;
use SoapHeader;
use SoapVar;
/**
* Class WSSESecurityHeader.
*/
class WSSESecurityHeader extends SoapHeader
{
const WSS_NAMESPACE = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
public function __construct($username, $password)
{
$security = new SoapVar(
[new SoapVar(
[
new SoapVar($username, XSD_STRING, null, null, 'Username', self::WSS_NAMESPACE),
new SoapVar($password, XSD_STRING, null, null, 'Password', self::WSS_NAMESPACE),
],
SOAP_ENC_OBJECT,
null,
null,
'UsernameToken',
self::WSS_NAMESPACE
)],
SOAP_ENC_OBJECT
);
$this->SoapHeader(self::WSS_NAMESPACE, 'Security', $security, false);
}
}
|
fix(command): Fix NPE when caching commands | package valandur.webapi.cache.command;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.text.Text;
import valandur.webapi.api.cache.command.ICachedCommand;
import valandur.webapi.cache.CachedObject;
import static valandur.webapi.command.CommandSource.instance;
public class CachedCommand extends CachedObject implements ICachedCommand {
private String name;
@Override
public String getName() {
return name;
}
private String description;
@Override
public String getDescription() {
return description;
}
private String[] aliases;
@Override
public String[] getAliases() {
return aliases;
}
private String usage;
@Override
public String getUsage() {
return usage;
}
private String help;
@Override
public String getHelp() {
return help;
}
public CachedCommand(CommandMapping cmd) {
super(null);
this.name = cmd.getPrimaryAlias();
this.aliases = cmd.getAllAliases().toArray(new String[cmd.getAllAliases().size()]);
try {
this.usage = cmd.getCallable().getUsage(instance).toPlain();
this.description = cmd.getCallable().getShortDescription(instance).orElse(Text.EMPTY).toPlain();
this.help = cmd.getCallable().getHelp(instance).orElse(Text.EMPTY).toPlain();
} catch (Exception ignored) {}
}
@Override
public String getLink() {
return "/api/cmd/" + name;
}
}
| package valandur.webapi.cache.command;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.text.Text;
import valandur.webapi.api.cache.command.ICachedCommand;
import valandur.webapi.cache.CachedObject;
import static valandur.webapi.command.CommandSource.instance;
public class CachedCommand extends CachedObject implements ICachedCommand {
private String name;
@Override
public String getName() {
return name;
}
private String description;
@Override
public String getDescription() {
return description;
}
private String[] aliases;
@Override
public String[] getAliases() {
return aliases;
}
private String usage;
@Override
public String getUsage() {
return usage;
}
private String help;
@Override
public String getHelp() {
return help;
}
public CachedCommand(CommandMapping cmd) {
super(null);
this.name = cmd.getPrimaryAlias();
this.aliases = cmd.getAllAliases().toArray(new String[cmd.getAllAliases().size()]);
try {
this.usage = cmd.getCallable().getUsage(instance).toPlain();
} catch (Exception ignored) {}
this.description = cmd.getCallable().getShortDescription(instance).orElse(Text.EMPTY).toPlain();
this.help = cmd.getCallable().getHelp(instance).orElse(Text.EMPTY).toPlain();
}
@Override
public String getLink() {
return "/api/cmd/" + name;
}
}
|
Add geocode delay to prevent DDOS | class GeocodeAPI {
constructor(geocodeCache) {
this.cache = geocodeCache;
}
async getGeocode(cityName, postCode) {
const location = this.makeLocation(cityName, postCode);
const cachedGeocode = this.cache.geocodeWithLocation(location);
if (cachedGeocode) {
log(`Geocode for '${location}' was already in cache : ${JSON.stringify(cachedGeocode)}`);
return cachedGeocode;
}
log(`Will retrieve "${location}" from data gouv api...`);
// wait 10 ms to prevent triggering anti-ddos chrome protection (https://www.chromium.org/throttling)
var dt = new Date(); while ((new Date()) - dt <= 10) { }
return await this.retrieveGeocodeFromDataGouv(cityName, postCode);
}
async retrieveGeocodeFromDataGouv(cityName, postCode) {
const location = this.makeLocation(cityName, postCode);
const response = await fetch(`https://api-adresse.data.gouv.fr/search/?q=${cityName}&postcode=${postCode}&limit=1`);
const json = await response.json();
const feature = json.features[0];
if (!feature) { throw new Error(`No feature was found for location "${location}. Received JSON : ${json}"`)}
const coordinates = feature.geometry.coordinates;
const longitude = coordinates[0];
const latitude = coordinates[1];
const geocode = new Geocode(location, longitude, latitude);
this.cache.cacheGeocode(geocode);
return geocode;
}
makeLocation(cityName, postCode) {
return `${cityName} ${postCode}`;
}
}
| class GeocodeAPI {
constructor(geocodeCache) {
this.cache = geocodeCache;
}
async getGeocode(cityName, postCode) {
const location = this.makeLocation(cityName, postCode);
const cachedGeocode = this.cache.geocodeWithLocation(location);
if (cachedGeocode) {
log(`Geocode for '${location}' was already in cache : ${JSON.stringify(cachedGeocode)}`);
return cachedGeocode;
}
log(`Will retrieve "${location}" from data gouv api...`);
return await this.retrieveGeocodeFromDataGouv(cityName, postCode);
}
async retrieveGeocodeFromDataGouv(cityName, postCode) {
const location = this.makeLocation(cityName, postCode);
const response = await fetch(`https://api-adresse.data.gouv.fr/search/?q=${cityName}&postcode=${postCode}&limit=1`);
const json = await response.json();
const feature = json.features[0];
if (!feature) { throw new Error(`No feature was found for location "${location}. Received JSON : ${json}"`)}
const coordinates = feature.geometry.coordinates;
const longitude = coordinates[0];
const latitude = coordinates[1];
const geocode = new Geocode(location, longitude, latitude);
this.cache.cacheGeocode(geocode);
return geocode;
}
makeLocation(cityName, postCode) {
return `${cityName} ${postCode}`;
}
}
|
Fix event behaviour when typing | import {
Component,
h
} from 'skatejs';
import styles from './styles';
const deleteCode = 8;
customElements.define('sk-tags', class extends Component {
static get props() {
return {
delimiter: {
attribute: true,
default: ' '
},
tags: {
default: []
}
};
}
renderCallback() {
const tags = this.tags;
const tagElements = tags.map(t => h('span', {class: 'tag'}, t));
return [
h('style', styles),
h('div', {class: 'wrapper'},
h('span', ...tagElements),
h('input', {
oninput: this.onInput(),
onkeydown: this.onKeydown(),
autofocus: true,
class: 'input'
})
)
];
}
onKeydown() {
const component = this;
return function(e) {
const value = this.value;
const isDel = e.keyCode === deleteCode;
if (isDel && value.length <= 0) {
component.removeTag();
}
}
}
onInput() {
const component = this;
return function(e) {
const lastChar = this.value.substr(-1);
const value = this.value.trim();
const isDelimiter = lastChar === component.delimiter;
if (value && isDelimiter) {
component.addTag(value);
this.value = '';
}
};
}
addTag(value) {
this.tags = this.tags.concat(value);
}
removeTag() {
const tags = this.tags.slice();
tags.pop();
this.tags = tags;
}
}); | import {
Component,
h
} from 'skatejs';
import styles from './styles';
const deleteCode = 8;
customElements.define('sk-tags', class extends Component {
static get props() {
return {
delimiter: {
attribute: true,
default: ' '
},
tags: {
default: []
}
};
}
renderCallback() {
const tags = this.tags;
const tagElements = tags.map(t => h('span', {class: 'tag'}, t));
return [
h('style', styles),
h('div', {class: 'wrapper'},
h('span', ...tagElements),
h('input', {
onkeyup: this.onKey(),
autofocus: true,
class: 'input'
})
)
];
}
onKey() {
const component = this;
return function(e) {
const lastChar = this.value.substr(-1);
const value = this.value.trim();
const code = e.keyCode;
const isDel = code === deleteCode;
const isDelimiter = lastChar === component.delimiter;
if (isDel && value.length <= 0) {
component.removeTag();
}
if (value && isDelimiter) {
component.addTag(value);
this.value = '';
}
};
}
addTag(value) {
this.tags = this.tags.concat(value);
}
removeTag() {
const tags = this.tags.slice();
tags.pop();
this.tags = tags;
}
}); |
Fix bug when loading projects | package org.deidentifier.arx.gui.view.impl.analyze;
import java.awt.Panel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
public abstract class ViewStatistics extends Panel{
private static final long serialVersionUID = 5170104283288654748L;
protected ModelPart target;
protected Model model;
/**
* Returns the data handle
* @return
*/
protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
}
| package org.deidentifier.arx.gui.view.impl.analyze;
import java.awt.Panel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
public abstract class ViewStatistics extends Panel{
private static final long serialVersionUID = 5170104283288654748L;
protected ModelPart target;
protected Model model;
/**
* Returns the data handle
* @return
*/
protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
}
|
Increase version number for Python 3.9 support | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="[email protected]",
name="stego_lsb",
version="1.3.1",
description="stego lsb",
keywords="stego lsb",
license="MIT",
long_description=readme,
long_description_content_type="text/markdown",
url="https://github.com/ragibson/Steganography",
install_requires=requirements,
entry_points="""
[console_scripts]
stegolsb=stego_lsb.cli:main
""",
include_package_data=True,
packages=find_packages(include=["stego_lsb"]),
zip_safe=False,
python_requires=">=3.6",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="[email protected]",
name="stego_lsb",
version="1.3",
description="stego lsb",
keywords="stego lsb",
license="MIT",
long_description=readme,
long_description_content_type="text/markdown",
url="https://github.com/ragibson/Steganography",
install_requires=requirements,
entry_points="""
[console_scripts]
stegolsb=stego_lsb.cli:main
""",
include_package_data=True,
packages=find_packages(include=["stego_lsb"]),
zip_safe=False,
python_requires=">=3.6",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
)
|
Change path tot adminlte less file
Copy the fonts to build folder because we will be using elixir | var elixir = require('laravel-elixir');
elixir(function(mix) {
mix.copy(
'node_modules/bootstrap/dist/fonts',
'public/build/fonts'
);
mix.copy(
'node_modules/font-awesome/fonts',
'public/build/fonts'
);
mix.copy(
'node_modules/ionicons/dist/fonts',
'public/build/fonts'
);
mix.scripts([
'../../../node_modules/jquery/dist/jquery.min.js',
'../../../node_modules/bootstrap/dist/js/bootstrap.min.js'
], 'public/js/vendor.js');
mix.scripts([
'app.js'
], 'public/js/app.js');
mix.less([
'../../../node_modules/bootstrap/less/bootstrap.less',
'../../../node_modules/font-awesome/less/font-awesome.less',
'../../../node_modules/ionicons/dist/css/ionicons.min.css',
'adminlte/AdminLTE.less',
'adminlte/skins/_all-skins.less'
], 'public/css/vendor.css');
mix.less([
'app.less'
], 'public/css/app.css');
mix.less([
'welcome.less'
], 'public/css/welcome.css');
mix.version([
'public/css/app.css',
'public/css/welcome.css',
'public/css/vendor.css',
'public/js/app.js',
'public/js/vendor.js'
]);
}); | var elixir = require('laravel-elixir');
elixir(function(mix) {
mix.copy(
'node_modules/bootstrap/dist/fonts',
'public/fonts'
);
mix.copy(
'node_modules/font-awesome/fonts',
'public/fonts'
);
mix.copy(
'node_modules/ionicons/dist/fonts',
'public/fonts'
);
mix.scripts([
'../../../node_modules/jquery/dist/jquery.min.js',
'../../../node_modules/bootstrap/dist/js/bootstrap.min.js'
], 'public/js/vendor.js');
mix.scripts([
'app.js'
], 'public/js/app.js');
mix.less([
'../../../node_modules/bootstrap/less/bootstrap.less',
'../../../node_modules/font-awesome/less/font-awesome.less',
'../../../node_modules/ionicons/dist/css/ionicons.min.css',
'admin-lte/AdminLTE.less',
'admin-lte/skins/_all-skins.less'
], 'public/css/vendor.css');
mix.less([
'app.less'
], 'public/css/app.css');
mix.less([
'welcome.less'
], 'public/css/welcome.css');
mix.version([
'public/css/app.css',
'public/css/welcome.css',
'public/css/vendor.css',
'public/js/app.js',
'public/js/vendor.js'
]);
}); |
Make table prop columns an array of column objects | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import TableRow from './TableRow/index.js'
import Button from '../../Components/Button/index.js'
export default class Table extends Component {
static propTypes = {
tableName: PropTypes.string,
columns: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
type: PropTypes.string
}).isRequired)
}
static defaultProps = {
columns: {
name: "",
type: "text"
}
}
state = {
addedRows: []
}
addRow = () => {
const defaultValues = this.props.columns.map(() => {return ""})
const newRow = <TableRow key={this.state.addedRows.length + 1} editing cellTypes={this.props.columns.map((column) => {return column.type})} cellValues={defaultValues} />
this.setState((prevState) => ({
addedRows: prevState.addedRows.concat([newRow])
}))
}
render(){
if(this.props.readOnly){
return(
<div>
{this.props.children}
</div>
)
}else{
return(
<div>
<TableRow
readOnly
cellValues={this.props.columns.map((column) => {return column.name})}
cellTypes={this.props.columns.map((column) => {return column.type})}
/>
{this.props.children}
{this.state.addedRows}
<Button
className="round"
buttonText="+"
onClick={this.addRow}
/>
</div>
)
}
}
} | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import TableRow from './TableRow/index.js'
import Button from '../../Components/Button/index.js'
export default class Table extends Component {
static propTypes = {
tableName: PropTypes.string,
columnTypes: PropTypes.object.isRequired
}
state = {
addedRows: []
}
addRow = () => {
const defaultValues = Object.keys(this.props.columnTypes).map(() => {return ""})
const newRow = <TableRow key={this.state.addedRows.length + 1} editing cellTypes={Object.values(this.props.columnTypes)} cellValues={defaultValues} />
this.setState((prevState) => ({
addedRows: prevState.addedRows.concat([newRow])
}))
}
render(){
if(this.props.readOnly){
return(
<div>
{this.props.children}
</div>
)
}else{
return(
<div>
<TableRow
readOnly
cellValues={Object.keys(this.props.columnTypes)}
cellTypes={Object.values(this.props.columnTypes)}
/>
{this.props.children}
{this.state.addedRows}
<Button
className="round"
buttonText="+"
onClick={this.addRow}
/>
</div>
)
}
}
} |
Set default ordering for blog post tags | from django.db import models
class BlogPostTag(models.Model):
name = models.CharField(max_length=255)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class BlogPost(models.Model):
datetime = models.DateTimeField()
title = models.CharField(max_length=255)
content = models.TextField()
live = models.BooleanField(default=False)
blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True)
class Meta:
ordering = ['-datetime']
def __str__(self):
return '%s (%s)' % (self.title, self.datetime)
def __repr__(self):
return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title)
def prev_post(self):
prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max']
try:
return BlogPost.objects.filter(datetime=prev_datetime)[0]
except IndexError:
return None
def next_post(self):
next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min']
try:
return BlogPost.objects.filter(datetime=next_datetime)[0]
except IndexError:
return None
| from django.db import models
class BlogPostTag(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class BlogPost(models.Model):
datetime = models.DateTimeField()
title = models.CharField(max_length=255)
content = models.TextField()
live = models.BooleanField(default=False)
blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True)
class Meta:
ordering = ['-datetime']
def __str__(self):
return '%s (%s)' % (self.title, self.datetime)
def __repr__(self):
return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title)
def prev_post(self):
prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max']
try:
return BlogPost.objects.filter(datetime=prev_datetime)[0]
except IndexError:
return None
def next_post(self):
next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min']
try:
return BlogPost.objects.filter(datetime=next_datetime)[0]
except IndexError:
return None
|
Switch <TouchableHighlight> for simpler <TouchableOpacity> | /**
* Created by BK on 21/06/16.
*
* @flow
*/
'use strict';
import React, { Component } from 'react';
import {
Text,
View,
TouchableOpacity,
StyleSheet
} from 'react-native';
type Props = {
row: {
title: string,
desc: string,
reward: string,
complete: string
}
}
export default class TasksListRow extends Component {
props: Props;
render() {
return (
<TouchableOpacity>
<View style={styles.container}>
<View style={styles.leftColumn}>
<Text style={styles.title}>{this.props.row.title}</Text>
<Text style={styles.desc}>{this.props.row.desc}</Text>
</View>
<View style={styles.rightColumn}>
<Text style={styles.reward}>{this.props.row.reward}</Text>
<Text style={styles.complete}>{this.props.row.complete}</Text>
</View>
</View>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
backgroundColor: '#dedede'
},
leftColumn: {
flex: 1,
backgroundColor: '#ededed',
justifyContent: 'center',
alignItems: 'center'
},
rightColumn: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
title: {
fontSize: 20,
},
desc: {
},
reward: {
},
complete: {
}
})
| /**
* Created by BK on 21/06/16.
*
* @flow
*/
'use strict';
import React, { Component } from 'react';
import {
Text,
View,
TouchableHighlight,
StyleSheet
} from 'react-native';
type Props = {
row: {
title: string,
desc: string,
reward: string,
complete: string
}
}
export default class TasksListRow extends Component {
props: Props;
render() {
return (
<TouchableHighlight>
<View style={styles.container}>
<View style={styles.leftColumn}>
<Text style={styles.title}>{this.props.row.title}</Text>
<Text style={styles.desc}>{this.props.row.desc}</Text>
</View>
<View style={styles.rightColumn}>
<Text style={styles.reward}>{this.props.row.reward}</Text>
<Text style={styles.complete}>{this.props.row.complete}</Text>
</View>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
backgroundColor: '#dedede'
},
leftColumn: {
flex: 1,
backgroundColor: '#ededed',
justifyContent: 'center',
alignItems: 'center'
},
rightColumn: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
title: {
fontSize: 20,
},
desc: {
},
reward: {
},
complete: {
}
})
|
Use correct m2m join table name in LatestCommentsFeed
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@9089 bcc190cf-cafb-0310-a4f2-bffc1f526a37 | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
| from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
Refactor for better logical flow. | import logging
import os
VERSION = (1, 2, 9)
def get_version():
return '%s.%s.%s' % VERSION
try:
# check for existing logging configuration
# valid for Django>=1.3
from django.conf import settings
if settings.LOGGING:
pass
except ImportError:
# if we have any problems, we most likely don't have a settings module
# loaded
pass
except AttributeError:
# fallback configuration if there is no logging configuration
LOGFILE = os.path.join(settings.DIRNAME, 'axes.log')
log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
logging.basicConfig(level=logging.DEBUG,
format=log_format,
datefmt='%a, %d %b %Y %H:%M:%S',
filename=LOGFILE,
filemode='w')
fileLog = logging.FileHandler(LOGFILE, 'w')
fileLog.setLevel(logging.DEBUG)
# set a format which is simpler for console use
console_format = '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s'
formatter = logging.Formatter(console_format)
# tell the handler to use this format
fileLog.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(fileLog)
| import logging
import os
from django.conf import settings
VERSION = (1, 2, 9)
def get_version():
return '%s.%s.%s' % VERSION
try:
LOGFILE = os.path.join(settings.DIRNAME, 'axes.log')
except (ImportError, AttributeError):
# if we have any problems, we most likely don't have a settings module
# loaded
pass
else:
try:
# check for existing logging configuration
# valid for Django>=1.3
if settings.LOGGING:
pass
except:
log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
logging.basicConfig(level=logging.DEBUG,
format=log_format,
datefmt='%a, %d %b %Y %H:%M:%S',
filename=LOGFILE,
filemode='w')
fileLog = logging.FileHandler(LOGFILE, 'w')
fileLog.setLevel(logging.DEBUG)
# set a format which is simpler for console use
console_format = '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s'
formatter = logging.Formatter(console_format)
# tell the handler to use this format
fileLog.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(fileLog)
|
Fix eslint config file checks. | 'use strict';
// Load modules
const Fs = require('fs');
const Path = require('path');
const Eslint = require('eslint');
const Hoek = require('hoek');
// Declare internals
const internals = {};
exports.lint = function () {
const configuration = {
ignore: true,
useEslintrc: true
};
const options = process.argv[2] ? JSON.parse(process.argv[2]) : undefined;
if (!Fs.existsSync('.eslintrc.js') &&
!Fs.existsSync('.eslintrc.yaml') &&
!Fs.existsSync('.eslintrc.yml') &&
!Fs.existsSync('.eslintrc.json') &&
!Fs.existsSync('.eslintrc')) {
configuration.configFile = Path.join(__dirname, '.eslintrc');
}
if (!Fs.existsSync('.eslintignore')) {
configuration.ignorePath = Path.join(__dirname, '.eslintignore');
}
if (options) {
Hoek.merge(configuration, options, true, false);
}
const engine = new Eslint.CLIEngine(configuration);
const results = engine.executeOnFiles(['.']);
return results.results.map((result) => {
return {
filename: result.filePath,
errors: result.messages.map((err) => {
return {
line: err.line,
severity: err.severity === 1 ? 'WARNING' : 'ERROR',
message: err.ruleId + ' - ' + err.message
};
})
};
});
};
process.send(exports.lint());
| 'use strict';
// Load modules
const Fs = require('fs');
const Path = require('path');
const Eslint = require('eslint');
const Hoek = require('hoek');
// Declare internals
const internals = {};
exports.lint = function () {
const configuration = {
ignore: true,
useEslintrc: true
};
const options = process.argv[2] ? JSON.parse(process.argv[2]) : undefined;
if (!Fs.existsSync('.eslintrc')) {
configuration.configFile = Path.join(__dirname, '.eslintrc');
}
if (!Fs.existsSync('.eslintignore')) {
configuration.ignorePath = Path.join(__dirname, '.eslintignore');
}
if (options) {
Hoek.merge(configuration, options, true, false);
}
const engine = new Eslint.CLIEngine(configuration);
const results = engine.executeOnFiles(['.']);
return results.results.map((result) => {
return {
filename: result.filePath,
errors: result.messages.map((err) => {
return {
line: err.line,
severity: err.severity === 1 ? 'WARNING' : 'ERROR',
message: err.ruleId + ' - ' + err.message
};
})
};
});
};
process.send(exports.lint());
|
Add manifest and bump version | #!/usr/bin/env python
import os
from setuptools import setup
def _read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except IOError:
return ''
REQUIREMENTS = [l for l in _read('requirements.txt').split('\n') if l and not l.startswith('#')]
VERSION = '1.0.1'
setup(
name='bottle-swagger',
version=VERSION,
url='https://github.com/ampedandwired/bottle-swagger',
download_url='https://github.com/ampedandwired/bottle-swagger/archive/v{}.tar.gz'.format(VERSION),
description='Swagger integration for Bottle',
author='Charles Blaxland',
author_email='[email protected]',
license='MIT',
platforms='any',
py_modules=['bottle_swagger'],
install_requires=REQUIREMENTS,
classifiers=[
'Environment :: Web Environment',
'Environment :: Plugins',
'Framework :: Bottle',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
| #!/usr/bin/env python
import os
from setuptools import setup
def _read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except IOError:
return ''
REQUIREMENTS = [l for l in _read('requirements.txt').split('\n') if l and not l.startswith('#')]
VERSION = '1.0.0'
setup(
name='bottle-swagger',
version=VERSION,
url='https://github.com/ampedandwired/bottle-swagger',
download_url='https://github.com/ampedandwired/bottle-swagger/archive/v{}.tar.gz'.format(VERSION),
description='Swagger integration for Bottle',
author='Charles Blaxland',
author_email='[email protected]',
license='MIT',
platforms='any',
py_modules=['bottle_swagger'],
install_requires=REQUIREMENTS,
classifiers=[
'Environment :: Web Environment',
'Environment :: Plugins',
'Framework :: Bottle',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
|
Improve the error handling and error response message. | import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from vehicles.models import Vehicle
import control.tasks
#@api_view(['POST'])
@csrf_exempt
def handle_control(request, vehicle_vin='-1'):
print 'vehicle: ', vehicle_vin
try:
vehicle = Vehicle.objects.filter(veh_vin=vehicle_vin)[0]
if request.method == 'POST':
try:
received_json_data = json.loads(request.body)
print 'received json data', received_json_data
command = received_json_data['command']
print 'command: ', command
try:
control.tasks.handle_control(vehicle, command)
response_data = str(received_json_data)
return HttpResponse(response_data, content_type="application/json")
except Exception as e:
print str(e)
return HttpResponse('Send control command failed', content_type="plain/text")
except:
return HttpResponse('Invalid control message format', content_type="plain/text")
else:
return HttpResponse('POST action is expected', content_type="plain/text")
except:
return HttpResponse('No valid vehicle found.', content_type="plain/text")
| import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from vehicles.models import Vehicle
import control.tasks
#@api_view(['POST'])
@csrf_exempt
def handle_control(request, vehicle_vin='-1'):
print 'vehicle: ', vehicle_vin
try:
vehicle = Vehicle.objects.filter(veh_vin=vehicle_vin)[0]
if request.method == 'POST':
received_json_data = json.loads(request.body)
print 'received json data', received_json_data
try:
command = received_json_data['command']
print 'command: ', command
try:
control.tasks.handle_control(vehicle, command)
response_data = str(received_json_data)
return HttpResponse(response_data, content_type="application/json")
except Exception as e:
print str(e)
return HttpResponse('Send control command failed', content_type="plain/text")
except:
return HttpResponse('Invalid command format', content_type="plain/text")
except:
return HttpResponse('No valid vehicle found.', content_type="plain/text")
|
Update classifier tags, email and url. | import re
import ast
from setuptools import setup, find_packages
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('pgspecial/__init__.py', 'rb') as f:
version = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
description = 'Meta-commands handler for Postgres Database.'
setup(
name='pgspecial',
author='PGCLI Core Team',
author_email='[email protected]',
version=version,
license='LICENSE.txt',
url='https://www.dbcli.com',
packages=find_packages(),
description=description,
long_description=open('README.rst').read(),
install_requires=[
'click >= 4.1',
'sqlparse >= 0.1.19',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: SQL',
'Topic :: Database',
'Topic :: Database :: Front-Ends',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| import re
import ast
from setuptools import setup, find_packages
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('pgspecial/__init__.py', 'rb') as f:
version = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
description = 'Meta-commands handler for Postgres Database.'
setup(
name='pgspecial',
author='Amjith Ramanujam',
author_email='amjith[dot]r[at]gmail.com',
version=version,
license='LICENSE.txt',
url='http://pgcli.com',
packages=find_packages(),
description=description,
long_description=open('README.rst').read(),
install_requires=[
'click >= 4.1',
'sqlparse >= 0.1.19',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: SQL',
'Topic :: Database',
'Topic :: Database :: Front-Ends',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix for Python 2.6 and Python 3. | """Like the input built-in, but with bells and whistles."""
import getpass
# Use raw_input for Python 2.x
try:
input = raw_input
except NameError:
pass
def user_input(field, default='', choices=None, password=False, empty_ok=False, accept=False):
"""Prompt user for input until a value is retrieved or default
is accepted. Return the input.
Arguments:
field Description of the input being prompted for.
default Default value for the input accepted with a Return-key.
password Whether the user input should not be echoed to screen.
empty_ok Whether it's okay to accept an empty input.
accept Whether to skip getting actual user input and just accept
the default value, unless prevented by the combination of
arguments "empty_ok" and "default". That is, unless "default"
is an empty string and "empty_ok" is False.
"""
result = ''
while not result:
prompt = field
if default:
prompt += ' [{0}]'.format(default)
prompt += ': '
if accept and not (not default and not empty_ok):
print(prompt)
result = '{0}'.format(default)
else:
if password:
result = getpass.getpass(prompt)
else:
result = input(prompt)
result = result.strip()
if not result:
result = default
if choices and result not in choices:
print('Must be one of {0}'.format(choices))
result = ''
if empty_ok:
break
return result
| """Like the raw_input built-in, but with bells and whistles."""
import getpass
def user_input(field, default='', choices=None, password=False, empty_ok=False, accept=False):
"""Prompt user for input until a value is retrieved or default
is accepted. Return the input.
Arguments:
field Description of the input being prompted for.
default Default value for the input accepted with a Return-key.
password Whether the user input should not be echoed to screen.
empty_ok Whether it's okay to accept an empty input.
accept Whether to skip getting actual user input and just accept
the default value, unless prevented by the combination of
arguments "empty_ok" and "default". That is, unless "default"
is an empty string and "empty_ok" is False.
"""
result = ''
while not result:
prompt = field
if default:
prompt += ' [{:}]'.format(default)
prompt += ': '
if accept and not (not default and not empty_ok):
print(prompt)
result = '{:}'.format(default)
else:
if password:
result = getpass.getpass(prompt)
else:
result = raw_input(prompt)
result = result.strip()
if not result:
result = default
if choices and result not in choices:
print('Must be one of {:}'.format(choices))
result = ''
if empty_ok:
break
return result
|
Remove cannotBeEmpty call on integernode | <?php
namespace Blablacar\RedisBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* Generates the configuration tree.
*
* @return TreeBuilder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('blablacar_redis');
$rootNode
->children()
->arrayNode('clients')
->isRequired()
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('host')->defaultValue('127.0.0.1')->cannotBeEmpty()->end()
->integerNode('port')->defaultValue(6379)->end()
->integerNode('base')->treatNullLike(0)->defaultValue(0)->end()
->end()
->end()
->end()
->arrayNode('session')
->canBeUnset()
->children()
->scalarNode('client')->isRequired()->end()
->scalarNode('prefix')->defaultValue('session')->cannotBeEmpty()->end()
->integerNode('ttl')->end()
->integerNode('spin_lock_wait')->defaultValue(150000)->end()
->integerNode('lock_max_wait')->defaultValue(500000)->end()
->end()
->end()
->booleanNode('enable_logger')->defaultTrue()->end()
->end()
;
return $treeBuilder;
}
}
| <?php
namespace Blablacar\RedisBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* Generates the configuration tree.
*
* @return TreeBuilder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('blablacar_redis');
$rootNode
->children()
->arrayNode('clients')
->isRequired()
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('host')->defaultValue('127.0.0.1')->cannotBeEmpty()->end()
->integerNode('port')->defaultValue(6379)->cannotBeEmpty()->end()
->integerNode('base')->treatNullLike(0)->defaultValue(0)->end()
->end()
->end()
->end()
->arrayNode('session')
->canBeUnset()
->children()
->scalarNode('client')->isRequired()->end()
->scalarNode('prefix')->defaultValue('session')->cannotBeEmpty()->end()
->integerNode('ttl')->end()
->integerNode('spin_lock_wait')->defaultValue(150000)->end()
->integerNode('lock_max_wait')->defaultValue(500000)->end()
->end()
->end()
->booleanNode('enable_logger')->defaultTrue()->end()
->end()
;
return $treeBuilder;
}
}
|
Fix JS error preventing newly created dictionary items from opening automatically | /**
* @ngdoc controller
* @name Umbraco.Editors.Dictionary.CreateController
* @function
*
* @description
* The controller for creating dictionary items
*/
function DictionaryCreateController($scope, $location, dictionaryResource, navigationService, notificationsService, formHelper, appState) {
var vm = this;
vm.itemKey = "";
vm.createItem = createItem;
function createItem() {
if (formHelper.submitForm({ scope: $scope, formCtrl: $scope.createDictionaryForm })) {
var node = $scope.currentNode;
dictionaryResource.create(node.id, vm.itemKey).then(function (data) {
navigationService.hideMenu();
// set new item as active in tree
var currPath = node.path ? node.path : "-1";
navigationService.syncTree({ tree: "dictionary", path: currPath + "," + data, forceReload: true, activate: true });
// reset form state
formHelper.resetForm({ scope: $scope, formCtrl: $scope.createDictionaryForm });
// navigate to edit view
var currentSection = appState.getSectionState("currentSection");
$location.path("/" + currentSection + "/dictionary/edit/" + data);
}, function (err) {
formHelper.resetForm({ scope: $scope, formCtrl: $scope.createDictionaryForm, hasErrors: true });
if (err.data && err.data.message) {
notificationsService.error(err.data.message);
navigationService.hideMenu();
}
});
}
}
}
angular.module("umbraco").controller("Umbraco.Editors.Dictionary.CreateController", DictionaryCreateController);
| /**
* @ngdoc controller
* @name Umbraco.Editors.Dictionary.CreateController
* @function
*
* @description
* The controller for creating dictionary items
*/
function DictionaryCreateController($scope, $location, dictionaryResource, navigationService, notificationsService, formHelper, appState) {
var vm = this;
vm.itemKey = "";
vm.createItem = createItem;
function createItem() {
if (formHelper.submitForm({ scope: $scope, formCtrl: this.createDictionaryForm })) {
var node = $scope.currentNode;
dictionaryResource.create(node.id, vm.itemKey).then(function (data) {
navigationService.hideMenu();
// set new item as active in tree
var currPath = node.path ? node.path : "-1";
navigationService.syncTree({ tree: "dictionary", path: currPath + "," + data, forceReload: true, activate: true });
// reset form state
formHelper.resetForm({ scope: $scope, formCtrl: this.createDictionaryForm });
// navigate to edit view
var currentSection = appState.getSectionState("currentSection");
$location.path("/" + currentSection + "/dictionary/edit/" + data);
}, function (err) {
formHelper.resetForm({ scope: $scope, formCtrl: this.createDictionaryForm, hasErrors: true });
if (err.data && err.data.message) {
notificationsService.error(err.data.message);
navigationService.hideMenu();
}
});
}
}
}
angular.module("umbraco").controller("Umbraco.Editors.Dictionary.CreateController", DictionaryCreateController);
|
Add line separator in logs from JSON event log to another to facilitate json log parsers | package io.dropwizard.logging.layout;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.jackson.JacksonJsonFormatter;
import ch.qos.logback.contrib.json.JsonLayoutBase;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import io.dropwizard.logging.DropwizardLayout;
import io.dropwizard.logging.JsonStacktraceLayout;
import java.util.TimeZone;
/**
* Factory that creates a {@link DropwizardLayout}
*/
public class DropwizardLayoutFactory implements LayoutFactory<ILoggingEvent> {
@Override
public PatternLayoutBase<ILoggingEvent> buildPatternLayout(LoggerContext context, TimeZone timeZone) {
return new DropwizardLayout(context, timeZone);
}
@Override
public JsonLayoutBase<ILoggingEvent> buildJsonLayout(LoggerContext context, TimeZone timeZone,
String timestampFormat, boolean includeStackTrace,
boolean prettyPrint) {
JacksonJsonFormatter jsonFormatter = new JacksonJsonFormatter();
jsonFormatter.setPrettyPrint(prettyPrint);
JsonStacktraceLayout jsonLayout = new JsonStacktraceLayout();
jsonLayout.setJsonFormatter(jsonFormatter);
jsonLayout.setIncludeStacktrace(includeStackTrace);
jsonLayout.setContext(context);
jsonLayout.setTimestampFormat(timestampFormat);
jsonLayout.setTimestampFormatTimezoneId(timeZone.getID());
jsonLayout.setAppendLineSeparator(true);
return jsonLayout;
}
}
| package io.dropwizard.logging.layout;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.jackson.JacksonJsonFormatter;
import ch.qos.logback.contrib.json.JsonLayoutBase;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import io.dropwizard.logging.DropwizardLayout;
import io.dropwizard.logging.JsonStacktraceLayout;
import java.util.TimeZone;
/**
* Factory that creates a {@link DropwizardLayout}
*/
public class DropwizardLayoutFactory implements LayoutFactory<ILoggingEvent> {
@Override
public PatternLayoutBase<ILoggingEvent> buildPatternLayout(LoggerContext context, TimeZone timeZone) {
return new DropwizardLayout(context, timeZone);
}
@Override
public JsonLayoutBase<ILoggingEvent> buildJsonLayout(LoggerContext context, TimeZone timeZone,
String timestampFormat, boolean includeStackTrace,
boolean prettyPrint) {
JacksonJsonFormatter jsonFormatter = new JacksonJsonFormatter();
jsonFormatter.setPrettyPrint(prettyPrint);
JsonStacktraceLayout jsonLayout = new JsonStacktraceLayout();
jsonLayout.setJsonFormatter(jsonFormatter);
jsonLayout.setIncludeStacktrace(includeStackTrace);
jsonLayout.setContext(context);
jsonLayout.setTimestampFormat(timestampFormat);
jsonLayout.setTimestampFormatTimezoneId(timeZone.getID());
return jsonLayout;
}
}
|
Use Line::EOL for line detection | <?php
namespace WyriHaximus\React\ChildProcess\Messenger;
use WyriHaximus\React\ChildProcess\Messenger\Messages\Line;
/**
* @todo code smell with $source
*/
trait OnDataTrait
{
/**
* @var string[]
*/
protected $buffers = [
'stdin' => '',
'stdout' => '',
'stderr' => '',
];
/**
* @param string $data
* @param string $source
*/
protected function onData($data, $source)
{
$this->buffers[$source] .= $data;
if (strpos($this->buffers[$source], Line::EOL) !== false) {
$messages = explode(Line::EOL, $this->buffers[$source]);
$this->buffers[$source] = array_pop($messages);
$this->iterateMessages($messages, $source);
}
}
/**
* @param array $messages
* @param string $source
*/
protected function iterateMessages(array $messages, $source)
{
foreach ($messages as $message) {
$this->handleMessage(json_decode($message, true), $source);
}
}
/**
* @param array $message
* @param $source
* @return void
*/
abstract protected function handleMessage(array $message, $source);
}
| <?php
namespace WyriHaximus\React\ChildProcess\Messenger;
/**
* @todo code smell with $source
*/
trait OnDataTrait
{
/**
* @var string[]
*/
protected $buffers = [
'stdin' => '',
'stdout' => '',
'stderr' => '',
];
/**
* @param string $data
* @param string $source
*/
protected function onData($data, $source)
{
$this->buffers[$source] .= $data;
if (strpos($this->buffers[$source], PHP_EOL) !== false) {
$messages = explode(PHP_EOL, $this->buffers[$source]);
$this->buffers[$source] = array_pop($messages);
$this->iterateMessages($messages, $source);
}
}
/**
* @param array $messages
* @param string $source
*/
protected function iterateMessages(array $messages, $source)
{
foreach ($messages as $message) {
$this->handleMessage(json_decode($message, true), $source);
}
}
/**
* @param array $message
* @param $source
* @return void
*/
abstract protected function handleMessage(array $message, $source);
}
|
Drop content type in migration as well | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def forwards_remove_content_types(apps, schema_editor):
db = schema_editor.connection.alias
ContentType = apps.get_model('contenttypes', 'ContentType')
ContentType.objects.using(db).filter(
app_label='oauth',
model__in=['githubproject', 'githuborganization',
'bitbucketproject', 'bitbucketteam']
).delete()
class Migration(migrations.Migration):
dependencies = [
('oauth', '0003_move_github'),
]
operations = [
migrations.RemoveField(
model_name='bitbucketproject',
name='organization',
),
migrations.RemoveField(
model_name='bitbucketproject',
name='users',
),
migrations.RemoveField(
model_name='bitbucketteam',
name='users',
),
migrations.RemoveField(
model_name='githuborganization',
name='users',
),
migrations.RemoveField(
model_name='githubproject',
name='organization',
),
migrations.RemoveField(
model_name='githubproject',
name='users',
),
migrations.DeleteModel(
name='BitbucketProject',
),
migrations.DeleteModel(
name='BitbucketTeam',
),
migrations.DeleteModel(
name='GithubOrganization',
),
migrations.DeleteModel(
name='GithubProject',
),
migrations.RunPython(forwards_remove_content_types),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('oauth', '0003_move_github'),
]
operations = [
migrations.RemoveField(
model_name='bitbucketproject',
name='organization',
),
migrations.RemoveField(
model_name='bitbucketproject',
name='users',
),
migrations.RemoveField(
model_name='bitbucketteam',
name='users',
),
migrations.RemoveField(
model_name='githuborganization',
name='users',
),
migrations.RemoveField(
model_name='githubproject',
name='organization',
),
migrations.RemoveField(
model_name='githubproject',
name='users',
),
migrations.DeleteModel(
name='BitbucketProject',
),
migrations.DeleteModel(
name='BitbucketTeam',
),
migrations.DeleteModel(
name='GithubOrganization',
),
migrations.DeleteModel(
name='GithubProject',
),
]
|
Add a simple type for null | import Context from "../context"
import ContextTypes from "../context-types"
import Expression from "./expression"
import Doc from "./doc"
import {PHPSimpleType, PHPTypeUnion} from "../phptype"
import Identifier from "./identifier"
export default class ConstRef extends Expression {
/** @type {string|Identifier} */
get name() {
return this.cacheOptionalNode("name")
}
/**
* Checks that syntax seems ok
* @param {Context} context
* @param {boolean} [in_call]
* @param {?Doc} [doc]
* @returns {?ContextTypes} The set of types applicable to this value
*/
check(context, in_call = false, doc = null) {
super.check(context, in_call, doc)
if(this.name instanceof Identifier) {
switch(this.name.name) {
case "array":
case "null":
return new ContextTypes(PHPSimpleType.named(this.name.name))
default:
}
let constant_type = context.findName(this.name.name)
if(constant_type) {
return new ContextTypes(constant_type)
}
let constant_type_munged = context.findName(this.name.name.toUpperCase())
if(constant_type_munged) {
return new ContextTypes(constant_type_munged)
}
}
let classContext = context.findClass(context.resolveNodeName(this))
if(classContext) {
return new ContextTypes(PHPSimpleType.named(classContext.name))
} else {
return new ContextTypes(PHPSimpleType.coreTypes.mixed)
}
}
}
| import Context from "../context"
import ContextTypes from "../context-types"
import Expression from "./expression"
import Doc from "./doc"
import {PHPSimpleType, PHPTypeUnion} from "../phptype"
import Identifier from "./identifier"
export default class ConstRef extends Expression {
/** @type {string|Identifier} */
get name() {
return this.cacheOptionalNode("name")
}
/**
* Checks that syntax seems ok
* @param {Context} context
* @param {boolean} [in_call]
* @param {?Doc} [doc]
* @returns {?ContextTypes} The set of types applicable to this value
*/
check(context, in_call = false, doc = null) {
super.check(context, in_call, doc)
if(this.name instanceof Identifier) {
switch(this.name.name) {
case "array":
return new ContextTypes(PHPSimpleType.named(this.name.name))
default:
}
let constant_type = context.findName(this.name.name)
if(constant_type) {
return new ContextTypes(constant_type)
}
let constant_type_munged = context.findName(this.name.name.toUpperCase())
if(constant_type_munged) {
return new ContextTypes(constant_type_munged)
}
}
let classContext = context.findClass(context.resolveNodeName(this))
if(classContext) {
return new ContextTypes(PHPSimpleType.named(classContext.name))
} else {
return new ContextTypes(PHPSimpleType.coreTypes.mixed)
}
}
}
|
Fix sourcemaps so they write to separate .map file | var gulp = require("gulp"),
plugins = require("gulp-load-plugins")(),
pkg = require("./package.json"),
paths = {
src: {
css: "./src/main/resources/static/sass"
},
dist: {
css: "./src/main/resources/static/css"
}
},
config = {
autoprefixer: {
browsers: ["last 2 versions", "> 1%"]
}
};
// Build the Sass
gulp.task("build:css", function() {
return gulp.src(paths.src.css + "/**/*")
// Prevents Sass from hanging on errors (syntax error, etc.)
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
// Need to use sass.sync() to work with Plumber correctly
.pipe(plugins.sass.sync())
.pipe(plugins.autoprefixer(config.autoprefixer))
.pipe(plugins.sourcemaps.write("./"))
.pipe(gulp.dest(paths.dist.css));
});
// Clean the Sass build directory
gulp.task("clean:css", function() {
return gulp.src(paths.dist.css, { read: false })
.pipe(plugins.clean());
})
gulp.task("build", ["build:css"]);
gulp.task("clean", ["clean:css"]);
gulp.task("watch", function() {
gulp.src(paths.src.css+ "/**/*", ["build:css"]);
});
| var gulp = require("gulp"),
plugins = require("gulp-load-plugins")(),
pkg = require("./package.json"),
paths = {
src: {
css: "./src/main/resources/static/sass"
},
dist: {
css: "./src/main/resources/static/css"
}
},
config = {
autoprefixer: {
browsers: ["last 2 versions", "> 1%"]
}
};
// Build the Sass
gulp.task("build:css", function() {
return gulp.src(paths.src.css + "/**/*")
// Prevents Sass from hanging on errors (syntax error, etc.)
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
// Need to use sass.sync() to work with Plumber correctly
.pipe(plugins.sass.sync())
.pipe(plugins.autoprefixer(config.autoprefixer))
.pipe(gulp.dest(paths.dist.css));
});
// Clean the Sass build directory
gulp.task("clean:css", function() {
return gulp.src(paths.dist.css, { read: false })
.pipe(plugins.clean());
})
gulp.task("build", ["build:css"]);
gulp.task("clean", ["clean:css"]);
gulp.task("watch", function() {
gulp.src(paths.src.css+ "/**/*", ["build:css"]);
});
|
Use let instead of var | import { isString, isArray, isFunction } from './util';
let resolved = {};
function loadScript(url, callback, errorCallback) {
let invokeCallback = function() {
resolved[url] = true;
if (isFunction(callback)) {
callback();
}
};
if (resolved[url]) {
invokeCallback();
return;
}
let script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) {
//IE
script.onreadystatechange = function() {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
invokeCallback();
}
};
} else {
//Others
script.onload = function() {
invokeCallback();
};
}
script.onerror = function(e) {
resolved[url] = false;
console.log('error', e);
if (isFunction(errorCallback)) {
errorCallback();
}
};
script.src = url;
let parent = document.body || document.head || document;
parent.appendChild(script);
}
function get(src, opts) {
if (isString(src)) {
return new Promise((resolve, reject) => {
loadScript(src, () => resolve(true), () => reject());
});
} else if (isArray(src)) {
let p = Promise.resolve(true);
src.forEach(url => {
p = p.then(() => get(url));
});
return p;
}
throw new Error('Invalid argument for get()');
}
export default get;
| import { isString, isArray, isFunction } from './util';
let resolved = {};
function loadScript(url, callback, errorCallback) {
var invokeCallback = function() {
resolved[url] = true;
if (isFunction(callback)) {
callback();
}
};
if (resolved[url]) {
invokeCallback();
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) {
//IE
script.onreadystatechange = function() {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
invokeCallback();
}
};
} else {
//Others
script.onload = function() {
invokeCallback();
};
}
script.onerror = function(e) {
resolved[url] = false;
console.log('error', e);
if (isFunction(errorCallback)) {
errorCallback();
}
};
script.src = url;
var parent = document.body || document.head || document;
parent.appendChild(script);
}
function get(src, opts) {
if (isString(src)) {
return new Promise((resolve, reject) => {
loadScript(src, () => resolve(true), () => reject());
});
} else if (isArray(src)) {
let p = Promise.resolve(true);
src.forEach(url => {
p = p.then(() => get(url));
});
return p;
}
throw new Error('Invalid argument for get()');
}
export default get;
|
Create a parent with the same dataset type | import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
'type': data_dict.get('type', 'dataset'),
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
| import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
|
Use grid_on icon for QnA | export default class {
constructor($scope, auth, toast) {
'ngInject';
$scope.buttons = [
{
name: 'View Code',
icon: 'code',
show: true,
href: 'https://github.com/mjhasbach/material-qna'
},
{
name: 'QnA',
icon: 'grid_on',
get show() {
return $scope.user.data && $scope.view.current !== 'qna';
},
onClick: function() {
$scope.view.current = 'qna';
}
},
{
name: 'Dashboard',
icon: 'view_list',
get show() {
return $scope.user.data && $scope.view.current !== 'dashboard';
},
onClick: function() {
$scope.view.current = 'dashboard';
}
},
{
name: 'Logout',
icon: 'exit_to_app',
get show() {
return $scope.user.data;
},
onClick: function() {
auth.logout().then(function() {
$scope.user.data = null;
$scope.view.current = 'auth';
}).catch(function() {
toast.show('Unable to log out');
});
}
}
];
}
} | export default class {
constructor($scope, auth, toast) {
'ngInject';
$scope.buttons = [
{
name: 'View Code',
icon: 'code',
show: true,
href: 'https://github.com/mjhasbach/material-qna'
},
{
name: 'QnA',
icon: 'question_answer',
get show() {
return $scope.user.data && $scope.view.current !== 'qna';
},
onClick: function() {
$scope.view.current = 'qna';
}
},
{
name: 'Dashboard',
icon: 'view_list',
get show() {
return $scope.user.data && $scope.view.current !== 'dashboard';
},
onClick: function() {
$scope.view.current = 'dashboard';
}
},
{
name: 'Logout',
icon: 'exit_to_app',
get show() {
return $scope.user.data;
},
onClick: function() {
auth.logout().then(function() {
$scope.user.data = null;
$scope.view.current = 'auth';
}).catch(function() {
toast.show('Unable to log out');
});
}
}
];
}
} |
Add get registration count to service | <?php
namespace Shaygan\AffiliateBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ReferralRegistrationRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ReferralRegistrationRepository extends EntityRepository
{
public function getRegistrationByUser($user)
{
return $this->_em
->createQuery('SELECT rr FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'JOIN rr.referrer r '
. 'WHERE r.id=:id '
. 'ORDER BY rr.id DESC ')
->setParameter("id", $user->getId())
;
}
public function getRegistrationCountByUser($user)
{
return $this->_em
->createQuery('SELECT COUNT(rr) FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'WHERE rr.id=:id ')
->setParameter("id", $user->getId())
->getSingleScalarResult()
;
}
}
| <?php
namespace Shaygan\AffiliateBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ReferralRegistrationRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ReferralRegistrationRepository extends EntityRepository
{
public function getRegistrationByUser($user)
{
return $this->_em
->createQuery('SELECT rr,r FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'JOIN rr.referrer r '
. 'WHERE r.id=:id '
. 'ORDER BY rr.id DESC ')
->setParameter("id", $user->getId())
;
}
public function getRegistrationCountByUser($user)
{
return $this->_em
->createQuery('SELECT COUNT(*) FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'WHERE r.id=:id ')
->setParameter("id", $user->getId())
->getSingleScalarResult()
;
}
}
|
Add logic for multiremote object when setting tunnelIdentifier | import SauceConnectLauncher from 'sauce-connect-launcher'
class SauceLaunchService {
/**
* modify config and launch sauce connect
*/
onPrepare (config, capabilities) {
if (!config.sauceConnect) {
return
}
this.sauceConnectOpts = Object.assign({
username: config.user,
accessKey: config.key
}, config.sauceConnectOpts)
config.protocol = 'http'
config.host = 'localhost'
config.port = this.sauceConnectOpts.port || 4445
const sauceConnectTunnelIdentifier = this.sauceConnectOpts.tunnelIdentifier
if (sauceConnectTunnelIdentifier) {
if (Array.isArray(capabilities)) {
capabilities.forEach((capability) => {
capability.tunnelIdentifier = capability.tunnelIdentifier || sauceConnectTunnelIdentifier
})
} else {
Object.keys(capabilities).forEach((browser) => {
if (capabilities[browser].desiredCapabilities) {
capabilities[browser].desiredCapabilities.tunnelIdentifier = capabilities[browser].desiredCapabilities.tunnelIdentifier || sauceConnectTunnelIdentifier
}
})
}
}
return new Promise((resolve, reject) => SauceConnectLauncher(this.sauceConnectOpts, (err, sauceConnectProcess) => {
if (err) {
return reject(err)
}
this.sauceConnectProcess = sauceConnectProcess
resolve()
}))
}
/**
* shut down sauce connect
*/
onComplete () {
if (!this.sauceConnectProcess) {
return
}
return new Promise((resolve) => this.sauceConnectProcess.close(resolve))
}
}
export default SauceLaunchService
| import SauceConnectLauncher from 'sauce-connect-launcher'
class SauceLaunchService {
/**
* modify config and launch sauce connect
*/
onPrepare (config, capabilities) {
if (!config.sauceConnect) {
return
}
this.sauceConnectOpts = Object.assign({
username: config.user,
accessKey: config.key
}, config.sauceConnectOpts)
config.protocol = 'http'
config.host = 'localhost'
config.port = this.sauceConnectOpts.port || 4445
const sauceConnectTunnelIdentifier = this.sauceConnectOpts.tunnelIdentifier
if (sauceConnectTunnelIdentifier) {
capabilities.forEach((capability) => {
capability.tunnelIdentifier = capability.tunnelIdentifier || sauceConnectTunnelIdentifier
})
}
return new Promise((resolve, reject) => SauceConnectLauncher(this.sauceConnectOpts, (err, sauceConnectProcess) => {
if (err) {
return reject(err)
}
this.sauceConnectProcess = sauceConnectProcess
resolve()
}))
}
/**
* shut down sauce connect
*/
onComplete () {
if (!this.sauceConnectProcess) {
return
}
return new Promise((resolve) => this.sauceConnectProcess.close(resolve))
}
}
export default SauceLaunchService
|
Put the bundle set value in a new while loop. | package com.brg.dao;
import com.brg.ServiceProvider;
import com.brg.domain.RuleValueBundle;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class RuleValueBundleDAO implements DAO{
@Override
public ArrayList<RuleValueBundle> executeRead(String sql) {
ArrayList<RuleValueBundle> values = new ArrayList<RuleValueBundle>();
try{
Statement stmt = ServiceProvider.getInstance().getPersistanceService().getConnection().createStatement();
ResultSet set = stmt.executeQuery(sql);
while(set.next()) {
RuleValueBundle bundle = new RuleValueBundle();
Statement valueStmt = ServiceProvider.getInstance().getPersistanceService().getConnection().createStatement();
ResultSet valueSet = valueStmt
.executeQuery("SELECT Key FROM BundleKeyEntry WHERE BundleID=" + set.getInt("BundleID"));
while(valueSet.next()) {
bundle.setValue(valueSet.getString("Key"), null);
}
}
} catch(Exception e){
e.printStackTrace();
}
return values;
}
public RuleValueBundle getRuleValueBundleById(int id){
ArrayList<RuleValueBundle> values = new ArrayList<RuleValueBundle>(); //temp
return values.size() >= 1 ? values.get(0) : null;
}
public ArrayList<RuleValueBundle> getAllRuleValueBundle(){
return this.executeRead("SELECT * FROM Rule;");
}
}
| package com.brg.dao;
import com.brg.ServiceProvider;
import com.brg.domain.RuleValueBundle;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class RuleValueBundleDAO implements DAO{
@Override
public ArrayList<RuleValueBundle> executeRead(String sql) {
ArrayList<RuleValueBundle> values = new ArrayList<RuleValueBundle>();
try{
Statement stmt = ServiceProvider.getInstance().getPersistanceService().getConnection().createStatement();
ResultSet set = stmt.executeQuery(sql);
while(set.next()) {
RuleValueBundle bundle = new RuleValueBundle();
Statement valueStmt = ServiceProvider.getInstance().getPersistanceService().getConnection().createStatement();
ResultSet valueSet = valueStmt
.executeQuery("SELECT Key FROM BundleKeyEntry WHERE BundleID=" + set.getInt("BundleID"));
bundle.setValue(valueSet.getString("Key"), null);
}
} catch(Exception e){
e.printStackTrace();
}
return values;
}
public RuleValueBundle getRuleValueBundleById(int id){
ArrayList<RuleValueBundle> values = new ArrayList<RuleValueBundle>(); //temp
return values.size() >= 1 ? values.get(0) : null;
}
public ArrayList<RuleValueBundle> getAllRuleValueBundle(){
return this.executeRead("SELECT * FROM Rule;");
}
}
|
Fix bug in onBootsrap function | <?php
namespace TreeLayoutStack;
class Module implements \Zend\ModuleManager\Feature\AutoloaderProviderInterface{
/**
* @param \Zend\EventManager\EventInterface $oEvent
*/
public function onBootstrap(\Zend\EventManager\EventInterface $oEvent){
$oServiceManager = $oEvent->getApplication()->getServiceManager();
//Attach templating service to render event
if(
is_callable(array($oEvent,'getApplication'))
&& ($oApplication = call_user_func(array($oEvent,'getApplication'))) instanceof \Zend\Mvc\Application
&& ($oEventManager = $oApplication->getEventManager()) instanceof \Zend\EventManager\EventManagerInterface
&& $oServiceManager->has('ViewRenderer')
&& $oServiceManager->get('ViewRenderer') instanceof \Zend\View\Renderer\PhpRenderer
)$oEventManager->attach(
\Zend\Mvc\MvcEvent::EVENT_RENDER,
array($oServiceManager->get('TemplatingService'), 'buildLayoutTemplate')
);
}
/**
* @see \Zend\ModuleManager\Feature\AutoloaderProviderInterface::getAutoloaderConfig()
* @return array
*/
public function getAutoloaderConfig(){
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__.DIRECTORY_SEPARATOR.'autoload_classmap.php'
)
);
}
/**
* @return array
*/
public function getConfig(){
return include __DIR__.DIRECTORY_SEPARATOR.'config/module.config.php';
}
} | <?php
namespace TreeLayoutStack;
class Module implements \Zend\ModuleManager\Feature\AutoloaderProviderInterface{
/**
* @param \Zend\EventManager\EventInterface $oEvent
*/
public function onBootstrap(\Zend\EventManager\EventInterface $oEvent){
$oServiceManager = $oEvent->getApplication()->getServiceManager();
//Attach templating service to render event
if(
is_callable(array($oEvent,'getApplication'))
&& ($oApplication = call_user_func(array($oEvent,'getApplication'))) instanceof \Zend\Mvc\Application
&& ($oEventManager = $oApplication->getEventManager()) instanceof \Zend\EventManager\EventManagerInterface
&& $oServiceManager->has('ViewRenderer')
&& $oServiceManager->get('ViewRenderer') instanceof \Zend\View\Renderer\PhpRenderer
)$oEventManager->attach(
\Zend\Mvc\MvcEvent::EVENT_RENDER,
array($oServiceManager->get('TemplatingService'), 'onRender')
);
}
/**
* @see \Zend\ModuleManager\Feature\AutoloaderProviderInterface::getAutoloaderConfig()
* @return array
*/
public function getAutoloaderConfig(){
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__.DIRECTORY_SEPARATOR.'autoload_classmap.php'
)
);
}
/**
* @return array
*/
public function getConfig(){
return include __DIR__.DIRECTORY_SEPARATOR.'config/module.config.php';
}
} |
Add missing class property declarations | <?php
namespace RIPS\APIConnector;
use GuzzleHttp\Client;
use RIPS\APIConnector\Requests\UserRequests;
use RIPS\APIConnector\Requests\OrgRequests;
use RIPS\APIConnector\Requests\QuotaRequests;
class API
{
// @var UserRequests
public $users;
// @var OrgRequests
public $orgs;
// @var QuotaRequests
public $quotas;
// @var array - Config values for $client
protected $clientConfig = [
'base_uri' => 'https://api-test2.internal.ripstech.com',
'timeout' => 10,
'connect_timeout' => 10,
];
/**
* Initialize new API
*
* @param string $username
* @param string $password
* @param array $clientConfig
*/
public function __construct(string $username, string $password, array $clientConfig = [])
{
$mergedConfig = array_merge($this->clientConfig, $clientConfig, [
'headers' => [
'X-API-Username' => $username,
'X-API-Password' => $password,
'User-Agent' => 'RIPS-API-Connector/0.0.1',
],
]);
$client = new Client($mergedConfig);
$this->users = new UserRequests($client);
$this->orgs = new OrgRequests($client);
$this->quotas = new QuotaRequests($client);
}
}
| <?php
namespace RIPS\APIConnector;
use GuzzleHttp\Client;
use RIPS\APIConnector\Requests\UserRequests;
use RIPS\APIConnector\Requests\OrgRequests;
use RIPS\APIConnector\Requests\QuotaRequests;
class API
{
// @var UserRequests
public $users;
// @var GuzzleHttp/Client
protected $client;
// @var array - Config values for $client
protected $clientConfig = [
'base_uri' => 'https://api-test2.internal.ripstech.com',
'timeout' => 10,
'connect_timeout' => 10,
];
/**
* Initialize new API
*
* @param string $username
* @param string $password
* @param array $clientConfig
*/
public function __construct(string $username, string $password, array $clientConfig = [])
{
$mergedConfig = array_merge($this->clientConfig, $clientConfig, [
'headers' => [
'X-API-Username' => $username,
'X-API-Password' => $password,
'User-Agent' => 'RIPS-API-Connector/0.0.1',
],
]);
$this->client = new Client($mergedConfig);
$this->users = new UserRequests($this->client);
$this->orgs = new OrgRequests($this->client);
$this->quotas = new QuotaRequests($this->client);
}
}
|
Split arg parsing into function | import argparse
import os
import string
def generate_rpm_spec(template, patch_file):
spec_template = string.Template(template)
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
'target_kernel': '3.10.0-229.el7',
'target_arch': 'x86_64',
}
return spec_template.substitute(values)
def get_args():
parser = argparse.ArgumentParser(description='Generate RPM spec file to '
'build a kpatch package')
parser.add_argument('patch', metavar='PATCH',
help='patch file from which to build the livepatch '
'module')
parser.add_argument('-o', '--output', metavar='FILE', default=None,
help='name of output spec file')
return parser.parse_args()
if __name__ == '__main__':
args = get_args()
with open('kpatch-patch.spec') as f:
template = f.read()
spec_content = generate_rpm_spec(template, args.patch)
with open(args.output, 'w') as f:
f.write(spec_content)
| import argparse
import os
import string
def generate_rpm_spec(template, patch_file):
spec_template = string.Template(template)
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
'target_kernel': '3.10.0-229.el7',
'target_arch': 'x86_64',
}
return spec_template.substitute(values)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate RPM spec file to '
'build a kpatch package')
parser.add_argument('patch', metavar='PATCH',
help='patch file from which to build the livepatch '
'module')
parser.add_argument('-o', '--output', metavar='FILE', default=None,
help='name of output spec file')
args = parser.parse_args()
with open('kpatch-patch.spec') as f:
template = f.read()
spec_content = generate_rpm_spec(template, args.patch)
with open(args.output, 'w') as f:
f.write(spec_content)
|
Add a waterfalled event on active tab change
This allows us to do extra bullshit since Enyo doesn't tend to like
being shown/hidden. | enyo.kind({
name: "bootstrap.TabHolder",
handlers: {
onNavItemClicked: "showTabContent"
},
showTabContent: function(inSender, inEvent){
this.waterfall("showTabContent", inEvent);
}
});
enyo.kind({
name: "bootstrap.TabContent",
classes: "tab-content",
published: {
active: false
},
handlers: {
showTabContent: "showTab"
},
showTab: function(inSender, inEvent){
var tabPanes = this.children,
id = inEvent.originator.getAttribute('href').slice(1);
tabPanes.forEach(function(pane){
if(pane.getAttribute('id') === id){
pane.setActive(true);
} else{
pane.setActive(false);
}
});
}
});
enyo.kind({
name: "bootstrap.TabPane",
classes: "tab-pane fade",
attributes: {
id: ''
},
published: {
active: false
},
create: function(){
this.inherited(arguments);
this.activeChanged();
},
activeChanged: function(){
var $this = this;
if($this.active) {
$this.addRemoveClass('active', $this.active);
$this.waterfall('tabShown');
setTimeout(function(){
$this.addRemoveClass('in', $this.active);
},150);
} else {
$this.addRemoveClass('in', $this.active);
$this.addRemoveClass('active', $this.active);
}
}
});
| enyo.kind({
name: "bootstrap.TabHolder",
handlers: {
onNavItemClicked: "showTabContent"
},
showTabContent: function(inSender, inEvent){
this.waterfall("showTabContent", inEvent);
}
});
enyo.kind({
name: "bootstrap.TabContent",
classes: "tab-content",
published: {
active: false
},
handlers: {
showTabContent: "showTab"
},
showTab: function(inSender, inEvent){
var tabPanes = this.children,
id = inEvent.originator.getAttribute('href').slice(1);
tabPanes.forEach(function(pane){
if(pane.getAttribute('id') === id){
pane.setActive(true);
} else{
pane.setActive(false);
}
});
}
});
enyo.kind({
name: "bootstrap.TabPane",
classes: "tab-pane fade",
attributes: {
id: ''
},
published: {
active: false
},
create: function(){
this.inherited(arguments);
this.activeChanged();
},
activeChanged: function(){
var $this = this;
if($this.active) {
$this.addRemoveClass('active', $this.active);
setTimeout(function(){
$this.addRemoveClass('in', $this.active);
},150);
} else {
$this.addRemoveClass('in', $this.active);
$this.addRemoveClass('active', $this.active);
}
}
});
|
Remove binding as got moved to concierge package | <?php
namespace App\Providers;
use Timegridio\Concierge\Models\Appointment;
use Timegridio\Concierge\Models\Business;
use Timegridio\Concierge\Models\Contact;
use Timegridio\Concierge\Models\Service;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Routing\Router;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
*
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
$router->model('contact', Contact::class);
$router->model('service', Service::class);
$router->model('appointment', Appointment::class);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
*
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
}
}
| <?php
namespace App\Providers;
use Timegridio\Concierge\Models\Appointment;
use Timegridio\Concierge\Models\Business;
use Timegridio\Concierge\Models\Contact;
use Timegridio\Concierge\Models\Service;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Routing\Router;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
*
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
$router->model('contact', Contact::class);
$router->model('service', Service::class);
$router->model('appointment', Appointment::class);
$router->bind('business', function ($businessSlug) {
return Business::where('slug', $businessSlug)->first();
});
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
*
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
}
}
|
Use source keyword argument (instead of overriding get_attribute)
This allows the ImageRenditionField to be used on models that contain an
image field. | from __future__ import absolute_import, unicode_literals
from collections import OrderedDict
from rest_framework.fields import Field
from ...models import SourceImageIOError
from ..v2.serializers import ImageSerializer
class ImageRenditionField(Field):
"""
A field that generates a rendition with the specified filter spec, and serialises
details of that rendition.
Example:
"thumbnail": {
"url": "/media/images/myimage.max-165x165.jpg",
"width": 165,
"height": 100
}
If there is an error with the source image. The dict will only contain a single
key, "error", indicating this error:
"thumbnail": {
"error": "SourceImageIOError"
}
"""
def __init__(self, filter_spec, *args, **kwargs):
self.filter_spec = filter_spec
super(ImageRenditionField, self).__init__(*args, **kwargs)
def to_representation(self, image):
try:
thumbnail = image.get_rendition(self.filter_spec)
return OrderedDict([
('url', thumbnail.url),
('width', thumbnail.width),
('height', thumbnail.height),
])
except SourceImageIOError:
return OrderedDict([
('error', 'SourceImageIOError'),
])
class AdminImageSerializer(ImageSerializer):
thumbnail = ImageRenditionField('max-165x165', source='*', read_only=True)
| from __future__ import absolute_import, unicode_literals
from collections import OrderedDict
from rest_framework.fields import Field
from ...models import SourceImageIOError
from ..v2.serializers import ImageSerializer
class ImageRenditionField(Field):
"""
A field that generates a rendition with the specified filter spec, and serialises
details of that rendition.
Example:
"thumbnail": {
"url": "/media/images/myimage.max-165x165.jpg",
"width": 165,
"height": 100
}
If there is an error with the source image. The dict will only contain a single
key, "error", indicating this error:
"thumbnail": {
"error": "SourceImageIOError"
}
"""
def __init__(self, filter_spec, *args, **kwargs):
self.filter_spec = filter_spec
super(ImageRenditionField, self).__init__(*args, **kwargs)
def get_attribute(self, instance):
return instance
def to_representation(self, image):
try:
thumbnail = image.get_rendition(self.filter_spec)
return OrderedDict([
('url', thumbnail.url),
('width', thumbnail.width),
('height', thumbnail.height),
])
except SourceImageIOError:
return OrderedDict([
('error', 'SourceImageIOError'),
])
class AdminImageSerializer(ImageSerializer):
thumbnail = ImageRenditionField('max-165x165', read_only=True)
|
Add data-automation tag to text field error message | import styles from './TextField.less';
import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';
import ErrorIcon from '../../icons/ErrorIcon/ErrorIcon';
export default class TextField extends Component {
static propTypes = {
className: PropTypes.string,
inputProps: PropTypes.object,
invalid: PropTypes.bool,
message: PropTypes.string
};
static defaultProps = {
className: '',
inputProps: {},
invalid: false,
message: ''
};
constructor() {
super();
this.storeInputReference = this.storeInputReference.bind(this);
}
storeInputReference(input) {
if (input !== null) {
this.input = input;
}
}
render() {
const { className, invalid, message, inputProps, ...props } = this.props;
const { className: inputClassName, ...remainingInputProps } = inputProps;
return (
<div className={classNames(styles.root, className, { [styles.invalid]: invalid })} {...props}>
<input className={classNames(styles.input, inputClassName)} ref={this.storeInputReference} {...remainingInputProps} />
{
invalid &&
<p className={styles.message} data-automation="textfield-invalid-message">
{ message && <ErrorIcon filled={true} className={styles.messageIcon} svgClassName={styles.messageIconSvg} /> }
{ message }
</p>
}
</div>
);
}
}
| import styles from './TextField.less';
import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';
import ErrorIcon from '../../icons/ErrorIcon/ErrorIcon';
export default class TextField extends Component {
static propTypes = {
className: PropTypes.string,
inputProps: PropTypes.object,
invalid: PropTypes.bool,
message: PropTypes.string
};
static defaultProps = {
className: '',
inputProps: {},
invalid: false,
message: ''
};
constructor() {
super();
this.storeInputReference = this.storeInputReference.bind(this);
}
storeInputReference(input) {
if (input !== null) {
this.input = input;
}
}
render() {
const { className, invalid, message, inputProps, ...props } = this.props;
const { className: inputClassName, ...remainingInputProps } = inputProps;
return (
<div className={classNames(styles.root, className, { [styles.invalid]: invalid })} {...props}>
<input className={classNames(styles.input, inputClassName)} ref={this.storeInputReference} {...remainingInputProps} />
{
invalid &&
<p className={styles.message}>
{ message && <ErrorIcon filled={true} className={styles.messageIcon} svgClassName={styles.messageIconSvg} /> }
{ message }
</p>
}
</div>
);
}
}
|
Tweak partner form to use textarea for description | from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from casepro.msgs.models import Label
from .models import Partner
class BasePartnerForm(forms.ModelForm):
description = forms.CharField(label=_("Description"), max_length=255, required=False, widget=forms.Textarea)
labels = forms.ModelMultipleChoiceField(label=_("Can Access"),
queryset=Label.objects.none(),
widget=forms.CheckboxSelectMultiple(),
required=False)
def __init__(self, *args, **kwargs):
org = kwargs.pop('org')
super(BasePartnerForm, self).__init__(*args, **kwargs)
self.fields['labels'].queryset = Label.get_all(org).order_by('name')
class PartnerUpdateForm(BasePartnerForm):
def __init__(self, *args, **kwargs):
super(PartnerUpdateForm, self).__init__(*args, **kwargs)
self.fields['primary_contact'].queryset = kwargs['instance'].get_users()
class Meta:
model = Partner
fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels')
class PartnerCreateForm(BasePartnerForm):
def __init__(self, *args, **kwargs):
super(PartnerCreateForm, self).__init__(*args, **kwargs)
class Meta:
model = Partner
fields = ('name', 'description', 'logo', 'is_restricted', 'labels')
| from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from casepro.msgs.models import Label
from .models import Partner
class PartnerUpdateForm(forms.ModelForm):
labels = forms.ModelMultipleChoiceField(label=_("Can Access"),
queryset=Label.objects.none(),
widget=forms.CheckboxSelectMultiple(),
required=False)
def __init__(self, *args, **kwargs):
org = kwargs.pop('org')
super(PartnerUpdateForm, self).__init__(*args, **kwargs)
self.fields['primary_contact'].queryset = kwargs['instance'].get_users()
self.fields['labels'].queryset = Label.get_all(org).order_by('name')
class Meta:
model = Partner
fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels')
class PartnerCreateForm(forms.ModelForm):
labels = forms.ModelMultipleChoiceField(label=_("Can Access"),
queryset=Label.objects.none(),
widget=forms.CheckboxSelectMultiple(),
required=False)
def __init__(self, *args, **kwargs):
org = kwargs.pop('org')
super(PartnerCreateForm, self).__init__(*args, **kwargs)
self.fields['labels'].queryset = Label.get_all(org).order_by('name')
class Meta:
model = Partner
fields = ('name', 'description', 'logo', 'is_restricted', 'labels')
|
Fix a platform detection bug | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = 'bsd'
DIRECTORIES = ['functional'] # Unit tests to be added here
def run_test(file):
print "Running test: %s" % file
print
proc = subprocess.Popen("python %s" % file,
shell=True,
stdout=subprocess.PIPE)
output = proc.communicate()[0]
print output
# We don't do anything with this yet but I'll probably try and group all
# these calls up and keep track of the data at the top level
if output.find('OK'):
return True
return False
for directory in DIRECTORIES:
files = os.listdir(directory)
for file in files:
file_path = os.path.join(directory, file)
if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
if file[:-3] in PLATFORMS:
if platform == file[:-3]:
run_test(file_path)
else:
run_test(file_path)
| """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = 'bsd'
DIRECTORIES = ['functional'] # Unit tests to be added here
def run_test(file):
print "Running test: %s" % file
print
proc = subprocess.Popen("python %s" % file,
shell=True,
stdout=subprocess.PIPE)
output = proc.communicate()[0]
print output
# We don't do anything with this yet but I'll probably try and group all
# these calls up and keep track of the data at the top level
if output.find('OK'):
return True
return False
for directory in DIRECTORIES:
files = os.listdir(directory)
for file in files:
file_path = os.path.join(directory, file)
if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
if file[:-3] in PLATFORMS:
if platform == file[:3]:
run_test(file_path)
else:
run_test(file_path)
|
Add comment to traverseDOM function | const Bulma = {
/**
* Current BulmaJS version.
* @type {String}
*/
VERSION: '0.3.0',
/**
* Helper method to create a new plugin.
* @param {String} key
* @param {Object} options
* @return {Object}
*/
create(key, options) {
if(!key || !Bulma.hasOwnProperty(key)) {
throw new Error('[BulmaJS] A plugin with the key \''+key+'\' has not been registered.');
}
return Bulma[key].create(options);
},
/**
* Register a new plugin
* @param {String} key
* @param {Object} plugin
*/
registerPlugin(key, plugin) {
if(!key) {
throw new Error('[BulmaJS] Key attribute is required.');
}
this[key] = plugin;
},
/**
* Parse the HTML DOM searching for data-bulma attributes. We will then pass
* each element to the appropriate plugin to handle the required processing.
*/
traverseDOM() {
let elements = document.querySelectorAll('[data-bulma]');
elements.forEach(function(element) {
let plugin = element.getAttribute('data-bulma');
if(!Bulma.hasOwnProperty(plugin)) {
throw new Error('[BulmaJS] Plugin with the key \''+plugin+'\' has not been registered.');
}
if(Bulma[plugin].hasOwnProperty('handleDomParsing')) {
Bulma[element.getAttribute('data-bulma')].handleDomParsing(element);
}
});
}
};
document.addEventListener('DOMContentLoaded', () => {
Bulma.traverseDOM();
});
export default Bulma;
| const Bulma = {
/**
* Current BulmaJS version.
* @type {String}
*/
VERSION: '0.3.0',
/**
* Helper method to create a new plugin.
* @param {String} key
* @param {Object} options
* @return {Object}
*/
create(key, options) {
if(!key || !Bulma.hasOwnProperty(key)) {
throw new Error('[BulmaJS] A plugin with the key \''+key+'\' has not been registered.');
}
return Bulma[key].create(options);
},
/**
* Register a new plugin
* @param {String} key
* @param {Object} plugin
*/
registerPlugin(key, plugin) {
if(!key) {
throw new Error('[BulmaJS] Key attribute is required.');
}
this[key] = plugin;
},
traverseDOM() {
let elements = document.querySelectorAll('[data-bulma]');
elements.forEach(function(element) {
let plugin = element.getAttribute('data-bulma');
if(!Bulma.hasOwnProperty(plugin)) {
throw new Error('[BulmaJS] Plugin with the key \''+plugin+'\' has not been registered.');
}
if(Bulma[plugin].hasOwnProperty('handleDomParsing')) {
Bulma[element.getAttribute('data-bulma')].handleDomParsing(element);
}
});
}
};
document.addEventListener('DOMContentLoaded', () => {
Bulma.traverseDOM();
});
export default Bulma;
|
Make zero-element bubbles a bit smaller | import { hierarchy } from 'd3-hierarchy';
export default class Clusters {
constructor () {
this.data = {
children: [
{
cluster: 'non-anomalous',
value: 0
},
{
cluster: 'anomalous',
value: 0,
children: []
}
]
};
}
add () {
this.data.children[0].value++;
}
remove () {
this.data.children[0].value--;
}
addAnomalous (cluster) {
this.ensureCluster(cluster);
this.data.children[1].children[cluster].value++;
}
removeAnomalous (cluster) {
this.data.children[1].children[cluster].value--;
}
ensureCluster (cluster) {
if (this.data.children[1].children.length <= cluster) {
for (let i = this.data.children[1].children.length; i < cluster + 1; i++) {
this.data.children[1].children[i] = {
cluster: i,
value: 0
};
}
}
}
hierarchy () {
return hierarchy(this.data)
.sum(d => d.value || 0.01);
}
count () {
return this.data.children[0].value;
}
anomalousCounts () {
return this.data.children[1].children
.sort((a, b) => a.cluster - b.cluster)
.map(d => d.value);
}
}
| import { hierarchy } from 'd3-hierarchy';
export default class Clusters {
constructor () {
this.data = {
children: [
{
cluster: 'non-anomalous',
value: 0
},
{
cluster: 'anomalous',
value: 0,
children: []
}
]
};
}
add () {
this.data.children[0].value++;
}
remove () {
this.data.children[0].value--;
}
addAnomalous (cluster) {
this.ensureCluster(cluster);
this.data.children[1].children[cluster].value++;
}
removeAnomalous (cluster) {
this.data.children[1].children[cluster].value--;
}
ensureCluster (cluster) {
if (this.data.children[1].children.length <= cluster) {
for (let i = this.data.children[1].children.length; i < cluster + 1; i++) {
this.data.children[1].children[i] = {
cluster: i,
value: 0
};
}
}
}
hierarchy () {
return hierarchy(this.data)
.sum(d => d.value || 0.1);
}
count () {
return this.data.children[0].value;
}
anomalousCounts () {
return this.data.children[1].children
.sort((a, b) => a.cluster - b.cluster)
.map(d => d.value);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.