text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update for github payload structure | var express = require('express'),
pubnub = require('pubnub');
pubnub = pubnub.init({
publish_key: process.env.PUBNUB_PUBLISH_KEY || 'demo',
subscribe_key: process.env.PUBNUB_SUBSCRIBE_KEY || 'demo',
secret_key: process.env.PUBNUB_SECRET_KEY || '',
ssl: false
});
var app = express.createServer();
app.configure(function() {
app.use(express.logger());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.post('/githubpub/:channel', function(req, res, next) {
try {
var payload = JSON.parse(req.body.payload),
message = {
repo: payload.repository.url,
ref: payload.ref,
before: payload.before,
after: payload.after
};
console.log('sending message on channel', req.params.channel, message);
pubnub.publish({
channel: req.params.channel,
message: message
}, function(response) {
res.send(200);
});
} catch (err) {
console.error('Request failed', payload || req.body, err.stack);
res.send(500);
}
});
var port = process.env.PORT || 5000;
console.log('Starting phoenix proxy server on port', port);
app.listen(port);
| var express = require('express'),
pubnub = require('pubnub');
pubnub = pubnub.init({
publish_key: process.env.PUBNUB_PUBLISH_KEY || 'demo',
subscribe_key: process.env.PUBNUB_SUBSCRIBE_KEY || 'demo',
secret_key: process.env.PUBNUB_SECRET_KEY || '',
ssl: false
});
var app = express.createServer();
app.configure(function() {
app.use(express.logger());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.post('/githubpub/:channel', function(req, res, next) {
try {
var message = {
repo: req.body.repository.url,
ref: req.body.ref,
before: req.body.before,
after: req.body.after
};
console.log('sending message on channel', req.params.channel, message);
pubnub.publish({
channel: req.params.channel,
message: message
}, function(response) {
res.send(200);
});
} catch (err) {
console.error('Request failed', req.body, err.stack);
res.send(500);
}
});
var port = process.env.PORT || 5000;
console.log('Starting phoenix proxy server on port', port);
app.listen(port);
|
Add public API entties from 'bigquery.table'. | # Copyright 2015 Google Inc. 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.
"""Google Cloud BigQuery API wrapper.
The main concepts with this API are:
- :class:`gcloud.bigquery.dataset.Dataset` represents an collection of tables.
- :class:`gcloud.bigquery.table.Table` represents a single "relation".
"""
from gcloud.bigquery.client import Client
from gcloud.bigquery.connection import SCOPE
from gcloud.bigquery.dataset import Dataset
from gcloud.bigquery.table import SchemaField
from gcloud.bigquery.table import Table
| # Copyright 2015 Google Inc. 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.
"""Google Cloud BigQuery API wrapper.
The main concepts with this API are:
- :class:`gcloud.bigquery.dataset.Dataset` represents an collection of tables.
- :class:`gcloud.bigquery.table.Table` represents a single "relation".
"""
from gcloud.bigquery.client import Client
from gcloud.bigquery.connection import SCOPE
from gcloud.bigquery.dataset import Dataset
|
Use minified "remarkable" version in production | /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var vendorFiles = {};
if (EmberApp.env() !== 'test') {
vendorFiles['jquery.js'] = null;
}
var app = new EmberApp(defaults, {
storeConfigInMeta: false,
fingerprint: {
enabled: false,
},
vendorFiles: vendorFiles,
gzip: {
keepUncompressed: true,
},
});
// 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('vendor/shims/openlayers.js');
app.import('vendor/shims/ol3-cesium.js');
app.import({
development: 'bower_components/remarkable/dist/remarkable.js',
production: 'bower_components/remarkable/dist/remarkable.min.js',
});
app.import('vendor/shims/remarkable.js');
return app.toTree();
};
| /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var vendorFiles = {};
if (EmberApp.env() !== 'test') {
vendorFiles['jquery.js'] = null;
}
var app = new EmberApp(defaults, {
storeConfigInMeta: false,
fingerprint: {
enabled: false,
},
vendorFiles: vendorFiles,
gzip: {
keepUncompressed: true,
},
});
// 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('vendor/shims/openlayers.js');
app.import('vendor/shims/ol3-cesium.js');
app.import('bower_components/remarkable/dist/remarkable.js');
app.import('vendor/shims/remarkable.js');
return app.toTree();
};
|
Fix up "artisan test" help message | <?php
/**
* A Command that runs all of the available tests and outputs
* the results to the console.
*/
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class RunTests extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'test';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run all automated tests';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
passthru('vendor/bin/phpunit');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [];
}
}
| <?php
/**
* A Command that runs all of the available tests and outputs
* the results to the console.
*/
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class RunTests extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'test';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run all available tests.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
passthru('vendor/bin/phpunit');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [];
}
}
|
multiview: Update to new keybinding API | package main
import (
"github.com/marcusolsson/tui-go"
)
func main() {
var currentView int
views := []tui.Widget{
tui.NewVBox(tui.NewLabel("Press right arrow to continue ...")),
tui.NewVBox(tui.NewLabel("Almost there, one more time!")),
tui.NewVBox(tui.NewLabel("Congratulations, you've finished the example!")),
}
root := tui.NewVBox(views[0])
ui := tui.New(root)
ui.SetKeybinding("Esc", func() { ui.Quit() })
ui.SetKeybinding("Left", func() {
currentView = clamp(currentView-1, 0, len(views)-1)
ui.SetWidget(views[currentView])
})
ui.SetKeybinding("Right", func() {
currentView = clamp(currentView+1, 0, len(views)-1)
ui.SetWidget(views[currentView])
})
if err := ui.Run(); err != nil {
panic(err)
}
}
func clamp(n, min, max int) int {
if n < min {
return min
}
if n > max {
return max
}
return n
}
| package main
import (
"github.com/marcusolsson/tui-go"
)
func main() {
var currentView int
views := []tui.Widget{
tui.NewVBox(tui.NewLabel("Press right arrow to continue ...")),
tui.NewVBox(tui.NewLabel("Almost there, one more time!")),
tui.NewVBox(tui.NewLabel("Congratulations, you've finished the example!")),
}
root := tui.NewVBox(views[0])
ui := tui.New(root)
ui.SetKeybinding(tui.KeyEsc, func() { ui.Quit() })
ui.SetKeybinding(tui.KeyArrowLeft, func() {
currentView = clamp(currentView-1, 0, len(views)-1)
ui.SetWidget(views[currentView])
})
ui.SetKeybinding(tui.KeyArrowRight, func() {
currentView = clamp(currentView+1, 0, len(views)-1)
ui.SetWidget(views[currentView])
})
if err := ui.Run(); err != nil {
panic(err)
}
}
func clamp(n, min, max int) int {
if n < min {
return min
}
if n > max {
return max
}
return n
}
|
Comment out 'static' and 'deform' methods; disagreements on long-term API. | """
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, self.request)
@reify
def app(self):
return self.request.application_url
def route(self, route_name, *elements, **kw):
return url.route_url(route_name, self.request, *elements, **kw)
# sugar for calling url('home')
__call__ = route
def current(self, *elements, **kw):
return url.current_route_url(self.request, *elements, **kw)
## Commented because I'm unsure of the long-term API.
## If you want to use this, or a more particular one for your
## static package(s), define it in a subclass.
##
# A future version might make 'path' optional, defaulting to
# a value passed to the constructor ("myapp:static/").
#
#def static(self, path, **kw):
# return url.static_url(path, self.request, **kw)
## If you're using the Deform package you may find this useful.
#
#@reify
#def deform(self):
# return url.static_url("deform:static/", self.request)
| """
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, self.request)
@reify
def app(self):
return self.request.application_url
def route(self, route_name, *elements, **kw):
return url.route_url(route_name, self.request, *elements, **kw)
# sugar for calling url('home')
__call__ = route
def current(self, *elements, **kw):
return url.current_route_url(self.request, *elements, **kw)
@reify
def static(self):
return url.static_url('baseline:static/', self.request)
@reify
def deform(self):
return url.static_url('deform:static/', self.request)
|
Add duration to notifications API | import AppDispatcher from '../dispatcher/AppDispatcher';
import AppConstants from '../constants/AppConstants';
export default {
add: function(type, content, duration) {
if(duration === undefined) duration = 3000;
var id = Date.now();
var notification = { _id: id, type: type, content: content };
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_ADD,
notification : notification
});
setTimeout(() => {
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_REMOVE,
_id : id
});
}, duration);
}
}
| import AppDispatcher from '../dispatcher/AppDispatcher';
import AppConstants from '../constants/AppConstants';
export default {
add: function(type, content) {
var id = Date.now();
var notification = { _id: id, type: type, content: content };
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_ADD,
notification : notification
});
setTimeout(() => {
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_REMOVE,
_id : id
});
}, 2000);
}
}
|
Remove a TODO that's been taken care of
This piece of code is needed on Firefox because the public key is
passed in as a string, not a JSON object. | navigator.id.beginProvisioning(function(email, cert_duration) {
$.get('/api/loggedin')
.success(function(r) {
navigator.id.genKeyPair(function(pubkey) {
if (typeof(pubkey) == "string") {
pubkey = JSON.parse(pubkey);
}
$.ajax({
url: '/api/cert_key',
data: JSON.stringify({
pubkey: pubkey,
duration: cert_duration
}),
type: 'POST',
headers: { "Content-Type": 'application/json' },
dataType: 'json',
success: function(r) {
navigator.id.registerCertificate(r.cert);
},
error: function() {
navigator.id.raiseProvisioningFailure("couldn't certify key");
}
});
});
})
.error(function() {
navigator.id.raiseProvisioningFailure('user is not authenticated');
});
});
| navigator.id.beginProvisioning(function(email, cert_duration) {
$.get('/api/loggedin')
.success(function(r) {
navigator.id.genKeyPair(function(pubkey) {
// TODO: find out whether or not this is needed
if (typeof(pubkey) == "string") {
pubkey = JSON.parse(pubkey);
}
$.ajax({
url: '/api/cert_key',
data: JSON.stringify({
pubkey: pubkey,
duration: cert_duration
}),
type: 'POST',
headers: { "Content-Type": 'application/json' },
dataType: 'json',
success: function(r) {
navigator.id.registerCertificate(r.cert);
},
error: function() {
navigator.id.raiseProvisioningFailure("couldn't certify key");
}
});
});
})
.error(function() {
navigator.id.raiseProvisioningFailure('user is not authenticated');
});
});
|
Add test suit and requirements. | #!/usr/bin/env python
from setuptools import setup
import versioneer
versioneer.versionfile_source = "circuit/_version.py"
versioneer.versionfile_build = "circuit/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = ""
commands = versioneer.get_cmdclass().copy()
with open('README.md') as f:
long_description = f.read().strip()
setup(name='python-circuit',
version=versioneer.get_version(),
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Edgeware',
author_email='info@edgeware.tv',
url='https://github.com/edgeware/python-circuit',
packages=['circuit'],
test_suite='circuit.test',
tests_require=[
'mockito==0.5.2',
'Twisted>=10.2'
],
cmdclass=commands)
| #!/usr/bin/env python
from distutils.core import setup
import os.path
import versioneer
versioneer.versionfile_source = "circuit/_version.py"
versioneer.versionfile_build = "circuit/_version.py"
versioneer.tag_prefix = ""
versioneer.parentdir_prefix = ""
commands = versioneer.get_cmdclass().copy()
## Get long_description from index.txt:
here = os.path.dirname(os.path.abspath(__file__))
f = open(os.path.join(here, 'README.md'))
long_description = f.read().strip()
f.close()
setup(name='python-circuit',
version=versioneer.get_version(),
description='Simple implementation of the Circuit Breaker pattern',
long_description=long_description,
author='Johan Rydberg',
author_email='johan.rydberg@gmail.com',
url='https://github.com/edgeware/python-circuit',
packages=['circuit'],
cmdclass=commands)
|
Modify event listeners to use new html | $().ready(() => {
loadContentSection().then(() =>{
$("#loader").addClass("hide");
$("#real-body").removeClass("hide");
$("#real-body").addClass("body");
});
});
$("body").on('click', '.keyword', function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$("body").on('click', ".close", function(event) {
event.stopPropagation();
$(".extended").removeClass("extended");
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$("body").on('click', ".active .item", function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.href = url;
});
$("body").on('click', '.level-name', function() {
const isThisExtended = $(this).parent().hasClass("extended");
$(".extended").removeClass("extended");
if (!isThisExtended) {
$(this).parent().addClass("extended");
}
});
| $().ready(() => {
loadContentSection().then(() =>{
$("#loader").addClass("hide");
$("#real-body").removeClass("hide");
$("#real-body").addClass("body");
});
});
$("body").on('click', '.keyword', function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$("body").on('click', ".close", function(event) {
event.stopPropagation();
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$("body").on('click', ".active .item", function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.href = url;
});
$(".level").on('click', function() {
const isThisExtended = $(this).hasClass("extended");
$(".extended").removeClass("extended");
if (!isThisExtended) {
$(this).addClass("extended");
}
});
|
Add get methods for updater variables. | package com.github.tnerevival.core;
import com.github.tnerevival.core.version.ReleaseType;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class UpdateChecker {
private String url;
private String build;
private String currentBuild;
public UpdateChecker(String url, String currentBuild) {
this.url = url;
this.currentBuild = currentBuild;
getLatestBuild();
}
public void getLatestBuild() {
build = currentBuild;
try {
URL url = new URL(this.url);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
this.build = in.readLine();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public ReleaseType getRelease() {
Integer latest = Integer.valueOf(build.replace(".", ""));
Integer current = Integer.valueOf(currentBuild.replace(".", ""));
if(latest < current) return ReleaseType.PRERELEASE;
if(latest.equals(current)) return ReleaseType.LATEST;
return ReleaseType.OUTDATED;
}
public String getBuild() {
return build;
}
public String getCurrentBuild() {
return currentBuild;
}
} | package com.github.tnerevival.core;
import com.github.tnerevival.core.version.ReleaseType;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class UpdateChecker {
private String url;
private String build;
private String currentBuild;
public UpdateChecker(String url, String currentBuild) {
this.url = url;
this.currentBuild = currentBuild;
getLatestBuild();
}
public void getLatestBuild() {
build = currentBuild;
try {
URL url = new URL(this.url);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
build = in.readLine();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public ReleaseType getRelease() {
Integer latest = Integer.valueOf(build.replace(".", ""));
Integer current = Integer.valueOf(currentBuild.replace(".", ""));
if(latest < current) return ReleaseType.PRERELEASE;
if(latest.equals(current)) return ReleaseType.LATEST;
return ReleaseType.OUTDATED;
}
} |
Add simple test to deprecated test class | <?php
class Papi_Lib_Core_Deprecated_Test extends WP_UnitTestCase {
public function setUp() {
parent::setUp();
$_GET = [];
add_action( 'deprecated_function_run', [$this, 'deprecated_function_run'] );
tests_add_filter( 'papi/settings/directories', function () {
return [1, PAPI_FIXTURE_DIR . '/page-types'];
} );
$this->post_id = $this->factory->post->create();
update_post_meta( $this->post_id, PAPI_PAGE_TYPE_KEY, 'simple-page-type' );
}
public function deprecated_function_run( $function ) {
add_filter( 'deprecated_function_trigger_error', '__return_false' );
}
public function tearDown() {
parent::tearDown();
remove_filter( 'deprecated_function_trigger_error', '__return_false' );
unset( $_GET, $this->post_id );
}
public function test_deprecated() {
$this->assertTrue( true );
}
}
| <?php
class Papi_Lib_Core_Deprecated_Test extends WP_UnitTestCase {
public function setUp() {
parent::setUp();
$_GET = [];
add_action( 'deprecated_function_run', [$this, 'deprecated_function_run'] );
tests_add_filter( 'papi/settings/directories', function () {
return [1, PAPI_FIXTURE_DIR . '/page-types'];
} );
$this->post_id = $this->factory->post->create();
update_post_meta( $this->post_id, PAPI_PAGE_TYPE_KEY, 'simple-page-type' );
}
public function deprecated_function_run( $function ) {
add_filter( 'deprecated_function_trigger_error', '__return_false' );
}
public function tearDown() {
parent::tearDown();
remove_filter( 'deprecated_function_trigger_error', '__return_false' );
unset( $_GET, $this->post_id );
}
}
|
Fix object has no db_log_failed_attempt | """
A utility class which wraps the RateLimitMixin 3rd party class to do bad request counting
which can be used for rate limiting
"""
from ratelimitbackend.backends import RateLimitMixin
from django.conf import settings
if settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
from edraak_ratelimit.backends import EdraakRateLimitMixin
RateLimitMixin = EdraakRateLimitMixin
class BadRequestRateLimiter(RateLimitMixin):
"""
Use the 3rd party RateLimitMixin to help do rate limiting on the Password Reset flows
"""
def is_rate_limit_exceeded(self, request):
"""
Returns if the client has been rated limited
"""
counts = self.get_counters(request)
is_exceeded = sum(counts.values()) >= self.requests
if is_exceeded and settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
self.db_log_failed_attempt(request)
return is_exceeded
def tick_bad_request_counter(self, request):
"""
Ticks any counters used to compute when rate limt has been reached
"""
self.cache_incr(self.get_cache_key(request))
| """
A utility class which wraps the RateLimitMixin 3rd party class to do bad request counting
which can be used for rate limiting
"""
from ratelimitbackend.backends import RateLimitMixin
from django.conf import settings
if settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
from edraak_ratelimit.backends import EdraakRateLimitMixin
RateLimitMixin = EdraakRateLimitMixin
class BadRequestRateLimiter(RateLimitMixin):
"""
Use the 3rd party RateLimitMixin to help do rate limiting on the Password Reset flows
"""
def is_rate_limit_exceeded(self, request):
"""
Returns if the client has been rated limited
"""
counts = self.get_counters(request)
is_exceeded = sum(counts.values()) >= self.requests
if is_exceeded:
self.db_log_failed_attempt(request)
return is_exceeded
def tick_bad_request_counter(self, request):
"""
Ticks any counters used to compute when rate limt has been reached
"""
self.cache_incr(self.get_cache_key(request))
|
Make unit test slightly less weird. | /**
* Smoke-test the default
*/
var assert = require('chai').assert;
var breakWords = require('../../build/intermediate').wordBreakers['uax29'];
const SHY = '\u00AD';
describe('The default word breaker', function () {
it('should break multilingual text', function () {
let breaks = breakWords(
`Добрый день! ᑕᐻ᙮ — after working on ka${SHY}wen${SHY}non:${SHY}nis,
let's eat phở! 🥣`
);
let words = breaks.map(span => span.text);
assert.deepEqual(words, [
'Добрый', 'день', '!', 'ᑕᐻ', '᙮', '—', 'after',
'working', 'on', `ka${SHY}wen${SHY}non:${SHY}nis`, ',',
"let's", 'eat', 'phở', '!', '🥣'
]);
});
});
| /**
* Smoke-test the default
*/
var assert = require('chai').assert;
var breakWords = require('../../build/intermediate').wordBreakers['uax29'];
const SHY = '\u00AD';
describe('The default word breaker', function () {
it('should break multilingual text', function () {
let breaks = breakWords(
`ᑖᓂᓯ᙮ рабочий — after working on ka${SHY}wen${SHY}non:${SHY}nis
let's eat phở! 🥣`
);
let words = breaks.map(span => span.text);
assert.deepEqual(words, [
'ᑖᓂᓯ', '᙮', 'рабочий', '—', 'after', 'working', 'on',
`ka${SHY}wen${SHY}non:${SHY}nis`,
"let's", 'eat', 'phở', '!', '🥣'
]);
});
}); |
Improve ObjectWithoutField.__str__ to idenfify singleton values
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de> | from rlib.jit import promote
from som.vmobjects.abstract_object import AbstractObject
class ObjectWithoutFields(AbstractObject):
_immutable_fields_ = ["_object_layout?"]
def __init__(self, layout): # pylint: disable=W
self._object_layout = layout
def get_class(self, universe):
assert self._object_layout is not None
return self._object_layout.for_class
def get_object_layout(self, _universe):
return promote(self._object_layout)
def set_class(self, clazz):
layout = clazz.get_layout_for_instances()
assert layout is not None
self._object_layout = layout
def get_number_of_fields(self): # pylint: disable=no-self-use
return 0
def __str__(self):
from som.vm.globals import nilObject, trueObject, falseObject
if self is nilObject:
return "nil"
if self is trueObject:
return "true"
if self is falseObject:
return "false"
return AbstractObject.__str__(self)
| from rlib.jit import promote
from som.vmobjects.abstract_object import AbstractObject
class ObjectWithoutFields(AbstractObject):
_immutable_fields_ = ["_object_layout?"]
def __init__(self, layout): # pylint: disable=W
self._object_layout = layout
def get_class(self, universe):
assert self._object_layout is not None
return self._object_layout.for_class
def get_object_layout(self, _universe):
return promote(self._object_layout)
def set_class(self, clazz):
layout = clazz.get_layout_for_instances()
assert layout is not None
self._object_layout = layout
def get_number_of_fields(self): # pylint: disable=no-self-use
return 0
|
Add default rank to User for simplified tests | import re
class User:
Groups = {' ':0,'+':1,'☆':1,'%':2,'@':3,'*':3.1,'&':4,'#':5,'~':6}
@staticmethod
def compareRanks(rank1, rank2):
try:
return User.Groups[rank1] >= User.Groups[rank2]
except:
if not rank1 in User.Groups:
print('{rank} is not a supported usergroup'.format(rank = rank1))
if not rank2 in User.Groups:
print('{rank} is not a supported usergroup'.format(rank = rank2))
return False
def __init__(self, name, rank = ' ', owner = False):
self.name = name
self.id = re.sub(r'[^a-zA-z0-9]', '', name).lower()
self.rank = rank
self.owner = owner
def hasRank(self, rank):
return self.owner or User.compareRanks(self.rank, rank)
def isOwner(self):
return self.owner | import re
class User:
Groups = {' ':0,'+':1,'☆':1,'%':2,'@':3,'*':3.1,'&':4,'#':5,'~':6}
@staticmethod
def compareRanks(rank1, rank2):
try:
return User.Groups[rank1] >= User.Groups[rank2]
except:
if not rank1 in User.Groups:
print('{rank} is not a supported usergroup'.format(rank = rank1))
if not rank2 in User.Groups:
print('{rank} is not a supported usergroup'.format(rank = rank2))
return False
def __init__(self, name, rank, owner = False):
self.name = name
self.id = re.sub(r'[^a-zA-z0-9]', '', name).lower()
self.rank = rank
self.owner = owner
def hasRank(self, rank):
return self.owner or User.compareRanks(self.rank, rank)
def isOwner(self):
return self.owner |
Extend block context in order to support additional compilation engines (e.g. Assemble). | /*!
* helper-markdown <https://github.com/jonschlinkert/helper-markdown>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/
'use strict';
var isObject = require('isobject');
var Remarkable = require('remarkable');
var merge = require('mixin-deep');
module.exports = function markdown(config) {
if (typeof config === 'string') {
return helper.apply(this, arguments);
}
config = config || {};
if (config.fn || config.hash || arguments.length > 1) {
return helper.apply(this, arguments);
}
function helper(context, options) {
if (typeof context === 'string') {
var opts = merge({}, config, options);
var md = new Remarkable(opts);
return md.render(context);
}
if (isObject(context) && typeof context.fn === 'function') {
options = context;
context = {};
}
options = merge({ html: true, breaks: true }, config, options);
options = merge({}, options, options.markdown, options.hash);
if (options.hasOwnProperty('lang')) {
options.langPrefix = options.lang;
}
var md = new Remarkable(options);
var ctx = merge({}, options, this, this.context, context);
return md.render(options.fn(ctx));
}
return helper;
};
| /*!
* helper-markdown <https://github.com/jonschlinkert/helper-markdown>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/
'use strict';
var isObject = require('isobject');
var Remarkable = require('remarkable');
var merge = require('mixin-deep');
module.exports = function markdown(config) {
if (typeof config === 'string') {
return helper.apply(this, arguments);
}
config = config || {};
if (config.fn || config.hash || arguments.length > 1) {
return helper.apply(this, arguments);
}
function helper(context, options) {
if (typeof context === 'string') {
var opts = merge({}, config, options);
var md = new Remarkable(opts);
return md.render(context);
}
if (isObject(context) && typeof context.fn === 'function') {
options = context;
context = {};
}
options = merge({ html: true, breaks: true }, config, options);
options = merge({}, options, options.markdown, options.hash);
if (options.hasOwnProperty('lang')) {
options.langPrefix = options.lang;
}
var md = new Remarkable(options);
var ctx = merge({}, options, this, context);
return md.render(options.fn(ctx));
}
return helper;
};
|
Fix angular jqflot integration error | /**
* Created with IntelliJ IDEA.
* User: issa
* Date: 2/10/14
* Time: 1:18 AM
*/
app.directive('aFloat', function() {
function link(scope, element, attrs){
scope.$watch('afData', function(){
init(scope.afData,scope.afOption);
});
scope.$watch('afOption', function(){
init(scope.afData,scope.afOption);
});
function init(o,d){
var totalWidth = element.width(), totalHeight = element.height();
if (totalHeight === 0 || totalWidth === 0) {
throw new Error('Please set height and width for the aFloat element'+'width is '+element);
}
if(element.is(":visible") && !isUndefined(d) && !isUndefined(o)){
$.plot(element, o , d);
}
}
}
return {
restrict: 'EA',
template: '<div></div>',
link: link,
replace:true,
scope: {
afOption: '=',
afData: '='
}
};
}); | /**
* Created with IntelliJ IDEA.
* User: issa
* Date: 2/10/14
* Time: 1:18 AM
*/
app.directive('aFloat', function() {
function link(scope, element, attrs){
scope.$watch('afData', function(){
init(scope.afData,scope.afOption);
});
scope.$watch('afOption', function(){
init(scope.afData,scope.afOption);
});
function init(o,d){
var totalWidth = element.width(), totalHeight = element.height();
if (totalHeight === 0 || totalWidth === 0) {
throw new Error('Please set height and width for the aFloat element'+'width is '+ele);
}
if(element.is(":visible") && !isUndefined(d)){
$.plot(element, o , d);
}
}
}
return {
restrict: 'EA',
template: '<div></div>',
link: link,
replace:true,
scope: {
afOption: '=',
afData: '='
}
};
}); |
Update base line-height to 150% | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import Search from './search'
import Results from './results'
const Container = styled.div`
line-height: 150%;
margin: 10px 20px 0 20px;
padding: 20px;
@media (max-width: 330px) {
margin: 10px 10px 0 10px;
padding: 10px;
}
`
const App = props => {
return (
<Container>
<Search
langs={props.allLangs}
onLangSelectionChange={props.onLangSelectionChange}
onSearch={props.onSearch} />
<Results langLinks={props.langLinks} loading={props.loading} />
</Container>
)
}
App.propTypes = {
allLangs: PropTypes.array.isRequired,
langLinks: PropTypes.array.isRequired,
loading: PropTypes.bool.isRequired,
onLangSelectionChange: PropTypes.func.isRequired,
onSearch: PropTypes.func.isRequired
}
export default App
| import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import Search from './search'
import Results from './results'
const Container = styled.div`
line-height: 120%;
margin: 10px 20px 0 20px;
padding: 20px;
@media (max-width: 330px) {
margin: 10px 10px 0 10px;
padding: 10px;
}
`
const App = props => {
return (
<Container>
<Search
langs={props.allLangs}
onLangSelectionChange={props.onLangSelectionChange}
onSearch={props.onSearch} />
<Results langLinks={props.langLinks} loading={props.loading} />
</Container>
)
}
App.propTypes = {
allLangs: PropTypes.array.isRequired,
langLinks: PropTypes.array.isRequired,
loading: PropTypes.bool.isRequired,
onLangSelectionChange: PropTypes.func.isRequired,
onSearch: PropTypes.func.isRequired
}
export default App
|
Allow underscores and hyphens in Youtube video ID
Fixes #122 | /**
* Helper functions
*/
'use strict';
module.exports = {
parseVideoUrl(url) {
function getIdFromUrl(url, re) {
let matches = url.match(re);
return (matches && matches[1]) || null;
}
let id;
// https://www.youtube.com/watch?v=24X9FpeSASY
// http://stackoverflow.com/questions/5830387/how-to-find-all-youtube-video-ids-in-a-string-using-a-regex/5831191#5831191
if (url.indexOf('youtube.com/') > -1) {
id = getIdFromUrl(url, /\/watch\?v=([A-Z0-9_-]+)/i);
return id ? ['youtube', id] : null;
}
// https://vimeo.com/27986705
if (url.indexOf('vimeo.com/') > -1) {
id = getIdFromUrl(url, /\/([0-9]+)/);
return id ? ['vimeo', id] : null;
}
return null;
}
};
| /**
* Helper functions
*/
'use strict';
module.exports = {
parseVideoUrl(url) {
function getIdFromUrl(url, re) {
let matches = url.match(re);
return (matches && matches[1]) || null;
}
let id;
// https://www.youtube.com/watch?v=24X9FpeSASY
if (url.indexOf('youtube.com/') > -1) {
id = getIdFromUrl(url, /\/watch\?v=([A-Z0-9]+)/i);
return id ? ['youtube', id] : null;
}
// https://vimeo.com/27986705
if (url.indexOf('vimeo.com/') > -1) {
id = getIdFromUrl(url, /\/([0-9]+)/);
return id ? ['vimeo', id] : null;
}
return null;
}
};
|
Rename force flag to force-revalidation | from optparse import make_option
from django.core.management.base import BaseCommand
from django.db.models.loading import cache
from ...utils import validate_app_cache
class Command(BaseCommand):
help = ('Validates the image cache for a list of apps.')
args = '[apps]'
requires_model_validation = True
can_import_settings = True
option_list = BaseCommand.option_list + (
make_option('--force-revalidation',
dest='force_revalidation',
action='store_true',
default=False,
help='Invalidate each image file before validating it, thereby'
' ensuring its revalidation. This is very similar to'
' running ikcacheinvalidate and then running'
' ikcachevalidate; the difference being that this option'
' causes files to be invalidated and validated'
' one-at-a-time, whereas running the two commands in series'
' would invalidate all images before validating any.'
),
)
def handle(self, *args, **options):
apps = args or cache.app_models.keys()
validate_app_cache(apps, options['force_revalidation'])
| from optparse import make_option
from django.core.management.base import BaseCommand
from django.db.models.loading import cache
from ...utils import validate_app_cache
class Command(BaseCommand):
help = ('Validates the image cache for a list of apps.')
args = '[apps]'
requires_model_validation = True
can_import_settings = True
option_list = BaseCommand.option_list + (
make_option('--force',
dest='force_revalidation',
action='store_true',
default=False,
help='Invalidate each image file before validating it, thereby'
' ensuring its revalidation. This is very similar to'
' running ikcacheinvalidate and then running'
' ikcachevalidate; the difference being that this option'
' causes files to be invalidated and validated'
' one-at-a-time, whereas running the two commands in series'
' would invalidate all images before validating any.'
),
)
def handle(self, *args, **options):
apps = args or cache.app_models.keys()
validate_app_cache(apps, options['force_revalidation'])
|
[VarDumper] Fix dumping of non-nested stubs | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Casts a caster's Stub.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class StubCaster
{
public static function castStub(Stub $c, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->type = $c->type;
$stub->class = $c->class;
$stub->value = $c->value;
$stub->handle = $c->handle;
$stub->cut = $c->cut;
$a = array();
}
return $a;
}
public static function cutInternals($obj, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->cut += count($a);
return array();
}
return $a;
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Casts a caster's Stub.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class StubCaster
{
public static function castStub(Stub $c, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->type = $c->type;
$stub->class = $c->class;
$stub->value = $c->value;
$stub->handle = $c->handle;
$stub->cut = $c->cut;
return array();
}
}
public static function cutInternals($obj, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->cut += count($a);
return array();
}
return $a;
}
}
|
Add neon version and print the package version in the usage info | #!/usr/bin/env node
var path = require('path')
var minimist = require('minimist');
var pkg = require(path.resolve(__dirname, '../package.json'));
if (process.argv.length < 3) {
printUsage();
process.exit(1);
}
var command = process.argv[2];
var args = minimist(process.argv.slice(3));
var pwd = process.cwd();
switch (command) {
case 'version':
console.log(pkg.version)
break;
case 'help':
printUsage();
break;
case 'new':
if (args._.length !== 1) {
printUsage();
process.exit(1);
}
var create = require('../lib/create.js').default;
create(pwd, args._[0], args.rust || args.r || 'default');
break;
}
function printUsage() {
console.log();
console.log("Usage:");
console.log();
console.log(" neon new <name> [--rust|-r nightly|stable|default]");
console.log(" create a new Neon project");
console.log();
console.log(" neon help");
console.log(" print this usage information");
console.log();
console.log(" neon version");
console.log(" print neon-cli version");
console.log();
console.log("neon-cli@" + pkg.version + " " + path.dirname(__dirname));
}
| #!/usr/bin/env node
var minimist = require('minimist');
if (process.argv.length < 3) {
printUsage();
process.exit(1);
}
var command = process.argv[2];
var args = minimist(process.argv.slice(3));
var pwd = process.cwd();
switch (command) {
case 'help':
printUsage();
break;
case 'new':
if (args._.length !== 1) {
printUsage();
process.exit(1);
}
var create = require('../lib/create.js').default;
create(pwd, args._[0], args.rust || args.r || 'default');
break;
}
function printUsage() {
console.log("Usage:");
console.log();
console.log(" neon new <name> [--rust|-r nightly|stable|default]");
console.log(" create a new Neon project");
console.log();
console.log(" neon help");
console.log(" print this usage information");
console.log();
}
|
lathe[cuboid]: Convert BoxGeometry debug texture helper to ES2015. | /* eslint-env es6 */
/* global THREE */
window.createBoxTextures = (function() {
'use strict';
return function textures(
keys = [ 'px', 'nx', 'py', 'ny', 'pz', 'nz' ],
size = 512
) {
return keys.map( key => {
const canvas = document.createElement( 'canvas' );
const ctx = canvas.getContext( '2d' );
canvas.width = size;
canvas.height = size;
ctx.fillStyle = '#000'
ctx.fillRect( 0, 0, size, size );
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#fff';
ctx.font = ( canvas.width / 4 ) + 'px Menlo, Monaco, monospace';
ctx.fillText( key, canvas.width / 2, canvas.height / 2 );
const texture = new THREE.Texture( canvas );
texture.needsUpdate = true;
return texture;
});
};
}());
| /* global THREE */
/* exported createBoxTextures */
function createBoxTextures( keys, size ) {
keys = keys || [ 'px', 'nx', 'py', 'ny', 'pz', 'nz' ];
size = size || 512;
return keys.map(function( key ) {
var canvas = document.createElement( 'canvas' );
var ctx = canvas.getContext( '2d' );
canvas.width = size;
canvas.height = size;
ctx.fillStyle = '#000'
ctx.fillRect( 0, 0, size, size );
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#fff';
ctx.font = ( canvas.width / 4 ) + 'px Menlo, Monaco, monospace';
ctx.fillText( key, canvas.width / 2, canvas.height / 2 );
var texture = new THREE.Texture( canvas );
texture.needsUpdate = true;
return texture;
});
}
|
chore(fix-codeclimate-error): Fix violated ESLINT rule on codeclimate | import axios from 'axios';
const API_URL = '/api/v1/users';
/**
* setAuthorizationToken - set token to request headers
* @param {string} token Authorization token
* @return {void} no return or void
*/
export function setAuthorizationToken(token) {
if (token) {
axios.defaults.headers.common.Authorization = `Bearer ${token}`;
} else {
delete axios.defaults.headers.common.Authorization;
}
}
export function getUserData(email) {
return axios.post(`${API_URL}/getemail`, email)
.then(response => response.data.user)
.catch(error => error);
}
export function registerGoogleUser(userDetails) {
return axios.post(`${API_URL}/signup`, userDetails)
.then((res) => {
const token = res.data.Token;
localStorage.setItem('token', token);
setAuthorizationToken(token);
window.location.href = '/dashboard';
});
}
export function editProfile(userId, userData) {
return axios.put(`${API_URL}/edit/${userId}`, userData)
.then(() => axios.get(`${API_URL}/userId`)
.then(res => res.data.token))
.catch(error => error.data.response);
}
| import axios from 'axios';
const API_URL = '/api/v1/users';
/**
* setAuthorizationToken - set token to request headers
* @param {string} token Authorization token
* @return {void} no return or void
*/
export function setAuthorizationToken(token) {
if (token) {
axios.defaults.headers.common.Authorization = `Bearer ${token}`;
} else {
delete axios.defaults.headers.common.Authorization;
}
}
export function getUserData(email) {
return axios.post(`${API_URL}/getemail`, email)
.then(response => response.data.user)
.catch(error => error);
}
export function registerGoogleUser(userDetails) {
return axios.post(`${API_URL}/signup`, userDetails)
.then((res) => {
const token = res.data.Token;
localStorage.setItem('token', token);
setAuthorizationToken(token);
window.location.href = '/dashboard';
});
}
export function editProfile(userId, userData) {
return axios.put(`${API_URL}/edit/${userId}`, userData)
.then(() => axios.get(`${API_URL}/userId`)
.then(res => res.data.token))
.catch(error => error.data.response);
}
|
Add a tiny bit of output | # The import tests in here should be only those that
# 1. Require an X11 display on linux
test_imports = [
'pyglet.font',
'pyglet.gl',
'pyglet.graphics',
'pyglet.image',
'pyglet.image.codecs',
'pyglet.input',
'pyglet.media',
'pyglet.media.drivers',
'pyglet.media.drivers.directsound',
'pyglet.window',
'pyglet.text',
'pyglet.text.formats',
]
def expected_fail(module):
try:
print('Importing {}'.format(module))
__import__(module)
except Exception as e:
# Yes, make the exception general, because we can't import the specific
# exception on linux without an actual display. Look at the source
# code if you want to see why.
assert 'No standard config is available.' in str(e)
# Handle an import that should only happen on linux and requires
# a display.
for module in test_imports:
expected_fail(module)
import sys
if sys.platform.startswith('linux'):
expected_fail('pyglet.window.xlib')
# And another import that is expected to fail in...
if sys.platform == 'darwin':
expected_fail('pyglet.window.cocoa')
| # The import tests in here should be only those that
# 1. Require an X11 display on linux
test_imports = [
'pyglet.font',
'pyglet.gl',
'pyglet.graphics',
'pyglet.image',
'pyglet.image.codecs',
'pyglet.input',
'pyglet.media',
'pyglet.media.drivers',
'pyglet.media.drivers.directsound',
'pyglet.window',
'pyglet.text',
'pyglet.text.formats',
]
def expected_fail(module):
try:
__import__(module)
except Exception as e:
# Yes, make the exception general, because we can't import the specific
# exception on linux without an actual display. Look at the source
# code if you want to see why.
assert 'No standard config is available.' in str(e)
# Handle an import that should only happen on linux and requires
# a display.
for module in test_imports:
expected_fail(module)
import sys
if sys.platform.startswith('linux'):
expected_fail('pyglet.window.xlib')
# And another import that is expected to fail in...
if sys.platform == 'darwin':
expected_fail('pyglet.window.cocoa')
|
Fix map update and insert | package orm
import (
"github.com/go-pg/pg/v10/types"
)
type mapModel struct {
hookStubs
ptr *map[string]interface{}
m map[string]interface{}
}
var _ Model = (*mapModel)(nil)
func newMapModel(ptr *map[string]interface{}) *mapModel {
model := &mapModel{
ptr: ptr,
}
if ptr != nil {
model.m = *ptr
}
return model
}
func (mapModel) Init() error {
return nil
}
func (m *mapModel) NextColumnScanner() ColumnScanner {
return m
}
func (m mapModel) AddColumnScanner(ColumnScanner) error {
return nil
}
func (m *mapModel) ScanColumn(col types.ColumnInfo, rd types.Reader, n int) error {
val, err := types.ReadColumnValue(col, rd, n)
if err != nil {
return err
}
if m.m == nil {
m.m = make(map[string]interface{})
*m.ptr = m.m
}
m.m[col.Name] = val
return nil
}
func (mapModel) useQueryOne() bool {
return true
}
| package orm
import (
"github.com/go-pg/pg/v10/types"
)
type mapModel struct {
hookStubs
ptr *map[string]interface{}
m map[string]interface{}
}
var _ Model = (*mapModel)(nil)
func newMapModel(ptr *map[string]interface{}) *mapModel {
return &mapModel{
ptr: ptr,
}
}
func (mapModel) Init() error {
return nil
}
func (m mapModel) NextColumnScanner() ColumnScanner {
return m
}
func (m mapModel) AddColumnScanner(ColumnScanner) error {
return nil
}
func (m mapModel) ScanColumn(col types.ColumnInfo, rd types.Reader, n int) error {
val, err := types.ReadColumnValue(col, rd, n)
if err != nil {
return err
}
if m.m == nil {
m.m = make(map[string]interface{})
*m.ptr = m.m
}
m.m[col.Name] = val
return nil
}
func (mapModel) useQueryOne() bool {
return true
}
|
Implement read.json parsing and proper error messages | package sel
import (
"os"
"flag"
"fmt"
"log"
"encoding/json"
"link-select/types"
)
func SelectLink(arg *flag.Flag) {
fmt.Fprintf(os.Stdout, "Selecting %s from json file\n", arg.Value)
readFile, err := os.Open("files/read.json")
if err != nil {
fmt.Fprintf(os.Stderr, "Error while opening read JSON file\n")
os.Exit(-1)
}
var readList types.ReadList
jsonParser := json.NewDecoder(readFile)
if err = jsonParser.Decode(&readList); err != nil {
fmt.Fprintf(os.Stderr, "Error while parsing read JSON file\n")
log.Fatal(err)
os.Exit(-1)
}
//for i, v := range articles {
//fmt.Fprintf("title: %s, link: %s\n", article.Title, article.Link)
} | package sel
import (
"encoding/json"
"os"
"flag"
"fmt"
"link-select/types"
)
func SelectLink(arg *flag.Flag) {
fmt.Fprintf(os.Stdout, "Selecting %s from json file\n", arg.Value)
readFile, err := os.Open("files/read.json")
if err != nil {
fmt.Fprintf(os.Stderr, "Error while opening read.json")
os.Exit(-1)
}
var article types.Article
jsonParser := json.NewDecoder(readFile)
if err = jsonParser.Decode(&article); err != nil {
fmt.Fprintf(os.Stderr, "Error while parsing read.json")
os.Exit(-1)
}
//for i, v := range articles {
//fmt.Fprintf("title: %s, link: %s\n", article.Title, article.Link)
} |
Improve the trait - it doesn't have to inherit assertThat | <?php
declare(strict_types=1);
namespace Asynchronicity\PHPUnit;
use PHPUnit\Framework\Assert;
trait Asynchronicity
{
/**
* Provide a callable. It will be invoked until it doesn't throw an exception anymore, or the given timeout in milliseconds has passed.
* Before trying again, the process will wait (sleep) for the duration of the optionally provided amount of milliseconds.
*
* @param callable $probe
* @param int $timeoutMilliseconds
* @param int $waitMilliseconds
*/
public static function assertEventually(callable $probe, int $timeoutMilliseconds = 5000, int $waitMilliseconds = 500): void
{
Assert::assertThat(
$probe,
new Eventually($timeoutMilliseconds, $waitMilliseconds)
);
}
}
| <?php
declare(strict_types=1);
namespace Asynchronicity\PHPUnit;
use PHPUnit\Framework\Constraint\Constraint;
/**
* @method static assertThat($value, Constraint $constraint)
*/
trait Asynchronicity
{
/**
* Provide a callable. It will be invoked until it doesn't throw an exception anymore, or the given timeout in milliseconds has passed.
* Before trying again, the process will wait (sleep) for the duration of the optionally provided amount of milliseconds.
*
* @param callable $probe
* @param int $timeoutMilliseconds
* @param int $waitMilliseconds
*/
public static function assertEventually(callable $probe, int $timeoutMilliseconds = 5000, int $waitMilliseconds = 500): void
{
self::assertThat(
$probe,
new Eventually($timeoutMilliseconds, $waitMilliseconds)
);
}
}
|
Remove unncessary and wrong way to check for empty or null in js | import React, { Component } from "react";
import LoaderImage from "../assets/img/small-loader.svg";
class Util extends Component {
static Row(label, item, lclass = "col-sm-3 text-sm-right", rclass = "col-sm-21", link="") {
if(item) {
if (link) {
item = `<a href='${link}:${item}'>${item}</a>`;
};
return (
<div className="form-group row">
<div className={lclass}>{label}:</div>
<div className={rclass}>{item}</div>
</div>
);
}
}
static numberList(item) {
let number = [];
if(item.length > 0) {
const list = item.split(',');
list.forEach(function(value) {
if(value.trim() !== '')
number.push(value.trim());
});
}
return number;
}
static loaderImage(width = 20, className="loader-image") {
return (
<img src={LoaderImage} width={width} className={className} alt="loader" />
);
}
}
export default Util; | import React, { Component } from "react";
import LoaderImage from "../assets/img/small-loader.svg";
class Util extends Component {
static Row(label, item, lclass = "col-sm-3 text-sm-right", rclass = "col-sm-21", link="") {
if(Util.isEmpty(item)) {
if (link) {
item = `<a href='${link}:${item}'>${item}</a>`;
};
return (
<div className="form-group row">
<div className={lclass}>{label}:</div>
<div className={rclass}>{item}</div>
</div>
);
}
}
static numberList(item) {
let number = [];
if(item.length > 0) {
const list = item.split(',');
list.forEach(function(value) {
if(value.trim() !== '')
number.push(value.trim());
});
}
return number;
}
static isEmpty(item) {
return (item !== 'null' && item !== undefined && item !== '');
}
static loaderImage(width = 20, className="loader-image") {
return (
<img src={LoaderImage} width={width} className={className} alt="loader" />
);
}
}
export default Util; |
Fix for Nelmio API Doc | <?php declare(strict_types = 1);
/*
* This file is part of the Bukashk0zzzTimestampTypeBundle
*
* (c) Denis Golubovskiy <bukashk0zzz@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Bukashk0zzz\TimestampTypeBundle\Form\Type;
use Bukashk0zzz\TimestampTypeBundle\Form\DataTransformer\TimestampToDateTimeTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class TimestampType
*/
class TimestampType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param mixed[] $options
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->addModelTransformer(new TimestampToDateTimeTransformer());
}
/**
* @return mixed
*/
public function getParent()
{
return IntegerType::class;
}
/**
* @return string
*/
public function getBlockPrefix(): string
{
return 'integer';
}
}
| <?php declare(strict_types = 1);
/*
* This file is part of the Bukashk0zzzTimestampTypeBundle
*
* (c) Denis Golubovskiy <bukashk0zzz@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Bukashk0zzz\TimestampTypeBundle\Form\Type;
use Bukashk0zzz\TimestampTypeBundle\Form\DataTransformer\TimestampToDateTimeTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class TimestampType
*/
class TimestampType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param mixed[] $options
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->addModelTransformer(new TimestampToDateTimeTransformer());
}
/**
* @return mixed
*/
public function getParent()
{
return IntegerType::class;
}
}
|
Fix docstring and remove unnecessary imports. | """
Braubuddy Auto thermometer unit tests.
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import auto
from braubuddy.thermometer import dummy
from braubuddy.thermometer import ds18b20_gpio
from braubuddy.thermometer import temper_usb
class TestAuto(unittest.TestCase):
@patch('braubuddy.thermometer.ds18b20_gpio.ds18b20')
@patch('braubuddy.thermometer.temper_usb.temperusb')
def test_dummy_returned_if_no_devices(self, mk_temperusb, mk_ds18b20):
"""Dummy thermometer is created if no real thermometers discovered."""
mk_ds18b20.DS18B20 = MagicMock(side_effect = Exception('Some Error'))
mk_temperusb.TemperHandler.return_value.get_devices.return_value = []
thermometer = auto.AutoThermometer()
self.assertIsInstance(thermometer, dummy.DummyThermometer)
| """
Braubuddy Dummy thermometer unit tests.
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import auto
from braubuddy.thermometer import dummy
from braubuddy.thermometer import ds18b20_gpio
from braubuddy.thermometer import temper_usb
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestAuto(unittest.TestCase):
@patch('braubuddy.thermometer.ds18b20_gpio.ds18b20')
@patch('braubuddy.thermometer.temper_usb.temperusb')
def test_dummy_returned_if_no_devices(self, mk_temperusb, mk_ds18b20):
"""Dummy thermometer is created if no real thermometers discovered."""
mk_ds18b20.DS18B20 = MagicMock(side_effect = Exception('Some Error'))
mk_temperusb.TemperHandler.return_value.get_devices.return_value = []
thermometer = auto.AutoThermometer()
self.assertIsInstance(thermometer, dummy.DummyThermometer)
|
Make master_key config param optional to support unencrypted workflow | package io.ifar.skidroad.dropwizard.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.DecimalMin;
/**
*
*/
public class RequestLogPrepConfiguration {
@JsonProperty("master_key")
//optional; only needed if using encryption
private String masterKey;
/**
* Fixed master IV no longer used during encryption. May optionally be supplied
* for decrypting legacy data.
*/
@JsonProperty("master_iv")
private String masterIV;
@JsonProperty("report_unhealthy_at_queue_depth")
@DecimalMin(value="1")
private int reportUnhealthyAtQueueDepth = 10;
@Range(min = 1)
@JsonProperty("retry_interval_seconds")
private int retryIntervalSeconds= 300;
@Range(min = 1)
@JsonProperty("max_concurrency")
private Integer maxConcurrency = 5; //depends on network bandwidth, not CPUs
public String getMasterIV() {
return masterIV;
}
public String getMasterKey() {
return masterKey;
}
public int getReportUnhealthyAtQueueDepth() {
return reportUnhealthyAtQueueDepth;
}
public int getRetryIntervalSeconds() {
return retryIntervalSeconds;
}
public Integer getMaxConcurrency() {
return maxConcurrency;
}
} | package io.ifar.skidroad.dropwizard.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.DecimalMin;
/**
*
*/
public class RequestLogPrepConfiguration {
@JsonProperty("master_key")
@NotEmpty
private String masterKey;
/**
* Fixed master IV no longer used during encryption. May optionally be supplied
* for decrypting legacy data.
*/
@JsonProperty("master_iv")
private String masterIV;
@JsonProperty("report_unhealthy_at_queue_depth")
@DecimalMin(value="1")
private int reportUnhealthyAtQueueDepth = 10;
@Range(min = 1)
@JsonProperty("retry_interval_seconds")
private int retryIntervalSeconds= 300;
@Range(min = 1)
@JsonProperty("max_concurrency")
private Integer maxConcurrency = 5; //depends on network bandwidth, not CPUs
public String getMasterIV() {
return masterIV;
}
public String getMasterKey() {
return masterKey;
}
public int getReportUnhealthyAtQueueDepth() {
return reportUnhealthyAtQueueDepth;
}
public int getRetryIntervalSeconds() {
return retryIntervalSeconds;
}
public Integer getMaxConcurrency() {
return maxConcurrency;
}
} |
Move @ComponentDependency to the field as that is the latest recomendation | package arez.doc.examples.at_component_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
@ComponentDependency
@Nonnull
final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@Nonnull
public final Person getPerson()
{
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@ComponentDependency( action = ComponentDependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
| package arez.doc.examples.at_component_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
@Nonnull
private final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@ComponentDependency
@Nonnull
public final Person getPerson()
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@ComponentDependency( action = ComponentDependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
|
Tweak the error limit a little | <?php
return array(
/*
|--------------------------------------------------------------------------
| SeAT Version
|--------------------------------------------------------------------------
|
*/
'version' => '0.9.2',
/*
|--------------------------------------------------------------------------
| Ban Limit
|--------------------------------------------------------------------------
|
| Specifies the amount of times a API call should fail before it should
| should be banned from being called again
|
*/
'ban_limit' => 20,
/*
|--------------------------------------------------------------------------
| Ban Grance Period
|--------------------------------------------------------------------------
|
| Specifies the amount of minutes a key should live in the cache when
| counting the bans for it.
|
| It is important to note that the actual schedule at which API calls are
| made should be taken into account when setting this Value. ie: For
| character API Updates, which occur hourly, it would take 10 hours
| to reach the limit and get banned. If we set the ban_grace key
| annything below 600, we will never reach a point where a ban
| will occur
|
*/
'ban_grace' => 60 * 24,
/*
|--------------------------------------------------------------------------
| Eve API Error Count Maximum
|--------------------------------------------------------------------------
|
| Specifies the maximum amount of errors that should occur before the SeAT
| API updator workers will stop processing update jobs. This allows us
| be aware of the fact that the EVE API may be down/sick and prevent
| the storm ahead with updates.
|
*/
'error_limit' => 60,
);
| <?php
return array(
/*
|--------------------------------------------------------------------------
| SeAT Version
|--------------------------------------------------------------------------
|
*/
'version' => '0.9.2',
/*
|--------------------------------------------------------------------------
| Ban Limit
|--------------------------------------------------------------------------
|
| Specifies the amount of times a API call should fail before it should
| should be banned from being called again
|
*/
'ban_limit' => 20,
/*
|--------------------------------------------------------------------------
| Ban Grance Period
|--------------------------------------------------------------------------
|
| Specifies the amount of minutes a key should live in the cache when
| counting the bans for it.
|
| It is important to note that the actual schedule at which API calls are
| made should be taken into account when setting this Value. ie: For
| character API Updates, which occur hourly, it would take 10 hours
| to reach the limit and get banned. If we set the ban_grace key
| annything below 600, we will never reach a point where a ban
| will occur
|
*/
'ban_grace' => 60 * 24,
/*
|--------------------------------------------------------------------------
| Eve API Error Count Maximum
|--------------------------------------------------------------------------
|
| Specifies the maximum amount of errors that should occur before the SeAT
| API updator workers will stop processing update jobs. This allows us
| be aware of the fact that the EVE API may be down/sick and prevent
| the storm ahead with updates.
|
*/
'error_limit' => 120,
);
|
Fix setns syscall number for ARM, this has been wrong all along.
See: http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=571503e10045c89af951962ea0bb783482663aad
Signed-off-by: Adam Conrad <6afcdb68eb9b55ab20be6196a160d519aa4934fb@0c3.net> | package system
import (
"fmt"
"runtime"
"syscall"
)
// Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092
//
// We need different setns values for the different platforms and arch
// We are declaring the macro here because the SETNS syscall does not exist in th stdlib
var setNsMap = map[string]uintptr{
"linux/386": 346,
"linux/arm64": 268,
"linux/amd64": 308,
"linux/arm": 375,
"linux/ppc64": 350,
"linux/ppc64le": 350,
"linux/s390x": 339,
}
func Setns(fd uintptr, flags uintptr) error {
ns, exists := setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
if !exists {
return fmt.Errorf("unsupported platform %s/%s", runtime.GOOS, runtime.GOARCH)
}
_, _, err := syscall.RawSyscall(ns, fd, flags, 0)
if err != 0 {
return err
}
return nil
}
| package system
import (
"fmt"
"runtime"
"syscall"
)
// Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092
//
// We need different setns values for the different platforms and arch
// We are declaring the macro here because the SETNS syscall does not exist in th stdlib
var setNsMap = map[string]uintptr{
"linux/386": 346,
"linux/arm64": 268,
"linux/amd64": 308,
"linux/arm": 374,
"linux/ppc64": 350,
"linux/ppc64le": 350,
"linux/s390x": 339,
}
func Setns(fd uintptr, flags uintptr) error {
ns, exists := setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
if !exists {
return fmt.Errorf("unsupported platform %s/%s", runtime.GOOS, runtime.GOARCH)
}
_, _, err := syscall.RawSyscall(ns, fd, flags, 0)
if err != 0 {
return err
}
return nil
}
|
Set cryopod layer to "Objective" | package com.ezardlabs.lostsector.missions.objectives;
import com.ezardlabs.dethsquare.Layers;
import com.ezardlabs.dethsquare.Level;
import com.ezardlabs.dethsquare.LevelManager;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;
import com.ezardlabs.lostsector.levels.DefenseLevel;
import com.ezardlabs.lostsector.objects.ShieldedEntity;
public class Cryopod extends ShieldedEntity {
private int id;
public Cryopod() {
super(100, 200, 1000);
}
@Override
public void start() {
gameObject.renderer.setImage("data/objectives/cryopod/cryopod.png", 300, 100);
gameObject.renderer.setOffsets(50, 100);
gameObject.setLayer(Layers.getLayer("Objective"));
}
public void setId(int id) {
this.id = id;
}
@Override
protected void die(DamageType damageType, Vector2 attackOrigin) {
Level level = LevelManager.getCurrentLevel();
if (level instanceof DefenseLevel) {
((DefenseLevel) level).getMission().onCryopodDestroyed(id);
}
}
}
| package com.ezardlabs.lostsector.missions.objectives;
import com.ezardlabs.dethsquare.Level;
import com.ezardlabs.dethsquare.LevelManager;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;
import com.ezardlabs.lostsector.levels.DefenseLevel;
import com.ezardlabs.lostsector.objects.ShieldedEntity;
public class Cryopod extends ShieldedEntity {
private int id;
public Cryopod() {
super(100, 200, 1000);
}
@Override
public void start() {
gameObject.renderer.setImage("data/objectives/cryopod/cryopod.png", 300, 100);
gameObject.renderer.setOffsets(50, 100);
}
public void setId(int id) {
this.id = id;
}
@Override
protected void die(DamageType damageType, Vector2 attackOrigin) {
Level level = LevelManager.getCurrentLevel();
if (level instanceof DefenseLevel) {
((DefenseLevel) level).getMission().onCryopodDestroyed(id);
}
}
}
|
Replace direct use of props.builders with indirect variable for type security | import * as React from "react";
import {getField} from "./utils/getField";
/**
* Component used as an indicator for build status.
* Statuses are differentiated by alternative
* styling rules.
* @param props.status the build status. Partially determines
* the styling of the rules.
*/
const StatusIndicator = (props) => {
const className = 'indicator #'.replace('#', props.status);
return (
<div className={className}></div>
);
}
/**
* Component used to display information for a builder.
* @param props.status the build status of the bot.
* @param props.name the name of the bot.
*/
const Builder = (props) => {
return (
<button className='builder' onClick={props.onClick}>
<StatusIndicator status={props.status}/>
{props.name}
</button>
);
}
/**
* Component used to display the list of builders that built a commit.
*
* @param props.builders
* @param props.builders[].builder.status
* @param props.builders[].builder.name
*/
export const BuilderGrid = (props) => {
const builders = getField(props, 'builders', []);
return (
<div className='builder-grid'>
{builders.map((b, idx) => <Builder key={idx} status={b.status} name={b.name} onClick={props.onClick.bind(this, idx)}/>)}
</div>
);
} | import * as React from "react";
/**
* Component used as an indicator for build status.
* Statuses are differentiated by alternative
* styling rules.
* @param props.status the build status. Partially determines
* the styling of the rules.
*/
const StatusIndicator = (props) => {
const className = 'indicator #'.replace('#', props.status);
return (
<div className={className}></div>
);
}
/**
* Component used to display information for a builder.
* @param props.status the build status of the bot.
* @param props.name the name of the bot.
*/
const Builder = (props) => {
return (
<button className='builder' onClick={props.onClick}>
<StatusIndicator status={props.status}/>
{props.name}
</button>
);
}
/**
* Component used to display the list of builders that built a commit.
*
* @param props.builders
* @param props.builders[].builder.status
* @param props.builders[].builder.name
*/
export const BuilderGrid = (props) => {
return (
<div className='builder-grid'>
{props.builders.map((b, idx) => <Builder key={idx} status={b.status} name={b.name} onClick={props.onClick.bind(this, idx)}/>)}
</div>
);
} |
Use a symmetric eazing curve with flat center | 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = Circles
function Circles (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = 0.95 * curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(0, 0.5, 1, 0.5).get(value)
}
| 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = Circles
function Circles (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = 0.95 * curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(0.10, 0.45, 0.9, 0.45).get(value)
}
|
Send http_x_requested_with header to be able to check for ajax request | /**
* Fetch module.
* @module base/utils/fetch
*/
import fetchJsonP from 'fetch-jsonp'
export var defaultOptions = {
credentials: 'same-origin',
headers: {
'http_x_requested_with': 'fetch'
}
}
export var defaultJsonpOptions = {
timeout: 5000,
jsonpCallback: 'callback',
jsonpCallbackFunction: null
}
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}
export function url(u, opts = {}) {
opts = Object.assign({}, defaultOptions, opts)
// TODO: implement queryParams
// if (opts.queryParams) {
// }
return fetch(u, opts).then(checkStatus)
}
export function json(u, opts = {}) {
return url(u, opts).then(r => r.json())
}
export function jsonP(u, opts = {}) {
opts = Object.assign({}, defaultJsonpOptions, opts)
// TODO: implement queryParams
// if (opts.queryParams) {
// }
return fetchJsonP(u, opts).then(r => r.json())
}
export function text(u, opts = {}) {
return url(u, opts).then(r => r.text())
}
export default {
defaultOptions,
defaultJsonpOptions,
url, json, jsonP, text
}
| /**
* Fetch module.
* @module base/utils/fetch
*/
import fetchJsonP from 'fetch-jsonp'
export var defaultOptions = {
credentials: 'same-origin'
}
export var defaultJsonpOptions = {
timeout: 5000,
jsonpCallback: 'callback',
jsonpCallbackFunction: null
}
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}
export function url(u, opts = {}) {
opts = Object.assign({}, defaultOptions, opts)
return fetch(u, opts).then(checkStatus)
}
export function json(u, opts = {}) {
return url(u, opts).then(r => r.json())
}
export function jsonP(u, opts = {}) {
opts = Object.assign({}, defaultJsonpOptions, opts)
return fetchJsonP(u, opts).then(r => r.json())
}
export function text(u, opts = {}) {
return url(u, opts).then(r => r.text())
}
export default {
defaultOptions,
defaultJsonpOptions,
url, json, jsonP, text
}
|
Fix issue where inteded path was not being used in login form handler | <?php namespace Anomaly\UsersModule\User\Login;
use Anomaly\UsersModule\User\UserAuthenticator;
use Illuminate\Routing\Redirector;
/**
* Class LoginFormHandler
*
* @link http://anomaly.is/streams-platform
* @author AnomalyLabs, Inc. <hello@anomaly.is>
* @author Ryan Thompson <ryan@anomaly.is>
* @package Anomaly\UsersModule\User\Login
*/
class LoginFormHandler
{
/**
* Handle the form.
*
* @param LoginFormBuilder $builder
* @param UserAuthenticator $authenticator
* @param Redirector $redirect
*/
public function handle(LoginFormBuilder $builder, UserAuthenticator $authenticator, Redirector $redirect)
{
if (!$user = $builder->getUser()) {
return;
}
$authenticator->login($user, $builder->getFormValue('remember_me'));
$builder->setFormResponse($redirect->intended($builder->getFormOption('redirect')));
}
}
| <?php namespace Anomaly\UsersModule\User\Login;
use Anomaly\UsersModule\User\UserAuthenticator;
/**
* Class LoginFormHandler
*
* @link http://anomaly.is/streams-platform
* @author AnomalyLabs, Inc. <hello@anomaly.is>
* @author Ryan Thompson <ryan@anomaly.is>
* @package Anomaly\UsersModule\User\Login
*/
class LoginFormHandler
{
/**
* Handle the form.
*
* @param LoginFormBuilder $builder
* @param UserAuthenticator $authenticator
*/
public function handle(LoginFormBuilder $builder, UserAuthenticator $authenticator)
{
if (!$user = $builder->getUser()) {
return;
}
$authenticator->login($user, $builder->getFormValue('remember_me'));
}
}
|
Use standard method instead of rolling our own | package nl.hsac.fitnesse.fixture.util.selenium;
import nl.hsac.fitnesse.fixture.util.selenium.by.ConstantBy;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.List;
/**
* Helper to determine which value(s) of a select is currently selected.
*/
public class SelectHelper {
private static final By SELECTED_OPTIONS_BY = ConstantBy.getSelectedOptionsBy();
private final WebElement selectElement;
public SelectHelper(WebElement element) {
selectElement = element;
}
public WebElement getFirstSelectedOption() {
List<WebElement> selectedOptions = getAllSelectedOptions();
return selectedOptions.isEmpty()? null : selectedOptions.get(0);
}
public List<WebElement> getAllSelectedOptions() {
return selectElement.findElements(SELECTED_OPTIONS_BY);
}
/**
* @param element element to check
* @return true if element is indeed a 'select'.
*/
public static boolean isSelect(WebElement element) {
String tagName = element.getTagName();
return "select".equalsIgnoreCase(tagName);
}
}
| package nl.hsac.fitnesse.fixture.util.selenium;
import nl.hsac.fitnesse.fixture.util.selenium.by.ConstantBy;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.List;
/**
* Helper to determine which value(s) of a select is currently selected.
*/
public class SelectHelper {
private static final By SELECTED_OPTIONS_BY = ConstantBy.getSelectedOptionsBy();
private final WebElement selectElement;
public SelectHelper(WebElement element) {
selectElement = element;
}
public WebElement getFirstSelectedOption() {
List<WebElement> selectedOptions = getAllSelectedOptions();
return selectedOptions.isEmpty()? null : selectedOptions.get(0);
}
public List<WebElement> getAllSelectedOptions() {
return selectElement.findElements(SELECTED_OPTIONS_BY);
}
/**
* @param element element to check
* @return true if element is indeed a 'select'.
*/
public static boolean isSelect(WebElement element) {
String tagName = element.getTagName();
return tagName != null && "select".equals(tagName.toLowerCase());
}
}
|
Correct imports for new directory structure | """An Edition reflects a base install, the default being BioLinux.
Editions are shared between multiple projects. To specialize an edition, create
a Flavor instead.
Other editions can be found in this directory
"""
from cloudbio.edition.base import Edition, Minimal, BioNode
_edition_map = {None: Edition,
"minimal": Minimal,
"bionode": BioNode}
def _setup_edition(env):
"""Setup one of the BioLinux editions (which are derived from
the Edition base class)
"""
# fetch Edition from environment and load relevant class. Use
# an existing edition, if possible, and override behaviour through
# the Flavor mechanism.
edition_class = _edition_map[env.get("edition", None)]
env.edition = edition_class(env)
env.logger.debug("%s %s" % (env.edition.name, env.edition.version))
env.logger.info("This is a %s" % env.edition.short_name)
| """An Edition reflects a base install, the default being BioLinux.
Editions are shared between multiple projects. To specialize an edition, create
a Flavor instead.
Other editions can be found in this directory
"""
from cloudbio.edition.base import Edition
from cloudbio.edition.minimal import Minimal
from cloudbio.edition.bionode import BioNode
_edition_map = {None: Edition,
"minimal": Minimal,
"bionode": BioNode}
def _setup_edition(env):
"""Setup one of the BioLinux editions (which are derived from
the Edition base class)
"""
# fetch Edition from environment and load relevant class. Use
# an existing edition, if possible, and override behaviour through
# the Flavor mechanism.
edition_class = _edition_map[env.get("edition", None)]
env.edition = edition_class(env)
env.logger.debug("%s %s" % (env.edition.name, env.edition.version))
env.logger.info("This is a %s" % env.edition.short_name)
|
Change Click Event to match new design | chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
var click_event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
switch(request.action){
case 'NEXT-MK':
document.getElementById('play-next').dispatchEvent(click_event);
break;
case 'PREV-MK':
document.getElementById('play-prev').dispatchEvent(click_event);
break;
case 'PLAY-PAUSE-MK':
document.getElementById('play-pause').dispatchEvent(click_event);
break;
}
}); | chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
var click_event = new Event('click');
switch(request.action){
case 'NEXT-MK':
//NEXT_MK
document.getElementById('play-next').dispatchEvent(click_event);
break;
case 'PREV-MK':
//PREV_MK
document.getElementById('play-prev').dispatchEvent(click_event);
break;
case 'PLAY-PAUSE-MK':
//PLAY_MK
document.getElementById('play-pause').dispatchEvent(click_event);
break;
}
}); |
Clean up, comments, liveness checking, robust data transfer | import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if utilities.multiping(port, machines):
success = True
print "hey"
break
except Exception as e:
print "ouups"
time.sleep(1)
attempted += 1
return success
| import random
import json
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if utilities.multiping(port, machines):
success = True
print "hey"
break
except Exception as e:
print "ouups"
attempted += 1
return success
|
Feature: Use api/v2 instead of drf_api/ | from django.conf import settings
from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.views.static import serve
from rest_framework.documentation import include_docs_urls
from core.views import drf_router
admin.autodiscover()
urlpatterns = [
# drf api
url(r'^api/v2/', include(drf_router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace="rest_framework")),
url(r'^api/v2/docs/', include_docs_urls(title='PinryAPI', schema_url='/')),
# old api and views
url(r'^admin/', include(admin.site.urls)),
url(r'', include('core.urls', namespace='core')),
url(r'', include('users.urls', namespace='users')),
]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),
]
if settings.IS_TEST:
urlpatterns += staticfiles_urlpatterns()
# For test running of django_images
urlpatterns += [
url(r'^__images/', include('django_images.urls')),
]
| from django.conf import settings
from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.views.static import serve
from rest_framework.documentation import include_docs_urls
from core.views import drf_router
admin.autodiscover()
urlpatterns = [
# drf api
url(r'^drf_api/', include(drf_router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace="rest_framework")),
url(r'^drf_api/docs/', include_docs_urls(title='PinryAPI', schema_url='/')),
# old api and views
url(r'^admin/', include(admin.site.urls)),
url(r'', include('core.urls', namespace='core')),
url(r'', include('users.urls', namespace='users')),
]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),
]
if settings.IS_TEST:
urlpatterns += staticfiles_urlpatterns()
# For test running of django_images
urlpatterns += [
url(r'^__images/', include('django_images.urls')),
]
|
Remove strange old "showTaskList" call now and forever! | package org.scenarioo.mytinytodo;
import org.junit.Before;
import org.junit.Test;
import org.scenarioo.mytinytodo.base.TinyTodoWebTest;
import org.scenarioo.mytinytodo.pages.TaskListsPage;
import org.scenarioo.mytinytodo.pages.TasksPage;
public class TaskListManagementWebTest extends TinyTodoWebTest {
private TaskListsPage taskListsPage;
private TasksPage tasksPage;
@Before
public void init() {
taskListsPage = create(TaskListsPage.class);
tasksPage = create(TasksPage.class);
}
@Test
public void createTaskList() {
start();
taskListsPage.createTaskList("Todo 2");
taskListsPage.selectTaskList("Todo 2");
tasksPage.assertIsEmpty();
}
@Test
public void renameTaskList() {
start();
taskListsPage.createTaskList("Todo with spelling mstake");
taskListsPage.selectTaskList("Todo with spelling mstake");
taskListsPage.renameSelectedTaskList("Todo without spelling mistake");
}
@Test
public void deleteTaskList() {
start();
taskListsPage.createTaskList("Todo to be removed");
taskListsPage.selectTaskList("Todo to be removed");
taskListsPage.deleteSelectedTaskList();
}
}
| package org.scenarioo.mytinytodo;
import org.junit.Before;
import org.junit.Test;
import org.scenarioo.mytinytodo.base.TinyTodoWebTest;
import org.scenarioo.mytinytodo.pages.TaskListsPage;
import org.scenarioo.mytinytodo.pages.TasksPage;
public class TaskListManagementWebTest extends TinyTodoWebTest {
private TaskListsPage taskListsPage;
private TasksPage tasksPage;
@Before
public void init() {
taskListsPage = create(TaskListsPage.class);
tasksPage = create(TasksPage.class);
}
@Test
public void createTaskList() {
start();
taskListsPage.createTaskList("Todo 2");
taskListsPage.showTaskList("Todo 2");
tasksPage.assertIsEmpty();
}
@Test
public void renameTaskList() {
start();
taskListsPage.createTaskList("Todo with spelling mstake");
taskListsPage.selectTaskList("Todo with spelling mstake");
taskListsPage.renameSelectedTaskList("Todo without spelling mistake");
}
@Test
public void deleteTaskList() {
start();
taskListsPage.createTaskList("Todo to be removed");
taskListsPage.selectTaskList("Todo to be removed");
taskListsPage.deleteSelectedTaskList();
}
}
|
Add canonical url for docs | import React from 'react'
import Head from 'next/head'
import {MDXProvider} from '@mdx-js/react'
import IndexMDX from './index.mdx'
import CodeBlock from '../doc-components/CodeBlock'
const components = {
pre: props => <div {...props} />,
code: CodeBlock
}
export default () => (
<MDXProvider components={components}>
<Head>
<title>
React Slidy 🍃 - a simple and minimal slider component for React
</title>
<meta
name="description"
content="A carousel component for React with the basics. It just works. For minimal setup and needs. Focused on performance ⚡"
/>
<link rel="canonical" href="https://react-slidy.midu.dev/" />
</Head>
<IndexMDX />
<style jsx global>
{`
body {
background-color: #fff;
color: #000;
font-family: system-ui, sans-serif;
line-height: 1.5;
margin: 0 auto;
max-width: 1000px;
padding: 16px;
}
pre {
overflow: auto;
max-width: 100%;
}
`}
</style>
</MDXProvider>
)
| import React from 'react'
import Head from 'next/head'
import {MDXProvider} from '@mdx-js/react'
import IndexMDX from './index.mdx'
import CodeBlock from '../doc-components/CodeBlock'
const components = {
pre: props => <div {...props} />,
code: CodeBlock
}
export default () => (
<MDXProvider components={components}>
<Head>
<title>
React Slidy 🍃 - a simple and minimal slider component for React
</title>
<meta
name="description"
content="A carousel component for React with the basics. It just works. For minimal setup and needs. Focused on performance ⚡"
/>
</Head>
<IndexMDX />
<style jsx global>
{`
body {
background-color: #fff;
color: #000;
font-family: system-ui, sans-serif;
line-height: 1.5;
margin: 0 auto;
max-width: 1000px;
padding: 16px;
}
pre {
overflow: auto;
max-width: 100%;
}
`}
</style>
</MDXProvider>
)
|
Clean up comments and validity check | angular.module('app').directive("validateBitcoinAddress", function() {
return {
require: 'ngModel',
link: function(scope, ele, attrs, ctrl) {
ctrl.$parsers.unshift(function(value) {
var valid = window.bitcoinAddress.validate(value);
ctrl.$setValidity('validateBitcoinAddress', valid);
return valid ? value : undefined;
});
ctrl.$formatters.unshift(function(value) {
var valid = window.bitcoinAddress.validate(value);
ctrl.$setValidity('validateBitcoinAddress', valid);
return value;
});
}
};
});
| angular.module('app').directive("validateBitcoinAddress", function() {
return {
require: 'ngModel',
link: function(scope, ele, attrs, ctrl) {
ctrl.$parsers.unshift(function(value) {
// test and set the validity after update.
var valid = window.bitcoinAddress.validate(value);
ctrl.$setValidity('validateBitcoinAddress', valid);
// if it's valid, return the value to the model,
// otherwise return undefined.
return valid ? value : undefined;
});
ctrl.$formatters.unshift(function(value) {
// validate.
ctrl.$setValidity('validateBitcoinAddress', window.bitcoinAddress.validate(value));
// return the value or nothing will be written to the DOM.
return value;
});
}
};
});
|
Use jsonfile helper to create package.json fixture. | /**
* Dependencies
*/
var TemplateManifest = require('./fixtures/TemplateManifest');
var FileHeap = require('./fixtures/FileHeap');
var GenerateJSONFileHelper = require('../generators/_helpers/jsonfile');
before(function (cb) {
var self = this;
/*
* Use an allocator to make it easier to manage files
* generated during testing
*/
self.heap = new FileHeap();
/*
* Another file allocator made to look like a Sails app
* to test behavior with and without `--force`, inside
* and outside of a Sails project directory.
*/
self.sailsHeap = new FileHeap();
GenerateJSONFileHelper({
pathToNew: self.sailsHeap.alloc('package.json'),
data: {
dependencies: {
sails: '~5.0.0'
}
}
}, { ok: cb });
/*
* Load template fixtures up front so they're accessible
* throughout the generator tests.
*/
// var self = this;
// TemplateManifest.load(function (err) {
// if (err) return err;
// self.templates = TemplateManifest;
// cb();
// });
});
after(function (cb) {
/*
* Clean up loose files afterwards
*/
this.heap.cleanAll(cb);
this.sailsHeap.cleanAll(cb);
}); | /**
* Dependencies
*/
var TemplateManifest = require('./fixtures/TemplateManifest');
var FileHeap = require('./fixtures/FileHeap');
before(function (cb) {
var self = this;
/*
* Use an allocator to make it easier to manage files
* generated during testing
*/
self.heap = new FileHeap();
/*
* Another file allocator made to look like a Sails app
* to test behavior with and without `--force`, inside
* and outside of a Sails project directory.
*/
self.sailsHeap = new FileHeap();
self.sailsHeap.outputJSON(
self.sailsHeap.alloc('package.json'),
{
dependencies: {
sails: '~5.0.0'
}
},
cb
);
/*
* Load template fixtures up front so they're accessible
* throughout the generator tests.
*/
// var self = this;
// TemplateManifest.load(function (err) {
// if (err) return err;
// self.templates = TemplateManifest;
// cb();
// });
});
after(function (cb) {
/*
* Clean up loose files afterwards
*/
this.heap.cleanAll(cb);
this.sailsHeap.cleanAll(cb);
}); |
Add variant columns to the metas table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMetasTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('metas', function(Blueprint $table)
{
$table->increments('id');
$table->unsignedInteger('metable_id')->nullable();
$table->string('metable_type')->nullable();
$table->string('identifier')->nullable()->index();
$table->boolean('default')->default(false);
$table->unsignedInteger('variant_id')->nullable();
$table->string('variant_type')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('metas');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMetasTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('metas', function(Blueprint $table)
{
$table->increments('id');
$table->unsignedInteger('metable_id')->nullable();
$table->string('metable_type')->nullable();
$table->string('identifier')->nullable()->index();
$table->boolean('default')->default(false);
$table->unsignedInteger('groupable_id')->nullable();
$table->string('groupable_type')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('metas');
}
}
|
Increase timeout from 400 to 800 seconds. | import unittest, time, sys, os
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
localhost = h2o.decide_if_localhost()
if (localhost):
h2o.build_cloud(4)
else:
h2o_hosts.build_cloud_with_hosts()
@classmethod
def tearDownClass(cls):
h2o.tear_down_cloud()
def test_rf_200x4_fvec(self):
h2o.beta_features = True
csvPathname = 'hhp.cut3.214.data.gz'
print "RF start on ", csvPathname, "this will probably take 1 minute.."
start = time.time()
parseResult = h2i.import_parse(bucket='smalldata', path=csvPathname, schema='put')
h2o_cmd.runRF(parseResult=parseResult, ntrees=5,
timeoutSecs=800, retryDelaySecs=15)
print "RF end on ", csvPathname, 'took', time.time() - start, 'seconds'
if __name__ == '__main__':
h2o.unit_main()
| import unittest, time, sys, os
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
localhost = h2o.decide_if_localhost()
if (localhost):
h2o.build_cloud(4)
else:
h2o_hosts.build_cloud_with_hosts()
@classmethod
def tearDownClass(cls):
h2o.tear_down_cloud()
def test_rf_200x4_fvec(self):
h2o.beta_features = True
csvPathname = 'hhp.cut3.214.data.gz'
print "RF start on ", csvPathname, "this will probably take 1 minute.."
start = time.time()
parseResult = h2i.import_parse(bucket='smalldata', path=csvPathname, schema='put')
h2o_cmd.runRF(parseResult=parseResult, ntrees=5,
timeoutSecs=400, retryDelaySecs=15)
print "RF end on ", csvPathname, 'took', time.time() - start, 'seconds'
if __name__ == '__main__':
h2o.unit_main()
|
Set default background-size to contain
This sets the default background-size attribute to contain, so we always shows the full image specified by the user. | <?php
/*
* This file is part of WordPlate.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
// Set custom login logo.
add_action('login_head', function () {
$args = get_theme_support('plate-login-logo');
if (empty($args[0])) {
return;
}
$styles = [
'background-position: center;',
'background-size: contain;',
sprintf('background-image: url(%s);', $args[0]),
];
if (count($args) >= 2) {
$styles[] = sprintf('width: %dpx;', $args[1]);
}
echo sprintf('<style> .login h1 a { %s } </style>', implode(' ', $styles));
});
// Set custom login logo url.
add_filter('login_headerurl', function () {
return get_bloginfo('url');
});
// Set custom login error message.
add_filter('login_errors', function () {
return '<strong>Whoops!</strong> Looks like you missed something there. Have another go.';
});
| <?php
/*
* This file is part of WordPlate.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
// Set custom login logo.
add_action('login_head', function () {
$args = get_theme_support('plate-login-logo');
if (empty($args[0])) {
return;
}
$styles = [
'background-position: center;',
sprintf('background-image: url(%s);', $args[0]),
];
if (count($args) >= 2) {
$styles[] = sprintf('width: %dpx;', $args[1]);
$styles[] = sprintf('background-size: %dpx auto;', $args[1]);
}
echo sprintf('<style> .login h1 a { %s } </style>', implode(' ', $styles));
});
// Set custom login logo url.
add_filter('login_headerurl', function () {
return get_bloginfo('url');
});
// Set custom login error message.
add_filter('login_errors', function () {
return '<strong>Whoops!</strong> Looks like you missed something there. Have another go.';
});
|
Add dialog title to example | """Example showing the Ask User dialog controls and overall usage."""
import fusionless as fu
dialog = fu.AskUserDialog("Example Ask User Dialog")
dialog.add_text("text", default="Default text value")
dialog.add_position("position", default=(0.2, 0.8))
dialog.add_slider("slider", default=0.5, min=-10, max=10)
dialog.add_screw("screw")
dialog.add_file_browse("file", default="C:/path/to/foo")
dialog.add_path_browse("path")
dialog.add_clip_browse("clip")
dialog.add_checkbox("checkbox", name="Do not check this!")
dialog.add_dropdown("dropdown", options=["A", "B", "C"])
dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"])
result = dialog.show()
if result is None:
# Dialog was cancelled
pass
else:
checked = result['checkbox']
if checked:
print("You sure are living on the edge!")
import pprint
pprint.pprint(result)
| """Example showing the Ask User dialog controls and overall usage."""
import fusionless as fu
dialog = fu.AskUserDialog()
dialog.add_text("text", default="Default text value")
dialog.add_position("position", default=(0.2, 0.8))
dialog.add_slider("slider", default=0.5, min=-10, max=10)
dialog.add_screw("screw")
dialog.add_file_browse("file", default="C:/path/to/foo")
dialog.add_path_browse("path")
dialog.add_clip_browse("clip")
dialog.add_checkbox("checkbox", name="Do not check this!")
dialog.add_dropdown("dropdown", options=["A", "B", "C"])
dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"])
result = dialog.show()
if result is None:
# Dialog was cancelled
pass
else:
checked = result['checkbox']
if checked:
print("You sure are living on the edge!")
import pprint
pprint.pprint(result)
|
fix: Make sure the card template returns the correct text for points
return no text for undefined points and 0pts when it costs 0 points | const utilities = require('./utilities');
const limited = (card) => card.limited ? ' | limited' : '';
const unique = (card) => card.unique ? ' | unique' : '';
const points = (card) => (typeof card.points !== 'undefined' ? `${card.points}pt${card.points > 1 || card.points === 0 ? 's': ''}` : '');
const multiCard = (card) => `\n• *${card.name}* (${card.slot}) use \`/card ${card.name} (${card.slot})\` or \`/card #id ${utilities.cardId(card)}\``;
const effect = (card) => card.effect ? `\n> ${card.effect}` : '';
function cardReduce(currentString, card) {
if(typeof currentString === 'object') {
currentString = cardReduce('', currentString);
}
return currentString + multiCard(card);
}
const templates = {
// Template for a single card
card: (card) => `${card.name} (${card.slot}${limited(card)}${unique(card)}): ${points(card)}\n${card.text}${effect(card)}`,
// Template for multiple cards
multiple: (cards, query) => {
let cardString = cards.reduce(cardReduce);
return `I found more than one card matching *'${query.text}'*:${cardString}`;
},
// Template for no results
notFound: (query) => `Sorry i couldn't find a card for *'${query.text}'*`
};
module.exports = templates;
| const utilities = require('./utilities');
const limited = (card) => card.limited ? ' | limited' : '';
const unique = (card) => card.unique ? ' | unique' : '';
const points = (card) => `${card.points}pt${card.points > 1 ? 's': ''}`;
const multiCard = (card) => `\n• *${card.name}* (${card.slot}) use \`/card ${card.name} (${card.slot})\` or \`/card #id ${utilities.cardId(card)}\``;
const effect = (card) => card.effect ? `\n> ${card.effect}` : '';
function cardReduce(currentString, card) {
if(typeof currentString === 'object') {
currentString = cardReduce('', currentString);
}
return currentString + multiCard(card);
}
const templates = {
// Template for a single card
card: (card) => `${card.name} (${card.slot}${limited(card)}${unique(card)}): ${points(card)}\n${card.text}${effect(card)}`,
// Template for multiple cards
multiple: (cards, query) => {
let cardString = cards.reduce(cardReduce);
return `I found more than one card matching *'${query.text}'*:${cardString}`;
},
// Template for no results
notFound: (query) => `Sorry i couldn't find a card for *'${query.text}'*`
};
module.exports = templates;
|
Use map for creating the nodes | import * as _ from 'lodash';
/**
* View for viewing downloaded videos.
*/
export default class DownloadedList {
/**
* Default constructor for setting the values
*
* @param {HTMLElement} element - The HTML element to bind/adopt
* @param {Array<Object>} [mediaItems=null] - The array containing media items
*/
constructor(element, mediaItems = null) {
this.element = element;
this.mediaItems = mediaItems;
}
/**
* Render page.
*/
render() {
this.element.innerHTML = _.map(this.mediaItems, (media) => {
return `<a href="#downloaded/${media.getId()}"><div class="mdc-card">
<i class="material-icons">play arrow</i>
<h5 class="image-title">${media.getTitle()}</h1>
</div></a>`;
}).join('');
// this.mediaItems.forEach((media) => {
// this.element.innerHTML += `
// <a href="#downloaded/${media.getId()}"><div class="mdc-card">
// <i class="material-icons">play arrow</i>
// <h5 class="image-title">${media.getTitle()}</h1>
// </div></a>
// `;
// });
}
}
| /**
* View for viewing downloaded videos.
*/
export default class DownloadedList {
/**
* Default constructor for setting the values
*
* @param {HTMLElement} element - The HTML element to bind/adopt
* @param {Array<Object>} [mediaItems=null] - The array containing media items
*/
constructor(element, mediaItems = null) {
this.element = element;
this.mediaItems = mediaItems;
}
/**
* Render page.
*/
render() {
this.element.innerHTML = '';
this.mediaItems.forEach((media) => {
this.element.innerHTML += `
<a href="#downloaded/${media.getId()}"><div class="mdc-card">
<i class="material-icons">play arrow</i>
<h5 class="image-title">${media.getTitle()}</h1>
</div></a>
`;
});
}
}
|
Allow access to HTTP response status code.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
namespace Laravel\Passport\Exceptions;
use Exception;
use Illuminate\Http\Response;
use League\OAuth2\Server\Exception\OAuthServerException as LeagueException;
class OAuthServerException extends Exception
{
/**
* The response to render.
*
* @var \Illuminate\Http\Response
*/
protected $response;
/**
* Create a new OAuthServerException.
*
* @param \League\OAuth2\Server\Exception\OAuthServerException $e
* @param \Illuminate\Http\Response $response
* @return void
*/
public function __construct(LeagueException $e, Response $response)
{
parent::__construct($e->getMessage(), $e->getCode(), $e);
$this->response = $response;
}
/**
* Render the exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function render($request)
{
return $this->response;
}
/**
* Get HTTP response status code.
*
* @return int
*/
public function getStatusCode()
{
return $this->response->getStatusCode();
}
}
| <?php
namespace Laravel\Passport\Exceptions;
use Exception;
use Illuminate\Http\Response;
use League\OAuth2\Server\Exception\OAuthServerException as LeagueException;
class OAuthServerException extends Exception
{
/**
* The response to render.
*
* @var \Illuminate\Http\Response
*/
protected $response;
/**
* Create a new OAuthServerException.
*
* @param \League\OAuth2\Server\Exception\OAuthServerException $e
* @param \Illuminate\Http\Response $response
* @return void
*/
public function __construct(LeagueException $e, Response $response)
{
parent::__construct($e->getMessage(), $e->getCode(), $e);
$this->response = $response;
}
/**
* Render the exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function render($request)
{
return $this->response;
}
}
|
Change initial year in slider for 100 years ago from now | $().ready(function(){
function init(){
var initialYear = new Date().getFullYear() - 100;
renderMap();
requestYears(function(years, formattedYears){
renderSlider(years, formattedYears, {
onChange: function(currentYear){
requestInfluences(currentYear, function(influences){
renderInfluencesInMap(influences);
});
},
onInit: function(){
changeSliderTo(initialYear);
requestInfluences(initialYear, function(influences){
renderInfluencesInMap(influences);
});
}
});
});
listenSearch({
onSearch: function(term){
requestYearByInfluenceName(term, function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
})
}
});
listenRequestYear({
onSearch: function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
}
});
}
init();
});
| $().ready(function(){
function init(){
var initialYear = new Date().getFullYear() - 100;
renderMap();
requestYears(function(years, formattedYears){
renderSlider(years, formattedYears, {
onChange: function(currentYear){
requestInfluences(currentYear, function(influences){
renderInfluencesInMap(influences);
});
},
onInit: function(){
requestInfluences(initialYear, function(influences){
renderInfluencesInMap(influences);
});
}
});
});
listenSearch({
onSearch: function(term){
requestYearByInfluenceName(term, function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
})
}
});
listenRequestYear({
onSearch: function(year){
changeSliderTo(year);
requestInfluences(year, function(influences){
renderInfluencesInMap(influences);
});
}
});
}
init();
});
|
Fix issue refreshing list content. | import Ember from "ember";
export default Ember.Component.extend({
name: "select-or-typeahead",
class: null,
content: null,
label: null,
list: null,
property: null,
selection: null,
userCanAdd: true,
/**
* If list is set, pull the value as the content
* and the userCanAdd flag from the list.
*/
_setup: function() {
this.listChanged();
}.on('init'),
listChanged: function() {
var list = this.get('list');
if (!Ember.isEmpty(list)) {
this.set('content', list.get('value'));
this.set('userCanAdd', list.get('userCanAdd'));
}
}.observes('list')
}); | import Ember from "ember";
export default Ember.Component.extend({
name: "select-or-typeahead",
class: null,
content: null,
label: null,
list: null,
property: null,
selection: null,
userCanAdd: true,
/**
* If list is set, pull the value as the content
* and the userCanAdd flag from the list.
*/
_setup: function() {
var list = this.get('list');
if (!Ember.isEmpty(list)) {
this.set('content', list.get('value'));
this.set('userCanAdd', list.get('userCanAdd'));
}
}.on('init'),
}); |
Update comment line for createKeyPair method | /*
Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
This file 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.
*/
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
var params = {
KeyName: 'primary-key-pair'
};
// Create key pair
ec2.createKeyPair(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log(JSON.stringify(data));
}
});
| /*
Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
This file 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.
*/
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
var params = {
KeyName: 'primary-key-pair'
};
// Create the instance
ec2.createKeyPair(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log(JSON.stringify(data));
}
});
|
Use let instead of var | 'use strict';
const Botkit = require('botkit');
const apiaibotkit = require('../api-ai-botkit');
const slackToken = process.env.SLACK_TOKEN;
const apiaiToken = process.env.APIAI_TOKEN;
const apiai = apiaibotkit(apiaiToken);
const controller = Botkit.slackbot();
controller.hears('.*', ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
apiai.process(message, bot);
});
controller.on('reaction_added', function (bot, message) {
console.log(message);
});
apiai.all(function (message, resp, bot) {
console.log(resp.result.action);
});
apiai
.action('smalltalk.greetings', function (message, resp, bot) {
let responseText = resp.result.fulfillment.speech;
bot.reply(message, responseText);
})
.action('input.unknown', function (message, resp, bot) {
bot.reply(message, "Sorry, I don't understand");
});
controller.spawn({
token: slackToken
}).startRTM(); | 'use strict';
const Botkit = require('botkit');
const apiaibotkit = require('../api-ai-botkit');
const slackToken = process.env.SLACK_TOKEN;
const apiaiToken = process.env.APIAI_TOKEN;
const apiai = apiaibotkit(apiaiToken);
const controller = Botkit.slackbot();
controller.hears('.*', ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
apiai.process(message, bot);
});
controller.on('reaction_added', function (bot, message) {
console.log(message);
});
apiai.all(function (message, resp, bot) {
console.log(resp.result.action);
});
apiai
.action('smalltalk.greetings', function (message, resp, bot) {
var responseText = resp.result.fulfillment.speech;
bot.reply(message, responseText);
})
.action('input.unknown', function (message, resp, bot) {
bot.reply(message, "Sorry, I don't understand");
});
controller.spawn({
token: slackToken
}).startRTM(); |
TASK: Replace RouteComponent::class matchResults with ServerRequestAttributes::ROUTING_RESULTS | <?php
namespace Neos\Flow\Mvc;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Http\Component\ComponentContext;
use Neos\Flow\Http\Component\ComponentInterface;
use Neos\Flow\Http\ServerRequestAttributes;
use Neos\Flow\Security\Context;
/**
*
*/
class PrepareMvcRequestComponent implements ComponentInterface
{
/**
* @Flow\Inject(lazy=false)
* @var Context
*/
protected $securityContext;
/**
* @Flow\Inject
* @var ActionRequestFactory
*/
protected $actionRequestFactory;
/**
* @inheritDoc
*/
public function handle(ComponentContext $componentContext)
{
$httpRequest = $componentContext->getHttpRequest();
$routingMatchResults = $httpRequest->getAttribute(ServerRequestAttributes::ROUTING_RESULTS) ?? [];
$actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults);
$this->securityContext->setRequest($actionRequest);
$componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest);
}
}
| <?php
namespace Neos\Flow\Mvc;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Http\Component\ComponentContext;
use Neos\Flow\Http\Component\ComponentInterface;
use Neos\Flow\Mvc\Routing\RoutingComponent;
use Neos\Flow\Security\Context;
/**
*
*/
class PrepareMvcRequestComponent implements ComponentInterface
{
/**
* @Flow\Inject(lazy=false)
* @var Context
*/
protected $securityContext;
/**
* @Flow\Inject
* @var ActionRequestFactory
*/
protected $actionRequestFactory;
/**
* @inheritDoc
*/
public function handle(ComponentContext $componentContext)
{
$httpRequest = $componentContext->getHttpRequest();
$routingMatchResults = $componentContext->getParameter(RoutingComponent::class, 'matchResults');
$actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults ?? []);
$this->securityContext->setRequest($actionRequest);
$componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest);
}
}
|
Set PDO fetch mode when setting up database. | <?php
namespace FluxBB\Database;
use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Support\ServiceProvider;
use PDO;
class DatabaseServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('Illuminate\Database\ConnectionInterface', function () {
$factory = new ConnectionFactory($this->app);
$connection = $factory->make($this->app['config']->get('fluxbb.database'));
$connection->setEventDispatcher($this->app->make('Illuminate\Contracts\Events\Dispatcher'));
$connection->setFetchMode(PDO::FETCH_CLASS);
return $connection;
});
}
}
| <?php
namespace FluxBB\Database;
use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Support\ServiceProvider;
class DatabaseServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('Illuminate\Database\ConnectionInterface', function () {
$factory = new ConnectionFactory($this->app);
$connection = $factory->make($this->app['config']->get('fluxbb.database'));
$connection->setEventDispatcher($this->app->make('Illuminate\Contracts\Events\Dispatcher'));
return $connection;
});
}
}
|
chore(templating): Update the newest templating API | import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating';
import {Injector, Inject} from 'di';
@TemplateDirective({selector: 'router-view-port'})
export class RouterViewPort {
@Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs)
constructor(viewFactory, viewPort, executionContext, attrs) {
this.viewFactory = viewFactory;
this.viewPort = viewPort;
this.executionContext = executionContext;
this.view = null;
if ('router' in this.executionContext) {
this.executionContext.router.registerViewPort(this, attrs.name);
}
}
createComponentView(directive, providers){
return this.viewFactory.createComponentView({
component: directive,
providers: providers,
viewPort: this.viewPort
});
}
process(viewPortInstruction) {
this.tryRemoveView();
this.view = viewPortInstruction.component;
this.view.appendTo(this.viewPort);
}
tryRemoveView() {
if (this.view) {
this.view.remove();
this.view = null;
}
}
}
| import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating';
import {Injector, Inject} from 'di';
@TemplateDirective({selector: 'router-view-port'})
export class RouterViewPort {
@Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs)
constructor(viewFactory, viewPort, executionContext, attrs) {
this.viewFactory = viewFactory;
this.viewPort = viewPort;
this.executionContext = executionContext;
this.view = null;
if ('router' in this.executionContext) {
this.executionContext.router.registerViewPort(this, attrs.name);
}
}
createComponentView(directive, providers){
return this.viewFactory.createComponentView({
component: directive,
providers: providers,
viewPort: this.viewPort
});
}
process(viewPortInstruction) {
this.tryRemoveView();
this.view = viewPortInstruction.component;
this.viewPort.append(this.view);
}
tryRemoveView() {
if (this.view) {
this.view.remove();
this.view = null;
}
}
}
|
Fix unwanted escape for CKEditor display
Fixes: #117 | # -*- coding: utf-8 -*-
from wtforms import fields, widgets
from flask import Markup
# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_string += ("""<script>
CKEDITOR.replace( '%s', {
enterMode: CKEDITOR.ENTER_BR
} );
</script>""" % field.id)
return widgets.HTMLString(Markup(html_string))
class CKTextAreaField(fields.TextAreaField):
widget = CKTextAreaWidget()
# Widget which returns a complete search bar with a glyphicon button
class SearchButtonWidget(widgets.SubmitInput):
html_params = staticmethod(widgets.html_params)
input_type = 'submit'
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.setdefault('type', self.input_type)
kwargs.setdefault('value', field.label.text)
if 'value' not in kwargs:
kwargs['value'] = field._value()
return widgets.HTMLString('<button %s><i class="glyphicon glyphicon-search"></i></button>' % self.html_params(name=field.name, **kwargs))
# SearchButtonField used for display the previous widget
class SearchButtonField(fields.BooleanField):
widget = SearchButtonWidget()
| # -*- coding: utf-8 -*-
from wtforms import fields, widgets
# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_string += ("""<script>
CKEDITOR.replace( '%s', {
enterMode: CKEDITOR.ENTER_BR
} );
</script>""" % field.id)
return widgets.HTMLString(html_string)
class CKTextAreaField(fields.TextAreaField):
widget = CKTextAreaWidget()
# Widget which returns a complete search bar with a glyphicon button
class SearchButtonWidget(widgets.SubmitInput):
html_params = staticmethod(widgets.html_params)
input_type = 'submit'
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.setdefault('type', self.input_type)
kwargs.setdefault('value', field.label.text)
if 'value' not in kwargs:
kwargs['value'] = field._value()
return widgets.HTMLString('<button %s><i class="glyphicon glyphicon-search"></i></button>' % self.html_params(name=field.name, **kwargs))
# SearchButtonField used for display the previous widget
class SearchButtonField(fields.BooleanField):
widget = SearchButtonWidget()
|
Add thumbnail support to event post type. | <?php
add_action('init', 'create_post_type');
function create_post_type()
{
add_post_type_support('page', 'excerpt');
register_post_type('event',
array(
'labels' => array(
'name' => __('Událost'),
),
'public' => true,
'has_archive' => true,
'supports' => array(
'title',
'author',
'excerpt',
'editor',
'thumbnail',
)
)
);
register_post_type('krizovatka',
array(
'labels' => array(
'name' => __('Křižovatka'),
),
'public' => true,
'has_archive' => true,
)
);
}
| <?php
add_action('init', 'create_post_type');
function create_post_type()
{
add_post_type_support('page', 'excerpt');
register_post_type('event',
array(
'labels' => array(
'name' => __('Událost'),
),
'public' => true,
'has_archive' => true,
)
);
register_post_type('krizovatka',
array(
'labels' => array(
'name' => __('Křižovatka'),
),
'public' => true,
'has_archive' => true,
)
);
}
|
Fix the license header regex.
Most of the files are attributed to Google Inc so I used this instead of
Chromium Authors.
R=mark@chromium.org
BUG=
TEST=
Review URL: http://codereview.chromium.org/7108074 | # Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
def CheckChangeOnUpload(input_api, output_api):
report = []
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api))
return report
def CheckChangeOnCommit(input_api, output_api):
report = []
license = (
r'.*? Copyright \(c\) %(year)s Google Inc\. All rights reserved\.\n'
r'.*? Use of this source code is governed by a BSD-style license that '
r'can be\n'
r'.*? found in the LICENSE file\.\n'
) % {
'year': input_api.time.strftime('%Y'),
}
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api, license_header=license))
report.extend(input_api.canned_checks.CheckTreeIsOpen(
input_api, output_api,
'http://gyp-status.appspot.com/status',
'http://gyp-status.appspot.com/current'))
return report
def GetPreferredTrySlaves():
return ['gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac']
| # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
def CheckChangeOnUpload(input_api, output_api):
report = []
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api))
return report
def CheckChangeOnCommit(input_api, output_api):
report = []
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api))
report.extend(input_api.canned_checks.CheckTreeIsOpen(
input_api, output_api,
'http://gyp-status.appspot.com/status',
'http://gyp-status.appspot.com/current'))
return report
def GetPreferredTrySlaves():
return ['gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac']
|
Return object, not an integer, from getStorageVersion when no version is currently stored. | var storage = chrome.storage.sync;
const DEFAULT_STORAGE = chrome.storage.sync;
const TEST_STORAGE = chrome.storage.local;
var count = 0;
chrome.storage.onChanged.addListener(function(changes, areaName) {
if (areaName == "sync")
console.log(++count, changes);
});
/**
* Reset the storage to the default storage for normal use.
*/
function resetStorageToDefault() {
storage = DEFAULT_STORAGE;
}
/**
* Get the version of the storage.
* @param {Function} callback Function taking in a version
*/
function getStorageVersion(callback) {
storage.get('version', function(items) {
if (!items || !items.version) {
return callback({
major: 1,
minor: 0,
patch: 0
});
} else {
return callback(items.version);
}
});
}
/**
* Set the storage to a version.
* @param {int} version Some version
* @param {Function} callback
*/
function setStorageVersion(version, callback) {
storage.set({ 'version': version }, callback);
}
function storageVersionExists(callback) {
storage.get('version', function(items) {
return callback(!items || !items.version);
});
}
function versionsAreEqual(a, b) {
if (!a || !b) {
return false;
}
return a.major == b.major
&& a.minor == b.minor
&& a.patch == b.patch;
} | var storage = chrome.storage.sync;
const DEFAULT_STORAGE = chrome.storage.sync;
const TEST_STORAGE = chrome.storage.local;
var count = 0;
chrome.storage.onChanged.addListener(function(changes, areaName) {
if (areaName == "sync")
console.log(++count, changes);
});
/**
* Reset the storage to the default storage for normal use.
*/
function resetStorageToDefault() {
storage = DEFAULT_STORAGE;
}
/**
* Get the version of the storage.
* @param {Function} callback Function taking in a version
*/
function getStorageVersion(callback) {
storage.get('version', function(items) {
if (!items || !items.version) {
return callback(1);
} else {
return callback(items.version);
}
});
}
/**
* Set the storage to a version.
* @param {int} version Some version
* @param {Function} callback
*/
function setStorageVersion(version, callback) {
storage.set({ 'version': version }, callback);
}
function storageVersionExists(callback) {
storage.get('version', function(items) {
return callback(!items || !items.version);
});
}
function versionsAreEqual(a, b) {
if (!a || !b) {
return false;
}
return a.major == b.major
&& a.minor == b.minor
&& a.patch == b.patch;
} |
Clean up of text
Proper exit when exception has been raised | import os
import pkgutil
import site
from sys import exit
if pkgutil.find_loader('gi'):
try:
import gi
print("Found gi at:", os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import Gst
except ValueError:
print("Couldn\'t find Gst",
'\n',
"Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'")
exit(False)
print("Environment seems to be ok.")
else:
print("No gi available in this environment",
'\n',
"Please run \'sudo apt-get install python3-gi\'",
'\n',
"A virtual environment might need extra actions like symlinking,",
'\n',
"you might need to do a symlink looking similar to this:",
'\n',
"ln -s /usr/lib/python3/dist-packages/gi",
"/srv/homeassistant/lib/python3.4/site-packages",
'\n',
"run this script inside and outside of the virtual environment",
"to find the paths needed")
print(site.getsitepackages())
| import os
import pkgutil
import site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
return False
print('Environment seems to be ok.')
else:
print('No gi installed', '\n',
'Please run \'sudo apt-get install python3-gi\'',
'\n',
'A virtual environment might need extra actions like symlinking, ',
'\n',
'you might need to do a symlink looking similar to this:',
'\n',
'ln -s /usr/lib/python3/dist-packages/gi ',
'/srv/homeassistant/lib/python3.4/site-packages',
'\n',
'run this script inside and outside of the virtual environment to find the paths needed')
print(site.getsitepackages()) |
Increase ArtifactBuild for Mock Test | package com.modesteam.urutau.builder;
import com.modesteam.urutau.model.Artifact;
import com.modesteam.urutau.model.Epic;
import com.modesteam.urutau.model.Feature;
import com.modesteam.urutau.model.Storie;
import com.modesteam.urutau.model.UseCase;
import com.modesteam.urutau.model.User;
public class ArtifactBuilder {
private String title;
private String description;
private Long id;
public ArtifactBuilder title(String title){
this.title = title;
return this;
}
public ArtifactBuilder description(String description){
this.description = description;
return this;
}
public ArtifactBuilder id(Long id) {
this.id = id;
return this;
}
public Epic buildEpic(){
Epic epic = new Epic();
epic.setId(id);
epic.setTitle(title);
epic.setDescription(description);
return epic;
}
public Feature buildFeature(){
Feature feature = new Feature();
feature.setId(id);
feature.setTitle(title);
feature.setDescription(description);
return feature;
}
public Storie buildStorie(){
Storie storie = new Storie();
storie.setId(id);
storie.setTitle(title);
storie.setDescription(description);
return storie;
}
public UseCase buildUseCase(){
UseCase useCase = new UseCase();
useCase.setId(id);
useCase.setTitle(title);
useCase.setDescription(description);
return useCase;
}
}
| package com.modesteam.urutau.builder;
import com.modesteam.urutau.model.Artifact;
import com.modesteam.urutau.model.Epic;
import com.modesteam.urutau.model.Feature;
import com.modesteam.urutau.model.User;
public class ArtifactBuilder {
private String title;
private String description;
private Long id;
public ArtifactBuilder title(String title){
this.title = title;
return this;
}
public ArtifactBuilder description(String description){
this.description = description;
return this;
}
public ArtifactBuilder id(Long id) {
this.id = id;
return this;
}
public Epic buildEpic(){
Epic epic = new Epic();
epic.setId(id);
epic.setTitle(title);
epic.setDescription(description);
return epic;
}
public Feature buildFeature(){
Feature feature = new Feature();
feature.setId(id);
feature.setTitle(title);
feature.setDescription(description);
return feature;
}
}
|
Add option to force docker pull
mesos v 0.22.0 has option to force pull of docker image, marathon will get the same option in 0.8.2
see mesosphere/marathon#837 for more details | package mesosphere.marathon.client.model.v2;
import mesosphere.marathon.client.utils.ModelUtils;
import java.util.Collection;
import java.util.List;
public class Docker {
private String image;
private String network;
private boolean forcePullImage;
private Collection<Port> portMappings;
private List<Parameter> parameters;
private boolean privileged;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNetwork() {
return network;
}
public void setNetwork(String network) {
this.network = network;
}
public Collection<Port> getPortMappings() {
return portMappings;
}
public void setPortMappings(Collection<Port> portMappings) {
this.portMappings = portMappings;
}
public boolean isPrivileged() {
return privileged;
}
public void setPrivileged(boolean privileged) {
this.privileged = privileged;
}
public List<Parameter> getParameters() {
return parameters;
}
public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}
public boolean isForcePullImage() {
return forcePullImage;
}
public void setForcePullImage(boolean forcePullImage) {
this.forcePullImage = forcePullImage;
}
@Override
public String toString() {
return ModelUtils.toString(this);
}
}
| package mesosphere.marathon.client.model.v2;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import mesosphere.marathon.client.utils.ModelUtils;
public class Docker {
private String image;
private String network;
private Collection<Port> portMappings;
private List<Parameter> parameters;
private boolean privileged;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNetwork() {
return network;
}
public void setNetwork(String network) {
this.network = network;
}
public Collection<Port> getPortMappings() {
return portMappings;
}
public void setPortMappings(Collection<Port> portMappings) {
this.portMappings = portMappings;
}
public boolean isPrivileged() {
return privileged;
}
public void setPrivileged(boolean privileged) {
this.privileged = privileged;
}
public List<Parameter> getParameters() {
return parameters;
}
public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}
@Override
public String toString() {
return ModelUtils.toString(this);
}
}
|
Test for headers and stderr changes | var assert = require('./');
var execFile = require('child_process').execFile;
assert(assert, 'assert exists');
assert(assert.equal, 'assert.equal exists');
assert.equal(typeof assert.strictEqual, 'function',
'assert.strictEqual is a function');
assert.doesNotThrow(function() {
assert.throws(function() {
throw Error('expected!');
}, /expected/, 'supports assert.throws');
}, 'nested asserts are weird.');
execFile(process.execPath, ['test-bad-tests.js'], {}, assertBad);
execFile(process.execPath, ['.'], {}, assertNoTests);
function assertBad(err, stdout, stderr) {
assertHeader(err, stdout, stderr);
assert(err, 'bad file exits with an error');
assert.notEqual(stderr, '', 'tapsert does not clear stderr');
assert(/Premature exit with code \d/.test(stdout), 'exits prematurely');
assert(/No assertions run/.test(stdout),
'notices that no asserions were run');
}
function assertNoTests(err, stdout, stderr) {
assertHeader(err, stdout, stderr);
assert(err, 'no assertions run is considered a failure');
assert.equal(stderr, '', 'tapsert does not write to stderr');
assert(!/Premature exit with code/.test(stdout),
'does not exit prematurely');
assert(/No assertions run/.test(stdout), 'says no assertions were run');
}
function assertHeader(err, stdout, stderr) {
assert(/^[\s]*TAP version 13/.test(stdout),
'TAP version header is the first non-whitespace output');
}
| var assert = require('./');
var execFile = require('child_process').execFile;
assert(assert, 'assert exists');
assert(assert.equal, 'assert.equal exists');
assert.equal(typeof assert.strictEqual, 'function',
'assert.strictEqual is a function');
assert.doesNotThrow(function() {
assert.throws(function() {
throw Error('expected!');
}, /expected/, 'supports assert.throws');
}, 'nested asserts are weird.');
execFile(process.execPath, ['test-bad-tests.js'], {}, assertBad);
execFile(process.execPath, ['.'], {}, assertNoTests);
function assertBad(err, stdout, stderr) {
assert(err, 'bad file exits with an error');
assert(/Premature exit with code \d/.test(stdout), 'exits prematurely');
assert(/No assertions run/.test(stdout),
'notices that no asserions were run');
}
function assertNoTests(err, stdout, stderr) {
assert(err, 'no assertions run is considered a failure');
assert(!/Premature exit with code/.test(stdout),
'does not exit prematurely');
assert(/No assertions run/.test(stdout), 'says no assertions were run');
}
|
[VarDumper] Fix dumping of non-nested stubs | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Casts a caster's Stub.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class StubCaster
{
public static function castStub(Stub $c, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->type = $c->type;
$stub->class = $c->class;
$stub->value = $c->value;
$stub->handle = $c->handle;
$stub->cut = $c->cut;
$a = array();
}
return $a;
}
public static function cutInternals($obj, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->cut += count($a);
return array();
}
return $a;
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Casts a caster's Stub.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class StubCaster
{
public static function castStub(Stub $c, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->type = $c->type;
$stub->class = $c->class;
$stub->value = $c->value;
$stub->handle = $c->handle;
$stub->cut = $c->cut;
return array();
}
}
public static function cutInternals($obj, array $a, Stub $stub, $isNested)
{
if ($isNested) {
$stub->cut += count($a);
return array();
}
return $a;
}
}
|
Add test for progress bar | /* eslint-env jest */
import React from 'react';
import { shallow } from 'enzyme';
import ProgressBar from './../ProgressBar';
const REQUIRED_PROPS = {
delay: 5000,
isRunning: true,
closeToast: jest.fn()
};
describe('ProgressBar', () => {
it('Should merge className', () => {
const component = shallow(
<ProgressBar
{...REQUIRED_PROPS}
className="test"
/>
);
expect(component.find('.test')).toHaveLength(1);
});
it('Should call closeToast function when animation end', () => {
const component = shallow(<ProgressBar {...REQUIRED_PROPS} />);
expect(REQUIRED_PROPS.closeToast).not.toHaveBeenCalled();
component.simulate('animationEnd');
expect(REQUIRED_PROPS.closeToast).toHaveBeenCalled();
});
it("Should be able to hide the progress bar", () => {
const component = shallow(<ProgressBar {...REQUIRED_PROPS} hide/>);
expect(component.props().style.opacity).toBe(0);
});
it("Should be able to pause animation", () => {
const component = shallow(<ProgressBar {...REQUIRED_PROPS} isRunning={false} />);
expect(component.props().style.animationPlayState).toBe("paused");
});
});
| /* eslint-env jest */
import React from 'react';
import { shallow } from 'enzyme';
import ProgressBar from './../ProgressBar';
const REQUIRED_PROPS = {
delay: 5000,
isRunning: true,
closeToast: jest.fn()
};
describe('ProgressBar', () => {
it('Should merge className', () => {
const component = shallow(
<ProgressBar
{...REQUIRED_PROPS}
className="test"
/>
);
expect(component.find('.test')).toHaveLength(1);
});
it('Should call closeToast function when animation end', () => {
const component = shallow(<ProgressBar {...REQUIRED_PROPS} />);
expect(REQUIRED_PROPS.closeToast).not.toHaveBeenCalled();
component.simulate('animationEnd');
expect(REQUIRED_PROPS.closeToast).toHaveBeenCalled();
});
});
|
Read all the lines of the md files and return them in the response | import koaRouter from 'koa-router';
import fs from 'fs';
import path from 'path'
import readline from 'readline';
const router = koaRouter();
function readPostFile(postFilePath) {
return function(done) {
var lines = [];
var lineReader = readline.createInterface({
input: fs.createReadStream(postFilePath)
});
lineReader.on('line', function(line){
lines.push(line);
});
lineReader.on('close', function(){
done(null, lines);
});
}
}
router.get('/posts', function*(next) {
const postsBaseDir = path.resolve(__dirname, '../../../posts');
const posts = fs.readdirSync(postsBaseDir);
var postData = {};
for (let i = 0, len = posts.length; i < len; i++) {
let postFilename = posts[i];
const postFilePath = path.resolve(postsBaseDir, postFilename);
postData[postFilename] = yield readPostFile(postFilePath);
}
this.body = postData;
});
export default router.middleware(); | import koaRouter from 'koa-router';
import fs from 'fs';
import path from 'path'
import readline from 'readline';
const router = koaRouter();
function lineReaderThunk(lineReader) {
return function(done) {
lineReader.on('line', function (line) {
done(null, line);
});
}
}
router.get('/posts', function*(next) {
const postsBaseDir = path.resolve(__dirname, '../../../posts');
const posts = fs.readdirSync(postsBaseDir);
var postData = {};
for (let i = 0, len = posts.length; i < len; i++) {
let postFilename = posts[i];
const postFilePath = path.resolve(postsBaseDir, postFilename);
var lineReader = readline.createInterface({
input: fs.createReadStream(postFilePath)
});
postData[postFilename] = [];
var line = yield lineReaderThunk(lineReader);
postData[postFilename].push(line);
}
this.body = postData;
});
export default router.middleware(); |
Add getter of the size of total tasks. | 'use strict';
module.exports = class TCache {
constructor(tag) {
this.tag = tag;
this._tasks = [];
this._fetching = false;
}
get size() {
return this._tasks.length;
}
_run() {
this._fetching = true;
let firstTask = this._tasks[0];
firstTask[0](...firstTask.slice(1,-1), (err, result) => {
let curTask;
while (curTask = this._tasks.shift()) {
setImmediate(curTask.slice(-1)[0], err, result);
}
this._fetching = false;
});
}
push(func, ...args) {
if (typeof func !== 'function' ||
typeof args.slice(-1)[0] !== 'function') {
return false;
}
this._tasks.push([func, ...args]);
if (!this._fetching) this._run();
return true;
}
}
| 'use strict';
module.exports = class TCache {
constructor(tag) {
this.tag = tag;
this._tasks = [];
this._fetching = false;
}
_run() {
this._fetching = true;
let firstTask = this._tasks[0];
firstTask[0](...firstTask.slice(1,-1), (err, result) => {
let curTask;
while (curTask = this._tasks.shift()) {
setImmediate(curTask.slice(-1)[0], err, result);
}
this._fetching = false;
});
}
push(func, ...args) {
if (typeof func !== 'function' ||
typeof args.slice(-1)[0] !== 'function') {
return false;
}
this._tasks.push([func, ...args]);
if (!this._fetching) this._run();
return true;
}
}
|
Test struct works with mock client | package mock
import (
"testing"
"github.com/micro/go-micro/errors"
"golang.org/x/net/context"
)
func TestClient(t *testing.T) {
type TestRequest struct {
Param string
}
response := []MockResponse{
{Method: "Foo.Bar", Response: map[string]interface{}{"foo": "bar"}},
{Method: "Foo.Struct", Response: &TestRequest{Param: "aparam"}},
{Method: "Foo.Fail", Error: errors.InternalServerError("go.mock", "failed")},
}
c := NewClient(Response("go.mock", response))
for _, r := range response {
req := c.NewJsonRequest("go.mock", r.Method, map[string]interface{}{"foo": "bar"})
var rsp interface{}
err := c.Call(context.TODO(), req, &rsp)
if err != r.Error {
t.Fatalf("Expecter error %v got %v", r.Error, err)
}
t.Log(rsp)
}
}
| package mock
import (
"testing"
"github.com/micro/go-micro/errors"
"golang.org/x/net/context"
)
func TestClient(t *testing.T) {
response := []MockResponse{
{Method: "Foo.Bar", Response: map[string]interface{}{"foo": "bar"}},
{Method: "Foo.Fail", Error: errors.InternalServerError("go.mock", "failed")},
}
c := NewClient(Response("go.mock", response))
for _, r := range response {
req := c.NewJsonRequest("go.mock", r.Method, map[string]interface{}{"foo": "bar"})
var rsp map[string]interface{}
err := c.Call(context.TODO(), req, &rsp)
if err != r.Error {
t.Fatalf("Expecter error %v got %v", r.Error, err)
}
t.Log(rsp)
}
}
|
Add output with images mixed with binary version of output labels | import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)
return
| import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
return
|
Change lifted store structure to fit Redux DevTools 3.0 | export default function createDevToolsStore(onDispatch) {
let currentState = {
actionsById: {},
computedStates: [],
currentStateIndex: 0,
monitorState: {},
nextActionId: 0,
skippedActionIds: [],
stagedActionIds: []
};
let listeners = [];
let initiated = false;
function dispatch(action) {
if (action.type[0] !== '@') onDispatch(action);
return action;
}
function getState() {
return currentState;
}
function isSet() {
return initiated;
}
function setState(state) {
currentState = state;
listeners.forEach(listener => listener());
initiated = true;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
dispatch,
getState,
subscribe,
liftedStore: {
dispatch,
getState,
setState,
subscribe,
isSet
}
};
}
| export default function createDevToolsStore(onDispatch) {
let currentState = {
committedState: {},
stagedActions: [],
computedStates: [],
skippedActions: {},
currentStateIndex: 0
};
let listeners = [];
let initiated = false;
function dispatch(action) {
if (action.type[0] !== '@') onDispatch(action);
return action;
}
function getState() {
return currentState;
}
function isSet() {
return initiated;
}
function setState(state) {
currentState = state;
listeners.forEach(listener => listener());
initiated = true;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
dispatch,
getState,
subscribe,
liftedStore: {
dispatch,
getState,
setState,
subscribe,
isSet
}
};
}
|
Set margin 0 for divider | import MJMLColumnElement from './decorators/MJMLColumnElement'
import React, { Component } from 'react'
import _ from 'lodash'
/**
* Displays a customizable divider
*/
@MJMLColumnElement({
tagName: 'mj-divider',
attributes: {
'border-color': '#000000',
'border-style': 'solid',
'border-width': '4px',
'horizontal-spacing': '10px',
'padding-bottom': '10px',
'padding-left': '25px',
'padding-right': '25px',
'padding-top': '10px',
'vertical-spacing': '30px',
'width': '150px'
}
})
class Divider extends Component {
static baseStyles = {
p: {
fontSize: '1px',
margin: '0'
}
};
getStyles() {
const { mjAttribute } = this.props
return _.merge({}, this.constructor.baseStyles, {
p: {
borderTop: `${mjAttribute('border-width')} ${mjAttribute('border-style')} ${mjAttribute('border-color')}`,
width: "100%"
}
})
}
render() {
this.styles = this.getStyles()
return <p className="outlook-divider-fix" style={this.styles.p} />
}
}
export default Divider
| import MJMLColumnElement from './decorators/MJMLColumnElement'
import React, { Component } from 'react'
import _ from 'lodash'
/**
* Displays a customizable divider
*/
@MJMLColumnElement({
tagName: 'mj-divider',
attributes: {
'border-color': '#000000',
'border-style': 'solid',
'border-width': '4px',
'horizontal-spacing': '10px',
'padding-bottom': '10px',
'padding-left': '25px',
'padding-right': '25px',
'padding-top': '10px',
'vertical-spacing': '30px',
'width': '150px'
}
})
class Divider extends Component {
static baseStyles = {
p: {
fontSize: '1px'
}
};
getStyles() {
const { mjAttribute } = this.props
return _.merge({}, this.constructor.baseStyles, {
p: {
borderTop: `${mjAttribute('border-width')} ${mjAttribute('border-style')} ${mjAttribute('border-color')}`,
width: "100%"
}
})
}
render() {
this.styles = this.getStyles()
return <p className="outlook-divider-fix" style={this.styles.p} />
}
}
export default Divider
|
Update Criteron to be self contained | import React, {PureComponent} from 'react';
import {Card, CardContent, CardHeader} from '@material-ui/core';
import SubjectPreference from './SubjectPreference';
import TimePreference from './TimePreference';
export default class Criterion extends PureComponent {
render() {
return (
<Card>
<CardHeader title="Preferences"/>
<CardContent>
<TimePreference
timeBefore={this.props.times.timeBefore}
timeAfter={this.props.times.timeAfter}
updateTimeBeforePreference={this.props.updateTimeBeforePreference}
updateTimeAfterPreference={this.props.updateTimeAfterPreference}
/>
<SubjectPreference
subject={this.props.subject}
updateSubjectPreference={this.props.updateSubjectPreference}
/>
</CardContent>
</Card>
);
}
}
| import React, {PureComponent} from 'react';
import {Card, CardContent} from '@material-ui/core';
import SubjectPreference from './SubjectPreference';
import TimePreference from './TimePreference';
export default class Criterion extends PureComponent {
render() {
return (
<Card>
<CardContent>
<TimePreference
timeBefore={this.props.times.timeBefore}
timeAfter={this.props.times.timeAfter}
updateTimeBeforePreference={this.props.updateTimeBeforePreference}
updateTimeAfterPreference={this.props.updateTimeAfterPreference}
/>
<SubjectPreference
subject={this.props.subject}
updateSubjectPreference={this.props.updateSubjectPreference}
/>
</CardContent>
</Card>
);
}
}
|
Revert "moving httpresponse to view"
This reverts commit a6f501bb9de6382e35372996851916adac067fa0. | from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User.from_django_user(request.user)
restore_id = request.GET.get('since')
return generate_restore_response(user, restore_id)
def xml_for_case(request, case_id, version="1.0"):
"""
Test view to get the xml for a particular case
"""
case = CommCareCase.get(case_id)
return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
const.CASE_ACTION_UPDATE],
version), mimetype="text/xml")
| from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User.from_django_user(request.user)
restore_id = request.GET.get('since')
return generate_restore_response(user, restore_id)
def xml_for_case(request, case_id, version="1.0"):
"""
Test view to get the xml for a particular case
"""
from django.http import HttpResponse
case = CommCareCase.get(case_id)
return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
const.CASE_ACTION_UPDATE],
version), mimetype="text/xml")
|
Return k with other results. | '''
comparison.py - Comparison of analytic and calculated solutions
Created on 12 Aug 2010
@author: Ian Huston
'''
from __future__ import division
import numpy as np
import analyticsolution
import calcedsolution
import fixtures
def compare_one_step(m, srcclass, nix):
"""
Compare the analytic and calculated solutions for equations from `srclass` using the
results from `m` at the timestep `nix`.
"""
fx = fixtures.fixture_from_model(m)
asol = analyticsolution.NoPhaseBunchDaviesSolution(fx, srcclass)
csol = calcedsolution.NoPhaseBunchDaviesCalced(fx, srcclass)
#Need to make analytic solution use 128 bit floats to avoid overruns
asol.srceqns.k = np.float128(asol.srceqns.k)
analytic_result = asol.full_source_from_model(m, nix)
calced_result = csol.full_source_from_model(m, nix)
difference = analytic_result - calced_result
error = np.abs(difference)/np.abs(analytic_result)
return difference, error, analytic_result, calced_result, asol.srceqns.k | '''
comparison.py - Comparison of analytic and calculated solutions
Created on 12 Aug 2010
@author: Ian Huston
'''
from __future__ import division
import numpy as np
import analyticsolution
import calcedsolution
import fixtures
def compare_one_step(m, srcclass, nix):
"""
Compare the analytic and calculated solutions for equations from `srclass` using the
results from `m` at the timestep `nix`.
"""
fx = fixtures.fixture_from_model(m)
asol = analyticsolution.NoPhaseBunchDaviesSolution(fx, srcclass)
csol = calcedsolution.NoPhaseBunchDaviesCalced(fx, srcclass)
#Need to make analytic solution use 128 bit floats to avoid overruns
asol.srceqns.k = np.float128(asol.srceqns.k)
analytic_result = asol.full_source_from_model(m, nix)
calced_result = csol.full_source_from_model(m, nix)
difference = analytic_result - calced_result
error = np.abs(difference)/np.abs(analytic_result)
return difference, error, analytic_result, calced_result |
Add the -json_logging flag to enable logging in JSON | package main
import (
"flag"
"log"
"net"
"os"
"github.com/sirupsen/logrus"
)
func main() {
configFileName := flag.String("config", "", "config file")
jsonLogging := flag.Bool("json_logging", false, "enable JSON logging")
flag.Parse()
cfg, err := getConfig(*configFileName)
if err != nil {
log.Fatalln("Failed to get config:", err)
}
sshServerConfig := cfg.createSSHServerConfig()
listener, err := net.Listen("tcp", cfg.ListenAddress)
if err != nil {
log.Fatalln("Failed to listen for connections:", err)
}
defer listener.Close()
logrus.SetOutput(os.Stdout)
if *jsonLogging {
logrus.SetFormatter(&logrus.JSONFormatter{})
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Failed to accept connection:", err)
continue
}
logrus.WithFields(logrus.Fields{"remote_address": conn.RemoteAddr().String()}).Infoln("Connection accepted")
go handleConnection(conn, sshServerConfig)
}
}
| package main
import (
"flag"
"log"
"net"
"os"
"github.com/sirupsen/logrus"
)
func main() {
configFileName := flag.String("config", "", "config file")
flag.Parse()
cfg, err := getConfig(*configFileName)
if err != nil {
log.Fatalln("Failed to get config:", err)
}
sshServerConfig := cfg.createSSHServerConfig()
listener, err := net.Listen("tcp", cfg.ListenAddress)
if err != nil {
log.Fatalln("Failed to listen for connections:", err)
}
defer listener.Close()
logrus.SetOutput(os.Stdout)
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Failed to accept connection:", err)
continue
}
logrus.WithFields(logrus.Fields{"remote_address": conn.RemoteAddr().String()}).Infoln("Connection accepted")
go handleConnection(conn, sshServerConfig)
}
}
|
Set up flask to handle login redirects.
Fix #147. | # -*- coding: utf-8 -*-
"""
Basic utilities for the Flask app
These are basic utilities necessary for the Flask app which are
disjoint from any blueprint.
"""
from flask import request, session
from flask_login import AnonymousUserMixin, LoginManager
from flask_babel import gettext
from werkzeug.routing import IntegerConverter as BaseIntegerConverter
from sipa.model import backends
login_manager = LoginManager()
login_manager.login_view = "generic.login"
login_manager.localize_callback = gettext
login_manager.login_message = "Bitte melde Dich an, um die Seite zu sehen."
class IntegerConverter(BaseIntegerConverter):
"""IntegerConverter supporting negative values
This is a Modification of the standard IntegerConverter which does
not support negative values. See the corresponding `werkzeug
documentation
<http://werkzeug.pocoo.org/docs/0.10/routing/#werkzeug.routing.IntegerConverter>`_.
"""
regex = r'-?\d+'
@login_manager.user_loader
def load_user(username):
"""Loads a User object from/into the session at every request
"""
if request.blueprint == "documents" or request.endpoint == "static":
return AnonymousUserMixin()
dormitory = backends.get_dormitory(session.get('dormitory', None))
if dormitory:
return dormitory.datasource.user_class.get(username)
else:
return AnonymousUserMixin()
| # -*- coding: utf-8 -*-
"""
Basic utilities for the Flask app
These are basic utilities necessary for the Flask app which are
disjoint from any blueprint.
"""
from flask import request, session
from flask_login import AnonymousUserMixin, LoginManager
from werkzeug.routing import IntegerConverter as BaseIntegerConverter
from sipa.model import backends
login_manager = LoginManager()
class IntegerConverter(BaseIntegerConverter):
"""IntegerConverter supporting negative values
This is a Modification of the standard IntegerConverter which does
not support negative values. See the corresponding `werkzeug
documentation
<http://werkzeug.pocoo.org/docs/0.10/routing/#werkzeug.routing.IntegerConverter>`_.
"""
regex = r'-?\d+'
@login_manager.user_loader
def load_user(username):
"""Loads a User object from/into the session at every request
"""
if request.blueprint == "documents" or request.endpoint == "static":
return AnonymousUserMixin()
dormitory = backends.get_dormitory(session.get('dormitory', None))
if dormitory:
return dormitory.datasource.user_class.get(username)
else:
return AnonymousUserMixin()
|
openid: Fix notice about unititialized variable.
git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@3027 44740490-163a-0410-bde0-09ae8108e29a | <?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}
$error = NULL;
try {
if (!empty($_GET['openid_url'])) {
$authSource->doAuth($state, (string)$_GET['openid_url']);
}
} catch (Exception $e) {
$error = $e->getMessage();
}
$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();
| <?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}
try {
if (!empty($_GET['openid_url'])) {
$authSource->doAuth($state, (string)$_GET['openid_url']);
}
} catch (Exception $e) {
$error = $e->getMessage();
}
$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();
|
Replace CENOReqFlags array with an EnumSet | package plugins.CENO;
import java.util.EnumSet;
import plugins.CENO.FreenetInterface.FreemailAPI.Freemail;
public class CENORequest extends Freemail {
public enum CENOReqFlags {
X_Ceno_Rewritten
}
private EnumSet<CENOReqFlags> reqFlags;
public CENORequest(Freemail freemail) {
super(freemail.getFreemailFrom(), freemail.getFreemailTo(), freemail.getSubject(), freemail.getBody());
}
public CENORequest(Freemail freemail, EnumSet<CENOReqFlags> reqFlags) {
this(freemail);
this.reqFlags = reqFlags;
}
public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body) {
super(freemailFrom, freemailTo, subject, body);
}
public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body, EnumSet<CENOReqFlags> reqFlags) {
this(freemailFrom, freemailTo, subject, body);
this.reqFlags = reqFlags;
}
public EnumSet<CENOReqFlags> getReqFlags() {
return reqFlags;
}
}
| package plugins.CENO;
import plugins.CENO.FreenetInterface.FreemailAPI.Freemail;
public class CENORequest extends Freemail {
private CENOReqFlags[] reqFlags;
public CENORequest(Freemail freemail) {
super(freemail.getFreemailFrom(), freemail.getFreemailTo(), freemail.getSubject(), freemail.getBody());
}
public CENORequest(Freemail freemail, CENOReqFlags[] reqFlags) {
this(freemail);
this.reqFlags = reqFlags;
}
public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body) {
super(freemailFrom, freemailTo, subject, body);
}
public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body, CENOReqFlags[] reqFlags) {
this(freemailFrom, freemailTo, subject, body);
this.reqFlags = reqFlags;
}
public CENOReqFlags[] getReqFlags() {
return reqFlags;
}
public enum CENOReqFlags {
X_Ceno_Rewritten
}
}
|
Use all_of_type instead of isinstance check in feincms_render_region_appcontent | from django import template
# backwards compatibility import
from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment
register = template.Library()
register.tag(fragment)
register.tag(get_fragment)
register.filter(has_fragment)
@register.simple_tag
def feincms_render_region_appcontent(page, region, request):
"""Render only the application content for the region
This allows template authors to choose whether their page behaves
differently when displaying embedded application subpages by doing
something like this::
{% if not in_appcontent_subpage %}
{% feincms_render_region feincms_page "main" request %}
{% else %}
{% feincms_render_region_appcontent feincms_page "main" request %}
{% endif %}
"""
from feincms.content.application.models import ApplicationContent
from feincms.templatetags.feincms_tags import _render_content
return u''.join(_render_content(content, request=request) for content in\
page.content.all_of_type(ApplicationContent) if content.region == region)
| from django import template
# backwards compatibility import
from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment
register = template.Library()
register.tag(fragment)
register.tag(get_fragment)
register.filter(has_fragment)
@register.simple_tag
def feincms_render_region_appcontent(page, region, request):
"""Render only the application content for the region
This allows template authors to choose whether their page behaves
differently when displaying embedded application subpages by doing
something like this::
{% if not in_appcontent_subpage %}
{% feincms_render_region feincms_page "main" request %}
{% else %}
{% feincms_render_region_appcontent feincms_page "main" request %}
{% endif %}
"""
from feincms.content.application.models import ApplicationContent
from feincms.templatetags.feincms_tags import _render_content
return u''.join(_render_content(content, request=request) for content in\
getattr(page.content, region) if isinstance(content, ApplicationContent))
|
[Refactor] Set status to default to true | var Sequelize = require("sequelize");
module.exports = function(sequelize, tableConfig) {
return sequelize.define('UserUrl', {
email: {
type: Sequelize.STRING,
allowNull: false
},
webImage: {
type: Sequelize.STRING
},
cropImage: {
type: Sequelize.STRING,
allowNull: false
},
cropHeight: {
type: Sequelize.INTEGER,
allowNull: false
},
cropWidth: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginX: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginY: {
type: Sequelize.INTEGER,
allowNull: false
},
status: {
type: Sequelize.BOOLEAN,
defaultValue: true
},
frequency: {
type: Sequelize.INTEGER,
defaultValue: 5
},
}, tableConfig)
}
| var Sequelize = require("sequelize");
module.exports = function(sequelize, tableConfig) {
return sequelize.define('UserUrl', {
email: {
type: Sequelize.STRING,
allowNull: false
},
webImage: {
type: Sequelize.STRING
},
cropImage: {
type: Sequelize.STRING,
allowNull: false
},
cropHeight: {
type: Sequelize.INTEGER,
allowNull: false
},
cropWidth: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginX: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginY: {
type: Sequelize.INTEGER,
allowNull: false
},
status: Sequelize.BOOLEAN,
frequency: {
type: Sequelize.INTEGER,
defaultValue: 5
},
}, tableConfig)
}
|
Sort sets by sequence number.
The AllSets query uses only tags, which are
a boolean term. Therefore the result set wont
be affected by the sort field. However, it will
mean that the array we get back from xapian
is sorted by sequence number, which is needed
for the paraguayan constitution app, where, e.g.
we want to show Part I before Part II.
https://phabricator.endlessm.com/T12831 | /* exported AllSets */
// Copyright 2016 Endless Mobile, Inc.
const Actions = imports.app.actions;
const Dispatcher = imports.app.dispatcher;
const Module = imports.app.interfaces.module;
const QueryObject = imports.search.queryObject;
const Xapian = imports.app.modules.selection.xapian;
const AllSets = new Module.Class({
Name: 'Selection.AllSets',
Extends: Xapian.Xapian,
_init: function (props={}) {
this.parent(props);
this._set_needs_refresh(true);
},
construct_query_object: function (limit, query_index) {
if (query_index > 0)
return null;
return new QueryObject.QueryObject({
limit: limit,
tags_match_all: ['EknSetObject'],
sort: QueryObject.QueryObjectSort.SEQUENCE_NUMBER,
});
},
show_more: function () {
Dispatcher.get_default().dispatch({
action_type: Actions.ALL_SETS_CLICKED,
});
},
});
| /* exported AllSets */
// Copyright 2016 Endless Mobile, Inc.
const Actions = imports.app.actions;
const Dispatcher = imports.app.dispatcher;
const Module = imports.app.interfaces.module;
const QueryObject = imports.search.queryObject;
const Xapian = imports.app.modules.selection.xapian;
const AllSets = new Module.Class({
Name: 'Selection.AllSets',
Extends: Xapian.Xapian,
_init: function (props={}) {
this.parent(props);
this._set_needs_refresh(true);
},
construct_query_object: function (limit, query_index) {
if (query_index > 0)
return null;
return new QueryObject.QueryObject({
limit: limit,
tags_match_all: ['EknSetObject'],
});
},
show_more: function () {
Dispatcher.get_default().dispatch({
action_type: Actions.ALL_SETS_CLICKED,
});
},
});
|
Set the default size to 40 on SVGBoxes
The null value was causing some weird rendering issues on a few icons | import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: 40,
}
| import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size = '40' }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: null,
}
|
Add option to not include print link in data component | // Data view
'use strict';
var normalizeOptions = require('es5-ext/object/normalize-options')
, _ = require('mano').i18n.bind('View: Component: Data')
, renderSections = require('./render-sections-json');
module.exports = function (context/*, options*/) {
var options = normalizeOptions(arguments[1])
, businessProcess = context.businessProcess;
return section({ class: 'section-primary' },
options.prependContent,
_if(not(options.skipPrintLink),
div({ class: 'business-process-submitted-data-print-only' }, ' ',
a({
href: mmap(businessProcess.dataForms._lastEditStamp, function (lastEditStamp) {
return '/business-process-data-forms-' + businessProcess.__id__ +
'.pdf?' + lastEditStamp;
}),
target: '_blank'
}, span({ class: 'fa fa-print' }),
span(_("Print your application form"))))),
div({ class: 'document-preview-data business-process-submitted-data' },
renderSections(businessProcess.dataForms.dataSnapshot)));
};
| // Data view
'use strict';
var normalizeOptions = require('es5-ext/object/normalize-options')
, _ = require('mano').i18n.bind('View: Component: Data')
, renderSections = require('./render-sections-json');
module.exports = function (context/*, options*/) {
var options = normalizeOptions(arguments[1])
, businessProcess = context.businessProcess;
return section({ class: 'section-primary' },
options.prependContent,
div({ class: 'business-process-submitted-data-print-only' }, ' ',
a({
href: mmap(businessProcess.dataForms._lastEditStamp, function (lastEditStamp) {
return '/business-process-data-forms-' + businessProcess.__id__ +
'.pdf?' + lastEditStamp;
}),
target: '_blank'
}, span({ class: 'fa fa-print' }),
span(_("Print your application form")))),
div({ class: 'document-preview-data business-process-submitted-data' },
renderSections(businessProcess.dataForms.dataSnapshot)));
};
|
Allow additional args for ensure_table
I had this at some point in some diff somewhere, but it got lost... that's
worrying. Maybe in a stash somewhere. | import rethinkdb as r
# TODO(alpert): Read port and db from app.config?
def r_conn(box=[None]):
if box[0] is None:
box[0] = r.connect()
box[0].use('vim_awesome')
return box[0]
def get_first(query):
results = list(query.limit(1).run(r_conn()))
return results[0] if results else None
def ensure_table(table_name, *args, **kwargs):
"""Creates a table if it doesn't exist."""
try:
r.table_create(table_name, *args, **kwargs).run(r_conn())
except r.RqlRuntimeError:
pass # Ignore db already created
def ensure_index(table_name, index_name, *args, **kwargs):
"""Creates an index if it doesn't exist."""
indices = r.table(table_name).index_list().run(r_conn())
if index_name not in indices:
r.table(table_name).index_create(index_name, *args, **kwargs).run(
r_conn())
| import rethinkdb as r
# TODO(alpert): Read port and db from app.config?
def r_conn(box=[None]):
if box[0] is None:
box[0] = r.connect()
box[0].use('vim_awesome')
return box[0]
def get_first(query):
results = list(query.limit(1).run(r_conn()))
return results[0] if results else None
def ensure_table(table_name):
"""Creates a table if it doesn't exist."""
try:
r.table_create(table_name).run(r_conn())
except r.RqlRuntimeError:
pass # Ignore db already created
def ensure_index(table_name, index_name, *args, **kwargs):
"""Creates an index if it doesn't exist."""
indices = r.table(table_name).index_list().run(r_conn())
if index_name not in indices:
r.table(table_name).index_create(index_name, *args, **kwargs).run(
r_conn())
|
Remove some no-longer needed console.log()'s | /**
* The Turnpike router.
*/
var Routes = require('routes');
Router = {};
Router.routes = function(routes) {
delete Router.router;
Router.router = Routes();
Router.router.addRoute('/', "Index");
for (var route in routes) {
if (routes.hasOwnProperty(route)) {
Router.router.addRoute(route, routes[route]);
}
}
};
Router.resolve = function(path) {
var route = {}, resolve = Router.router.match(path);
if (resolve) {
route.params = resolve.params;
route.route = resolve.route;
route.controller = resolve.fn;
}
else {
route.controller = false;
}
return route;
};
module.exports.routes = Router.routes;
module.exports.resolve = Router.resolve;
| /**
* The Turnpike router.
*/
var Routes = require('routes');
Router = {};
Router.routes = function(routes) {
delete Router.router;
Router.router = Routes();
Router.router.addRoute('/', "Index");
for (var route in routes) {
if (routes.hasOwnProperty(route)) {
console.log(route);
console.log(routes[route]);
Router.router.addRoute(route, routes[route]);
}
}
};
Router.resolve = function(path) {
var route = {}, resolve = Router.router.match(path);
//console.log(resolve);
if (resolve) {
route.params = resolve.params;
route.route = resolve.route;
route.controller = resolve.fn;
}
else {
route.controller = false;
}
return route;
};
module.exports.routes = Router.routes;
module.exports.resolve = Router.resolve;
|
Make the command-line tool pass the right parameters. | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password] [remote]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options):
if len(args) != 5:
raise CommandError("must provide all parameters")
name, url, username, password, remote = args
import_jenkinsserver(
name, url, username, password, remote,
update=options["update"], stdout=self.stdout)
transaction.commit_unless_managed()
| from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password] [remote]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options):
if len(args) != 5:
raise CommandError("must provide all parameters")
name, url, username, password, remote = args
import_jenkinsserver(
update=options["update"], stdout=self.stdout)
transaction.commit_unless_managed()
|
Use fread() instead of socket_recv_from() | <?php
namespace React\Socket;
use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;
class Connection extends Stream implements ConnectionInterface
{
public function handleData($stream)
{
$data = fread($stream, $this->bufferSize);
if ('' === $data || false === $data) {
$this->end();
} else {
$this->emit('data', array($data, $this));
}
}
public function handleClose()
{
if (is_resource($this->stream)) {
stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
fclose($this->stream);
}
}
public function getRemoteAddress()
{
return $this->parseAddress(stream_socket_get_name($this->stream, true));
}
private function parseAddress($address)
{
return trim(substr($address, 0, strrpos($address, ':')), '[]');
}
}
| <?php
namespace React\Socket;
use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;
class Connection extends Stream implements ConnectionInterface
{
public function handleData($stream)
{
$data = stream_socket_recvfrom($stream, $this->bufferSize);
if ('' === $data || false === $data) {
$this->end();
} else {
$this->emit('data', array($data, $this));
}
}
public function handleClose()
{
if (is_resource($this->stream)) {
stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
fclose($this->stream);
}
}
public function getRemoteAddress()
{
return $this->parseAddress(stream_socket_get_name($this->stream, true));
}
private function parseAddress($address)
{
return trim(substr($address, 0, strrpos($address, ':')), '[]');
}
}
|
Add package data for GeoIP DB | __author__ = 'katharine'
import os
import sys
from setuptools import setup, find_packages
requirements_path = os.path.join(os.path.dirname(__file__), 'requirements.txt')
with open(requirements_path) as requirements_file:
requirements = [line.strip() for line in requirements_file.readlines()]
setup(name='pypkjs',
version='3.6',
description='PebbleKit JS in Python!',
url='https://github.com/pebble/pypkjs',
author='Pebble Technology Corporation',
author_email='katharine@pebble.com',
license='MIT',
packages=find_packages(),
install_requires=requirements,
package_data={
'javascript.navigator': 'GeoLiteCity.dat'
},
entry_points={
'console_scripts': [
'pypkjs=runner.websocket:run_tool'
],
},
zip_safe=False)
| __author__ = 'katharine'
import os
import sys
from setuptools import setup, find_packages
requirements_path = os.path.join(os.path.dirname(__file__), 'requirements.txt')
with open(requirements_path) as requirements_file:
requirements = [line.strip() for line in requirements_file.readlines()]
setup(name='pypkjs',
version='3.6',
description='PebbleKit JS in Python!',
url='https://github.com/pebble/pypkjs',
author='Pebble Technology Corporation',
author_email='katharine@pebble.com',
license='MIT',
packages=find_packages(),
install_requires=requirements,
entry_points={
'console_scripts': [
'pypkjs=runner.websocket:run_tool'
],
},
zip_safe=False)
|
Make links open up in new windows. | // Simple file for handling text.
var Text = (function() {
var emailRegex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/ig;
var emailReplacement = '<a class="email" href="mailto:$&">$&</a>';
var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig
var urlReplacement = '<a class="url" href="$&" target="_blank">$&</a>';
var lineRegex = /\n/g;
var lineReplacement = '<br>';
return {
/**
* Escape text so we can output it in a HTML page.
* It attempts to escape HTML characters and marks up emails and links.
* It currently has a bug in that a & in URL will get escaped twice.
* @param source The source text.
* @returns The escape/marked up version.
*/
"toHtml": function(source) {
var dest = source.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/, """);
dest = dest.replace(urlRegex, urlReplacement);
dest = dest.replace(emailRegex, emailReplacement);
dest = dest.replace(lineRegex, lineReplacement);
return dest;
}
};
})(); | // Simple file for handling text.
var Text = (function() {
var emailRegex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/ig;
var emailReplacement = '<a class="email" href="mailto:$&">$&</a>';
var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig
var urlReplacement = '<a class="url" href="$&">$&</a>';
var lineRegex = /\n/g;
var lineReplacement = '<br>';
return {
/**
* Escape text so we can output it in a HTML page.
* It attempts to escape HTML characters and marks up emails and links.
* It currently has a bug in that a & in URL will get escaped twice.
* @param source The source text.
* @returns The escape/marked up version.
*/
"toHtml": function(source) {
var dest = source.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/, """);
dest = dest.replace(urlRegex, urlReplacement);
dest = dest.replace(emailRegex, emailReplacement);
dest = dest.replace(lineRegex, lineReplacement);
return dest;
}
};
})(); |
Remove deprecation warning by using require.resolve to look up dompurify location | /* eslint-env node */
'use strict';
var path = require('path');
var Funnel = require('broccoli-funnel');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-purify',
// isDevelopingAddon: () => true,
included: function() {
this._super.included.apply(this, arguments);
this.import('vendor/dom-purify/purify.min.js');
this.import('vendor/shims/dom-purify.js');
},
treeForVendor(tree) {
let domPurifyPath = path.dirname(require.resolve('dompurify'));
let copiedTree = new Funnel(domPurifyPath, {
destDir: 'dom-purify',
files: ['purify.min.js', 'purify.min.js.map']
});
return mergeTrees([tree, copiedTree]);
}
};
| /* eslint-env node */
'use strict';
var path = require('path');
var Funnel = require('broccoli-funnel');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-purify',
// isDevelopingAddon: () => true,
included: function(app) {
this._super.included.apply(this, arguments);
this.import('vendor/dom-purify/purify.min.js');
this.import('vendor/shims/dom-purify.js');
},
treeForVendor(tree) {
let domPurifyPath = path.join(this.app.project.nodeModulesPath, 'dompurify/dist/');
let copiedTree = new Funnel(domPurifyPath, {
destDir: 'dom-purify',
files: ['purify.min.js', 'purify.min.js.map']
});
return mergeTrees([tree, copiedTree]);
}
};
|
Modify code according to dev tutorial | package fr.free.nrw.commons.auth;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.webkit.WebView;
import fr.free.nrw.commons.R;
public class SignupActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("SignupActivity", "Signup Activity started");
WebView webView = new WebView(this);
setContentView(webView);
//myWebView.loadUrl("https://commons.wikimedia.org/w/index.php?title=Special:CreateAccount&returnto=Main+Page");
//Mobile page, looks better than the above
webView.loadUrl("https://commons.m.wikimedia.org/w/index.php?title=Special:CreateAccount&returnto=Main+Page&returntoquery=welcome%3Dyes");
//After Create Account button is pressed within WebView, it brings user to https://commons.wikimedia.org/wiki/Main_Page. So can we just override that URL?
//Do we NEED to enable JS? Validation seems to work fine here
}
}
| package fr.free.nrw.commons.auth;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.webkit.WebView;
import fr.free.nrw.commons.R;
public class SignupActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Log.d("SignupActivity", "Signup Activity started");
WebView myWebView = (WebView) findViewById(R.id.webview);
//myWebView.loadUrl("https://commons.wikimedia.org/w/index.php?title=Special:CreateAccount&returnto=Main+Page");
//Mobile page, looks better than the above
myWebView.loadUrl("https://commons.m.wikimedia.org/w/index.php?title=Special:CreateAccount&returnto=Main+Page&returntoquery=welcome%3Dyes");
//After Create Account button is pressed within WebView, it brings user to https://commons.wikimedia.org/wiki/Main_Page. So can we just override that URL?
//Do we NEED to enable JS? Validation seems to work fine here
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.