text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add new components to top of sidebar | import Service from '@ember/service';
import Evented from '@ember/object/evented';
export default Service.extend(Evented, {
showWindow: false,
shownComponents: null,
popupContent: null,
addComponent(path) {
if (this.get('shownComponents') == null) {
this.set('shownComponents', []);
}
if (!this.get('shownComponents').includes(path)) {
this.get('shownComponents').unshift(path);
this.notifyPropertyChange('shownComponents');
}
},
removeComponent(path) {
if (!this.get('shownComponents'))
return;
var index = this.get('shownComponents').indexOf(path);
if (index !== -1){
this.get('shownComponents').splice(index, 1);
this.notifyPropertyChange('shownComponents');
}
// close everything when no components are left
if (this.get('shownComponents.length') == 0)
this.emptyAndClose()
},
emptyAndClose() {
this.close();
if (this.get('shownComponents')) {
this.set('shownComponents.length', 0);
}
},
close() {
this.set('showWindow', false);
this.trigger('showWindow');
},
openAdditionalData() {
this.set('showWindow', true);
this.trigger('showWindow');
},
setPopupContent(content) {
this.set('popupContent', content);
},
removePopup() {
this.set('popupContent', null);
}
});
| import Service from '@ember/service';
import Evented from '@ember/object/evented';
export default Service.extend(Evented, {
showWindow: false,
shownComponents: null,
popupContent: null,
addComponent(path) {
if (this.get('shownComponents') == null) {
this.set('shownComponents', []);
}
if (!this.get('shownComponents').includes(path)) {
this.get('shownComponents').push(path);
this.notifyPropertyChange('shownComponents');
}
},
removeComponent(path) {
if (!this.get('shownComponents'))
return;
var index = this.get('shownComponents').indexOf(path);
if (index !== -1){
this.get('shownComponents').splice(index, 1);
this.notifyPropertyChange('shownComponents');
}
// close everything when no components are left
if (this.get('shownComponents.length') == 0)
this.emptyAndClose()
},
emptyAndClose() {
this.close();
if (this.get('shownComponents')) {
this.set('shownComponents.length', 0);
}
},
close() {
this.set('showWindow', false);
this.trigger('showWindow');
},
openAdditionalData() {
this.set('showWindow', true);
this.trigger('showWindow');
},
setPopupContent(content) {
this.set('popupContent', content);
},
removePopup() {
this.set('popupContent', null);
}
});
|
Remove redundant status code from error response body. | """API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""
self.status = status or self.__class__.status
self.error = error or self.__class__.error
@property
def response(self):
"""Return the error as a repsonse tuple."""
return {'error': self.error}, self.status
def get_error_response(error):
"""Return an error as a response tuple."""
if isinstance(error, HTTPException):
error = Error(error.name, error.code)
if not isinstance(error, Error):
error = Error()
return error.response
| """API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""
self.status = status or self.__class__.status
self.error = error or self.__class__.error
@property
def response(self):
"""Return the error as a repsonse tuple."""
return {'status': self.status, 'error': self.error}, self.status
def get_error_response(error):
"""Return an error as a response tuple."""
if isinstance(error, HTTPException):
error = Error(error.name, error.code)
if not isinstance(error, Error):
error = Error()
return error.response
|
Remove unused '/matches/:year' API for now | 'use strict';
var moment = require('moment');
var restify = require('restify');
var mongoose = require('mongoose');
var Match = mongoose.model('match');
var server = restify.createServer();
server.get('/matches/:year/:week', function(req, res) {
var year = req.params.year;
var week = req.params.week;
var endOfWeek = moment().year(year).week(week).endOf('week');
var startOfWeek = moment().year(year).week(week).startOf('week');
var query = {
'startedAt': {
'$gte': startOfWeek.toDate(),
'$lte': endOfWeek.toDate(),
}
}
Match.find(query, function(err, matches) {
if(err) {
return res.send(500, err);
}
return res.json(200, matches);
});
});
module.exports = server;
| 'use strict';
var moment = require('moment');
var restify = require('restify');
var mongoose = require('mongoose');
var Match = mongoose.model('match');
var server = restify.createServer();
server.get('/matches/:year', function(req, res) {
});
server.get('/matches/:year/:week', function(req, res) {
var year = req.params.year;
var week = req.params.week;
var endOfWeek = moment().year(year).week(week).endOf('week');
var startOfWeek = moment().year(year).week(week).startOf('week');
var query = {
'startedAt': {
'$gte': startOfWeek.toDate(),
'$lte': endOfWeek.toDate(),
}
}
Match.find(query, function(err, matches) {
if(err) {
return res.send(500, err);
}
return res.json(200, matches);
});
});
module.exports = server;
|
Reduce title, description search boost on document | from elasticsearch_dsl.query import Q
from froide.helper.search.views import BaseSearchView
from froide.helper.search.filters import BaseSearchFilterSet
from filingcabinet.models import Page
from .documents import PageDocument
class DocumentFilterset(BaseSearchFilterSet):
query_fields = ['title^3', 'description^2', 'content']
class DocumentSearch(BaseSearchView):
search_name = 'document'
template_name = 'document/search.html'
object_template = 'document/result_item.html'
model = Page
document = PageDocument
filterset = DocumentFilterset
search_url_name = 'document-search'
select_related = ('document',)
def get_base_search(self):
# FIXME: add team
q = Q('term', public=True)
if self.request.user.is_authenticated:
q |= Q('term', user=self.request.user.pk)
return super().get_base_search().filter(q)
| from elasticsearch_dsl.query import Q
from froide.helper.search.views import BaseSearchView
from froide.helper.search.filters import BaseSearchFilterSet
from filingcabinet.models import Page
from .documents import PageDocument
class DocumentFilterset(BaseSearchFilterSet):
query_fields = ['title^5', 'description^3', 'content']
class DocumentSearch(BaseSearchView):
search_name = 'document'
template_name = 'document/search.html'
object_template = 'document/result_item.html'
model = Page
document = PageDocument
filterset = DocumentFilterset
search_url_name = 'document-search'
select_related = ('document',)
def get_base_search(self):
# FIXME: add team
q = Q('term', public=True)
if self.request.user.is_authenticated:
q |= Q('term', user=self.request.user.pk)
return super().get_base_search().filter(q)
|
Add NUS module information to display when searched | import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
Meteor.publish('modules', function(startUp, limit, PUField, regionField, search) {
check(search, Match.OneOf(String, null, undefined));
check(regionField, Match.OneOf(String, null, undefined));
check(PUField, Match.OneOf(String, null, undefined));
if (startUp === true) {
return null;
}
let query = {}, regex = new RegExp('');
const projection = {limit: 1, sort: {PrevMatch: -1, Similarity: -1, created: 1}};
// sort in descending order according to Similarity field
if (search) {
regex = new RegExp(`^`+search+`$`, 'i'); //search for PU modules that are mapped exactly to the NUS module code entered by user
if (PUField) {
query['UniversityName'] = PUField;
}
if (regionField) {
query['Region'] = regionField;
}
query['NUSModuleCode'] = regex;
projection.limit = limit;
}
return [NUSMods.find({'ModuleCode': regex}), Modules.find(query, projection)];
});
| import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
Meteor.publish('modules', function(limit, PUField, regionField, search) {
check(search, Match.OneOf(String, null, undefined));
check(regionField, Match.OneOf(String, null, undefined));
check(PUField, Match.OneOf(String, null, undefined));
let query = {};
const projection = {limit: limit, sort: {PrevMatch: -1, Similarity: -1, created: 1}};
// sort in descending order according to Similarity field
if (search) {
let regex = new RegExp(`^`+search+`$`, 'i'); //search for PU modules that are mapped exactly to the NUS module code entered by user
if (PUField) {
query['UniversityName'] = PUField;
}
if (regionField) {
query['Region'] = regionField;
}
query['NUSModuleCode'] = regex;
}
return Modules.find(query, projection);
});
|
Add description and author meta tags | import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render () {
return (
<html>
<head>
<title>
{this.props.title}
</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link type='text/css' rel='stylesheet' href='/app.bundle.css' />
<link rel='dns-prefetch' href='https://github.com/' />
<link rel='dns-prefetch' href='https://www.svager.cz/' />
<meta name='description' content='Analyze your site’s speed according to HTTP best practices.' />
<meta name='author' content='Jan Svager <https://www.svager.cz>' />
</head>
<body>
<div id='app' dangerouslySetInnerHTML={{ __html: this.props.children }} />
<script src='/init.bundle.js' />
<script async defer src='/react.bundle.js' />
<script async defer src='/app.bundle.js' />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
| import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render () {
return (
<html>
<head>
<title>
{this.props.title}
</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link type='text/css' rel='stylesheet' href='/app.bundle.css' />
<link rel='dns-prefetch' href='https://github.com/' />
<link rel='dns-prefetch' href='https://www.svager.cz/' />
</head>
<body>
<div id='app' dangerouslySetInnerHTML={{ __html: this.props.children }} />
<script src='/init.bundle.js' />
<script async defer src='/react.bundle.js' />
<script async defer src='/app.bundle.js' />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
|
Add comment explaining the version | /**
* Copyright 2016 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.keyvalue.cassandra;
import java.util.Arrays;
public class CassandraServerVersion {
private final int majorVersion;
private final int minorVersion;
public CassandraServerVersion(String versionString) {
String[] components = versionString.split("\\.");
if (components.length != 3) {
throw new UnsupportedOperationException(String.format("Illegal version of Thrift protocol detected; expected format '#.#.#', got '%s'", Arrays.toString(components)));
}
majorVersion = Integer.parseInt(components[0]);
minorVersion = Integer.parseInt(components[1]);
}
// This corresponds to the version change in https://github.com/apache/cassandra/commit/8b0e1868e8cf813ddfc98d11448aa2ad363eccc1#diff-2fa34d46c5a51e59f77d866bbe7ca02aR55
public boolean supportsCheckAndSet() {
return majorVersion > 19 || (majorVersion == 19 && minorVersion >= 37);
}
}
| /**
* Copyright 2016 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.keyvalue.cassandra;
import java.util.Arrays;
public class CassandraServerVersion {
private final int majorVersion;
private final int minorVersion;
public CassandraServerVersion(String versionString) {
String[] components = versionString.split("\\.");
if (components.length != 3) {
throw new UnsupportedOperationException(String.format("Illegal version of Thrift protocol detected; expected format '#.#.#', got '%s'", Arrays.toString(components)));
}
majorVersion = Integer.parseInt(components[0]);
minorVersion = Integer.parseInt(components[1]);
}
public boolean supportsCheckAndSet() {
return majorVersion > 19 || (majorVersion == 19 && minorVersion >= 37);
}
}
|
Refactor home test method names | <?php
namespace OpenDominion\Tests\Http;
use CoreDataSeeder;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use OpenDominion\Tests\AbstractHttpTestCase;
class HomeTest extends AbstractHttpTestCase
{
use DatabaseMigrations;
public function testIndex()
{
$this->get('/')
->assertStatus(200);
}
public function testRedirectLoggedUserWithoutSelectedDominionToDashboard()
{
$user = $this->createAndImpersonateUser();
$this->actingAs($user)
->get('/')
->assertRedirect('/dashboard');
}
public function testRedirectLoggedUserWithSelectedDominionToStatus()
{
$this->seed(CoreDataSeeder::class);
$user = $this->createAndImpersonateUser();
$round = $this->createRound();
$this->createAndSelectDominion($user, $round);
$this->actingAs($user)
->get('/')
->assertRedirect('/dominion/status');
}
}
| <?php
namespace OpenDominion\Tests\Http;
use CoreDataSeeder;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use OpenDominion\Tests\AbstractHttpTestCase;
class HomeTest extends AbstractHttpTestCase
{
use DatabaseMigrations;
public function testIndex()
{
$this->get('/')
->assertStatus(200);
}
public function testRedirectLoggedWithoutSelectedDominionToDashboard()
{
$user = $this->createAndImpersonateUser();
$this->actingAs($user)
->get('/')
->assertRedirect('/dashboard');
}
public function testRedirectLoggedWithSelectedDominionToStatus()
{
$this->seed(CoreDataSeeder::class);
$user = $this->createAndImpersonateUser();
$round = $this->createRound();
$this->createAndSelectDominion($user, $round);
$this->actingAs($user)
->get('/')
->assertRedirect('/dominion/status');
}
}
|
Make test in IE pass | describe('Operations', function () {
var isNode = typeof module !== 'undefined' && module.exports;
var Parallel = isNode ? require('../lib/parallel.js') : self.Parallel;
it('should require(), map() and reduce correctly (check console errors)', function () {
var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8], { evalPath: isNode ? undefined : 'lib/eval.js' });
function add(d) { return d[0] + d[1]; }
function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); }
p.require(factorial);
var done = false;
runs(function () {
p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(function() {
done = true;
});
});
waitsFor(function () {
return done;
}, "it should finish", 500);
});
}); | describe('Operations', function () {
var isNode = typeof module !== 'undefined' && module.exports;
var Parallel = isNode ? require('../lib/parallel.js') : self.Parallel;
it('should require(), map() and reduce correctly (check console errors)', function () {
var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8]);
function add(d) { return d[0] + d[1]; }
function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); }
p.require(factorial);
var done = false;
runs(function () {
p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(function() {
done = true;
});
});
waitsFor(function () {
return done;
}, "it should finish", 500);
});
}); |
Increase "around" margin as tests are running quite slowly sometimes. | /**
* Copyright (C) 2015 MicroWorld (contact@microworld.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.microworld.test.matchers;
import java.time.Instant;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
public class IsAround extends TypeSafeDiagnosingMatcher<Instant> {
private static final int MARGIN = 15;
private final Instant instant;
public IsAround(final Instant instant) {
this.instant = instant;
}
@Override
public void describeTo(final Description description) {
description.appendValue(instant);
}
@Override
protected boolean matchesSafely(final Instant item, final Description mismatchDescription) {
if (instant.minusSeconds(MARGIN).isAfter(item) || instant.plusSeconds(MARGIN).isBefore(item)) {
mismatchDescription.appendText("was ").appendValue(item);
return false;
}
return true;
}
}
| /**
* Copyright (C) 2015 MicroWorld (contact@microworld.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.microworld.test.matchers;
import java.time.Instant;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
public class IsAround extends TypeSafeDiagnosingMatcher<Instant> {
private final Instant instant;
public IsAround(final Instant instant) {
this.instant = instant;
}
@Override
public void describeTo(final Description description) {
description.appendValue(instant);
}
@Override
protected boolean matchesSafely(final Instant item, final Description mismatchDescription) {
if (instant.minusSeconds(10).isAfter(item) || instant.plusSeconds(10).isBefore(item)) {
mismatchDescription.appendText("was ").appendValue(item);
return false;
}
return true;
}
}
|
Fix proptype for linepath 'defined' prop | import React from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';
import { line } from 'd3-shape';
LinePath.propTypes = {
innerRef: PropTypes.func,
data: PropTypes.array,
curve: PropTypes.func,
defined: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
x: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
y: PropTypes.oneOfType([PropTypes.func, PropTypes.number])
};
export default function LinePath({
children,
data,
x,
y,
fill = 'transparent',
className,
curve,
innerRef,
defined = () => true,
...restProps
}) {
const path = line();
if (x) path.x(x);
if (y) path.y(y);
if (defined) path.defined(defined);
if (curve) path.curve(curve);
if (children) return children({ path });
return (
<path
ref={innerRef}
className={cx('vx-linepath', className)}
d={path(data)}
fill={fill}
{...restProps}
/>
);
}
| import React from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';
import { line } from 'd3-shape';
LinePath.propTypes = {
innerRef: PropTypes.func,
data: PropTypes.array,
curve: PropTypes.func,
defined: PropTypes.oneOf([PropTypes.func, PropTypes.bool]),
x: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
y: PropTypes.oneOfType([PropTypes.func, PropTypes.number])
};
export default function LinePath({
children,
data,
x,
y,
fill = 'transparent',
className,
curve,
innerRef,
defined = () => true,
...restProps
}) {
const path = line();
if (x) path.x(x);
if (y) path.y(y);
if (defined) path.defined(defined);
if (curve) path.curve(curve);
if (children) return children({ path });
return (
<path
ref={innerRef}
className={cx('vx-linepath', className)}
d={path(data)}
fill={fill}
{...restProps}
/>
);
}
|
Fix last value disappearing when it coincides with completion | import { Observable } from 'rxjs/Observable'
import { merge } from 'rxjs/observable/merge'
import { takeUntil } from 'rxjs/operator/takeUntil'
import { share } from 'rxjs/operator/share'
const makeVirtualEmission = (scheduler, value, delay) => {
return new Observable(observer => {
scheduler.schedule(() => {
observer.next(value)
}, delay, value)
})
}
const makeVirtualStream = (scheduler, diagram) => {
const { emissions, completion } = diagram
const partials = emissions.map(({ x, d }) => (
makeVirtualEmission(scheduler, d, x)
))
const completion$ = makeVirtualEmission(scheduler, null, completion + .0001)
const emission$ = merge(...partials)
::takeUntil(completion$)
::share()
return emission$
}
export default makeVirtualStream
| import { Observable } from 'rxjs/Observable'
import { merge } from 'rxjs/observable/merge'
import { takeUntil } from 'rxjs/operator/takeUntil'
import { share } from 'rxjs/operator/share'
const makeVirtualEmission = (scheduler, value, delay) => {
return new Observable(observer => {
scheduler.schedule(() => {
observer.next(value)
}, delay, value)
})
}
const makeVirtualStream = (scheduler, diagram) => {
const { emissions, completion } = diagram
const partials = emissions.map(({ x, d }) => (
makeVirtualEmission(scheduler, d, x)
))
const completion$ = makeVirtualEmission(scheduler, null, completion)
const emission$ = merge(...partials)
::takeUntil(completion$)
::share()
return emission$
}
export default makeVirtualStream
|
Update command line interface to accept floating point input | # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == 0:
return [ ticks[0] for t in data]
else:
return [ ticks[int((t - m) / n)] for t in data ]
def print_ansi_spark(d):
print ''.join(d)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process numbers')
parser.add_argument('numbers', metavar='N', type=float, nargs='+',
help='series of data to plot')
args = parser.parse_args()
print_ansi_spark(scale_data(args.numbers))
| # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == 0:
return [ ticks[0] for t in data]
else:
return [ ticks[int((t - m) / n)] for t in data ]
def print_ansi_spark(d):
print ''.join(d)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
args = parser.parse_args()
print_ansi_spark(scale_data(args.integers))
|
Make $argv and $argc globally accessible for command-line checks | <?php
use MarkLogic\MLPHP;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// For access to command-line options
global $argv, $argc;
// Create a logger for tests
$logger = new Logger('test');
$logger->pushHandler(new StreamHandler('php://stderr', Logger::ERROR));
// Global config properties for tests
$mlphp = new MLPHP\MLPHP([
'host' => '127.0.0.1',
'port' => 8234,
'managePort' => 8002,
'api' => 'mlphp-test-api',
'db' => 'mlphp-test-db',
'username' => 'admin',
'password' => 'admin',
'path' => '',
'managePath' => 'manage',
'version' => 'v1',
'manageVersion' => 'v2',
'auth' => 'digest',
'logger' => $logger
]);
// Create REST API for tests
$api = $mlphp->getAPI()->create();
// Run after all tests complete
register_shutdown_function(function(){
global $mlphp;
// Delete REST API
$api = $mlphp->getAPI();
if ($api->exists()) {
$api->delete();
}
});
?>
| <?php
use MarkLogic\MLPHP;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// Create a logger for tests
$logger = new Logger('test');
$logger->pushHandler(new StreamHandler('php://stderr', Logger::ERROR));
// Global config properties for tests
$mlphp = new MLPHP\MLPHP([
'host' => '127.0.0.1',
'port' => 8234,
'managePort' => 8002,
'api' => 'mlphp-test-api',
'db' => 'mlphp-test-db',
'username' => 'admin',
'password' => 'admin',
'path' => '',
'managePath' => 'manage',
'version' => 'v1',
'manageVersion' => 'v2',
'auth' => 'digest',
'logger' => $logger
]);
// Create REST API for tests
$api = $mlphp->getAPI()->create();
// Run after all tests complete
register_shutdown_function(function(){
global $mlphp;
// Delete REST API
$api = $mlphp->getAPI();
if ($api->exists()) {
$api->delete();
}
});
?>
|
Add separate "plotting" script for general plot setup.
git-svn-id: b93d21f79df1f7407664ec6e512ac344bf52ef2a@711 f9184c78-529c-4a83-b317-4cf1064cc5e0 | #!/usr/bin/env python
# encoding: utf-8
"""
__init__.py
Created by Gabriel Brammer on 2011-05-18.
$URL$
$Author$
$Date$
"""
__version__ = "$Rev$"
from socket import gethostname as hostname
if hostname().startswith('uni'):
GRISM_HOME = '/3DHST/Spectra/Work/'
else:
GRISM_HOME = '/research/HST/GRISM/3DHST/'
if hostname().startswith('850dhcp8'):
GRISM_HOME = '/3DHST/Spectra/Work/'
#threedhst.sex.RUN_MODE='direct'
import threedhst
try:
import utils_c #as utils_c
except:
print """Couldn't import "utils_c" """
import plotting
import prepare
import reduce
import candels
import analysis
import go_3dhst
import galfit
import catalogs
import survey_paper
import go_acs
import fast
import interlace_fit
import intersim
noNewLine = '\x1b[1A\x1b[1M'
| #!/usr/bin/env python
# encoding: utf-8
"""
__init__.py
Created by Gabriel Brammer on 2011-05-18.
$URL$
$Author$
$Date$
"""
__version__ = "$Rev$"
from socket import gethostname as hostname
if hostname().startswith('uni'):
GRISM_HOME = '/3DHST/Spectra/Work/'
else:
GRISM_HOME = '/research/HST/GRISM/3DHST/'
if hostname().startswith('850dhcp8'):
GRISM_HOME = '/3DHST/Spectra/Work/'
#threedhst.sex.RUN_MODE='direct'
import threedhst
try:
import utils_c #as utils_c
except:
print """Couldn't import "utils_c" """
import prepare
import reduce
import candels
import analysis
import go_3dhst
import galfit
import plotting
import catalogs
import survey_paper
import go_acs
import fast
import interlace_fit
import intersim
noNewLine = '\x1b[1A\x1b[1M'
|
Change fluid slot to only use IFluidHandlerModifiable | package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IFluidHandlerModifiable fluidHandler;
private final int index;
public final int x;
public final int y;
public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
| package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.InteractionType;
import info.u_team.u_team_core.api.fluid.IExtendedFluidHandler;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IExtendedFluidHandler fluidHandler;
private final int index;
public final int x;
public final int y;
public FluidSlot(IExtendedFluidHandler fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public FluidStack insert(FluidStack stack) {
return fluidHandler.insertFluid(index, stack, InteractionType.EXECUTE);
}
public FluidStack extract(int amount) {
return fluidHandler.extractFluid(index, amount, InteractionType.EXECUTE);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
|
Add support for arg "body" in rpc method proxy/requests | // Requires
var Q = require('q');
var _ = require('underscore');
var request = require('request');
function ProxyRPCService() {
_.bindAll(this);
}
ProxyRPCService.prototype.requests = function(args, meta) {
var deferred = Q.defer();
var url = args.url;
var method = args.method || "GET";
var options = {
"method": method,
"uri": url,
"body": args.body || meta.req.body
};
if (url == null) {
deferred.reject(new Error("need 'url'"));
} else {
request(options, function (error, response, body) {
deferred.resolve({
"statusCode": response.statusCode,
"body": response.body
});
});
}
return deferred.promise;
};
// Exports
exports.ProxyRPCService = ProxyRPCService;
| // Requires
var Q = require('q');
var _ = require('underscore');
var request = require('request');
function ProxyRPCService() {
_.bindAll(this);
}
ProxyRPCService.prototype.requests = function(args, meta) {
var deferred = Q.defer();
var url = args.url;
var method = args.method || "GET";
var options = {
"method": method,
"uri": url,
"body": meta.req.body
};
if (url == null) {
deferred.reject(new Error("need 'url'"));
} else {
request(options, function (error, response, body) {
deferred.resolve({
"statusCode": response.statusCode,
"body": response.body
});
});
}
return deferred.promise;
};
// Exports
exports.ProxyRPCService = ProxyRPCService;
|
[435610] Fix resource delegation in installer (icons were missing) | /*
* Copyright (c) 2014 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.oomph.setup.internal.installer;
import org.eclipse.oomph.setup.ui.SetupUIPlugin;
import org.eclipse.oomph.ui.AbstractOomphUIPlugin;
import org.eclipse.emf.common.ui.EclipseUIPlugin;
import org.eclipse.emf.common.util.ResourceLocator;
import org.osgi.framework.BundleContext;
/**
* @author Eike Stepper
*/
public final class SetupInstallerPlugin extends AbstractOomphUIPlugin
{
public static final SetupInstallerPlugin INSTANCE = new SetupInstallerPlugin();
private static Implementation plugin;
public SetupInstallerPlugin()
{
super(new ResourceLocator[] { SetupUIPlugin.INSTANCE });
}
@Override
public ResourceLocator getPluginResourceLocator()
{
return plugin;
}
/**
* @author Eike Stepper
*/
public static class Implementation extends EclipseUIPlugin
{
public Implementation()
{
plugin = this;
}
@Override
public void start(BundleContext context) throws Exception
{
super.start(context);
}
}
}
| /*
* Copyright (c) 2014 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.oomph.setup.internal.installer;
import org.eclipse.oomph.ui.AbstractOomphUIPlugin;
import org.eclipse.emf.common.ui.EclipseUIPlugin;
import org.eclipse.emf.common.util.ResourceLocator;
import org.osgi.framework.BundleContext;
/**
* @author Eike Stepper
*/
public final class SetupInstallerPlugin extends AbstractOomphUIPlugin
{
public static final SetupInstallerPlugin INSTANCE = new SetupInstallerPlugin();
private static Implementation plugin;
public SetupInstallerPlugin()
{
super(new ResourceLocator[] {});
}
@Override
public ResourceLocator getPluginResourceLocator()
{
return plugin;
}
/**
* @author Eike Stepper
*/
public static class Implementation extends EclipseUIPlugin
{
public Implementation()
{
plugin = this;
}
@Override
public void start(BundleContext context) throws Exception
{
super.start(context);
}
}
}
|
Add test case for hoisting a single function | multiple_functions: {
options = { if_return: true, hoist_funs: false };
input: {
( function() {
if ( !window ) {
return;
}
function f() {}
function g() {}
} )();
}
expect: {
( function() {
function f() {}
function g() {}
// NOTE: other compression steps will reduce this
// down to just `window`.
if ( window );
} )();
}
}
single_function: {
options = { if_return: true, hoist_funs: false };
input: {
( function() {
if ( !window ) {
return;
}
function f() {}
} )();
}
expect: {
( function() {
function f() {}
if ( window );
} )();
}
}
| hoist_funs_when_handling_if_return_rerversal: {
options = { if_return: true, hoist_funs: false };
input: {
"use strict";
( function() {
if ( !window ) {
return;
}
function f() {}
function g() {}
} )();
}
expect: {
"use strict";
( function() {
function f() {}
function g() {}
// NOTE: other compression steps will reduce this
// down to just `window`.
if ( window );
} )();
}
}
|
Make identifiers camel-case; remove redundant space. | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
# Camel-caes
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: ClassVar[str]
elif_var: ClassVar[str]
else_var: ClassVar[str]
try_var: ClassVar[str]
except_var: ClassVar[str]
finally_var: ClassVar[str]
with_var: ClassVar[str]
forVar: ClassVar[str]
whileVar: ClassVar[str]
defVar: ClassVar[str]
ifVar: ClassVar[str]
elifVar: ClassVar[str]
elseVar: ClassVar[str]
tryVar: ClassVar[str]
exceptVar: ClassVar[str]
finallyVar: ClassVar[str]
withVar: ClassVar[str]
def m(self):
xs: List[int] = []
| #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: ClassVar[str]
elif_var: ClassVar[str]
else_var: ClassVar[str]
try_var: ClassVar[str]
except_var: ClassVar[str]
finally_var: ClassVar[str]
with_var: ClassVar[str]
For_var: ClassVar[str]
While_var: ClassVar[str]
Def_var: ClassVar[str]
If_var: ClassVar[str]
Elif_var: ClassVar[str]
Else_var: ClassVar[str]
Try_var: ClassVar[str]
Except_var: ClassVar[str]
Finally_var: ClassVar[str]
With_var: ClassVar[str]
def m(self):
xs: List[int] = []
|
Fix Result status in Security Checker | <?php
namespace PragmaRX\Health\Checkers;
use PragmaRX\Health\Support\Result;
use SensioLabs\Security\SecurityChecker as SensioLabsSecurityChecker;
class SecurityChecker extends Base
{
/**
* Check resource.
*
* @return Result
*/
public function check()
{
$checker = new SensioLabsSecurityChecker();
$alerts = $checker->check(base_path('composer.lock'));
if (count($alerts) == 0) {
return $this->makeHealthyResult();
}
$problems = collect($alerts)
->keys()
->implode(', ');
return $this->makeResult(
false,
sprintf($this->target->getErrorMessage(), $problems)
);
}
}
| <?php
namespace PragmaRX\Health\Checkers;
use PragmaRX\Health\Support\Result;
use SensioLabs\Security\SecurityChecker as SensioLabsSecurityChecker;
class SecurityChecker extends Base
{
/**
* Check resource.
*
* @return Result
*/
public function check()
{
$checker = new SensioLabsSecurityChecker();
$alerts = $checker->check(base_path('composer.lock'));
if (count($alerts) == 0) {
return $this->makeHealthyResult();
}
$problems = collect($alerts)
->keys()
->implode(', ');
return $this->makeResult(
$isHealthy,
sprintf($this->target->getErrorMessage(), $problems)
);
}
}
|
Upgrade jade from 1.1.5 to 1.2.0 | Package.describe({
summary: "Jade template language for Meteor"
});
Package._transitional_registerBuildPlugin({
name: "compileJade",
use: [
"underscore",
"html-tools",
"spacebars-compiler",
],
sources: [
"plugin/lexer.js",
"plugin/parser.js",
"plugin/filters.js",
"plugin/compiler.js",
"plugin/handler.js",
],
npmDependencies: {
"jade": "1.2.0",
"markdown": "0.5.0",
}
});
Package.on_test(function (api) {
api.use("jade");
api.use("tinytest");
api.add_files("tests/tests.jade");
api.add_files("tests/client.js", "client");
api.add_files("tests/server.js", "server");
});
| Package.describe({
summary: "Jade template language for Meteor"
});
Package._transitional_registerBuildPlugin({
name: "compileJade",
use: [
"underscore",
"html-tools",
"spacebars-compiler",
],
sources: [
"plugin/lexer.js",
"plugin/parser.js",
"plugin/filters.js",
"plugin/compiler.js",
"plugin/handler.js",
],
npmDependencies: {
"jade": "1.1.5",
"markdown": "0.5.0",
}
});
Package.on_test(function (api) {
api.use("jade");
api.use("tinytest");
api.add_files("tests/tests.jade");
api.add_files("tests/client.js", "client");
api.add_files("tests/server.js", "server");
});
|
Use relative path in assignment test
This is likely the existing behavior, it seemed best to make it
explicit. | package main
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"testing"
)
func TestSavingAssignment(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "")
assert.NoError(t, err)
assignment := Assignment{
Track: "ruby",
Slug: "bob",
Files: map[string]string{
"bob_test.rb": "Tests text",
"README.md": "Readme text",
"path/to/file.rb": "File text",
},
}
err = SaveAssignment(tmpDir, assignment)
assert.NoError(t, err)
readme, err := ioutil.ReadFile(tmpDir + "/ruby/bob/README.md")
assert.NoError(t, err)
assert.Equal(t, string(readme), "Readme text")
tests, err := ioutil.ReadFile(tmpDir + "/ruby/bob/bob_test.rb")
assert.NoError(t, err)
assert.Equal(t, string(tests), "Tests text")
fileInDir, err := ioutil.ReadFile(tmpDir + "/ruby/bob/path/to/file.rb")
assert.NoError(t, err)
assert.Equal(t, string(fileInDir), "File text")
}
| package main
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"testing"
)
func TestSavingAssignment(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "")
assert.NoError(t, err)
assignment := Assignment{
Track: "ruby",
Slug: "bob",
Files: map[string]string{
"bob_test.rb": "Tests text",
"README.md": "Readme text",
"/path/to/file.rb": "File text",
},
}
err = SaveAssignment(tmpDir, assignment)
assert.NoError(t, err)
readme, err := ioutil.ReadFile(tmpDir + "/ruby/bob/README.md")
assert.NoError(t, err)
assert.Equal(t, string(readme), "Readme text")
tests, err := ioutil.ReadFile(tmpDir + "/ruby/bob/bob_test.rb")
assert.NoError(t, err)
assert.Equal(t, string(tests), "Tests text")
fileInDir, err := ioutil.ReadFile(tmpDir + "/ruby/bob/path/to/file.rb")
assert.NoError(t, err)
assert.Equal(t, string(fileInDir), "File text")
}
|
Change search url regexp to match all characters | from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from members import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', views.homepage, name='homepage'),
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^protocols/add/$', 'protocols.views.add', name='add-protocol'),
url(r'^projects/add/$', 'projects.views.add_project', name='add-project'),
url(r'^reports/add/$', 'reports.views.add_report', name='add-report'),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}),
)
| from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from members import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', views.homepage, name='homepage'),
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^search/(?P<name>\w+)/$', 'members.views.search', name='search'),
url(r'^protocols/add/$', 'protocols.views.add', name='add-protocol'),
url(r'^projects/add/$', 'projects.views.add_project', name='add-project'),
url(r'^reports/add/$', 'reports.views.add_report', name='add-report'),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}),
)
|
Exclude vtk.js from lean bundle | // The lean build does not include any of the third-party runtime dependencies, rather
// it assumes they are in the global namespace at runtime.
var config = require('./webpack.base.config');
var merge = require('webpack-merge');
module.exports = merge(config, {
entry: {
'geo.lean': './index.js',
'geo.lean.min': './index.js'
},
externals: {
d3: 'd3',
hammerjs: {
root: 'Hammer',
commonjs: 'hammerjs',
commonjs2: 'hammerjs',
amd: 'hammerjs',
// Since GeoJS's libraryTarget is "umd", defining this (undocumented) external library type
// will allow Webpack to create a better error message if a "hammerjs" import fails
umd: 'hammerjs'
},
'vtk.js': 'vtkjs'
}
});
| // The lean build does not include any of the third-party runtime dependencies, rather
// it assumes they are in the global namespace at runtime.
var config = require('./webpack.base.config');
var merge = require('webpack-merge');
module.exports = merge(config, {
entry: {
'geo.lean': './index.js',
'geo.lean.min': './index.js'
},
externals: {
d3: 'd3',
hammerjs: {
root: 'Hammer',
commonjs: 'hammerjs',
commonjs2: 'hammerjs',
amd: 'hammerjs',
// Since GeoJS's libraryTarget is "umd", defining this (undocumented) external library type
// will allow Webpack to create a better error message if a "hammerjs" import fails
umd: 'hammerjs'
}
}
});
|
Move imports to top of file | from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
| class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
Remove async again - not compatibile with leafletjs | var components = require('./components');
var javascript = require('../tasks/javascript');
var extend = require('extend');
/**
* Helper function for rendering a page
* Abstracted out here to reduce some duplication in the main server
*/
var renderPage = function(hbs, data) {
return new Promise(function(resolve, reject) {
var pageData = {
pageTitle: data.title + ' - Land Registry pattern library',
assetPath: '/',
homepageUrl: '/',
content: data.content,
scripts: [],
propositionName: 'Land Registry pattern library'
};
// If any of the demos define pageData we need to pop this up onto the page context
extend(pageData, data.pageData);
// Grab all our components, sort them into bundles and then output the
// necessary script tags to load them
components
.getComponents()
.then(javascript.sort)
.then(function(bundles) {
Object.keys(bundles).forEach(function(bundle) {
pageData.scripts.push('<script defer src="/javascripts/' + bundle + '.js"></script>')
});
})
.then(function() {
pageData.scripts = pageData.scripts.join('\n');
})
.then(function() {
resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData));
})
.catch(function(err) {
reject(err);
});
})
}
module.exports = renderPage;
| var components = require('./components');
var javascript = require('../tasks/javascript');
var extend = require('extend');
/**
* Helper function for rendering a page
* Abstracted out here to reduce some duplication in the main server
*/
var renderPage = function(hbs, data) {
return new Promise(function(resolve, reject) {
var pageData = {
pageTitle: data.title + ' - Land Registry pattern library',
assetPath: '/',
homepageUrl: '/',
content: data.content,
scripts: [],
propositionName: 'Land Registry pattern library'
};
// If any of the demos define pageData we need to pop this up onto the page context
extend(pageData, data.pageData);
// Grab all our components, sort them into bundles and then output the
// necessary script tags to load them
components
.getComponents()
.then(javascript.sort)
.then(function(bundles) {
Object.keys(bundles).forEach(function(bundle) {
pageData.scripts.push('<script async defer src="/javascripts/' + bundle + '.js"></script>')
});
})
.then(function() {
pageData.scripts = pageData.scripts.join('\n');
})
.then(function() {
resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData));
})
.catch(function(err) {
reject(err);
});
})
}
module.exports = renderPage;
|
Add scoreDirector benchmark in the app too | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.taskassigning.app;
import org.optaplanner.examples.common.app.CommonBenchmarkApp;
public class TaskAssigningBenchmarkApp extends CommonBenchmarkApp {
public static void main(String[] args) {
new TaskAssigningBenchmarkApp().buildAndBenchmark(args);
}
public TaskAssigningBenchmarkApp() {
super(
new ArgOption("default",
"org/optaplanner/examples/taskassigning/benchmark/taskAssigningBenchmarkConfig.xml"),
new ArgOption("scoreDirector",
"org/optaplanner/examples/taskassigning/benchmark/taskAssigningScoreDirectorBenchmarkConfig.xml")
);
}
}
| /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.taskassigning.app;
import org.optaplanner.examples.common.app.CommonBenchmarkApp;
public class TaskAssigningBenchmarkApp extends CommonBenchmarkApp {
public static void main(String[] args) {
new TaskAssigningBenchmarkApp().buildAndBenchmark(args);
}
public TaskAssigningBenchmarkApp() {
super(
new ArgOption("default",
"org/optaplanner/examples/taskassigning/benchmark/taskAssigningBenchmarkConfig.xml")
);
}
}
|
Disable web security checks for e2e tests. | /**
* Puppeteer config.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
const config = require( '@wordpress/scripts/config/puppeteer.config.js' );
const coreConfig = config || {};
const coreLaunch = coreConfig.launch || {};
const coreLaunchArgs = coreLaunch.args || [];
module.exports = {
...coreConfig,
launch: {
...coreLaunch,
args: [
// https://peter.sh/experiments/chromium-command-line-switches/
...coreLaunchArgs,
'--disable-gpu',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-web-security',
],
},
};
| /**
* Puppeteer config.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
const config = require( '@wordpress/scripts/config/puppeteer.config.js' );
const coreConfig = config || {};
const coreLaunch = coreConfig.launch || {};
const coreLaunchArgs = coreLaunch.args || [];
module.exports = {
...coreConfig,
launch: {
...coreLaunch,
args: [
// https://peter.sh/experiments/chromium-command-line-switches/
...coreLaunchArgs,
'--disable-gpu',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
],
},
};
|
Fix typo in error message | /*
* Copyright 2013, 2014 Deutsche Nationalbibliothek
*
* Licensed under the Apache License, Version 2.0 the "License";
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.metafacture.metamorph;
import org.metafacture.metamorph.api.MorphErrorHandler;
/**
* Default error handler used by {@link Metamorph}. It simply throw a
* {@link MetamorphException}.
*
* @author Markus Michael Geipel
*/
public final class DefaultErrorHandler implements MorphErrorHandler {
@Override
public void error(final Exception exception) {
throw new MetamorphException(
"Error while executing the Metamorph transformation pipeline: " +
exception.getMessage(), exception);
}
}
| /*
* Copyright 2013, 2014 Deutsche Nationalbibliothek
*
* Licensed under the Apache License, Version 2.0 the "License";
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.metafacture.metamorph;
import org.metafacture.metamorph.api.MorphErrorHandler;
/**
* Default error handler used by {@link Metamorph}. It simply throw a
* {@link MetamorphException}.
*
* @author Markus Michael Geipel
*/
public final class DefaultErrorHandler implements MorphErrorHandler {
@Override
public void error(final Exception exception) {
throw new MetamorphException(
"Error while exectuing the Metamorph transformation pipeline: " +
exception.getMessage(), exception);
}
}
|
Allow save job that had no GH project property before. | package org.jenkinsci.plugins.github.pullrequest;
import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.TransientProjectActionFactory;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRRepositoryFactory extends TransientProjectActionFactory {
private final static Logger LOGGER = Logger.getLogger(GitHubPRRepositoryFactory.class.getName());
@Override
public Collection<? extends Action> createFor(AbstractProject project) {
try {
if (project.getTrigger(GitHubPRTrigger.class) != null) {
return Collections.singleton(GitHubPRRepository.forProject(project));
}
} catch (Throwable t) {
// bad configured project i.e. github project property wrong
return Collections.emptyList();
}
return Collections.emptyList();
}
}
| package org.jenkinsci.plugins.github.pullrequest;
import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.TransientProjectActionFactory;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Kanstantsin Shautsou
*/
@Extension
public class GitHubPRRepositoryFactory extends TransientProjectActionFactory {
private final static Logger LOGGER = Logger.getLogger(GitHubPRRepositoryFactory.class.getName());
@Override
public Collection<? extends Action> createFor(AbstractProject project) {
if (project.getTrigger(GitHubPRTrigger.class) != null) {
return Collections.singleton(GitHubPRRepository.forProject(project));
}
return Collections.emptyList();
}
}
|
Set domain to null for safety | import React from 'react'
import shallowEqual from 'shallowequal'
export const withDomain = ({
domainClass,
mapPropsToArg,
mapPropsToArgsArray = props => mapPropsToArg ? [mapPropsToArg(props)] : [],
createDomain = props => new domainClass(...mapPropsToArgsArray(props)), // eslint-disable-line new-cap
propName = 'domain',
shouldRecreateDomain = (currentProps, nextProps) =>
! shallowEqual(mapPropsToArgsArray(currentProps), mapPropsToArgsArray(nextProps)),
}) =>
Component =>
class DomainProvider extends React.Component {
domain
componentWillMount() {
this.domain = createDomain(this.props)
}
componentWillUpdate(nextProps) {
if (shouldRecreateDomain(this.props, nextProps)) {
this.stop()
this.domain = createDomain(nextProps)
}
}
componentWillUnmount() {
this.stop()
this.domain = null
}
stop() {
if (this.domain && typeof this.domain.stop === 'function') {
this.domain.stop()
}
}
render() {
return React.createElement(Component, { ...this.props, [propName]: this.domain })
}
}
| import React from 'react'
import shallowEqual from 'shallowequal'
export const withDomain = ({
domainClass,
mapPropsToArg,
mapPropsToArgsArray = props => mapPropsToArg ? [mapPropsToArg(props)] : [],
createDomain = props => new domainClass(...mapPropsToArgsArray(props)), // eslint-disable-line new-cap
propName = 'domain',
shouldRecreateDomain = (currentProps, nextProps) =>
! shallowEqual(mapPropsToArgsArray(currentProps), mapPropsToArgsArray(nextProps)),
}) =>
Component =>
class DomainProvider extends React.Component {
domain
componentWillMount() {
this.domain = createDomain(this.props)
}
componentWillUpdate(nextProps) {
if (shouldRecreateDomain(this.props, nextProps)) {
this.stop()
this.domain = createDomain(nextProps)
}
}
componentWillUnmount() {
this.stop()
}
stop() {
if (this.domain && typeof this.domain.stop === 'function') {
this.domain.stop()
}
}
render() {
return React.createElement(Component, { ...this.props, [propName]: this.domain })
}
}
|
Enable throwing asserts for tests. | import './AnnotationCommand.test'
import './annotationHelpers.test'
import './ArrayOperation.test'
import './ChangeHistory.test'
import './Clipboard.test'
import './Component.test'
import './ContainerSelection.test'
import './CustomSelection.test'
import './DefaultDOMElement.test'
import './Document.test'
import './DocumentChange.test'
import './documentHelpers.test'
import './DocumentIndex.test'
import './DOMElement.test'
import './DOMImporter.test'
import './DOMSelection.test'
import './Editing.test'
import './EditorSession.test'
import './EditorSessionNew.test'
import './Fragmenter.test'
import './HTMLExporter.test'
import './HTMLImporter.test'
import './InlineNode.test'
import './IsolatedNode.test'
import './KeyboardManager.test'
import './NodeSchema.test'
import './ObjectOperation.test'
import './OperationSerializer.test'
import './ParentNode.test'
import './paste.test'
import './prettyPrintXML.test'
import './RenderingEngine.test'
import './sanitizeHTML.test'
import './Surface.test'
import './tableHelpers.test'
import './TextOperation.test'
import './TextPropertyComponent.test'
import './TreeIndex.test'
import './utils.test'
import './XMLExporter.test'
import './XMLImporter.test'
import { substanceGlobals } from 'substance'
// throw in failed asserts
substanceGlobals.ASSERTS = true
// enable this to see more info from the RenderingEngine
// substanceGlobals.VERBOSE_RENDERING_ENGINE = true
| import './AnnotationCommand.test'
import './annotationHelpers.test'
import './ArrayOperation.test'
import './ChangeHistory.test'
import './Clipboard.test'
import './Component.test'
import './ContainerSelection.test'
import './CustomSelection.test'
import './DefaultDOMElement.test'
import './Document.test'
import './DocumentChange.test'
import './documentHelpers.test'
import './DocumentIndex.test'
import './DOMElement.test'
import './DOMImporter.test'
import './DOMSelection.test'
import './Editing.test'
import './EditorSession.test'
import './EditorSessionNew.test'
import './Fragmenter.test'
import './HTMLExporter.test'
import './HTMLImporter.test'
import './InlineNode.test'
import './IsolatedNode.test'
import './KeyboardManager.test'
import './NodeSchema.test'
import './ObjectOperation.test'
import './OperationSerializer.test'
import './ParentNode.test'
import './paste.test'
import './prettyPrintXML.test'
import './RenderingEngine.test'
import './sanitizeHTML.test'
import './Surface.test'
import './tableHelpers.test'
import './TextOperation.test'
import './TextPropertyComponent.test'
import './TreeIndex.test'
import './utils.test'
import './XMLExporter.test'
import './XMLImporter.test'
|
Switch from complicated check to lodash get | import { createSelector } from 'reselect';
import { get } from 'lodash';
const userIdSelector = state => state.auth.userId;
const usersSelector = state => state.data.users;
const currentUserSelector = createSelector(
userIdSelector,
usersSelector,
(userId, users) => users[userId] || {}
);
/**
* Check if the user is staff and can see the private route.
*/
const isAdminSelector = createSelector(
currentUserSelector,
currentUser => Boolean(currentUser.isStaff)
);
function isLoggedInSelector(state) {
return Boolean(state.auth.userId && state.auth.token);
}
/**
* Check if a user has admin permission for a unit.
* TODO: Find a better name for this.
*/
function createIsStaffSelector(resourceSelector) {
return createSelector(
resourceSelector,
resource => Boolean(get(resource, 'userPermissions.isAdmin', false))
);
}
export {
createIsStaffSelector,
currentUserSelector,
isAdminSelector,
isLoggedInSelector,
};
| import { createSelector } from 'reselect';
const userIdSelector = state => state.auth.userId;
const usersSelector = state => state.data.users;
const currentUserSelector = createSelector(
userIdSelector,
usersSelector,
(userId, users) => users[userId] || {}
);
/**
* Check if the user is staff and can see the private route.
*/
const isAdminSelector = createSelector(
currentUserSelector,
currentUser => Boolean(currentUser.isStaff)
);
function isLoggedInSelector(state) {
return Boolean(state.auth.userId && state.auth.token);
}
/**
* Check if a user has admin permission for a unit.
* TODO: Find a better name for this.
*/
function createIsStaffSelector(resourceSelector) {
return createSelector(
resourceSelector,
resource => Boolean(resource && resource.userPermissions && resource.userPermissions.isAdmin)
);
}
export {
createIsStaffSelector,
currentUserSelector,
isAdminSelector,
isLoggedInSelector,
};
|
Add back a deleted newline. | # Copyright 2016 Twitter. All rights reserved.
#
# 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.
''' version.py '''
from heron.tools.cli.src.python.response import Response, Status
import heron.tools.cli.src.python.args as cli_args
import heron.tools.common.src.python.utils.config as config
def create_parser(subparsers):
'''
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'version',
help='Print version of heron-cli',
usage="%(prog)s",
add_help=False)
cli_args.add_titles(parser)
parser.set_defaults(subcommand='version')
return parser
# pylint: disable=unused-argument
def run(command, parser, args, unknown_args):
'''
:param command:
:param parser:
:param args:
:param unknown_args:
:return:
'''
config.print_build_info()
return Response(Status.Ok)
| # Copyright 2016 Twitter. All rights reserved.
#
# 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.
''' version.py '''
from heron.tools.cli.src.python.response import Response, Status
import heron.tools.cli.src.python.args as cli_args
import heron.tools.common.src.python.utils.config as config
def create_parser(subparsers):
'''
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'version',
help='Print version of heron-cli',
usage="%(prog)s",
add_help=False)
cli_args.add_titles(parser)
parser.set_defaults(subcommand='version')
return parser
# pylint: disable=unused-argument
def run(command, parser, args, unknown_args):
'''
:param command:
:param parser:
:param args:
:param unknown_args:
:return:
'''
config.print_build_info()
return Response(Status.Ok)
|
Remove \!, switch ternary outs | function Events(target){
var events = {}, i, list, args, A = Array;
target = target || this
/**
* On: listen to events
*/
target.on = function(type, func, ctx){
events[type] || (events[type] = [])
events[type].push({f:func, c:ctx})
}
/**
* Off: stop listening to event / specific callback
*/
target.off = function(type, func){
list = events[type] || []
i = list.length = func ? list.length : 0
while(i-->0) func == list[i].f && list.splice(i,1)
}
/**
* Emit: send event, callbacks will be triggered
*/
target.emit = function(){
args = A.apply([], arguments)
list = events[args.shift()] || []
i = list.length
for(j=0;j<i;j++) list[j].f.apply(list[j].c, args)
};
}
var u, module, cjs = module != u;
(cjs ? module : window)[(cjs ? 'exports' : 'Events')] = Events;
| function Events(target){
var events = {}, i, list, args, A = Array;
target = target || this
/**
* On: listen to events
*/
target.on = function(type, func, ctx){
events[type] || (events[type] = [])
events[type].push({f:func, c:ctx})
}
/**
* Off: stop listening to event / specific callback
*/
target.off = function(type, func){
list = events[type] || []
i = list.length = func ? list.length : 0
while(i-->0) func == list[i].f && list.splice(i,1)
}
/**
* Emit: send event, callbacks will be triggered
*/
target.emit = function(){
args = A.apply([], arguments)
list = events[args.shift()] || []
i = list.length
for(j=0;j<i;j++) list[j].f.apply(list[j].c, args)
};
}
var u, module, cjs = module != u;
(!cjs ? window : module)[(cjs ? 'exports' : 'Events')] = Events;
|
Add Cobertura Test coverage output | module.exports = {
"modulePaths": [
"<rootDir>/app",
"<rootDir>/node_modules"
],
"moduleFileExtensions": [
"js",
"json"
],
"testRegex": "/test/*/.*-test.js$",
"testEnvironment": "node",
"testTimeout": 10000,
"collectCoverage": true,
"reporters": [
"default",
[
"jest-junit",
{
"outputDirectory": "test/junit",
"outputName": "TESTS.xml"
}
]
],
"collectCoverageFrom": [
"app/**/*.js",
"!**/node_modules/**",
"!**/test/**"
],
"coverageDirectory": "<rootDir>/coverage",
"coverageReporters": [
"json",
"lcov",
"html",
"cobertura"
]
} | module.exports = {
"modulePaths": [
"<rootDir>/app",
"<rootDir>/node_modules"
],
"moduleFileExtensions": [
"js",
"json"
],
"testRegex": "/test/*/.*-test.js$",
"testEnvironment": "node",
"testTimeout": 10000,
"collectCoverage": true,
"reporters": [
"default",
[
"jest-junit",
{
"outputDirectory": "test/junit",
"outputName": "TESTS.xml"
}
]
],
"collectCoverageFrom": [
"app/**/*.js",
"!**/node_modules/**",
"!**/test/**"
],
"coverageDirectory": "<rootDir>/coverage",
"coverageReporters": [
"json",
"lcov",
"html"
]
} |
Remove unnecessary Python 3 declaration. | import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django-admin-sso',
'django-crispy-forms',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
)
from django.test.runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
| #! /usr/bin/env python3
import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django-admin-sso',
'django-crispy-forms',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
)
from django.test.runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
|
Disable test command (no tests) | module.exports = function(grunt) {
'use strict';
grunt.config.init({
pkg: grunt.file.readJSON('package.json')
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.config('clean', {
dist: 'dist'
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.config('copy', {
dist: {
files: {
'dist/sticky-header.js': 'sticky-header.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.config('jasmine', {
test: {
src: 'dist/sticky-header.js',
options: {
specs: 'test/*-spec.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.config('uglify', {
options: {
preserveComments: 'some'
},
dist: {
files: {
'dist/sticky-header.min.js': [
'sticky-header.js'
]
}
}
});
grunt.registerTask('dist', [
'clean:dist',
'copy:dist',
'uglify:dist'
]);
grunt.registerTask('test', [
//'jasmine:test',
]);
grunt.registerTask('default', [
'dist'
]);
};
| module.exports = function(grunt) {
'use strict';
grunt.config.init({
pkg: grunt.file.readJSON('package.json')
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.config('clean', {
dist: 'dist'
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.config('copy', {
dist: {
files: {
'dist/sticky-header.js': 'sticky-header.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.config('jasmine', {
test: {
src: 'dist/sticky-header.js',
options: {
specs: 'test/*-spec.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.config('uglify', {
options: {
preserveComments: 'some'
},
dist: {
files: {
'dist/sticky-header.min.js': [
'sticky-header.js'
]
}
}
});
grunt.registerTask('dist', [
'clean:dist',
'copy:dist',
'uglify:dist'
]);
grunt.registerTask('test', [
'jasmine:test',
]);
grunt.registerTask('default', [
'dist'
]);
};
|
:hammer: Simplify the checks for package.json objects | 'use strict';
const path = require('path');
const pkg = require(path.resolve('./package.json'));
const semver = require('semver');
const versions = require('./versions.json');
const presetEnv = require.resolve('babel-preset-env');
const presetStage3 = require.resolve('babel-preset-stage-3');
module.exports = function() {
const targets = {};
if (pkg.browserslist) {
targets.browsers = pkg.browserslist;
}
if (pkg.engines && pkg.engines.node) {
const version = pkg.engines.node;
if (semver.valid(version)) {
targets.node = version;
} else if (semver.validRange(version)) {
targets.node = semver.minSatisfying(versions.node, version);
}
}
return {
presets: [
[presetEnv, {targets}],
presetStage3,
],
};
};
| 'use strict';
const path = require('path');
const pkg = require(path.resolve('./package.json'));
const semver = require('semver');
const versions = require('./versions.json');
const presetEnv = require.resolve('babel-preset-env');
const presetStage3 = require.resolve('babel-preset-stage-3');
module.exports = function() {
const targets = {};
if (typeof pkg.browserslist === 'object' && pkg.browserslist.length) {
targets.browsers = pkg.browserslist;
}
if (typeof pkg.engines === 'object' && pkg.engines.node) {
const version = pkg.engines.node;
if (semver.valid(version)) {
targets.node = version;
} else if (semver.validRange(version)) {
targets.node = semver.minSatisfying(versions.node, version);
}
}
return {
presets: [
[presetEnv, {targets}],
presetStage3,
],
};
};
|
Use closure-util's ignoreRequires for the examples | var path = require('path');
var url = require('url');
var closure = require('closure-util');
var nomnom = require('nomnom');
var log = closure.log;
var options = nomnom.options({
port: {
abbr: 'p',
'default': 3000,
help: 'Port for incoming connections',
metavar: 'PORT'
},
loglevel: {
abbr: 'l',
choices: ['silly', 'verbose', 'info', 'warn', 'error'],
'default': 'info',
help: 'Log level',
metavar: 'LEVEL'
}
}).parse();
/** @type {string} */
log.level = options.loglevel;
log.info('ol3-cesium', 'Parsing dependencies ...');
var manager = new closure.Manager({
closure: true, // use the bundled Closure Library
lib: [
'src/**/*.js'
],
ignoreRequires: '^ol\\.'
});
manager.on('error', function(e) {
log.error('ol3-cesium', e.message);
});
manager.on('ready', function() {
var server = new closure.Server({
manager: manager,
loader: '/@loader'
});
server.listen(options.port, function() {
log.info('ol3-cesium', 'Listening on http://localhost:' +
options.port + '/ (Ctrl+C to stop)');
});
server.on('error', function(err) {
log.error('ol3-cesium', 'Server failed to start: ' + err.message);
process.exit(1);
});
});
| var path = require('path');
var url = require('url');
var closure = require('closure-util');
var nomnom = require('nomnom');
var log = closure.log;
var options = nomnom.options({
port: {
abbr: 'p',
'default': 3000,
help: 'Port for incoming connections',
metavar: 'PORT'
},
loglevel: {
abbr: 'l',
choices: ['silly', 'verbose', 'info', 'warn', 'error'],
'default': 'info',
help: 'Log level',
metavar: 'LEVEL'
}
}).parse();
/** @type {string} */
log.level = options.loglevel;
log.info('ol3-cesium', 'Parsing dependencies ...');
var manager = new closure.Manager({
closure: true, // use the bundled Closure Library
lib: [
'src/**/*.js'
]
});
manager.on('error', function(e) {
log.error('ol3-cesium', e.message);
});
manager.on('ready', function() {
var server = new closure.Server({
manager: manager,
loader: '/@loader'
});
server.listen(options.port, function() {
log.info('ol3-cesium', 'Listening on http://localhost:' +
options.port + '/ (Ctrl+C to stop)');
});
server.on('error', function(err) {
log.error('ol3-cesium', 'Server failed to start: ' + err.message);
process.exit(1);
});
});
|
Update author and email in package metadata | import sys
from setuptools import find_packages, setup
tests_require = [
'coverage>=4.0',
'pytest-isort',
'pytest-cache>=1.0',
'flake8<3.0.0',
'pytest-flake8>=0.5',
'pytest>=2.8.0',
'pytest-wholenodeid',
]
needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
setup(
name='jupyter-notebook-gist',
version='0.4a1',
description='Create a gist from the Jupyter Notebook UI',
author='Mozilla Firefox Data Platform',
author_email='fx-data-platform@mozilla.com',
packages=find_packages(where='src'),
package_dir={'': 'src'},
include_package_data=True,
license='MPL2',
install_requires=[
'ipython >= 4',
'notebook >= 4.2',
'jupyter',
'requests',
'widgetsnbextension',
],
setup_requires=[] + pytest_runner,
tests_require=tests_require,
url='https://github.com/mozilla/jupyter-notebook-gist',
zip_safe=False,
)
| import sys
from setuptools import find_packages, setup
tests_require = [
'coverage>=4.0',
'pytest-isort',
'pytest-cache>=1.0',
'flake8<3.0.0',
'pytest-flake8>=0.5',
'pytest>=2.8.0',
'pytest-wholenodeid',
]
needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
setup(
name='jupyter-notebook-gist',
version='0.4a1',
description='Create a gist from the Jupyter Notebook UI',
author='Mozilla Telemetry',
author_email='telemetry@lists.mozilla.org',
packages=find_packages(where='src'),
package_dir={'': 'src'},
include_package_data=True,
license='MPL2',
install_requires=[
'ipython >= 4',
'notebook >= 4.2',
'jupyter',
'requests',
'widgetsnbextension',
],
setup_requires=[] + pytest_runner,
tests_require=tests_require,
url='https://github.com/mozilla/jupyter-notebook-gist',
zip_safe=False,
)
|
Fix syntax for Python 2.6 - no set literals. | """Utilities for working with Python source files.
Exposes various functions from recent Python standard libraries, along with
equivalents for older Python versions.
"""
import os.path
try: # Python 3.2
from imp import source_from_cache, cache_from_source
except ImportError:
# Python <= 3.1: .pyc files go next to .py
def source_from_cache(path):
basename, ext = os.path.splitext(path)
if ext not in ('.pyc', '.pyo'):
raise ValueError('Not a cached Python file extension', ext)
# Should we look for .pyw files?
return basename + '.py'
def cache_from_source(path, debug_override=None):
if debug_override is None:
debug_override = __debug__
basename, ext = os.path.splitext(path)
return basename + '.pyc' if debug_override else '.pyo'
| """Utilities for working with Python source files.
Exposes various functions from recent Python standard libraries, along with
equivalents for older Python versions.
"""
import os.path
try: # Python 3.2
from imp import source_from_cache, cache_from_source
except ImportError:
# Python <= 3.1: .pyc files go next to .py
def source_from_cache(path):
basename, ext = os.path.splitext(path)
if ext not in {'.pyc', '.pyo'}:
raise ValueError('Not a cached Python file extension', ext)
# Should we look for .pyw files?
return basename + '.py'
def cache_from_source(path, debug_override=None):
if debug_override is None:
debug_override = __debug__
basename, ext = os.path.splitext(path)
return basename + '.pyc' if debug_override else '.pyo'
|
Fix copy constructor of SharedLinkBoxSession | package com.box.androidsdk.content.models;
import android.content.Context;
import java.util.ArrayList;
/**
* Session created from a shared link.
*/
public class BoxSharedLinkSession extends BoxSession {
String mSharedLink;
String mPassword;
public BoxSharedLinkSession(BoxSession session) {
super(session);
if (session instanceof BoxSharedLinkSession) {
BoxSharedLinkSession sharedLinkSession = (BoxSharedLinkSession) session;
setSharedLink(sharedLinkSession.getSharedLink());
setPassword(sharedLinkSession.getPassword());
}
}
public BoxSharedLinkSession(Context context) {
super(context);
}
public BoxSharedLinkSession(Context context, String userId ) {
super(context, userId);
}
public BoxSharedLinkSession(Context context, String userId, String clientId, String clientSecret, String redirectUrl) {
super(context, userId, clientId, clientSecret, redirectUrl);
}
public String getSharedLink() {
return mSharedLink;
}
public BoxSharedLinkSession setSharedLink(String sharedLink) {
mSharedLink = sharedLink;
return this;
}
public String getPassword() {
return mPassword;
}
public BoxSharedLinkSession setPassword(String password) {
mPassword = password;
return this;
}
}
| package com.box.androidsdk.content.models;
import android.content.Context;
import java.util.ArrayList;
/**
* Session created from a shared link.
*/
public class BoxSharedLinkSession extends BoxSession {
String mSharedLink;
String mPassword;
public BoxSharedLinkSession(BoxSession session) {
super(session);
}
public BoxSharedLinkSession(Context context) {
super(context);
}
public BoxSharedLinkSession(Context context, String userId ) {
super(context, userId);
}
public BoxSharedLinkSession(Context context, String userId, String clientId, String clientSecret, String redirectUrl) {
super(context, userId, clientId, clientSecret, redirectUrl);
}
public String getSharedLink() {
return mSharedLink;
}
public BoxSharedLinkSession setSharedLink(String sharedLink) {
mSharedLink = sharedLink;
return this;
}
public String getPassword() {
return mPassword;
}
public BoxSharedLinkSession setPassword(String password) {
mPassword = password;
return this;
}
}
|
BUGFIX: Check there is a service container before calling get on it. | <?php
/**
* This file is part of the Heystack package
*
* @package Heystack
*/
/**
* Core namespace
*/
namespace Heystack\Subsystem\Core;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Service store allows acess to the Symfony dependency injection container from SilverStripe code.
*
* SilverStripe services like controllers can't easily be created and accessed
* by SilverStripe through the dependency injection component, and so, a global
* store is made available for SilverStripe-centric classes that need to access
* services
*
* @copyright Heyday
* @author Cam Spiers <cameron@heyday.co.nz>
* @package Heystack
*
*/
class ServiceStore
{
/**
* Stores the service container
*/
private static $serviceContainer = null;
/**
* Returns the service container
* @return Container
*/
public static function get()
{
return self::$serviceContainer;
}
/**
* Sets the service container
* @param Container $container
* @return null
*/
public static function set(Container $container)
{
self::$serviceContainer = $container;
}
/**
* Gets a specific service by name from the service container
* @param string $service
* @return mixed
*/
public static function getService($service)
{
return self::$serviceContainer instanceof Container ? self::$serviceContainer->get($service, ContainerInterface::NULL_ON_INVALID_REFERENCE) : null;
}
}
| <?php
/**
* This file is part of the Heystack package
*
* @package Heystack
*/
/**
* Core namespace
*/
namespace Heystack\Subsystem\Core;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Service store allows acess to the Symfony dependency injection container from SilverStripe code.
*
* SilverStripe services like controllers can't easily be created and accessed
* by SilverStripe through the dependency injection component, and so, a global
* store is made available for SilverStripe-centric classes that need to access
* services
*
* @copyright Heyday
* @author Cam Spiers <cameron@heyday.co.nz>
* @package Heystack
*
*/
class ServiceStore
{
/**
* Stores the service container
*/
private static $serviceContainer = null;
/**
* Returns the service container
* @return Container
*/
public static function get()
{
return self::$serviceContainer;
}
/**
* Sets the service container
* @param Container $container
* @return null
*/
public static function set(Container $container)
{
self::$serviceContainer = $container;
}
/**
* Gets a specific service by name from the service container
* @param string $service
* @return mixed
*/
public static function getService($service)
{
return self::$serviceContainer->get($service, ContainerInterface::NULL_ON_INVALID_REFERENCE);
}
}
|
Fix bug in tree pruning caused by change in dev module flagging | 'use strict'
var validate = require('aproba')
var flattenTree = require('./flatten-tree.js')
function isNotPackage (mod) {
return function (parentMod) { return mod !== parentMod }
}
module.exports = function pruneTree (tree) {
validate('O', arguments)
var flat = flattenTree(tree)
// we just do this repeatedly until there are no more orphaned packages
// which isn't as effecient as it could be on a REALLY big tree
// but we'll face that if it proves to be an issue
var removedPackage
do {
removedPackage = false
Object.keys(flat).forEach(function (flatname) {
var child = flat[flatname]
if (!child.parent) return
child.package._requiredBy = (child.package._requiredBy || []).filter(function (req) {
var isDev = req.substr(0,4) === '#DEV'
if (req[0] === '#' && !isDev) return true
if (flat[req]) return true
return isDev && flat[req.substr(5)]
})
if (!child.package._requiredBy.length) {
removedPackage = true
delete flat[flatname]
child.parent.children = child.parent.children.filter(isNotPackage(child))
}
})
} while (removedPackage)
}
| 'use strict'
var validate = require('aproba')
var flattenTree = require('./flatten-tree.js')
function isNotPackage (mod) {
return function (parentMod) { return mod !== parentMod }
}
module.exports = function pruneTree (tree) {
validate('O', arguments)
var flat = flattenTree(tree)
// we just do this repeatedly until there are no more orphaned packages
// which isn't as effecient as it could be on a REALLY big tree
// but we'll face that if it proves to be an issue
var removedPackage
do {
removedPackage = false
Object.keys(flat).forEach(function (flatname) {
var child = flat[flatname]
if (!child.parent) return
child.package._requiredBy = (child.package._requiredBy || []).filter(function (req) {
return req[0] === '#' || flat[req]
})
if (!child.package._requiredBy.length) {
removedPackage = true
delete flat[flatname]
child.parent.children = child.parent.children.filter(isNotPackage(child))
}
})
} while (removedPackage)
}
|
Fix issue with out of bounds array check in recordable autonomous | package org.usfirst.frc2832.Robot_2016.HID;
import java.util.ArrayList;
public class VirtualGamepad {
private ArrayList<GamepadState> states;
private boolean done;
// Millisecond timings
long startTime, recordedOffset;
int lastIndex = 0;
public VirtualGamepad(ArrayList<GamepadState> states) {
this.states = states;
}
public void start() {
startTime = System.currentTimeMillis();
recordedOffset = states.get(0).timestamp;
done = false;
lastIndex = 0;
}
public boolean isDone() {
return (done);
}
public GamepadState getCurrentState() {
long time = System.currentTimeMillis();
// Interpolate the times, using the last recorded gamepad state.
while (lastIndex < states.size()) {
if (states.get(lastIndex).timestamp - recordedOffset <= time - startTime)
lastIndex++;
}
if (lastIndex >= states.size()) {
done = true;
return (null);
}
// We overshot in that interpolation stage, that was the first time it "failed"
lastIndex--;
// lastIndex now has the latest recorded data from the gamepad at this current time.
return (states.get(lastIndex));
}
}
| package org.usfirst.frc2832.Robot_2016.HID;
import java.util.ArrayList;
public class VirtualGamepad {
private ArrayList<GamepadState> states;
private boolean done;
// Millisecond timings
long startTime, recordedOffset;
int lastIndex = 0;
public VirtualGamepad(ArrayList<GamepadState> states) {
this.states = states;
}
public void start() {
startTime = System.currentTimeMillis();
recordedOffset = states.get(0).timestamp;
done = false;
lastIndex = 0;
}
public boolean isDone() {
return (done);
}
public GamepadState getCurrentState() {
long time = System.currentTimeMillis();
// Interpolate the times, using the last recorded gamepad state.
while (states.get(lastIndex).timestamp - recordedOffset <= time - startTime)
lastIndex++;
lastIndex--;
if (lastIndex >= states.size()) {
done = true;
return (null);
}
// lastIndex now has the latest recorded data from the gamepad at this current time.
return (states.get(lastIndex));
}
}
|
Tag version 3.0.4 for PyPI
3.x had a minor bug (see SHA:74b0a36) but it broke logging for Solr
errors which seems worth an easily deployed fix | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="pysolr",
version="3.0.4",
description="Lightweight python wrapper for Apache Solr.",
author='Daniel Lindsley',
author_email='daniel@toastdriven.com',
long_description=open('README.rst', 'r').read(),
py_modules=[
'pysolr'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
url='http://github.com/toastdriven/pysolr/',
license='BSD',
install_requires=[
'requests>=1.1.0'
],
extra_requires={
'tomcat': [
'lxml',
'cssselect',
],
}
)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="pysolr",
version="3.0.3",
description="Lightweight python wrapper for Apache Solr.",
author='Daniel Lindsley',
author_email='daniel@toastdriven.com',
long_description=open('README.rst', 'r').read(),
py_modules=[
'pysolr'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
url='http://github.com/toastdriven/pysolr/',
license='BSD',
install_requires=[
'requests>=1.1.0'
],
extra_requires={
'tomcat': [
'lxml',
'cssselect',
],
}
)
|
Add test for changing ajax type | var Uploader, file;
module("Ember.Uploader", {
setup: function() {
if (typeof WebKitBlobBuilder === "undefined") {
file = new Blob(['test'], { type: 'text/plain' });
} else {
var builder;
builder = new WebKitBlobBuilder();
builder.append('test');
file = builder.getBlob();
}
Uploader = Ember.Uploader.extend({
url: '/test',
});
}
});
test("has a url of '/test'", function() {
var uploader = Uploader.create();
equal(uploader.url, '/test');
});
test("has an ajax request of type 'PUT'", function() {
var uploader = Uploader.create({type: 'PUT'});
equal(uploader.type, 'PUT');
});
test("uploads to the given url", function() {
expect(1);
var uploader = Uploader.create({
url: '/upload',
file: file
});
uploader.on('didUpload', function(data) {
start();
equal(data, 'OK');
});
uploader.upload(file);
stop();
});
test("emits progress event", function() {
expect(1);
var uploader = Uploader.create({
url: '/upload',
file: file
});
uploader.on('progress', function(e) {
start();
equal(e.percent, 100);
});
uploader.upload(file);
stop();
});
| var Uploader, file;
module("Ember.Uploader", {
setup: function() {
if (typeof WebKitBlobBuilder === "undefined") {
file = new Blob(['test'], { type: 'text/plain' });
} else {
var builder;
builder = new WebKitBlobBuilder();
builder.append('test');
file = builder.getBlob();
}
Uploader = Ember.Uploader.extend({
url: '/test',
});
}
});
test("has a url of '/test'", function() {
var uploader = Uploader.create();
equal(uploader.url, '/test');
});
test("uploads to the given url", function() {
expect(1);
var uploader = Uploader.create({
url: '/upload',
file: file
});
uploader.on('didUpload', function(data) {
start();
equal(data, 'OK');
});
uploader.upload(file);
stop();
});
test("emits progress event", function() {
expect(1);
var uploader = Uploader.create({
url: '/upload',
file: file
});
uploader.on('progress', function(e) {
start();
equal(e.percent, 100);
});
uploader.upload(file);
stop();
});
|
Revert to python2, python3 converted code isn't working as expected | #!/usr/bin/env python
#Python app to run a K-30 Sensor
import serial
import time
from optparse import OptionParser
import sys
ser = serial.Serial("/dev/serial0")
#print("Serial Connected!", file=sys.stderr)
ser.flushInput()
time.sleep(1)
parser = OptionParser()
parser.add_option("-t", "--average-time", dest="avgtime",
help="Report value averaged across this period of time", metavar="SECONDS")
(options, args) = parser.parse_args()
sum = 0
num = int(options.avgtime)
num_init = num
while True:
#ser.write("\xFE\x44\x00\x08\x02\x9F\x25".encode())
ser.write("\xFE\x44\x00\x08\x02\x9F\x25")
time.sleep(.01)
resp = ser.read(7)
high = ord(resp[3])
low = ord(resp[4])
co2 = (high*256) + low
sum += co2
num -= 1
#print(time.strftime("%c") + ": CO2 = " + str(co2) + " ppm", file=sys.stderr)
if (num > 0):
time.sleep(1)
if (num == 0):
break
#print(int(sum/num_init))
print int(sum/num_init)
| #!/usr/bin/env python3
#Python app to run a K-30 Sensor
import serial
import time
from optparse import OptionParser
import sys
ser = serial.Serial("/dev/ttyAMA0")
print("Serial Connected!", file=sys.stderr)
ser.flushInput()
time.sleep(1)
parser = OptionParser()
parser.add_option("-t", "--average-time", dest="avgtime",
help="Report value averaged across this period of time", metavar="SECONDS")
(options, args) = parser.parse_args()
sum = 0
num = int(options.avgtime)
num_init = num
while True:
ser.write("\xFE\x44\x00\x08\x02\x9F\x25".encode())
time.sleep(.01)
resp = ser.read(7)
high = ord(resp[3])
low = ord(resp[4])
co2 = (high*256) + low
sum += co2
num -= 1
print(time.strftime("%c") + ": CO2 = " + str(co2) + " ppm", file=sys.stderr)
if (num > 0):
time.sleep(1)
if (num == 0):
break
print(int(sum/num_init))
|
Update import from docs to the new API | package main
import (
"path"
"gnd.la/app"
"gnd.la/apps/docs"
"gnd.la/net/urlutil"
)
const (
//gondolaURL = "http://www.gondolaweb.com"
gondolaURL = "ssh://abra.rm-fr.net/home/fiam/git/gondola.git"
)
func gndlaHandler(ctx *app.Context) {
if ctx.FormValue("go-get") == "1" {
ctx.MustExecute("goget.html", nil)
return
}
// Check if the request path is a pkg name
var p string
pkg := path.Join("gnd.la", ctx.R.URL.Path)
if _, err := docs.DefaultContext.Import(pkg, "", 0); err == nil {
p = ctx.MustReverse(docs.PackageHandlerName, pkg)
}
redir, err := urlutil.Join(gondolaURL, p)
if err != nil {
panic(err)
}
ctx.Redirect(redir, false)
}
| package main
import (
"gnd.la/app"
"gnd.la/apps/docs"
"gnd.la/apps/docs/doc"
"gnd.la/net/urlutil"
"path"
)
const (
//gondolaURL = "http://www.gondolaweb.com"
gondolaURL = "ssh://abra.rm-fr.net/home/fiam/git/gondola.git"
)
func gndlaHandler(ctx *app.Context) {
if ctx.FormValue("go-get") == "1" {
ctx.MustExecute("goget.html", nil)
return
}
// Check if the request path is a pkg name
var p string
pkg := path.Join("gnd.la", ctx.R.URL.Path)
if _, err := doc.Context.Import(pkg, "", 0); err == nil {
p = ctx.MustReverse(docs.PackageHandlerName, pkg)
}
redir, err := urlutil.Join(gondolaURL, p)
if err != nil {
panic(err)
}
ctx.Redirect(redir, false)
}
|
Remove padding on editor rows | /* eslint-disable react/forbid-prop-types */
/* eslint-disable arrow-body-style */
import React from 'react';
import PropTypes from 'prop-types';
import { Text } from 'react-native';
import { FlexRow } from './FlexRow';
import { SpacedChildren, Spacer } from './Spacer';
import { WithFixedDimensions } from './WithFixedDimensions';
import { APP_FONT_FAMILY, DARKER_GREY, WHITE } from '../globalStyles';
export const EditorRow = ({ children, label = '', Icon, containerStyle, labelStyle }) => {
return (
<FlexRow flex={1} alignItems="center" justifyContent="flex-start" style={containerStyle}>
<WithFixedDimensions width={30}>{Icon}</WithFixedDimensions>
<Spacer space={20} />
<Text style={labelStyle}>{label}</Text>
<SpacedChildren space={0}>{children}</SpacedChildren>
</FlexRow>
);
};
EditorRow.defaultProps = {
containerStyle: { maxHeight: 60, backgroundColor: WHITE },
labelStyle: {
fontSize: 12,
fontFamily: APP_FONT_FAMILY,
color: DARKER_GREY,
marginRight: 'auto',
width: 120,
},
};
EditorRow.propTypes = {
children: PropTypes.node.isRequired,
label: PropTypes.string.isRequired,
Icon: PropTypes.node.isRequired,
containerStyle: PropTypes.object,
labelStyle: PropTypes.object,
};
| /* eslint-disable react/forbid-prop-types */
/* eslint-disable arrow-body-style */
import React from 'react';
import PropTypes from 'prop-types';
import { Text } from 'react-native';
import { FlexRow } from './FlexRow';
import { SpacedChildren, Spacer } from './Spacer';
import { WithFixedDimensions } from './WithFixedDimensions';
import { APP_FONT_FAMILY, DARKER_GREY, WHITE } from '../globalStyles';
export const EditorRow = ({ children, label = '', Icon, containerStyle, labelStyle }) => {
return (
<FlexRow flex={1} alignItems="center" justifyContent="flex-start" style={containerStyle}>
<WithFixedDimensions width={30}>{Icon}</WithFixedDimensions>
<Spacer space={20} />
<Text style={labelStyle}>{label}</Text>
<SpacedChildren space={0}>{children}</SpacedChildren>
</FlexRow>
);
};
EditorRow.defaultProps = {
containerStyle: { maxHeight: 60, backgroundColor: WHITE, paddingHorizontal: 30 },
labelStyle: {
fontSize: 12,
fontFamily: APP_FONT_FAMILY,
color: DARKER_GREY,
marginRight: 'auto',
width: 120,
},
};
EditorRow.propTypes = {
children: PropTypes.node.isRequired,
label: PropTypes.string.isRequired,
Icon: PropTypes.node.isRequired,
containerStyle: PropTypes.object,
labelStyle: PropTypes.object,
};
|
Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend.
PiperOrigin-RevId: 466171774 | # Copyright 2021 The TensorFlow Probability Authors.
#
# 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.
# ============================================================================
"""Numpy stub for `tensor_spec`."""
from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor
__all__ = [
'TensorSpec',
]
class DenseSpec(object):
def __init__(self, shape, dtype, name=None):
self.shape = shape
self.dtype = dtype
self.name = name
def __repr__(self):
return '{}(shape={}, dtype={}, name={})'.format(
type(self).__name__, self.shape, repr(self.dtype), repr(self.name))
class TensorSpec(DenseSpec):
@classmethod
def from_tensor(cls, tensor, name=None):
tensor = _convert_to_tensor(tensor)
return cls(tensor.shape, tensor.dtype, name)
| # Copyright 2021 The TensorFlow Probability Authors.
#
# 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.
# ============================================================================
"""Numpy stub for `tensor_spec`."""
__all__ = [
'TensorSpec',
]
class DenseSpec(object):
def __init__(self, shape, dtype, name=None):
self.shape = shape
self.dtype = dtype
self.name = name
def __repr__(self):
return '{}(shape={}, dtype={}, name={})'.format(
type(self).__name__, self.shape, repr(self.dtype), repr(self.name))
class TensorSpec(DenseSpec):
pass
|
Update case on CodeMirror require in case web server is case sensitive (like gh-pages) | require.config({
paths: {
"knockout": "ext/knockout-2.1.0",
"jquery": "ext/jquery-1.7.2.min",
"text": "ext/text",
"codemirror": "ext/codemirror",
"bootstrap": "ext/bootstrap.min"
},
shim: {
"bootstrap": ["jquery"]
}
});
require(["knockout", "app", "jquery", "bootstrap", "utilities", "stringTemplateEngine", "text", "codemirror"], function(ko, App, $) {
var vm = new App();
//simple client-side routing - update hash when current section is changed
vm.currentSection.subscribe(function(newValue) {
location.hash = newValue.name;
});
var updateSection = function() {
vm.updateSection(location.hash.substr(1));
};
//respond to hashchange event
window.onhashchange = updateSection;
//initialize
updateSection();
//block alt navigation
$(document).keydown(function(event) {
if (event.altKey && (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40)) {
return false;
}
});
window.alert = function(text) {
$("#alert .modal-body").html("<p>" + text + "</p>").parent().modal();
};
ko.applyBindings(vm);
});
| require.config({
paths: {
"knockout": "ext/knockout-2.1.0",
"jquery": "ext/jquery-1.7.2.min",
"text": "ext/text",
"codemirror": "ext/CodeMirror",
"bootstrap": "ext/bootstrap.min"
},
shim: {
"bootstrap": ["jquery"]
}
});
require(["knockout", "app", "jquery", "bootstrap", "utilities", "stringTemplateEngine", "text", "codemirror"], function(ko, App, $) {
var vm = new App();
//simple client-side routing - update hash when current section is changed
vm.currentSection.subscribe(function(newValue) {
location.hash = newValue.name;
});
var updateSection = function() {
vm.updateSection(location.hash.substr(1));
};
//respond to hashchange event
window.onhashchange = updateSection;
//initialize
updateSection();
//block alt navigation
$(document).keydown(function(event) {
if (event.altKey && (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40)) {
return false;
}
});
window.alert = function(text) {
$("#alert .modal-body").html("<p>" + text + "</p>").parent().modal();
};
ko.applyBindings(vm);
});
|
Use threads in gunicorn rather than processes
This ensures that we share the auth-cache... will enable memory savings
and may improve performances when a higher number of cores is available
"smarter default" | #!/usr/bin/python3
import os
import logging as log
import sys
log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "INFO"))
os.system("flask mailu advertise")
os.system("flask db upgrade")
account = os.environ.get("INITIAL_ADMIN_ACCOUNT")
domain = os.environ.get("INITIAL_ADMIN_DOMAIN")
password = os.environ.get("INITIAL_ADMIN_PW")
if account is not None and domain is not None and password is not None:
mode = os.environ.get("INITIAL_ADMIN_MODE", default="ifmissing")
log.info("Creating initial admin accout %s@%s with mode %s",account,domain,mode)
os.system("flask mailu admin %s %s '%s' --mode %s" % (account, domain, password, mode))
start_command="".join([
"gunicorn --threads ", str(os.cpu_count()),
" -b :80 ",
"--access-logfile - " if (log.root.level<=log.INFO) else "",
"--error-logfile - ",
"--preload ",
"'mailu:create_app()'"])
os.system(start_command)
| #!/usr/bin/python3
import os
import logging as log
import sys
log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "INFO"))
os.system("flask mailu advertise")
os.system("flask db upgrade")
account = os.environ.get("INITIAL_ADMIN_ACCOUNT")
domain = os.environ.get("INITIAL_ADMIN_DOMAIN")
password = os.environ.get("INITIAL_ADMIN_PW")
if account is not None and domain is not None and password is not None:
mode = os.environ.get("INITIAL_ADMIN_MODE", default="ifmissing")
log.info("Creating initial admin accout %s@%s with mode %s",account,domain,mode)
os.system("flask mailu admin %s %s '%s' --mode %s" % (account, domain, password, mode))
start_command="".join([
"gunicorn -w 4 -b :80 ",
"--access-logfile - " if (log.root.level<=log.INFO) else "",
"--error-logfile - ",
"--preload ",
"'mailu:create_app()'"])
os.system(start_command)
|
Throw an exception on empty resource list | package de.fernunihagen.dna.jkn.scalephant.distribution.resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstance;
public class RandomResourcePlacementStrategy implements ResourcePlacementStrategy {
/**
* The random generator
*/
protected final Random randomGenerator;
public RandomResourcePlacementStrategy() {
randomGenerator = new Random();
}
@Override
public DistributedInstance findSystemToAllocate(final Collection<DistributedInstance> systems) {
if(systems.isEmpty()) {
throw new IllegalArgumentException("Unable to choose a system, list of systems is empty");
}
synchronized (systems) {
final List<DistributedInstance> elements = new ArrayList<DistributedInstance>(systems);
final int element = Math.abs(randomGenerator.nextInt()) % elements.size();
return elements.get(element);
}
}
}
| package de.fernunihagen.dna.jkn.scalephant.distribution.resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstance;
public class RandomResourcePlacementStrategy implements ResourcePlacementStrategy {
/**
* The random generator
*/
protected final Random randomGenerator;
public RandomResourcePlacementStrategy() {
randomGenerator = new Random();
}
@Override
public DistributedInstance findSystemToAllocate(final Collection<DistributedInstance> systems) {
synchronized (systems) {
final List<DistributedInstance> elements = new ArrayList<DistributedInstance>(systems);
final int element = Math.abs(randomGenerator.nextInt()) % elements.size();
return elements.get(element);
}
}
}
|
Make sure request.user is a user | from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
request = context.get("request")
if (
request is not None
and request.user is not None
and request.user.is_authenticated
):
user = request.user
if user.groups.filter(
name=settings.RETINA_GRADERS_GROUP_NAME
).exists():
if grader != user:
raise serializers.ValidationError(
"User is not allowed to create annotation for other grader"
)
| from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
request = context.get("request")
if request and request.user.is_authenticated:
user = request.user
if user.groups.filter(
name=settings.RETINA_GRADERS_GROUP_NAME
).exists():
if grader != user:
raise serializers.ValidationError(
"User is not allowed to create annotation for other grader"
)
|
Upgrade eslint-plugin-jsx-a11y to match eslint-config-airbnb peer dependency | const Base = require('yeoman-generator').Base;
const yarnInstall = require('yarn-install');
class ESLintGenerator extends Base {
install() {
yarnInstall([
'babel-core',
'babel-eslint',
'babel-preset-react-native',
'eslint',
'eslint-config-airbnb',
'eslint-plugin-import',
'eslint-plugin-jsx-a11y@^3.0.2',
'eslint-plugin-react',
], {
dev: true,
cwd: this.destinationRoot(),
});
}
writing() {
this.fs.copyTpl(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copyTpl(
this.templatePath('eslintignore'),
this.destinationPath('.eslintignore')
);
this.fs.extendJSON('package.json', {
scripts: { 'test:lint': 'eslint . --quiet' },
}, null, 2);
}
end() {
this.config.set('eslint', true);
this.config.save();
}
}
module.exports = ESLintGenerator;
| const Base = require('yeoman-generator').Base;
const yarnInstall = require('yarn-install');
class ESLintGenerator extends Base {
install() {
yarnInstall([
'babel-core',
'babel-eslint',
'babel-preset-react-native',
'eslint',
'eslint-config-airbnb',
'eslint-plugin-import',
'eslint-plugin-jsx-a11y@^2.0.0',
'eslint-plugin-react',
], {
dev: true,
cwd: this.destinationRoot(),
});
}
writing() {
this.fs.copyTpl(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copyTpl(
this.templatePath('eslintignore'),
this.destinationPath('.eslintignore')
);
this.fs.extendJSON('package.json', {
scripts: { 'test:lint': 'eslint . --quiet' },
}, null, 2);
}
end() {
this.config.set('eslint', true);
this.config.save();
}
}
module.exports = ESLintGenerator;
|
Use portable way to detect DEBUG mode | package net.rdrei.android.wakimail;
import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.os.StrictMode;
/**
* Sets up settings that are required for the application to run.
*
* @author pascal
*/
@ReportsCrashes(formUri = "http://www.bugsense.com/api/acra?api_key=2b0a6e7c", formKey = "")
public class WAKiMailApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (isDebuggable()) {
enableStrictMode();
} else {
// Only if DEBUG is disabled.
ACRA.init(this);
}
}
private boolean isDebuggable() {
final int applicationFlags = this.getApplicationInfo().flags;
return (applicationFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
}
private void enableStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
// Only on 11+ if I'm not mistaken.
.detectLeakedClosableObjects().penaltyLog().penaltyDeath()
.build());
}
}
| package net.rdrei.android.wakimail;
import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.os.StrictMode;
/**
* Sets up settings that are required for the application to run.
*
* @author pascal
*/
@ReportsCrashes(formUri = "http://www.bugsense.com/api/acra?api_key=2b0a6e7c", formKey = "")
public class WAKiMailApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
enableStrictMode();
} else {
// Only if DEBUG is disabled.
ACRA.init(this);
}
}
private void enableStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
// Only on 11+ if I'm not mistaken.
.detectLeakedClosableObjects().penaltyLog().penaltyDeath()
.build());
}
}
|
Add some debug code to try and track the issue down | package reborncore.mixin.implementations.asmInjector;
import javassist.ByteArrayClassPath;
import javassist.LoaderClassPath;
import reborncore.mixin.MixinManager;
import reborncore.mixin.implementations.prebaker.MixinPrebaker;
import reborncore.mixin.transformer.MixinTransformer;
/**
* Used by asm injector to load mixins into a jar at build time
*/
public class ASMInjectorSetupClass {
public static void main() {
MixinManager.logger = System.out::println;
MixinManager.logger.log("Loading mixin manager");
MixinManager.logger.log("Using dummy remapper");
MixinManager.mixinRemaper = new MixinPrebaker.DummyRemapper();
MixinManager.load();
}
public static void setClassLoader(ClassLoader classLoader) {
System.out.println("Setting logger");
MixinManager.logger = System.out::println;
MixinManager.logger.log("Setting class loader");
MixinTransformer.cp.appendClassPath(new LoaderClassPath(classLoader));
}
public static void loadClass(String name, byte[] bytes) {
MixinTransformer.cp.insertClassPath(new ByteArrayClassPath(name, bytes));
MixinTransformer.preLoadedClasses.add(name);
}
}
| package reborncore.mixin.implementations.asmInjector;
import javassist.ByteArrayClassPath;
import javassist.LoaderClassPath;
import reborncore.mixin.MixinManager;
import reborncore.mixin.implementations.prebaker.MixinPrebaker;
import reborncore.mixin.transformer.MixinTransformer;
/**
* Used by asm injector to load mixins into a jar at build time
*/
public class ASMInjectorSetupClass {
static {
MixinManager.logger = System.out::println;
}
public static void main() {
MixinManager.logger = System.out::println;
MixinManager.logger.log("Loading mixin manager");
MixinManager.logger.log("Using dummy remapper");
MixinManager.mixinRemaper = new MixinPrebaker.DummyRemapper();
MixinManager.load();
}
public static void setClassLoader(ClassLoader classLoader) {
MixinManager.logger = System.out::println;
MixinManager.logger.log("Setting class loader");
MixinTransformer.cp.appendClassPath(new LoaderClassPath(classLoader));
}
public static void loadClass(String name, byte[] bytes) {
MixinTransformer.cp.insertClassPath(new ByteArrayClassPath(name, bytes));
MixinTransformer.preLoadedClasses.add(name);
}
}
|
Bring in PropTypes and and set prop type for portalTo prop | let traps = [];
const PropTypes = require('prop-types');
const React = require('react');
const FocusTrap = require('focus-trap-react');
/**
* MXFocusTrap
*
* Why is this needed?
*
* FocusTrap does not un-pause the previous trap when the current trap is unmounted.
* This ensures that the previously trapped component is un-paused.
*/
class MXFocusTrap extends React.Component {
static propTypes = {
portalTo: PropTypes.string
}
state = {
paused: false
}
componentWillMount () {
// FocusTrap does it's own pausing but these React components also need to be paused
traps.forEach(component => component.setState({ paused: true }));
traps.push(this);
}
componentWillUnmount () {
traps = traps.filter(component => component !== this);
const lastTrap = traps[traps.length - 1];
if (lastTrap) lastTrap.setState({ paused: false });
}
render () {
return (
<FocusTrap {...this.props} paused={this.state.paused}>
{this.props.children}
</FocusTrap>
);
}
}
module.exports = MXFocusTrap; | let traps = [];
const React = require('react');
const FocusTrap = require('focus-trap-react');
/**
* MXFocusTrap
*
* Why is this needed?
*
* FocusTrap does not un-pause the previous trap when the current trap is unmounted.
* This ensures that the previously trapped component is un-paused.
*/
class MXFocusTrap extends React.Component {
state = {
paused: false
}
componentWillMount () {
// FocusTrap does it's own pausing but these React components also need to be paused
traps.forEach(component => component.setState({ paused: true }));
traps.push(this);
}
componentWillUnmount () {
traps = traps.filter(component => component !== this);
const lastTrap = traps[traps.length - 1];
if (lastTrap) lastTrap.setState({ paused: false });
}
render () {
return (
<FocusTrap {...this.props} paused={this.state.paused}>
{this.props.children}
</FocusTrap>
);
}
}
module.exports = MXFocusTrap; |
Handle migrating non-string values (i.e.: NULL) | # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-05-15 15:52
from __future__ import unicode_literals
import re
from django.db import migrations
REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})")
OUTPUT = "{{ review_url }}"
def replace_template(apps, schema_editor):
SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation')
settings = SettingValueTranslation.objects.all()
for setting in settings:
if isinstance(setting.value, str):
setting.value = re.sub(REGEX, OUTPUT, setting.value)
setting.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0038_xslt_1-3-8'),
]
operations = [
migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-05-15 15:52
from __future__ import unicode_literals
import re
from django.db import migrations
REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})")
OUTPUT = "{{ review_url }}"
def replace_template(apps, schema_editor):
SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation')
settings = SettingValueTranslation.objects.all()
for setting in settings:
setting.value = re.sub(REGEX, OUTPUT, setting.value)
setting.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0038_xslt_1-3-8'),
]
operations = [
migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop)
]
|
Fix the test command in the makefile | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='mafiademonstration',
version='0.4.5',
author='Isaac Smith, Hei Jing Tsang',
author_email='sentherus@gmail.com',
description='A user friendly interface for playing a simplified game of Mafia.',
long_description=read('README.rst'),
license='MIT',
keywords=(
"Python, kivy, pytest, projects, project, "
"documentation, setup.py, package "
),
url='https://github.com/zenohm/mafiademonstration',
install_requires=[
'kivy>=1.9.1',
'click',
],
zip_safe=False,
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: X11 Applications',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3',
'Topic :: Multimedia :: Graphics :: Presentation',
'Topic :: Software Development :: User Interfaces',
],
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='mafiademonstration',
version='0.4.5',
author='Isaac Smith, Hei Jing Tsang',
author_email='sentherus@gmail.com',
description='A user friendly interface for playing a simplified game of Mafia.',
long_description=read('README.rst'),
license='MIT',
keywords=(
"Python, kivy, pytest, projects, project, "
"documentation, setup.py, package "
),
url='https://github.com/zenohm/mafiademonstration',
install_requires=[
'kivy>=1.9.1',
'click',
],
zip_safe=False,
packages=find_packages(),
include_package_data=True,
tests_require=['unittest'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: X11 Applications',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3',
'Topic :: Multimedia :: Graphics :: Presentation',
'Topic :: Software Development :: User Interfaces',
],
)
|
Remove extraneous directory creation in examples environment. | const fs = require('fs')
const { promisify } = require('util')
const request = require('sync-request')
const AdmZip = require('adm-zip')
const lockfile = require('lockfile')
const lockPromise = promisify(lockfile.lock)
const test_version = '1.2.0'
const examples_lock = 'bids-validator/tests/data/examples.lockfile'
// Wait for up to five minutes for examples to finish
// downloading in another test worker
const examples_lock_opts = { wait: 300000 }
const loadExamples = async () => {
await lockPromise(examples_lock, examples_lock_opts)
if (
!fs.existsSync(
'bids-validator/tests/data/bids-examples-' + test_version + '/',
)
) {
console.log('downloading test data')
const response = request(
'GET',
'http://github.com/bids-standard/bids-examples/archive/' +
test_version +
'.zip',
)
fs.writeFileSync('bids-validator/tests/data/examples.zip', response.body)
const zip = new AdmZip('bids-validator/tests/data/examples.zip')
console.log('unzipping test data')
zip.extractAllTo('bids-validator/tests/data/', true)
}
lockfile.unlockSync(examples_lock)
return test_version
}
module.exports = loadExamples
| const fs = require('fs')
const { promisify } = require('util')
const request = require('sync-request')
const AdmZip = require('adm-zip')
const lockfile = require('lockfile')
const lockPromise = promisify(lockfile.lock)
const test_version = '1.2.0'
const examples_lock = 'bids-validator/tests/data/examples.lockfile'
// Wait for up to five minutes for examples to finish
// downloading in another test worker
const examples_lock_opts = { wait: 300000 }
const loadExamples = async () => {
await lockPromise(examples_lock, examples_lock_opts)
if (
!fs.existsSync(
'bids-validator/tests/data/bids-examples-' + test_version + '/',
)
) {
console.log('downloading test data')
const response = request(
'GET',
'http://github.com/bids-standard/bids-examples/archive/' +
test_version +
'.zip',
)
if (!fs.existsSync('bids-validator/tests/data')) {
fs.mkdirSync('bids-validator/tests/data')
}
fs.writeFileSync('bids-validator/tests/data/examples.zip', response.body)
const zip = new AdmZip('bids-validator/tests/data/examples.zip')
console.log('unzipping test data')
zip.extractAllTo('bids-validator/tests/data/', true)
}
lockfile.unlockSync(examples_lock)
return test_version
}
module.exports = loadExamples
|
Update eslint config for switch case construct | module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error",
4,
{
SwitchCase: 1
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"max-len": ["warn", 120]
}
};
| module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"max-len": ["warn", 120]
}
};
|
Remove-diff-signs: Fix alignment in expanded code blocks | // ==UserScript==
// @name GitHub Remove Diff Signs
// @version 1.3.1
// @description A userscript that hides the "+" and "-" from code diffs
// @license MIT
// @author Rob Garrison
// @namespace https://github.com/Mottie
// @include https://github.com/*
// @run-at document-idle
// @grant GM_addStyle
// @icon https://assets-cdn.github.com/pinned-octocat.svg
// @updateURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-remove-diff-signs.user.js
// @downloadURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-remove-diff-signs.user.js
// ==/UserScript==
(() => {
"use strict";
GM_addStyle(`
.blob-code-inner:before,
.blob-code-marker-context:before,
.blob-code-marker-addition:before,
.blob-code-marker-deletion:before {
visibility: hidden !important;
}`
);
})();
| // ==UserScript==
// @name GitHub Remove Diff Signs
// @version 1.3.0
// @description A userscript that hides the "+" and "-" from code diffs
// @license MIT
// @author Rob Garrison
// @namespace https://github.com/Mottie
// @include https://github.com/*
// @run-at document-idle
// @grant GM_addStyle
// @icon https://assets-cdn.github.com/pinned-octocat.svg
// @updateURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-remove-diff-signs.user.js
// @downloadURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-remove-diff-signs.user.js
// ==/UserScript==
(() => {
"use strict";
GM_addStyle(`
.blob-code-marker-context:before,
.blob-code-marker-addition:before,
.blob-code-marker-deletion:before {
display: none !important;
}`
);
})();
|
Remove whitespace before package declaration.
git-svn-id: 6ecf90c357d929aee58b51a998def805f2e9c62f@370915 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.logging;
import org.apache.commons.logging.impl.SimpleLog;
/**
*
*
*
*
*
*
*/
public class SimpleLogTestCase extends AbstractLogTest
{
/**
*
*
*
*/
public Log getLogObject()
{
return (Log) new SimpleLog(this.getClass().getName());
}
public static void main(String[] args) {
String[] testCaseName = { SimpleLogTestCase.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
}
| /*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.logging;
import org.apache.commons.logging.impl.SimpleLog;
/**
*
*
*
*
*
*
*/
public class SimpleLogTestCase extends AbstractLogTest
{
/**
*
*
*
*/
public Log getLogObject()
{
return (Log) new SimpleLog(this.getClass().getName());
}
public static void main(String[] args) {
String[] testCaseName = { SimpleLogTestCase.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
}
|
Tweak wording in doc comments | <?php
namespace Neos\Flow\Http;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestInterface;
/**
* Central authority to get hold of the active HTTP request.
* When no active HTTP request can be determined (for example in CLI context) an exception will be thrown
*
* Note: Usually this class is not being used directly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances
*
* @Flow\Scope("singleton")
*/
final class ActiveHttpRequestProvider
{
/**
* @Flow\Inject
* @var Bootstrap
*/
protected $bootstrap;
/**
* Returns the currently active HTTP request, if available.
* If the HTTP request can't be determined (for example in CLI context) a \Neos\Flow\Http\Exception is thrown
*
* @return ServerRequestInterface
* @throws Exception
*/
public function getActiveHttpRequest(): ServerRequestInterface
{
$requestHandler = $this->bootstrap->getActiveRequestHandler();
if (!$requestHandler instanceof HttpRequestHandlerInterface) {
throw new Exception(sprintf('The active HTTP request can\'t be determined because the request handler is not an instance of %s but a %s. Use a ServerRequestFactory to create a HTTP requests in CLI context', HttpRequestHandlerInterface::class, get_class($requestHandler)), 1600869131);
}
return $requestHandler->getHttpRequest();
}
}
| <?php
namespace Neos\Flow\Http;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestInterface;
/**
* Central authority to get hold of the active HTTP request.
* When no active HTTP request can be determined (for example in CLI context) an exception will be thrown
*
* Note: Naturally this class is not being used directly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances
*
* @Flow\Scope("singleton")
*/
final class ActiveHttpRequestProvider
{
/**
* @Flow\Inject
* @var Bootstrap
*/
protected $bootstrap;
/**
* Returns the currently active HTTP request, if available.
* If the HTTP request can't be determined (for example in CLI context) a \Neos\Flow\Http\Exception is thrown
*
* @return ServerRequestInterface
* @throws Exception
*/
public function getActiveHttpRequest(): ServerRequestInterface
{
$requestHandler = $this->bootstrap->getActiveRequestHandler();
if (!$requestHandler instanceof HttpRequestHandlerInterface) {
throw new Exception(sprintf('The active HTTP request can\'t be determined because the request handler is not an instance of %s but a %s. Use a ServerRequestFactory to create a HTTP requests in CLI context', HttpRequestHandlerInterface::class, get_class($requestHandler)), 1600869131);
}
return $requestHandler->getHttpRequest();
}
}
|
Fix the expand/close button text | require([ "jquery" ], function($) {
"use strict";
$("pre").each(function() {
if (this.firstChild.getBoundingClientRect().height > this.getBoundingClientRect().height) {
var button = $("<span/>")
.addClass("btn btn--white snippet-expand")
.text("Expand snippet")
.data("alt", "Close snippet");
$(button).on("click", function() {
var newText = $(this).data("alt"),
prevText = $(this).text();
$(this).text(newText).data("alt", prevText);
$(this).prev("pre").toggleClass("is-open");
});
$(this).after(button);
}
});
});
| require([ "jquery" ], function($) {
"use strict";
$("pre").each(function() {
if (this.firstChild.getBoundingClientRect().height > this.getBoundingClientRect().height) {
var button = $("<span/>")
.addClass("btn btn--white snippet-expand")
.text("Expand snippet")
.data("alt", "Close snippet");
$(button).on("click", function() {
var newText = $(this).attr("data-alt"),
prevText = $(this).text();
$(this).text(newText).attr("data-alt", prevText);
$(this).prev("pre").toggleClass("is-open");
});
$(this).after(button);
}
});
});
|
Stop serialising fields with no name | 'use strict';
function setElementsValueByName(name, value) {
var elements = document.getElementsByName(name);
for(var i = 0; i < elements.length; i++) {
elements[i].value = value;
}
}
function serializeForms() {
var fields = [];
for(var i = 0; i < document.forms.length; i++) {
var elements = document.forms[i].elements;
for(var j = 0; j < elements.length; j++) {
var el = elements[j];
if(!el.name || el.clientHeight < 1 || el.clientWidth < 1) {
continue;
}
fields.push({name: el.name, value: el.value});
}
}
return fields;
}
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
switch(message.type) {
case "SET_FORM":
message.data.fields.forEach(function(field) {
setElementsValueByName(field.name, field.value);
});
break;
case "GET_FORM":
sendResponse(serializeForms());
break;
}
});
| 'use strict';
function setElementsValueByName(name, value) {
var elements = document.getElementsByName(name);
for(var i = 0; i < elements.length; i++) {
elements[i].value = value;
}
}
function serializeForms() {
var fields = [];
for(var i = 0; i < document.forms.length; i++) {
var elements = document.forms[i].elements;
for(var j = 0; j < elements.length; j++) {
var el = elements[j];
if(el.clientHeight < 1 || el.clientWidth < 1) {
continue;
}
fields.push({name: el.name, value: el.value});
}
}
return fields;
}
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
switch(message.type) {
case "SET_FORM":
message.data.fields.forEach(function(field) {
setElementsValueByName(field.name, field.value);
});
break;
case "GET_FORM":
sendResponse(serializeForms());
break;
}
});
|
Replace `var` with `const` or `let` | const binding = require('bindings')('contextify');
const ContextifyContext = binding.ContextifyContext;
const ContextifyScript = binding.ContextifyScript;
function Contextify (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
let ctx = new ContextifyContext(sandbox);
sandbox.run = function () {
return ctx.run.apply(ctx, arguments);
};
sandbox.getGlobal = function () {
return ctx.getGlobal();
}
sandbox.dispose = function () {
sandbox.run = function () {
throw new Error("Called run() after dispose().");
};
sandbox.getGlobal = function () {
throw new Error("Called getGlobal() after dispose().");
};
sandbox.dispose = function () {
throw new Error("Called dispose() after dispose().");
};
ctx = null;
}
return sandbox;
}
Contextify.createContext = function (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
return new ContextifyContext(sandbox);
};
Contextify.createScript = function (code, filename) {
if (typeof code != 'string') {
throw new TypeError('Code argument is required');
}
return new ContextifyScript(code, filename);
};
module.exports = Contextify;
| var binding = require('bindings')('contextify');
var ContextifyContext = binding.ContextifyContext;
var ContextifyScript = binding.ContextifyScript;
function Contextify (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
var ctx = new ContextifyContext(sandbox);
sandbox.run = function () {
return ctx.run.apply(ctx, arguments);
};
sandbox.getGlobal = function () {
return ctx.getGlobal();
}
sandbox.dispose = function () {
sandbox.run = function () {
throw new Error("Called run() after dispose().");
};
sandbox.getGlobal = function () {
throw new Error("Called getGlobal() after dispose().");
};
sandbox.dispose = function () {
throw new Error("Called dispose() after dispose().");
};
ctx = null;
}
return sandbox;
}
Contextify.createContext = function (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
return new ContextifyContext(sandbox);
};
Contextify.createScript = function (code, filename) {
if (typeof code != 'string') {
throw new TypeError('Code argument is required');
}
return new ContextifyScript(code, filename);
};
module.exports = Contextify;
|
Fix sorter for fields with null sortable property | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Grid\Sorting;
use Sylius\Component\Grid\Data\DataSourceInterface;
use Sylius\Component\Grid\Definition\Grid;
use Sylius\Component\Grid\Parameters;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
final class Sorter implements SorterInterface
{
/**
* {@inheritdoc}
*/
public function sort(DataSourceInterface $dataSource, Grid $grid, Parameters $parameters)
{
$expressionBuilder = $dataSource->getExpressionBuilder();
$sorting = $parameters->get('sorting', $grid->getSorting());
foreach ($sorting as $field => $order) {
$gridField = $grid->getField($field);
$property = $gridField->getSortable();
if (null !== $property) {
$expressionBuilder->addOrderBy($property, $order);
}
}
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Grid\Sorting;
use Sylius\Component\Grid\Data\DataSourceInterface;
use Sylius\Component\Grid\Definition\Field;
use Sylius\Component\Grid\Definition\Grid;
use Sylius\Component\Grid\Parameters;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
final class Sorter implements SorterInterface
{
/**
* {@inheritdoc}
*/
public function sort(DataSourceInterface $dataSource, Grid $grid, Parameters $parameters)
{
$expressionBuilder = $dataSource->getExpressionBuilder();
$sorting = $parameters->get('sorting', $grid->getSorting());
foreach ($sorting as $field => $order) {
$gridField = $grid->getField($field);
$property = $gridField->getSortable();
$expressionBuilder->addOrderBy($property, $order);
}
}
}
|
Update test that is built directly in test. | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import com.yahoo.jrt.*;
public class MockupInvoke {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("error: Wrong number of parameters");
System.exit(0);
}
Transport transport = new Transport();
Supervisor orb = new Supervisor(transport);
Spec spec = new Spec(args[0]);
Request req = new Request("concat");
req.parameters().add(new StringValue(args[1]));
req.parameters().add(new StringValue(args[2]));
Target target = orb.connect(spec);
try {
target.invokeSync(req, 60.0);
} finally {
target.close();
}
if (req.isError()) {
System.out.println("error: " + req.errorCode()
+ ": " + req.errorMessage());
System.exit(0);
}
if (req.returnValues().size() != 1
|| req.returnValues().get(0).type() != 's') {
System.out.println("error: Wrong return values");
System.exit(0);
}
System.out.println("result: '"
+ req.returnValues().get(0).asString()
+ "'");
}
}
| // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import com.yahoo.jrt.*;
public class MockupInvoke {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("error: Wrong number of parameters");
System.exit(0);
}
Transport transport = new Transport();
Supervisor orb = new Supervisor(transport);
Spec spec = new Spec(args[0]);
Request req = new Request("concat");
req.parameters().add(new StringValue(args[1]));
req.parameters().add(new StringValue(args[2]));
orb.invokeBatch(spec, req, 60.0);
if (req.isError()) {
System.out.println("error: " + req.errorCode()
+ ": " + req.errorMessage());
System.exit(0);
}
if (req.returnValues().size() != 1
|| req.returnValues().get(0).type() != 's') {
System.out.println("error: Wrong return values");
System.exit(0);
}
System.out.println("result: '"
+ req.returnValues().get(0).asString()
+ "'");
}
}
|
Create Service if cloud Space | /*
* Copyright (C) 2016 Thinkenterprise
*
* 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.
*
*
* @author Michael Schaefer
*/
package com.thinkenterprise;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.thinkenterprise.service.CloudEnvironmentService;
import com.thinkenterprise.service.DevelopmentEnvironmentService;
import com.thinkenterprise.service.EnvironmentService;
@Configuration
public class ApplicationConfiguration {
@Bean
@Profile("development")
public EnvironmentService getDefaultEnvironmentService() {
return new DevelopmentEnvironmentService();
}
@Bean
@Profile("cloud")
public EnvironmentService getCloudEnvironmentService() {
return new CloudEnvironmentService();
}
}
| /*
* Copyright (C) 2016 Thinkenterprise
*
* 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.
*
*
* @author Michael Schaefer
*/
package com.thinkenterprise;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.thinkenterprise.service.CloudEnvironmentService;
import com.thinkenterprise.service.DevelopmentEnvironmentService;
import com.thinkenterprise.service.EnvironmentService;
@Configuration
public class ApplicationConfiguration {
@Bean
@Profile("development")
public EnvironmentService getDefaultEnvironmentService() {
return new DevelopmentEnvironmentService();
}
public EnvironmentService getCloudEnvironmentService() {
return new CloudEnvironmentService();
}
}
|
Move try-catch into the parsing logic, and display errors into the
output. | import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = `Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
function runParser() {
try {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.style.borderColor = "black";
outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
} catch (error) {
outputHtmlNode.style.borderColor = "red";
outputHtmlNode.innerHTML = error;
}
}
inputNode.addEventListener("input", runParser, 200);
runParser();
}); | import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = `Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
function runParser() {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
}
inputNode.addEventListener("input", runParser, 200);
try {
runParser();
} catch (err) {
console.error(err);
}
}); |
Include leaflet lib + assets | /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var Funnel = require('broccoli-funnel');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Any other options
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
// app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.js'); // Included as separate file in index.html
// app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.css'); // Included as separate file in index.html
var semanticUi = new Funnel(app.bowerDirectory + '/semantic-ui', {
srcDir: '/dist',
include: ['**/*.*'],
destDir: '/assets/semantic-ui'
});
var leaflet = new Funnel(app.bowerDirectory + '/leaflet', {
srcDir: '/dist',
include: ['**/*.*'],
destDir: '/assets/leaflet'
});
return app.toTree([semanticUi, leaflet]);
};
| /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var Funnel = require('broccoli-funnel');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Any other options
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
// app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.js'); // Included as separate file in index.html
// app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.css'); // Included as separate file in index.html
var extraAssets = new Funnel(app.bowerDirectory + '/semantic-ui', {
srcDir: '/dist',
include: ['**/*.*'],
destDir: '/assets/semantic-ui'
});
return app.toTree(extraAssets);
};
|
Adjust tests leave leading numbers on slugify. | <?php
use UWDOEM\Framework\Etc\StringUtils;
class StringUtilsTest extends PHPUnit_Framework_TestCase {
public function testSlugify() {
// Assert that it will correctly convert a simple string
$string = "I am the very model of a modern Major General";
$this->assertEquals("i-am-the-very-model-of-a-modern-major-general", StringUtils::slugify($string));
// Assert that it will remove non-alphanumeric characters
$string = "^a#%5m4ll3r^^7357!@ 57r1n6";
$this->assertEquals("a5m4ll3r7357-57r1n6", StringUtils::slugify($string));
// Assert that it will trim numbers from the beginning of the string
$string = "2^4a#%5m4ll3r^^7357!@ 57r1n6";
$this->assertEquals("24a5m4ll3r7357-57r1n6", StringUtils::slugify($string));
}
public function testToUpperCamelCase() {
$string = "I am the very-model of_a modern Major General";
$this->assertEquals("IAmTheVeryModelOfAModernMajorGeneral", StringUtils::toUpperCamelCase($string));
}
public function testToTitleCase() {
$string = "i am the very-model of_a modern Major General";
$this->assertEquals("I Am the Very Model of a Modern Major General", StringUtils::toTitleCase($string));
}
}
| <?php
use UWDOEM\Framework\Etc\StringUtils;
class StringUtilsTest extends PHPUnit_Framework_TestCase {
public function testSlugify() {
// Assert that it will correctly convert a simple string
$string = "I am the very model of a modern Major General";
$this->assertEquals("i-am-the-very-model-of-a-modern-major-general", StringUtils::slugify($string));
// Assert that it will remove non-alphanumeric characters
$string = "^a#%5m4ll3r^^7357!@ 57r1n6";
$this->assertEquals("a5m4ll3r7357-57r1n6", StringUtils::slugify($string));
// Assert that it will trim numbers from the beginning of the string
$string = "2^4a#%5m4ll3r^^7357!@ 57r1n6";
$this->assertEquals("a5m4ll3r7357-57r1n6", StringUtils::slugify($string));
}
public function testToUpperCamelCase() {
$string = "I am the very-model of_a modern Major General";
$this->assertEquals("IAmTheVeryModelOfAModernMajorGeneral", StringUtils::toUpperCamelCase($string));
}
public function testToTitleCase() {
$string = "i am the very-model of_a modern Major General";
$this->assertEquals("I Am the Very Model of a Modern Major General", StringUtils::toTitleCase($string));
}
}
|
Remove absolute path name from calls to phantomjs.
Change-Id: I58af53ecf9c77f68c730f7a429586a982ead8cb1 | // Copyright 2009 Google Inc. All Rights Reserved.
package com.google.appinventor.blocklyeditor;
import java.io.IOException;
import com.google.appinventor.common.testutils.TestUtils;
import junit.framework.TestCase;
/**
* Tests the App Inventor Blockly blocks evaluation of various YAIL code.
*
* TODO(andrew.f.mckinney): More tests needed!
*
* @author andrew.f.mckinney@gmail.com (Andrew.F.McKinney)
*/
public class BlocklyEvalTest extends TestCase {
public static final String testpath = TestUtils.APP_INVENTOR_ROOT_DIR + "/blocklyeditor";
public void testButtonClick() throws Exception {
String[] params = { "phantomjs", testpath + "/tests/com/google/appinventor/blocklyeditor/buttonClickTest.js" };
String result = "";
try {
result = CodeBlocksProcessHelper.exec(params, true).trim();
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("true", result.toString());
}
public void testIfThenBlock() throws Exception {
String[] params = { "phantomjs", testpath + "/tests/com/google/appinventor/blocklyeditor/ifThenBlockTest.js" };
String result = "";
try {
result = CodeBlocksProcessHelper.exec(params, true).trim();
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("true", result.toString());
}
}
| // Copyright 2009 Google Inc. All Rights Reserved.
package com.google.appinventor.blocklyeditor;
import java.io.IOException;
import com.google.appinventor.common.testutils.TestUtils;
import junit.framework.TestCase;
/**
* Tests the App Inventor Blockly blocks evaluation of various YAIL code.
*
* TODO(andrew.f.mckinney): More tests needed!
*
* @author andrew.f.mckinney@gmail.com (Andrew.F.McKinney)
*/
public class BlocklyEvalTest extends TestCase {
public static final String testpath = TestUtils.APP_INVENTOR_ROOT_DIR + "/blocklyeditor";
public void testButtonClick() throws Exception {
String[] params = { "/usr/local/bin/phantomjs", testpath + "/tests/com/google/appinventor/blocklyeditor/buttonClickTest.js" };
String result = "";
try {
result = CodeBlocksProcessHelper.exec(params, true).trim();
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("true", result.toString());
}
public void testIfThenBlock() throws Exception {
String[] params = { "/usr/local/bin/phantomjs", testpath + "/tests/com/google/appinventor/blocklyeditor/ifThenBlockTest.js" };
String result = "";
try {
result = CodeBlocksProcessHelper.exec(params, true).trim();
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("true", result.toString());
}
}
|
Adjust fixture usage in context tests | import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture
def ctx(base_ctor, request):
kwargs = getattr(request, 'param', {})
yield Context(**kwargs)
if hasattr(request, 'param'):
base_ctor.assert_called_once_with(**kwargs) # Skip unnecessary assertions
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
@pytest.mark.parametrize(
['ctx'],
[
({},),
({'asdf': 123},)
],
indirect=True
)
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
| import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture(params=[
{},
{'asdf': 123}
])
def ctx(base_ctor, request):
yield Context(**request.param)
base_ctor.assert_called_once_with(**request.param)
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
|
Add missing validation rules for v3 posts.
Users should *not* be able to specify whether their post is approved, and we should enforce some restrictions on other fields. | <?php
namespace Rogue\Http\Requests\Three;
use Rogue\Http\Requests\Request;
class PostRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'campaign_id' => 'required',
'campaign_run_id' => 'required_with:campaign_id|integer',
'why_participated' => 'nullable|string',
'caption' => 'required|nullable|string|max:140',
'quantity' => 'required|nullable|integer',
'file' => 'image|dimensions:min_width=400,min_height=400',
];
}
}
| <?php
namespace Rogue\Http\Requests\Three;
use Rogue\Http\Requests\Request;
class PostRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'status' => 'in:pending,accepted,rejected',
'caption' => 'string|max:140',
'quantity' => 'int',
];
}
}
|
Add hidden 'tab' input to make log search work | <?php
/**
* Logs view.
*
* @author Iron Bound Designs
* @since 1.0
* @license AGPL
* @copyright Iron Bound Designs, 2015.
*/
namespace ITELIC\Admin\Tab\View;
use IronBound\DBLogger\ListTable;
use ITELIC\Admin\Tab\View;
use ITELIC\Plugin;
/**
* Class Logs
* @package ITELIC\Admin\Tab\View
*/
class Logs extends View {
/**
* @var ListTable
*/
private $table;
/**
* Logs constructor.
*
* @param ListTable $table
*/
public function __construct( ListTable $table ) {
$this->table = $table;
}
/**
* Render the view.
*/
public function render() {
$this->table->prepare_items();
?>
<form method="GET">
<input type="hidden" name="page" value="<?php echo esc_attr( $_GET['page'] ); ?>">
<input type="hidden" name="tab" value="<?php echo esc_attr( $_GET['tab'] ); ?>">
<?php $this->table->views(); ?>
<?php $this->table->search_box( __( "Search", Plugin::SLUG ), 'itelic-search' ); ?>
<?php $this->table->display(); ?>
</form>
<?php
}
/**
* Get the title of this view.
*
* @return string
*/
protected function get_title() {
return __( "Logs", Plugin::SLUG );
}
} | <?php
/**
* Logs view.
*
* @author Iron Bound Designs
* @since 1.0
* @license AGPL
* @copyright Iron Bound Designs, 2015.
*/
namespace ITELIC\Admin\Tab\View;
use IronBound\DBLogger\ListTable;
use ITELIC\Admin\Tab\View;
use ITELIC\Plugin;
/**
* Class Logs
* @package ITELIC\Admin\Tab\View
*/
class Logs extends View {
/**
* @var ListTable
*/
private $table;
/**
* Logs constructor.
*
* @param ListTable $table
*/
public function __construct( ListTable $table ) {
$this->table = $table;
}
/**
* Render the view.
*/
public function render() {
$this->table->prepare_items();
?>
<form method="GET">
<input type="hidden" name="page" value="<?php echo esc_attr( $_GET['page'] ); ?>">
<?php $this->table->views(); ?>
<?php $this->table->search_box( __( "Search", Plugin::SLUG ), 'itelic-search' ); ?>
<?php $this->table->display(); ?>
</form>
<?php
}
/**
* Get the title of this view.
*
* @return string
*/
protected function get_title() {
return __( "Logs", Plugin::SLUG );
}
} |
Add aws-status-check to declared binaries | import os
from setuptools import setup, find_packages
version = __import__('aws_status').__version__
def read(path):
"""Return the content of a file."""
with open(path, 'r') as f:
return f.read()
setup(
name='aws-status',
version=version,
description='Wraps AWS status informations obtained via the status page.',
long_description=(read('README.rst')),
url='http://github.com/jbbarth/aws-status',
license='MIT',
author='Jean-Baptiste Barth',
author_email='jeanbaptiste.barth@gmail.com',
packages=find_packages(exclude=['tests*']),
scripts=[
'bin/aws-status-check',
'bin/aws-status-list',
],
install_requires=[
'feedparser>=5.1.3',
],
include_package_data=True,
#see http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: System :: Monitoring',
],
)
| import os
from setuptools import setup, find_packages
version = __import__('aws_status').__version__
def read(path):
"""Return the content of a file."""
with open(path, 'r') as f:
return f.read()
setup(
name='aws-status',
version=version,
description='Wraps AWS status informations obtained via the status page.',
long_description=(read('README.rst')),
url='http://github.com/jbbarth/aws-status',
license='MIT',
author='Jean-Baptiste Barth',
author_email='jeanbaptiste.barth@gmail.com',
packages=find_packages(exclude=['tests*']),
scripts=[
'bin/aws-status-list',
],
install_requires=[
'feedparser>=5.1.3',
],
include_package_data=True,
#see http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: System :: Monitoring',
],
)
|
Fix period validation in daily quota serializer. | from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
| from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
|
Allow overriding default system theme values | function MtkLabel (settings) {
MtkXaml.call (this, "<TextBlock/>", settings);
this.CustomSize = false;
this.CustomForeground = false;
this.CustomFamily = false;
this.MapProperties ([
[ "Text", "QueueResize" ],
[ "FontFamily", "QueueResize" ],
[ "FontSize", "QueueResize" ],
[ "FontStretch", "QueueResize" ],
[ "FontStyle", "QueueResize" ],
[ "FontWeight", "QueueResize" ],
[ "TextWrapping", "QueueResize" ],
[ "TextDecorations", "QueueResize" ],
[ "Foreground" ]
]);
if (typeof settings == "string") {
this.Text = settings;
}
this.Override ("OnStyleSet", function () {
if (!this.CustomFamily) this.FontFamily = MtkStyle.Font.Family;
if (!this.CustomSize) this.FontSize = MtkStyle.Font.Size;
if (!this.CustomForeground) this.Foreground = MtkStyle.GetColor ("window_fg");
});
// Override default XAlign = 0.5
this.XAlign = 0.0;
this.AfterConstructed ();
}
| function MtkLabel (settings) {
MtkXaml.call (this, "<TextBlock/>", settings);
this.MapProperties ([
[ "Text", "QueueResize" ],
[ "FontFamily", "QueueResize" ],
[ "FontSize", "QueueResize" ],
[ "FontStretch", "QueueResize" ],
[ "FontStyle", "QueueResize" ],
[ "FontWeight", "QueueResize" ],
[ "TextWrapping", "QueueResize" ],
[ "TextDecorations", "QueueResize" ],
[ "Foreground" ]
]);
if (typeof settings == "string") {
this.Text = settings;
}
this.Override ("OnStyleSet", function () {
this.FontFamily = MtkStyle.Font.Family;
this.FontSize = MtkStyle.Font.Size;
this.Foreground = MtkStyle.GetColor ("window_fg");
});
// Override default XAlign = 0.5
this.XAlign = 0.0;
this.AfterConstructed ();
}
|
Return the actual size written to bw, even when an error occurs. | package netascii
import (
"bufio"
"bytes"
"io"
)
func WriteTo(b []byte, bw *bufio.Writer) (n int, err error) {
b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
n, err = bw.Write(b)
if err != nil {
return n, err
}
return n, nil
}
func Convert(b []byte) []byte {
b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
return b
}
func ReadFull(r io.Reader, buf []byte) (n int, err error) {
if len(buf) == 0 {
return 0, io.ErrShortBuffer
}
n, err = r.Read(buf)
if err != nil {
return 0, err
}
buf = bytes.Replace(buf, []byte{'\r', 0}, []byte{'\r'}, -1)
buf = bytes.Replace(buf, []byte{'\r', '\n'}, []byte{'\n'}, -1)
return n, nil
}
| package netascii
import (
"bufio"
"bytes"
"io"
)
func WriteTo(b []byte, bw *bufio.Writer) (n int, err error) {
b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
n, err = bw.Write(b)
if err != nil {
return 0, err
}
return n, nil
}
func Convert(b []byte) []byte {
b = bytes.Replace(b, []byte{'\r', 0}, []byte{'\r'}, -1)
b = bytes.Replace(b, []byte{'\r', '\n'}, []byte{'\n'}, -1)
return b
}
func ReadFull(r io.Reader, buf []byte) (n int, err error) {
if len(buf) == 0 {
return 0, io.ErrShortBuffer
}
n, err = r.Read(buf)
if err != nil {
return 0, err
}
buf = bytes.Replace(buf, []byte{'\r', 0}, []byte{'\r'}, -1)
buf = bytes.Replace(buf, []byte{'\r', '\n'}, []byte{'\n'}, -1)
return n, nil
}
|
Move footer into container in guest-layout | <!DOCTYPE html>
<html lang="en">
<head>
@include('partials/header-sidewide-meta')
<!-- [[ HTML::style('css/bootstrap.min.css') ]] -->
<!-- [[ HTML::style('css/bootstrap-theme.min.css') ]] -->
[[ HTML::style('css/themes/paperwork-v1.min.css') ]]
</head>
<body class="paperwork-guest">
<div class="container">
<div class="guest-logo">
<img class="guest-logo-img" src="[[ asset('images/paperwork-logo.png') ]]">
</div>
@yield("content")
<div class="footer [[ Config::get('paperwork.showIssueReportingLink') ? '' : 'hide' ]]">
@include('partials/error-reporting-footer')
</div>
</div> <!-- /container -->
[[ HTML::script('js/jquery.min.js') ]]
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
[[ HTML::script('js/ltie9compat.min.js') ]]
<![endif]-->
<!--[if lt IE 11]>
[[ HTML::script('js/ltie11compat.js') ]]
<![endif]-->
[[ HTML::script('js/libraries.min.js') ]]
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
@include('partials/header-sidewide-meta')
<!-- [[ HTML::style('css/bootstrap.min.css') ]] -->
<!-- [[ HTML::style('css/bootstrap-theme.min.css') ]] -->
[[ HTML::style('css/themes/paperwork-v1.min.css') ]]
</head>
<body class="paperwork-guest">
<div class="container">
<div class="guest-logo">
<img class="guest-logo-img" src="[[ asset('images/paperwork-logo.png') ]]">
</div>
@yield("content")
</div> <!-- /container -->
<div class="footer [[ Config::get('paperwork.showIssueReportingLink') ? '' : 'hide' ]]">
@include('partials/error-reporting-footer')
</div>
[[ HTML::script('js/jquery.min.js') ]]
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
[[ HTML::script('js/ltie9compat.min.js') ]]
<![endif]-->
<!--[if lt IE 11]>
[[ HTML::script('js/ltie11compat.js') ]]
<![endif]-->
[[ HTML::script('js/libraries.min.js') ]]
</body>
</html>
|
Make sure app is not defined twice
Current code throws the following error,
```js
Identifier 'app' has already been declared
/home/vagrant/s2bv4-ui-core/addons/reporting-engine/node_modules/ember-cli-datepicker-bootstrap/index.js:21
let app = findHost.call(this);
```
I removed app argument to prevent double defined app. | /* jshint node: true */
'use strict';
// For ember-cli < 2.7 findHost doesnt exist so we backport from that version
// for earlier version of ember-cli.
//https://github.com/ember-cli/ember-cli/blame/16e4492c9ebf3348eb0f31df17215810674dbdf6/lib/models/addon.js#L533
function findHostShim() {
let current = this;
let app;
do {
app = current.app || app;
} while (current.parent.parent && (current = current.parent));
return app;
}
module.exports = {
name: 'ember-cli-bootstrap-datepicker',
included() {
let findHost = this._findHost || findHostShim;
let app = findHost.call(this);
app.import(app.bowerDirectory + '/bootstrap-datepicker/dist/js/bootstrap-datepicker.js');
app.import(app.bowerDirectory + '/bootstrap-datepicker/dist/css/bootstrap-datepicker.css');
}
};
| /* jshint node: true */
'use strict';
// For ember-cli < 2.7 findHost doesnt exist so we backport from that version
// for earlier version of ember-cli.
//https://github.com/ember-cli/ember-cli/blame/16e4492c9ebf3348eb0f31df17215810674dbdf6/lib/models/addon.js#L533
function findHostShim() {
let current = this;
let app;
do {
app = current.app || app;
} while (current.parent.parent && (current = current.parent));
return app;
}
module.exports = {
name: 'ember-cli-bootstrap-datepicker',
included: function(app) {
let findHost = this._findHost || findHostShim;
let app = findHost.call(this);
app.import(app.bowerDirectory + '/bootstrap-datepicker/dist/js/bootstrap-datepicker.js');
app.import(app.bowerDirectory + '/bootstrap-datepicker/dist/css/bootstrap-datepicker.css');
}
};
|
Set the component name through the documentable behavior | <?php
/**
* Kodekit Component - http://www.timble.net/kodekit
*
* @copyright Copyright (C) 2011 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit-application for the canonical source repository
*/
namespace Kodekit\Component\Application;
use Kodekit\Library;
/**
* Html Document View
*
* @author Johan Janssens <http://github.com/johanjanssens>
* @package Kodekit\Component\Application
*/
class ViewDocumentHtml extends ViewHtml
{
protected function _initialize(Library\ObjectConfig $config)
{
$config->append(array(
'template_filters' => array('style', 'link', 'meta', 'script', 'title', 'message'),
));
parent::_initialize($config);
}
} | <?php
/**
* Kodekit Component - http://www.timble.net/kodekit
*
* @copyright Copyright (C) 2011 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
* @link https://github.com/timble/kodekit-application for the canonical source repository
*/
namespace Kodekit\Component\Application;
use Kodekit\Library;
/**
* Html Document View
*
* @author Johan Janssens <http://github.com/johanjanssens>
* @package Kodekit\Component\Application
*/
class ViewDocumentHtml extends ViewHtml
{
protected function _initialize(Library\ObjectConfig $config)
{
$config->append(array(
'template_filters' => array('style', 'link', 'meta', 'script', 'title', 'message'),
));
parent::_initialize($config);
}
protected function _fetchData(Library\ViewContext $context)
{
if($this->getObject('manager')->isRegistered('dispatcher')) {
$context->data->component = $this->getObject('dispatcher')->getIdentifier()->package;
} else {
$context->data->component = '';
}
parent::_fetchData($context);
}
} |
Use beautiful scrolling if available | import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class ResultItem extends Component {
componentDidUpdate() {
if (this.props.selected) {
const node = ReactDOM.findDOMNode(this)
if (node.scrollIntoViewIfNeeded) {
node.scrollIntoViewIfNeeded(false)
} else {
node.scrollIntoView();
}
}
}
render() {
const { result, onClick, selected } = this.props;
return (
<li onClick={() => onClick(result)} className={selected ? 'selected' : ''}>
<img src={result.thumbnail} className="video-thumbnail" />
<div className="details">
<div className="name">
{result.name}
</div>
<div className="author">
{result.author}
</div>
</div>
</li>
);
}
}
| import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class ResultItem extends Component {
componentDidUpdate() {
if (this.props.selected) {
ReactDOM.findDOMNode(this).scrollIntoView(false);
}
}
render() {
const { result, onClick, selected } = this.props;
return (
<li onClick={() => onClick(result)} className={selected ? 'selected' : ''}>
<img src={result.thumbnail} className="video-thumbnail" />
<div className="details">
<div className="name">
{result.name}
</div>
<div className="author">
{result.author}
</div>
</div>
</li>
);
}
}
|
Implement ValueObject.sameValueAs(), and use that as delegate in equals() | package se.citerus.dddsample.domain;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Uniquely identifies a particular cargo. Automatically generated by the application.
*
*/
public final class TrackingId implements ValueObject<TrackingId> {
private String id;
/**
* Constructor.
*
* @param id Id string.
*/
public TrackingId(final String id) {
Validate.notNull(id);
this.id = id;
}
/**
* @return String representation of this tracking id.
*/
public String idString() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TrackingId other = (TrackingId) o;
return sameValueAs(other);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public boolean sameValueAs(TrackingId other) {
return other != null && EqualsBuilder.reflectionEquals(this, other);
}
TrackingId() {
// Needed by Hibernate
}
}
| package se.citerus.dddsample.domain;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Identifies a particular cargo.
* <p/>
* Make sure to put a constraint in the database to make sure TrackingId is unique.
*/
public final class TrackingId {
private String id;
/**
* Constructor.
*
* @param id Id string.
*/
public TrackingId(final String id) {
Validate.notNull(id);
this.id = id;
}
/**
* @return String representation of this tracking id.
*/
public String idString() {
return id;
}
@Override
public boolean equals(final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
TrackingId() {
// Needed by Hibernate
}
}
|
Fix handling of default groups for null world | package ru.tehkode.permissions.backends.caching;
import ru.tehkode.permissions.PermissionsGroupData;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
/**
* Cached data for groups
*/
public class CachingGroupData extends CachingData implements PermissionsGroupData {
private final PermissionsGroupData backingData;
private final Map<String, Boolean> defaultsMap = new HashMap<>();
public CachingGroupData(PermissionsGroupData backingData, Executor executor, Object lock) {
super(executor, lock);
this.backingData = backingData;
}
@Override
protected PermissionsGroupData getBackingData() {
return backingData;
}
@Override
protected void clearCache() {
super.clearCache();
defaultsMap.clear();
}
@Override
public boolean isDefault(String world) {
Boolean bool = defaultsMap.get(world);
if (bool == null) {
synchronized (lock) {
bool = getBackingData().isDefault(world);
}
defaultsMap.put(world, bool);
}
return bool;
}
@Override
public void setDefault(final boolean def, final String world) {
defaultsMap.put(world, def);
execute(new Runnable() {
@Override
public void run() {
getBackingData().setDefault(def, world);
}
});
}
}
| package ru.tehkode.permissions.backends.caching;
import ru.tehkode.permissions.PermissionsGroupData;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
/**
* Cached data for groups
*/
public class CachingGroupData extends CachingData implements PermissionsGroupData {
private final PermissionsGroupData backingData;
private final Map<String, Boolean> defaultsMap = new ConcurrentHashMap<>();
public CachingGroupData(PermissionsGroupData backingData, Executor executor, Object lock) {
super(executor, lock);
this.backingData = backingData;
}
@Override
protected PermissionsGroupData getBackingData() {
return backingData;
}
@Override
protected void clearCache() {
super.clearCache();
defaultsMap.clear();
}
@Override
public boolean isDefault(String world) {
Boolean bool = defaultsMap.get(world);
if (bool == null) {
synchronized (lock) {
bool = getBackingData().isDefault(world);
}
defaultsMap.put(world, bool);
}
return bool;
}
@Override
public void setDefault(final boolean def, final String world) {
defaultsMap.put(world, def);
execute(new Runnable() {
@Override
public void run() {
getBackingData().setDefault(def, world);
}
});
}
}
|
Add new timing metric with .sparse-avg suffix | package statsd
import (
"time"
"github.com/tecnickcom/statsd"
)
type MetricsService struct {
statsdClient *statsd.Client
prefix string
}
func NewMetricsService() *MetricsService {
statsdClient, e := statsd.New() // Connect to the UDP port 8125 by default.
if e != nil {
panic(e)
}
return &MetricsService{statsdClient: statsdClient, prefix: "bits."}
}
func (service *MetricsService) SendTimingMetric(name string, duration time.Duration) {
service.statsdClient.Timing(service.prefix+name, duration.Seconds()*1000)
// we send this additional metric, because our test envs use metrics.ng.bluemix.net
// and for aggregation purposes this service needs this suffix.
service.statsdClient.Timing(service.prefix+name+".sparse-avg", duration.Seconds()*1000)
}
func (service *MetricsService) SendGaugeMetric(name string, value int64) {
service.statsdClient.Gauge(service.prefix+name, value)
}
func (service *MetricsService) SendCounterMetric(name string, value int64) {
service.statsdClient.Count(service.prefix+name, value)
}
| package statsd
import (
"time"
"github.com/tecnickcom/statsd"
)
type MetricsService struct {
statsdClient *statsd.Client
prefix string
}
func NewMetricsService() *MetricsService {
statsdClient, e := statsd.New() // Connect to the UDP port 8125 by default.
if e != nil {
panic(e)
}
return &MetricsService{statsdClient: statsdClient, prefix: "bits."}
}
func (service *MetricsService) SendTimingMetric(name string, duration time.Duration) {
service.statsdClient.Timing(service.prefix+name, duration.Seconds()*1000)
}
func (service *MetricsService) SendGaugeMetric(name string, value int64) {
service.statsdClient.Gauge(service.prefix+name, value)
}
func (service *MetricsService) SendCounterMetric(name string, value int64) {
service.statsdClient.Count(service.prefix+name, value)
}
|
Use HTTPS URL for repository. | #!/usr/bin/env python
from distutils.core import setup
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='facebook-sdk',
version='0.3.2',
description='This client library is designed to support the Facebook '
'Graph API and the official Facebook JavaScript SDK, which '
'is the canonical way to implement Facebook authentication.',
author='Facebook',
url='https://github.com/pythonforfacebook/facebook-sdk',
license='Apache',
py_modules=[
'facebook',
],
long_description=read("README.rst"),
classifiers=[
'License :: OSI Approved :: Apache Software License',
],
)
| #!/usr/bin/env python
from distutils.core import setup
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='facebook-sdk',
version='0.3.2',
description='This client library is designed to support the Facebook '
'Graph API and the official Facebook JavaScript SDK, which '
'is the canonical way to implement Facebook authentication.',
author='Facebook',
url='http://github.com/pythonforfacebook/facebook-sdk',
license='Apache',
py_modules=[
'facebook',
],
long_description=read("README.rst"),
classifiers=[
'License :: OSI Approved :: Apache Software License',
],
)
|
Add callback to call to process | #!/usr/bin/env node
"use strict";
var path = require("path");
var fs = require("fs");
var commander = require("commander");
var libPath = path.join(path.dirname(fs.realpathSync(__filename)), "../lib/main.js");
var lib = require(libPath);
function collect(o, a) { a.push(o); return a; }
var packageJson = require("../package.json");
commander.description("CloudFormation Pre-Processor").version(packageJson.version)
.option("-r --region [region-name]", "AWS region. [eu-west-1]", "eu-west-1")
.option("-d --working-directory [working-directory]", "Working directory. [current working directory]")
.option("-f --config-file-pattern [config-file-pattern]", "Config file pattern. [*.cfnpp]", collect, [ ])
.option("-c --compact", "Compact template. [true]")
.option("-e --processed-template-extension [extension]", "Processed template extension. If blank, overwrites template. []", "")
.parse(process.argv);
console.log(commander.description() + " " + commander.version());
lib(commander.region,
commander.configFilePattern,
commander.workingDirectory,
commander.compact,
commander.processedTemplateExtension,
function(err) {
console.log("Done!");
});
| #!/usr/bin/env node
"use strict";
var path = require("path");
var fs = require("fs");
var commander = require("commander");
var libPath = path.join(path.dirname(fs.realpathSync(__filename)), "../lib/main.js");
var lib = require(libPath);
function collect(o, a) { a.push(o); return a; }
var packageJson = require("../package.json");
commander.description("CloudFormation Pre-Processor").version(packageJson.version)
.option("-r --region [region-name]", "AWS region. [eu-west-1]", "eu-west-1")
.option("-d --working-directory [working-directory]", "Working directory. [current working directory]")
.option("-f --config-file-pattern [config-file-pattern]", "Config file pattern. [*.cfnpp]", collect, [ ])
.option("-c --compact", "Compact template. [true]")
.option("-e --processed-template-extension [extension]", "Processed template extension. If blank, overwrites template. []", "")
.parse(process.argv);
console.log(commander.description() + " " + commander.version());
lib(commander.region, commander.configFilePattern, commander.workingDirectory, commander.compact, commander.processedTemplateExtension);
|
Fix unit test for redirecting unauthed user to index | import unittest
import flask_ssl_skeleton
class SkeletonTestCase(unittest.TestCase):
def setUp(self):
self.app = flask_ssl_skeleton.app
self.app.secret_key = "Unit secret"
self.client = self.app.test_client()
def test_root_returns_form_when_not_logged_on(self):
rv = self.client.get('/')
self.assertTrue('<form method="POST">' in rv.data)
def test_admin_redirects_to_login_when_not_logged_in(self):
rv = self.client.get('/admin')
self.assertEqual(302, rv.status_code)
self.assertTrue(rv.headers['Location'].endswith('/'))
def test_root_redirects_when_logged_in(self):
rv = self.client.post('/', data=dict(username='admin', password='password'))
self.assertEquals(302, rv.status_code)
self.assertTrue(rv.headers['Location'].endswith('/admin'))
| import unittest
import flask_ssl_skeleton
class SkeletonTestCase(unittest.TestCase):
def setUp(self):
self.app = flask_ssl_skeleton.app
self.app.secret_key = "Unit secret"
self.client = self.app.test_client()
def test_root_returns_form_when_not_logged_on(self):
rv = self.client.get('/')
self.assertTrue('<form method="POST">' in rv.data)
def test_admin_redirects_to_login_when_not_logged_in(self):
rv = self.client.get('/admin')
self.assertEqual(302, rv.status_code)
self.assertTrue(rv.headers['Location'].endswith('/'))
def test_root_redirects_when_logged_in(self):
rv = self.client.post('/', data=dict(username='admin', password='password'))
self.assertEquals(302, rv.status_code)
self.assertTrue(rv.headers['Location'].endswith('/admin'))
|
Make request argument in createQueryFromRequest optional | 'use strict'
class API {
static createQueryFromRequest (req) {
let request = Object.assign({}, req)
delete request.rats
delete request.CMDRs
let limit = parseInt(request.limit) || 25
delete request.limit
let offset = (parseInt(request.page) - 1) * limit || parseInt(request.offset) || 0
delete request.offset
delete request.page
let order = request.order || 'createdAt'
delete request.order
let direction = request.direction || 'ASC'
delete request.direction
if (request.firstLimpet) {
request.firstLimpetId = request.firstLimpet
delete request.firstLimpet
}
if (request.data) {
let dataQuery = request.data
delete request.data
request.data = {
$contains: JSON.parse(dataQuery)
}
}
let query = {
where: request,
order: [
[order, direction]
],
limit: limit,
offset: offset,
}
return query
}
static version (version) {
return function (req, res, next) {
req.apiVersion = version
next()
}
}
}
module.exports = API
| 'use strict'
class API {
static createQueryFromRequest (request) {
delete request.rats
delete request.CMDRs
let limit = parseInt(request.limit) || 25
delete request.limit
let offset = (parseInt(request.page) - 1) * limit || parseInt(request.offset) || 0
delete request.offset
delete request.page
let order = request.order || 'createdAt'
delete request.order
let direction = request.direction || 'ASC'
delete request.direction
if (request.firstLimpet) {
request.firstLimpetId = request.firstLimpet
delete request.firstLimpet
}
if (request.data) {
let dataQuery = request.data
delete request.data
request.data = {
$contains: JSON.parse(dataQuery)
}
}
let query = {
where: request,
order: [
[order, direction]
],
limit: limit,
offset: offset,
}
return query
}
static version (version) {
return function (req, res, next) {
req.apiVersion = version
next()
}
}
}
module.exports = API
|
Create variable to store restaurant name | function getRestaurants (latitude, longitude) {
if (latitude && longitude) {
var center = {lat: latitude, lng: longitude}
var map = new google.maps.Map(document.getElementsByClassName('map')[0], {
center: center,
zoom: 15
})
var service = new google.maps.places.PlacesService(map)
service.nearbySearch({
location: center,
radius: 500,
type: ['restaurant']
}, callback)
}
}
function callback (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var collection = '<div><h3>Restaurants</h3></div>'
for (var i = 0; i < results.length; i++) {
let restaurantName = results[i].name
let url = 'https://www.google.com/maps/place/' + restaurantName.replace(/\s/g, '+')
collection += ('<p>' + '<a href=' + url + '>' + restaurantName + '</p>')
}
$('.restaurants-list').html(collection)
}
}
| function getRestaurants (latitude, longitude) {
if (latitude && longitude) {
var center = {lat: latitude, lng: longitude}
var map = new google.maps.Map(document.getElementsByClassName('map')[0], {
center: center,
zoom: 15
})
var service = new google.maps.places.PlacesService(map)
service.nearbySearch({
location: center,
radius: 500,
type: ['restaurant']
}, callback)
}
}
function callback (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var collection = '<div><h3>Restaurants</h3></div>'
for (var i = 0; i < results.length; i++) {
let restaurantName
let url = 'https://www.google.com/maps/place/' + restaurantName.replace(/\s/g, '+')
collection += ('<p>' + '<a href=' + url + '>' + restaurantName + '</p>')
}
$('.restaurants-list').html(collection)
}
}
|
Use static factory method instead of constructor | package com.akikanellis.kata01.offer;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
/**
* A representation of a collection of {@link com.akikanellis.kata01.offer.OfferStrategies}.
*/
public final class OfferStrategies {
private final Set<OfferStrategy> strategies;
private OfferStrategies(Collection<OfferStrategy> strategies) { this.strategies = new HashSet<>(strategies); }
public static OfferStrategies fromCollection(Collection<OfferStrategy> offerStrategies) {
return new OfferStrategies(offerStrategies);
}
public static OfferStrategies empty() { return fromCollection(Collections.emptyList()); }
public boolean isEmpty() { return strategies.isEmpty(); }
public Set<OfferStrategy> asSet() { return new HashSet<>(strategies); }
public Stream<OfferStrategy> stream() { return strategies.stream(); }
}
| package com.akikanellis.kata01.offer;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
/**
* A representation of a collection of {@link com.akikanellis.kata01.offer.OfferStrategies}.
*/
public final class OfferStrategies {
private final Set<OfferStrategy> strategies;
private OfferStrategies(Collection<OfferStrategy> strategies) { this.strategies = new HashSet<>(strategies); }
public static OfferStrategies fromCollection(Collection<OfferStrategy> offerStrategies) {
return new OfferStrategies(offerStrategies);
}
public static OfferStrategies empty() { return new OfferStrategies(Collections.emptyList()); }
public boolean isEmpty() { return strategies.isEmpty(); }
public Set<OfferStrategy> asSet() { return new HashSet<>(strategies); }
public Stream<OfferStrategy> stream() { return strategies.stream(); }
}
|
Extend ServletModule instead of HttpPluginModule
As described in I3b89150d1.
Change-Id: Ic91ce95719c6bccc73cc29a2139a2274f20d1939 | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.javamelody;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.inject.Scopes;
import com.google.inject.servlet.ServletModule;
public class HttpModule extends ServletModule {
@Override
protected void configureServlets() {
DynamicSet.bind(binder(), AllRequestFilter.class)
.to(GerritMonitoringFilter.class)
.in(Scopes.SINGLETON);
}
}
| // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.javamelody;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.gerrit.httpd.plugins.HttpPluginModule;
import com.google.inject.Scopes;
public class HttpModule extends HttpPluginModule {
@Override
protected void configureServlets() {
DynamicSet.bind(binder(), AllRequestFilter.class)
.to(GerritMonitoringFilter.class)
.in(Scopes.SINGLETON);
}
}
|
Initialize texture maps with null | const Signal = require('signals')
let MaterialID = 0
function Material (opts) {
this.type = 'Material'
this.id = 'Material_' + MaterialID++
this.changed = new Signal()
this._uniforms = {}
const ctx = opts.ctx
this.baseColor = [0.95, 0.95, 0.95, 1]
this.baseColorMap = null
this.emissiveColor = [0, 0, 0, 1]
this.emissiveColorMap = null
this.metallic = 0.01
this.matallicMap = null
this.roughness = 0.5
this.roughnessMap = null
this.displacement = 0
this.depthTest = true
this.depthWrite = true
this.depthFunc = opts.ctx.DepthFunc.LessEqual
this.blendEnabled = false
this.blendSrcRGBFactor = ctx.BlendFactor.ONE
this.blendSrcAlphaFactor = ctx.BlendFactor.ONE
this.blendDstRGBFactor = ctx.BlendFactor.ONE
this.blendDstAlphaFactor = ctx.BlendFactor.ONE
this.castShadows = false
this.receiveShadows = false
this.cullFaceEnabled = true
this.set(opts)
}
Material.prototype.init = function (entity) {
this.entity = entity
}
Material.prototype.set = function (opts) {
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new Material(opts)
}
| const Signal = require('signals')
let MaterialID = 0
function Material (opts) {
this.type = 'Material'
this.id = 'Material_' + MaterialID++
this.changed = new Signal()
this._uniforms = {}
const ctx = opts.ctx
this.baseColor = [0.95, 0.95, 0.95, 1]
this.emissiveColor = [0, 0, 0, 1]
this.metallic = 0.01
this.roughness = 0.5
this.displacement = 0
this.depthTest = true
this.depthWrite = true
this.depthFunc = opts.ctx.DepthFunc.LessEqual
this.blendEnabled = false
this.blendSrcRGBFactor = ctx.BlendFactor.ONE
this.blendSrcAlphaFactor = ctx.BlendFactor.ONE
this.blendDstRGBFactor = ctx.BlendFactor.ONE
this.blendDstAlphaFactor = ctx.BlendFactor.ONE
this.castShadows = false
this.receiveShadows = false
this.cullFaceEnabled = true
this.set(opts)
}
Material.prototype.init = function (entity) {
this.entity = entity
}
Material.prototype.set = function (opts) {
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new Material(opts)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.