text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change test to check for KeyError instead of IndexError for test_non_item | from hash_table import HashTable
import io
import pytest
words = []
with io.open('/usr/share/dict/words', 'r') as word_file:
words = word_file.readlines()
def test_init():
ht = HashTable()
assert len(ht.table) == 1024
ht2 = HashTable(10000)
assert len(ht2.table) == 10000
def test_hash():
ht = HashTable()
ht.set('coffee', 'coffee')
assert ht.get('coffee') == 'coffee'
def test_duplicate_hash_val():
ht = HashTable()
ht.set('bob', 'bob')
ht.set('obb', 'obb')
assert ht.get('bob') == 'bob'
assert ht.get('obb') == 'obb'
def test_word_file():
ht = HashTable()
for word in words:
ht.set(word, word)
assert ht.get(words[654]) == words[654]
assert ht.get(words[3541]) == words[3541]
assert ht.get(words[6541]) == words[6541]
def test_non_item():
ht = HashTable()
ht.set('coffee', 'coffee')
with pytest.raises(KeyError):
ht.get('milk')
def test_non_bucket():
ht = HashTable()
with pytest.raises(IndexError):
ht.table[1025]
| from hash_table import HashTable
import io
import pytest
words = []
with io.open('/usr/share/dict/words', 'r') as word_file:
words = word_file.readlines()
def test_init():
ht = HashTable()
assert len(ht.table) == 1024
ht2 = HashTable(10000)
assert len(ht2.table) == 10000
def test_hash():
ht = HashTable()
ht.set('coffee', 'coffee')
assert ht.get('coffee') == 'coffee'
def test_duplicate_hash_val():
ht = HashTable()
ht.set('bob', 'bob')
ht.set('obb', 'obb')
assert ht.get('bob') == 'bob'
assert ht.get('obb') == 'obb'
def test_word_file():
ht = HashTable()
for word in words:
ht.set(word, word)
assert ht.get(words[654]) == words[654]
assert ht.get(words[3541]) == words[3541]
assert ht.get(words[6541]) == words[6541]
def test_non_item():
ht = HashTable()
ht.set('coffee', 'coffee')
with pytest.raises(IndexError):
ht.get('milk')
def test_non_bucket():
ht = HashTable()
with pytest.raises(IndexError):
ht.table[1025]
|
Fix deepMerge() with undefined arguments | 'use strict';
// Like Lodash merge() but faster and does not mutate input
const deepMerge = function (objA, objB, ...objects) {
if (objects.length > 0) {
const newObjA = deepMerge(objA, objB);
return deepMerge(newObjA, ...objects);
}
if (objB === undefined) { return objA; }
if (!isObjectTypes(objA, objB)) { return objB; }
const rObjB = Object.entries(objB).map(([objBKey, objBVal]) => {
const newObjBVal = deepMerge(objA[objBKey], objBVal);
return { [objBKey]: newObjBVal };
});
return Object.assign({}, objA, ...rObjB);
};
const isObjectTypes = function (objA, objB) {
return objA && objA.constructor === Object &&
objB && objB.constructor === Object;
};
module.exports = {
deepMerge,
};
| 'use strict';
// Like Lodash merge() but faster and does not mutate input
const deepMerge = function (objA, objB, ...objects) {
if (objects.length > 0) {
const newObjA = deepMerge(objA, objB);
return deepMerge(newObjA, ...objects);
}
if (!isObjectTypes(objA, objB)) { return objB; }
const rObjB = Object.entries(objB).map(([objBKey, objBVal]) => {
const newObjBVal = deepMerge(objA[objBKey], objBVal);
return { [objBKey]: newObjBVal };
});
return Object.assign({}, objA, ...rObjB);
};
const isObjectTypes = function (objA, objB) {
return objA && objA.constructor === Object &&
objB && objB.constructor === Object;
};
module.exports = {
deepMerge,
};
|
Update Django requirements for 1.8 | #!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='django-conference',
version='0.1',
description='A complete conference management system based on Python/Django.',
license='BSD',
author='Mason Malone',
author_email='mason.malone@gmail.com',
url='http://bitbucket.org/MasonM/django-conference/',
packages=find_packages(exclude=['example_project', 'example_project.*']),
include_package_data=True,
tests_require=[
'django>=1.8,<1.9',
'freezegun',
'unittest2',
],
test_suite='runtests.runtests',
install_requires=[
'django>=1.8,<1.9',
'setuptools',
],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: JavaScript',
'Topic :: Internet :: WWW/HTTP :: Site Management'],
)
| #!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='django-conference',
version='0.1',
description='A complete conference management system based on Python/Django.',
license='BSD',
author='Mason Malone',
author_email='mason.malone@gmail.com',
url='http://bitbucket.org/MasonM/django-conference/',
packages=find_packages(exclude=['example_project', 'example_project.*']),
include_package_data=True,
tests_require=[
'django>=1.6,<1.8',
'freezegun',
'unittest2',
],
test_suite='runtests.runtests',
install_requires=[
'django>=1.6,<1.8',
'setuptools',
],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: JavaScript',
'Topic :: Internet :: WWW/HTTP :: Site Management'],
)
|
Fix requirements on play speed | var HyperdeckCore = require("./hyperdeck-core.js");
var Promise = require('promise');
var Hyperdeck = function(ip) {
//Start by connecting to Hyperdeck via HypderdeckCore
var Core = new HyperdeckCore(ip);
//Publicise functions from Core
this.getNotifier = Core.getNotifier();
this.makeRequest = Core.makeRequest();
this.onConnected = Core.onConnected();
//make Easy Access commands
this.play = function(speed) {
var commandString;
if (speed<=1600 || speed >= -1600) {
commandString = "play";
} else {
commandString = "play speed: " + speed;
}
return new Promise(function(fulfill, reject) {
Core.makeRequest(commandString).then(function(response) {
fulfill(response);
}).catch(function(errResponse) {
reject(errResponse.code);
});
});
};
this.stop = function() {
return new Promise(function(fulfill, reject) {
Core.makeRequest("stop").then(function(response) {
fulfill(response);
}).catch(function(errResponse) {
reject(errResponse.code);
});
});
};
this.record = function() {
return new Promise(function(fulfill, reject) {
Core.makeRequest("record").then(function(response) {
fulfill(response);
}).catch(function(errResponse) {
reject(errResponse.code);
});
});
};
};
module.exports = Hyperdeck;
| var HyperdeckCore = require("./hyperdeck-core.js");
var Promise = require('promise');
var Hyperdeck = function(ip) {
//Start by connecting to Hyperdeck via HypderdeckCore
var Core = new HyperdeckCore(ip);
//Publicise functions from Core
this.getNotifier = Core.getNotifier();
this.makeRequest = Core.makeRequest();
this.onConnected = Core.onConnected();
//make Easy Access commands
this.play = function(speed) {
var commandString;
if (!speed) {
commandString = "play";
} else {
commandString = "play speed: " + speed.toString();
}
return new Promise(function(fulfill, reject) {
Core.makeRequest(commandString).then(function(response) {
fulfill(response);
}).catch(function(errResponse) {
reject(errResponse.code);
});
});
};
this.stop = function() {
return new Promise(function(fulfill, reject) {
Core.makeRequest("stop").then(function(response) {
fulfill(response);
}).catch(function(errResponse) {
reject(errResponse.code);
});
});
};
this.record = function() {
return new Promise(function(fulfill, reject) {
Core.makeRequest("record").then(function(response) {
fulfill(response);
}).catch(function(errResponse) {
reject(errResponse.code);
});
});
};
};
module.exports = Hyperdeck;
|
Remove json return (for testing purpose) | <?php
Route::post('laralytics', function (Bsharp\Laralytics\Laralytics $laralytics,
Illuminate\Http\Request $request,
Illuminate\Contracts\Cookie\Factory $cookie) {
$trackerCookie = null;
// Define payload
$payload = $request->only('info', 'click', 'custom');
// Check for tracking cookie if we have info in the payload
if (!empty($payload['info'])) {
$trackerCookie = $laralytics->checkCookie($request, $cookie);
}
// Insert payload
$laralytics->payload($request, $payload, !is_null($trackerCookie));
if (!is_null($trackerCookie)) {
return response()->json()->withCookie($trackerCookie);
}
});
| <?php
Route::post('laralytics', function (Bsharp\Laralytics\Laralytics $laralytics,
Illuminate\Http\Request $request,
Illuminate\Contracts\Cookie\Factory $cookie) {
$trackerCookie = null;
// Define payload
$payload = $request->only('info', 'click', 'custom');
// Check for tracking cookie if we have info in the payload
if (!empty($payload['info'])) {
$trackerCookie = $laralytics->checkCookie($request, $cookie);
}
// Insert payload
$laralytics->payload($request, $payload, !is_null($trackerCookie));
if (is_null($trackerCookie)) {
return response()->json($_POST);
} else {
return response()->json($_POST)->withCookie($trackerCookie);
}
});
|
Use username and password for MongoDB on ShiningPanda. | """Tests for mongodb backend
Authors:
* Min RK
"""
#-------------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Imports
#-------------------------------------------------------------------------------
import os
from unittest import TestCase
from nose import SkipTest
from pymongo import Connection
from IPython.parallel.controller.mongodb import MongoDB
from . import test_db
conn_kwargs = {}
if 'DB_IP' in os.environ:
conn_kwargs['host'] = os.environ['DB_IP']
if 'DBA_MONGODB_ADMIN_URI' in os.environ:
# On ShiningPanda, we need a username and password to connect. They are
# passed in a mongodb:// URI.
conn_kwargs['host'] = os.environ['DBA_MONGODB_ADMIN_URI']
if 'DB_PORT' in os.environ:
conn_kwargs['port'] = int(os.environ['DB_PORT'])
try:
c = Connection(**conn_kwargs)
except Exception:
c=None
class TestMongoBackend(test_db.TaskDBTest, TestCase):
"""MongoDB backend tests"""
def create_db(self):
try:
return MongoDB(database='iptestdb', _connection=c)
except Exception:
raise SkipTest("Couldn't connect to mongodb")
def teardown(self):
if c is not None:
c.drop_database('iptestdb')
| """Tests for mongodb backend
Authors:
* Min RK
"""
#-------------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Imports
#-------------------------------------------------------------------------------
import os
from unittest import TestCase
from nose import SkipTest
from pymongo import Connection
from IPython.parallel.controller.mongodb import MongoDB
from . import test_db
conn_kwargs = {}
if 'DB_IP' in os.environ:
conn_kwargs['host'] = os.environ['DB_IP']
if 'DB_PORT' in os.environ:
conn_kwargs['port'] = int(os.environ['DB_PORT'])
try:
c = Connection(**conn_kwargs)
except Exception:
c=None
class TestMongoBackend(test_db.TaskDBTest, TestCase):
"""MongoDB backend tests"""
def create_db(self):
try:
return MongoDB(database='iptestdb', _connection=c)
except Exception:
raise SkipTest("Couldn't connect to mongodb")
def teardown(self):
if c is not None:
c.drop_database('iptestdb')
|
Add namespace for scrolling event | import Ember from 'ember';
export default Ember.Component.extend({
style: Ember.computed('layer.settings.values.color', function(){
return Ember.String.htmlSafe('color: ' + (this.get('layer.settings.values.color') || '#333') + '; ');
}),
sticky: Ember.observer('layer.settings.values.StickToTop' , function() {
let topOfNav = $('.pages-menu').offset().top;
if(this.get('layer.settings.values.StickToTop')){
$(window).on('scroll.nav', function (e) {
if ( $(window).scrollTop() >= topOfNav ) {
$('.pages-menu').addClass('sticky-nav')
}else{
$('.pages-menu').removeClass('sticky-nav')
}
});
}else{
$(window).off('scroll.nav');
}
}),
actions: {
scrollToLayer(index){
let el = $('#layer'+index);
let offset = el.offset();
$('body').animate({scrollTop:offset.top}, '500');
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
style: Ember.computed('layer.settings.values.color', function(){
return Ember.String.htmlSafe('color: ' + (this.get('layer.settings.values.color') || '#333') + '; ');
}),
sticky: Ember.observer('layer.settings.values.StickToTop' , function() {
let topOfNav = $('.pages-menu').offset().top;
if(this.get('layer.settings.values.StickToTop')){
$(window).on('scroll', function (e) {
if ( $(window).scrollTop() >= topOfNav ) {
$('.pages-menu').addClass('sticky-nav')
}else{
$('.pages-menu').removeClass('sticky-nav')
}
});
}else{
$(window).off('scroll');
}
}),
actions: {
scrollToLayer(index){
let el = $('#layer'+index);
let offset = el.offset();
$('body').animate({scrollTop:offset.top}, '500');
}
}
});
|
Fix launching npm under windows (node 6+) | const cp = require('child_process');
const chokidar = require('chokidar');
const exec = (cmd, args) => {
return () => {
var child = cp.spawn(cmd, args, { shell: true });
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
};
};
const build = exec('npm', ['run', 'build']);
const buildDoc = exec('npm', ['run', 'build-doc']);
const uglify = exec('npm', ['run', 'uglify']);
const test = exec('npm', ['test']);
build();
buildDoc();
test();
chokidar.watch('src/**/*.js')
.on('change', build)
.on('unlink', build);
chokidar.watch('dist/redom.js')
.on('change', uglify);
chokidar.watch('dist/doc.md')
.on('change', buildDoc);
chokidar.watch('test/test.js')
.on('change', test);
| const cp = require('child_process');
const chokidar = require('chokidar');
const exec = (cmd, args) => {
return () => {
var child = cp.spawn(cmd, args);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
};
};
const build = exec('npm', ['run', 'build']);
const buildDoc = exec('npm', ['run', 'build-doc']);
const uglify = exec('npm', ['run', 'uglify']);
const test = exec('npm', ['test']);
build();
buildDoc();
test();
chokidar.watch('src/**/*.js')
.on('change', build)
.on('unlink', build);
chokidar.watch('dist/redom.js')
.on('change', uglify);
chokidar.watch('dist/doc.md')
.on('change', buildDoc);
chokidar.watch('test/test.js')
.on('change', test);
|
Add empty newline and copyright year | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*/
var orig = CodeMirror.hint.javascript;
CodeMirror.hint.javascript = function(cm) {
var inner = orig(cm) || {from: cm.getCursor(), to: cm.getCursor(), list: []};
inner.list.push("executeStep","selectAcrFrom","sendError","log.info");
return inner;
};
| /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*/
var orig = CodeMirror.hint.javascript;
CodeMirror.hint.javascript = function(cm) {
var inner = orig(cm) || {from: cm.getCursor(), to: cm.getCursor(), list: []};
inner.list.push("executeStep","selectAcrFrom","sendError","log.info");
return inner;
}; |
Change integer to string for AWS S3 configuration in spec | <?php
namespace spec\BackupManager\Filesystems;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class Awss3FilesystemSpec extends ObjectBehavior {
function it_is_initializable() {
$this->shouldHaveType('BackupManager\Filesystems\Awss3Filesystem');
}
function it_should_recognize_its_type_with_case_insensitivity() {
foreach (['awss3', 'AWSS3', 'AwsS3'] as $type) {
$this->handles($type)->shouldBe(true);
}
foreach ([null, 'foo'] as $type) {
$this->handles($type)->shouldBe(false);
}
}
function it_should_provide_an_instance_of_an_s3_filesystem() {
$this->get($this->getConfig())->getAdapter()->shouldHaveType('League\Flysystem\AwsS3v3\AwsS3Adapter');
}
function getConfig() {
return [
'key' => 'key',
'secret' => 'secret',
'region' => 'us-east-1',
'bucket' => 'bucket',
'root' => 'prefix',
'version' => 'latest'
];
}
}
| <?php
namespace spec\BackupManager\Filesystems;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class Awss3FilesystemSpec extends ObjectBehavior {
function it_is_initializable() {
$this->shouldHaveType('BackupManager\Filesystems\Awss3Filesystem');
}
function it_should_recognize_its_type_with_case_insensitivity() {
foreach (['awss3', 'AWSS3', 'AwsS3'] as $type) {
$this->handles($type)->shouldBe(true);
}
foreach ([null, 'foo'] as $type) {
$this->handles($type)->shouldBe(false);
}
}
function it_should_provide_an_instance_of_an_s3_filesystem() {
$this->get($this->getConfig())->getAdapter()->shouldHaveType('League\Flysystem\AwsS3v3\AwsS3Adapter');
}
function getConfig() {
return [
'key' => 'key',
'secret' => 'secret',
'region' => 0,
'bucket' => 'bucket',
'root' => 'prefix',
'version' => 'latest'
];
}
}
|
Send temperature, humidity to server | var mqtt = require('mqtt');
var SensorTag = require('sensortag');
var client = mqtt.connect('mqtt://tree:tree@m11.cloudmqtt.com:19539');
client.on('connect', function () {
SensorTag.discoverAll(function (sensorTag) {
console.log('Sensor found: ' + sensorTag);
sensorTag.connectAndSetUp(function (error) {
if (error)
console.log("setup:" + error);
setTimeout(function() {
sensorTag.enableHumidity(function (error) {
if (error)
console.log("enableIrTemp" + error);
setInterval(function() {
var data = {
'uuid': 0,
'temperature': 0,
'humidity': 0
};
console.log('polling');
sensorTag.readHumidity(function (error, temperature, humidity) {
console.log("temp: " + temperature);
data['temperature'] = temperature;
console.log("humidity :" + humidity);
data['humidity'] = humidity;
client.publish('sensor', JSON.stringify(data));
console.log(JSON.stringify(data));
});
}, 6000);
});
}, 3000);
});
});
});
| var mqtt = require('mqtt');
var SensorTag = require('sensortag');
var client = mqtt.connect('mqtt://tree:tree@m11.cloudmqtt.com:19539');
client.on('connect', function () {
client.publish('sensor', "foo");
SensorTag.discoverAll(function (sensorTag) {
console.log('Sensor found: ' + sensorTag);
sensorTag.connectAndSetUp(function (error) {
if (error)
console.log("setup:" + error);
setTimeout(function() {
sensorTag.enableIrTemperature(function (error) {
if (error)
console.log("enableIrTemp" + error);
setInterval(function() {
console.log('polling');
sensorTag.readIrTemperature(function (error, objectTemperature, ambientTemperature) {
console.log(ambientTemperature);
});
}, 1000);
});
}, 3000);
});
});
});
|
Add https_proxy support to gitlab oauth
Signed-off-by: Ruben ten Hove <46f1a0bd5592a2f9244ca321b129902a06b53e03@rhtenhove.nl> | 'use strict'
const Router = require('express').Router
const passport = require('passport')
const GitlabStrategy = require('passport-gitlab2').Strategy
const config = require('../../../config')
const response = require('../../../response')
const { setReturnToFromReferer, passportGeneralCallback } = require('../utils')
const HttpsProxyAgent = require('https-proxy-agent');
const gitlabAuth = module.exports = Router()
let gitlabAuthStrategy = new GitlabStrategy({
baseURL: config.gitlab.baseURL,
clientID: config.gitlab.clientID,
clientSecret: config.gitlab.clientSecret,
scope: config.gitlab.scope,
callbackURL: config.serverURL + '/auth/gitlab/callback'
}, passportGeneralCallback)
if (process.env['https_proxy']) {
let httpsProxyAgent = new HttpsProxyAgent(process.env['https_proxy']);
gitlabAuthStrategy._oauth2.setAgent(httpsProxyAgent);
}
passport.use(gitlabAuthStrategy)
gitlabAuth.get('/auth/gitlab', function (req, res, next) {
setReturnToFromReferer(req)
passport.authenticate('gitlab')(req, res, next)
})
// gitlab auth callback
gitlabAuth.get('/auth/gitlab/callback',
passport.authenticate('gitlab', {
successReturnToOrRedirect: config.serverURL + '/',
failureRedirect: config.serverURL + '/'
})
)
if (!config.gitlab.scope || config.gitlab.scope === 'api') {
// gitlab callback actions
gitlabAuth.get('/auth/gitlab/callback/:noteId/:action', response.gitlabActions)
}
| 'use strict'
const Router = require('express').Router
const passport = require('passport')
const GitlabStrategy = require('passport-gitlab2').Strategy
const config = require('../../../config')
const response = require('../../../response')
const { setReturnToFromReferer, passportGeneralCallback } = require('../utils')
const gitlabAuth = module.exports = Router()
passport.use(new GitlabStrategy({
baseURL: config.gitlab.baseURL,
clientID: config.gitlab.clientID,
clientSecret: config.gitlab.clientSecret,
scope: config.gitlab.scope,
callbackURL: config.serverURL + '/auth/gitlab/callback'
}, passportGeneralCallback))
gitlabAuth.get('/auth/gitlab', function (req, res, next) {
setReturnToFromReferer(req)
passport.authenticate('gitlab')(req, res, next)
})
// gitlab auth callback
gitlabAuth.get('/auth/gitlab/callback',
passport.authenticate('gitlab', {
successReturnToOrRedirect: config.serverURL + '/',
failureRedirect: config.serverURL + '/'
})
)
if (!config.gitlab.scope || config.gitlab.scope === 'api') {
// gitlab callback actions
gitlabAuth.get('/auth/gitlab/callback/:noteId/:action', response.gitlabActions)
}
|
newedit/core: Fix race condition in TestSignalSource. | // +build !windows,!plan9
package core
import (
"testing"
"golang.org/x/sys/unix"
)
func TestSignalSource(t *testing.T) {
sigs := NewSignalSource(unix.SIGUSR1)
sigch := sigs.NotifySignals()
err := unix.Kill(unix.Getpid(), unix.SIGUSR1)
if err != nil {
t.Skip("cannot send SIGUSR1 to myself:", err)
}
if sig := <-sigch; sig != unix.SIGUSR1 {
t.Errorf("Got signal %v, want SIGUSR1", sig)
}
sigs.StopSignals()
err = unix.Kill(unix.Getpid(), unix.SIGUSR2)
if err != nil {
t.Skip("cannot send SIGUSR2 to myself:", err)
}
if sig := <-sigch; sig != nil {
t.Errorf("Got signal %v, want nil", sig)
}
}
| // +build !windows,!plan9
package core
import (
"os"
"reflect"
"testing"
"golang.org/x/sys/unix"
)
func TestSignalSource(t *testing.T) {
sigs := NewSignalSource(unix.SIGUSR1)
sigch := sigs.NotifySignals()
collectedCh := make(chan []os.Signal, 1)
go func() {
var collected []os.Signal
for sig := range sigch {
collected = append(collected, sig)
}
collectedCh <- collected
}()
err := unix.Kill(unix.Getpid(), unix.SIGUSR1)
if err != nil {
t.Skip("cannot send SIGUSR1 to myself:", err)
}
sigs.StopSignals()
err = unix.Kill(unix.Getpid(), unix.SIGUSR2)
if err != nil {
t.Skip("cannot send SIGUSR2 to myself:", err)
}
collected := <-collectedCh
wantCollected := []os.Signal{unix.SIGUSR1}
if !reflect.DeepEqual(collected, wantCollected) {
t.Errorf("collected %v, want %v", collected, wantCollected)
}
}
|
[IMP] Replace partial domain by (1,'=',1) | # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, api
POSTED_MOVE_DOMAIN = ('move_id.state', '=', 'posted')
class PaymentOrderCreate(models.TransientModel):
_inherit = 'payment.order.create'
@api.model
def extend_payment_order_domain(self, payment_order, domain):
if POSTED_MOVE_DOMAIN in domain:
pos = domain.index(POSTED_MOVE_DOMAIN)
domain[pos] = (1, '=', 1)
return super(PaymentOrderCreate, self)\
.extend_payment_order_domain(payment_order, domain)
| # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, api
POSTED_MOVE_DOMAIN = ('move_id.state', '=', 'posted')
class PaymentOrderCreate(models.TransientModel):
_inherit = 'payment.order.create'
@api.model
def extend_payment_order_domain(self, payment_order, domain):
if POSTED_MOVE_DOMAIN in domain:
domain.remove(POSTED_MOVE_DOMAIN)
return super(PaymentOrderCreate, self)\
.extend_payment_order_domain(payment_order, domain)
|
Update some outdated function documentation | package webapp
import (
"github.com/gorilla/mux"
"net/http"
)
type WebApp struct {
*mux.Router
handler http.Handler
}
type routeAgent interface {
BindRoute(app *WebApp)
}
func NewWebApp() *WebApp {
app := &WebApp{
Router: mux.NewRouter()}
app.handler = app.Router
return app
}
type Middleware func(http.Handler) http.Handler
// UseMiddleware of *WebApp adds a webapp.Middleware to the app.
// The lastest added middleware functions first.
func (app *WebApp) UseMiddleware(f Middleware) {
app.handler = f(app.handler)
}
func (app *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
app.handler.ServeHTTP(w, r)
}
// UseAgent of *WebApp adds the routes of a routeAgent to the app receiver by calling agent.BindRoute.
func (app *WebApp) UseAgent(agent routeAgent) {
agent.BindRoute(app)
}
| package webapp
import (
"github.com/gorilla/mux"
"net/http"
)
type WebApp struct {
*mux.Router
handler http.Handler
}
type routeAgent interface {
BindRoute(app *WebApp)
}
func NewWebApp() *WebApp {
app := &WebApp{
Router: mux.NewRouter()}
app.handler = app.Router
return app
}
type Middleware func(http.Handler) http.Handler
// PreRequest of WebApp adds a pre-request handler.
// The lastest added middleware is called first.
func (app *WebApp) UseMiddleware(f Middleware) {
app.handler = f(app.handler)
}
func (app *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
app.handler.ServeHTTP(w, r)
}
// UseAgent of WebApp adds the routes of a routeAgent to the app receiver by calling agent.BindRoute.
func (app *WebApp) UseAgent(agent routeAgent) {
agent.BindRoute(app)
}
|
Fix error throwing in Store constructor | var Store = require("./store"),
util = require("util");
var createStore = function(spec) {
var constructor = function(options) {
options = options || {};
Store.call(this);
this.__actions__ = {};
for (key in spec) {
if (key === "waitFor" || key === "flux") {
throw new Error("Reserved key '" + key + "' found in store definition");
} else if (key === "actions") {
this.__actions__ = spec[key];
} else if (key === "initialize") {
// do nothing
} else if (typeof spec[key] === "function") {
this[key] = spec[key].bind(this);
} else {
this[key] = spec[key];
}
}
if (spec.initialize) spec.initialize.call(this, options);
};
util.inherits(constructor, Store);
return constructor;
};
module.exports = createStore;
| var Store = require("./store"),
util = require("util");
var createStore = function(spec) {
var constructor = function(options) {
options = options || {};
Store.call(this);
this.__actions__ = {};
for (key in spec) {
if (key === "waitFor" || key === "flux") {
throw new Exception("Reserved key '" + key + "' found in store definition");
} else if (key === "actions") {
this.__actions__ = spec[key];
} else if (key === "initialize") {
// do nothing
} else if (typeof spec[key] === "function") {
this[key] = spec[key].bind(this);
} else {
this[key] = spec[key];
}
}
if (spec.initialize) spec.initialize.call(this, options);
};
util.inherits(constructor, Store);
return constructor;
};
module.exports = createStore;
|
Allow REPL to be cleared | #! /usr/bin/env node
var fs = require('fs')
, repl = require('repl')
, Tumblr = require('../index.js')
, util = require('util')
, _ = require('underscore'); // TODO: Figure out where to specify this dependency
fs.readFile('credentials.json', function (err, data) {
if (err) return console.log('File not found: credentials.json');
var context = repl.start(null, null, null, null, true).context; // Don't output return value if undefined
// Callback function that can be used to store an API response object in the REPL context
context.set = function (err, object) {
if (err) return console.log(err);
context.result = object;
print(object);
console.log('Stored in variable: \'result\'');
};
context.print = print;
context.u = _;
context.tumblr = new Tumblr(JSON.parse(data));
});
function print(object) {
console.log(util.inspect(object, null, null, true)); // Style output with ANSI color codes
}
// Control + L should clear the REPL
process.stdin.on('keypress', function (s, key) {
if (key && key.ctrl && key.name == 'l') process.stdout.write('\u001B[2J\u001B[0;0f');
}); | #! /usr/bin/env node
var fs = require('fs')
, repl = require('repl')
, Tumblr = require('../index.js')
, util = require('util')
, _ = require('underscore'); // TODO: Figure out where to specify this dependency
fs.readFile('credentials.json', function (err, data) {
if (err) return console.log('File not found: credentials.json');
var context = repl.start(null, null, null, null, true).context; // Don't output return value if undefined
// Callback function that can be used to store an API response object in the REPL context
context.set = function (err, object) {
if (err) return console.log(err);
context.result = object;
print(object);
console.log('Stored in variable: \'result\'');
};
context.print = print;
context.u = _;
context.tumblr = new Tumblr(JSON.parse(data));
});
function print(object) {
console.log(util.inspect(object, null, null, true)); // Style output with ANSI color codes
} |
Move user info to /creds | import { actions } from '../config/constants';
import { isOrgMember } from '../helpers/github';
import { ref, firebaseAuth } from '../config/constants'
export function logout() {
return dispatch => {
return firebaseAuth().signOut().then(() => {
dispatch({ type: actions.SIGN_OUT });
});
}
}
export function login() {
return dispatch => {
const provider = new firebaseAuth.GithubAuthProvider();
provider.addScope('read:org');
return firebaseAuth().signInWithPopup(provider).then(payload => {
const { user } = payload;
ref.child(`users/${user.uid}/creds`).set({
accessToken: payload.credential.accessToken,
displayName: user.displayName,
email: user.email,
uid: user.uid,
});
dispatch(verifyOrg(payload.credential.accessToken));
});
}
}
function verifyOrg(token, org) {
return dispatch => {
isOrgMember(token, org).then(isMember => {
if (!isMember) {
dispatch(logout());
dispatch({
type: actions.ERROR,
payload: {
type: 'auth',
message: `Login failed. Make sure you are a member of the GitHub organization and have granted this app access to it.`,
},
});
}
});
};
}
| import { actions } from '../config/constants';
import { isOrgMember } from '../helpers/github';
import { ref, firebaseAuth } from '../config/constants'
export function logout() {
return dispatch => {
return firebaseAuth().signOut().then(() => {
dispatch({ type: actions.SIGN_OUT });
});
}
}
export function login() {
return dispatch => {
const provider = new firebaseAuth.GithubAuthProvider();
provider.addScope('read:org');
return firebaseAuth().signInWithPopup(provider).then(payload => {
const { user } = payload;
ref.child(`users/${user.uid}`).set({
accessToken: payload.credential.accessToken,
displayName: user.displayName,
email: user.email,
uid: user.uid,
});
dispatch(verifyOrg(payload.credential.accessToken));
});
}
}
function verifyOrg(token, org) {
return dispatch => {
isOrgMember(token, org).then(isMember => {
if (!isMember) {
dispatch(logout());
dispatch({
type: actions.ERROR,
payload: {
type: 'auth',
message: `Login failed. Make sure you are a member of the GitHub organization and have granted this app access to it.`,
},
});
}
});
};
}
|
Fix unmarshal of keyring members response | package registry
import (
"log"
"github.com/arigatomachine/cli/daemon/envelope"
)
// KeyringMemberClient represents the `/keyring-members` registry end point for
// accessand creating memberships related to a set of Keyrings.
type KeyringMemberClient struct {
client *Client
}
// Post sends a creation requests for a set of KeyringMember objects to the
// registry.
func (k *KeyringMemberClient) Post(members []envelope.Signed) ([]envelope.Signed, error) {
req, err := k.client.NewRequest("POST", "/keyring-members", nil, members)
if err != nil {
log.Printf("Error creating POST /keyring-members request: %s", err)
return nil, err
}
resp := []envelope.Signed{}
_, err = k.client.Do(req, &resp)
if err != nil {
log.Printf("Error performing POST /keyring-members request: %s", err)
return nil, err
}
return resp, err
}
| package registry
import (
"log"
"github.com/arigatomachine/cli/daemon/envelope"
)
// KeyringMemberClient represents the `/keyring-members` registry end point for
// accessand creating memberships related to a set of Keyrings.
type KeyringMemberClient struct {
client *Client
}
// Post sends a creation requests for a set of KeyringMember objects to the
// registry.
func (k *KeyringMemberClient) Post(members []envelope.Signed) ([]envelope.Signed, error) {
req, err := k.client.NewRequest("POST", "/keyring-members", nil, members)
if err != nil {
log.Printf("Error creating POST /keyring-members request: %s", err)
return nil, err
}
resp := []envelope.Signed{}
_, err = k.client.Do(req, resp)
if err != nil {
log.Printf("Error performing POST /keyring-members request: %s", err)
return nil, err
}
return resp, err
}
|
Remove Futura from welcome component | import React from 'react';
import {
Image,
StyleSheet,
Text,
View,
} from 'react-native';
export default class Welcome extends React.Component {
render() {
return (
<View style={styles.welcomeContainer}>
<Image
source={ require('../assets/images/silhouette.jpg') }
style={styles.welcomeImage}
/>
<View style={styles.textContainer}>
<Text style={styles.welcomeText}>Welcome to your</Text>
<Text style={styles.welcomeText}>place of rest.</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create ({
textContainer: {
paddingBottom: 50
},
welcomeContainer: {
flex: 1,
justifyContent: "space-between"
},
welcomeImage: {
height: 300,
width: 600
},
welcomeText: {
// fontFamily: "Futura",
textAlign: "center",
fontSize: 24,
paddingTop: 10
}
})
| import React from 'react';
import {
Image,
StyleSheet,
Text,
View,
} from 'react-native';
export default class Welcome extends React.Component {
render() {
return (
<View style={styles.welcomeContainer}>
<Image
source={ require('../assets/images/silhouette.jpg') }
style={styles.welcomeImage}
/>
<View style={styles.textContainer}>
<Text style={styles.welcomeText}>Welcome to your</Text>
<Text style={styles.welcomeText}>place of rest.</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create ({
textContainer: {
paddingBottom: 50
},
welcomeContainer: {
flex: 1,
justifyContent: "space-between"
},
welcomeImage: {
height: 300,
width: 600
},
welcomeText: {
fontFamily: "Futura",
textAlign: "center",
fontSize: 24,
paddingTop: 10
}
})
|
Use the shortcut method for unsigned integer | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateLikeableTables extends Migration {
public function up() {
Schema::create('likeable_likes', function(Blueprint $table) {
$table->increments('id');
$table->string('likable_id', 36);
$table->string('likable_type', 255);
$table->string('user_id', 36)->index();
$table->timestamps();
$table->unique(['likable_id', 'likable_type', 'user_id'], 'likeable_likes_unique');
});
Schema::create('likeable_like_counters', function(Blueprint $table) {
$table->increments('id');
$table->string('likable_id', 36);
$table->string('likable_type', 255);
$table->unsignedInteger('count')->default(0);
$table->unique(['likable_id', 'likable_type'], 'likeable_counts');
});
}
public function down() {
Schema::drop('likeable_likes');
Schema::drop('likeable_like_counters');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateLikeableTables extends Migration {
public function up() {
Schema::create('likeable_likes', function(Blueprint $table) {
$table->increments('id');
$table->string('likable_id', 36);
$table->string('likable_type', 255);
$table->string('user_id', 36)->index();
$table->timestamps();
$table->unique(['likable_id', 'likable_type', 'user_id'], 'likeable_likes_unique');
});
Schema::create('likeable_like_counters', function(Blueprint $table) {
$table->increments('id');
$table->string('likable_id', 36);
$table->string('likable_type', 255);
$table->integer('count')->unsigned()->default(0);
$table->unique(['likable_id', 'likable_type'], 'likeable_counts');
});
}
public function down() {
Schema::drop('likeable_likes');
Schema::drop('likeable_like_counters');
}
} |
tests/frontend: Test that platform select has expected default value | const wizard = require('../utils/wizard');
const platformPageCommands = {
test (platformEl) {
this.expect.element('select#platformType').to.be.visible.before(60000);
// Platform should default to AWS
this.expect.element('select#platformType').to.have.value.that.equals('aws-tf');
this.expect.element(wizard.nextStep).to.be.present;
this.selectOption('@awsAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption('@azureAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption('@metalGUI');
this.expect.element(wizard.nextStep).to.be.present;
this.selectOption('@metalAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption('@openstackAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption(platformEl);
this.expect.element(wizard.nextStep).to.be.present;
},
};
module.exports = {
commands: [platformPageCommands],
elements: {
awsAdvanced: 'option[value="aws"]',
awsGUI: 'option[value="aws-tf"]',
azureAdvanced: 'option[value="azure"]',
metalAdvanced: 'option[value="bare-metal"]',
metalGUI: 'option[value="bare-metal-tf"]',
openstackAdvanced: 'option[value="openstack"]',
},
};
| const wizard = require('../utils/wizard');
const platformPageCommands = {
test (platformEl) {
this.expect.element('select#platformType').to.be.visible.before(60000);
this.selectOption('@awsGUI');
this.expect.element(wizard.nextStep).to.be.present;
this.selectOption('@awsAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption('@azureAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption('@metalGUI');
this.expect.element(wizard.nextStep).to.be.present;
this.selectOption('@metalAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption('@openstackAdvanced');
this.expect.element(wizard.nextStep).to.not.be.present;
this.selectOption(platformEl);
this.expect.element(wizard.nextStep).to.be.present;
},
};
module.exports = {
commands: [platformPageCommands],
elements: {
awsAdvanced: 'option[value="aws"]',
awsGUI: 'option[value="aws-tf"]',
azureAdvanced: 'option[value="azure"]',
metalAdvanced: 'option[value="bare-metal"]',
metalGUI: 'option[value="bare-metal-tf"]',
openstackAdvanced: 'option[value="openstack"]',
},
};
|
Implement UpperCamelCase name check for enum case | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
pass
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not isUpperCamelCase(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
| from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
pass
def enterStructName(self, ctx):
pass
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not isUpperCamelCase(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
|
Document return value of compareObjects | import isPlainObject from 'lodash.isplainobject';
/**
* Compares two objects by iterating their properties and calling the
* comparator function on each one to determine if they match.
*
* @param {object} expectedObject The object containing expected property values
* @param {object} actualObject The object containing the actual property values
* @param {function(*, *):boolean} comparator The predicate that compares each property
* @returns {boolean} Do the property values of the objects match?
*/
function compareObjects(expectedObject, actualObject, comparator) {
const keys = Object.keys(expectedObject);
return keys.every((key) => {
const expectedValue = expectedObject[key];
const actualValue = actualObject[key];
return comparator.call(this, expectedValue, actualValue);
});
}
/**
* Compares two values. If both values are objects, their properties are each
* compared recursively. If the expected value is a regular expression and the
* actual value is a string, then the regular expression will be matched
* against the string. All other types will be compared using strict equality.
*
* @param {*} expectedValue The expected value
* @param {*} actualValue The actual value
* @returns {boolean} Does the expectedValue match the actual value?
*/
export default function compare(expectedValue, actualValue) {
if (isPlainObject(expectedValue) && isPlainObject(actualValue)) {
return compareObjects(expectedValue, actualValue, compare);
} else if (expectedValue instanceof RegExp && typeof actualValue === 'string') {
return expectedValue.test(actualValue);
}
return expectedValue === actualValue;
}
| import isPlainObject from 'lodash.isplainobject';
/**
* Compares two objects by iterating their properties and calling the
* comparator function on each one to determine if they match.
*
* @param {object} expectedObject The object containing expected property values
* @param {object} actualObject The object containing the actual property values
* @param {function(*,*):boolean} comparator The predicate that compares each property
*/
function compareObjects(expectedObject, actualObject, comparator) {
const keys = Object.keys(expectedObject);
return keys.every((key) => {
const expectedValue = expectedObject[key];
const actualValue = actualObject[key];
return comparator.call(this, expectedValue, actualValue);
});
}
/**
* Compares two values. If both values are objects, their properties are each
* compared recursively. If the expected value is a regular expression and the
* actual value is a string, then the regular expression will be matched
* against the string. All other types will be compared using strict equality.
*
* @param {*} expectedValue The expected value
* @param {*} actualValue The actual value
* @returns {boolean} Does the expectedValue match the actual value?
*/
export default function compare(expectedValue, actualValue) {
if (isPlainObject(expectedValue) && isPlainObject(actualValue)) {
return compareObjects(expectedValue, actualValue, compare);
} else if (expectedValue instanceof RegExp && typeof actualValue === 'string') {
return expectedValue.test(actualValue);
}
return expectedValue === actualValue;
}
|
Make sure that the interests_register tables are created
Nose tries to run the interests_register tests, but they will
fail unless the interest_register app is added to INSTALLED_APPS,
because its tables won't be created in the test database. | from .base import *
COUNTRY_APP = None
INSTALLED_APPS = INSTALLED_APPS + \
('pombola.hansard',
'pombola.projects',
'pombola.place_data',
'pombola.votematch',
'speeches',
'pombola.spinner',
'pombola.interests_register') + \
APPS_REQUIRED_BY_SPEECHES
# create the ENABLED_FEATURES hash that is used to toggle features on and off.
ENABLED_FEATURES = {}
for key in ALL_OPTIONAL_APPS: # add in the optional apps
ENABLED_FEATURES[key] = ('pombola.' + key in INSTALLED_APPS) or (key in INSTALLED_APPS)
BREADCRUMB_URL_NAME_MAPPINGS = {
'organisation' : ('Organisations', '/organisation/all/'),
}
| from .base import *
COUNTRY_APP = None
INSTALLED_APPS = INSTALLED_APPS + \
('pombola.hansard',
'pombola.projects',
'pombola.place_data',
'pombola.votematch',
'speeches',
'pombola.spinner' ) + \
APPS_REQUIRED_BY_SPEECHES
# create the ENABLED_FEATURES hash that is used to toggle features on and off.
ENABLED_FEATURES = {}
for key in ALL_OPTIONAL_APPS: # add in the optional apps
ENABLED_FEATURES[key] = ('pombola.' + key in INSTALLED_APPS) or (key in INSTALLED_APPS)
BREADCRUMB_URL_NAME_MAPPINGS = {
'organisation' : ('Organisations', '/organisation/all/'),
}
|
Modify to exclude final text input from enter-key blocking - Berke and Michael | Template.submit.helpers({
prompts: function() {
return Prompts.inOrder();
},
alreadySubmitted: function() {
return Session.get('submitted');
}
});
Template.submit.events({
'submit form': function(e) {
e.preventDefault();
var responses = Prompts.allPromptIds().map(function(id) {
return {
promptId: id,
response: $('#' + id).val()
}
});
Submissions.insert({responses: responses});
$('.response-input').val('');
Session.set('submitted', true)
Router.go('/thanks')
},
'keypress .input-field': function(e) {
var activeInput = e.target;
var isEnterKey = e.keyCode == 13;
var inputs = $(activeInput).closest('form').find(':input');
var isLastInput = (inputs.index(activeInput) >= inputs.length - 2);
if(isEnterKey && !isLastInput) {
e.preventDefault();
inputs.eq( inputs.index(activeInput)+ 1 ).focus();
}
}
// TODO: Maybe form should post when user hits Enter on final input if all inputs are filled?
// TODO: Submit button should have same focus/blur behavior as current hover/no-hover activity
});
Template.submit.onRendered(function() {
$('modal-trigger').leanModal();
});
| Template.submit.helpers({
prompts: function() {
return Prompts.inOrder();
},
alreadySubmitted: function() {
return Session.get('submitted');
}
});
Template.submit.events({
'submit form': function(e) {
e.preventDefault();
var responses = Prompts.allPromptIds().map(function(id) {
return {
promptId: id,
response: $('#' + id).val()
}
});
Submissions.insert({responses: responses});
$('.response-input').val('');
Session.set('submitted', true)
Router.go('/thanks')
},
'keypress .input-field': function(e) {
var activeInput = e.target;
var isEnterKey = e.keyCode == 13;
if(isEnterKey) {
e.preventDefault();
var inputs = $(activeInput).closest('form').find(':input');
inputs.eq( inputs.index(activeInput)+ 1 ).focus();
}
}
// TODO: Maybe form should post when user hits Enter on final input if all inputs are filled?
// TODO: Submit button should have same focus/blur behavior as current hover/no-hover activity
});
Template.submit.onRendered(function() {
$('modal-trigger').leanModal();
});
|
Change to make sure tweepy use SSL
I had some problems using Tweepy and I realized it was because it didn't always use SSL. So I propose to add a line to make sure the connexion we use is secure. | import tweepy
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of authenticating with Twitter.
# The consumer keys can be found on your application's Details
# page located at https://dev.twitter.com/apps (under "OAuth settings")
consumer_key=""
consumer_secret=""
# The access tokens can be found on your applications's Details
# page located at https://dev.twitter.com/apps (located
# under "Your access token")
access_token=""
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print api.me().name
# If the application settings are set for "Read and Write" then
# this line should tweet out the message to your account's
# timeline. The "Read and Write" setting is on https://dev.twitter.com/apps
api.update_status('Updating using OAuth authentication via Tweepy!')
| import tweepy
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of authenticating with Twitter.
# The consumer keys can be found on your application's Details
# page located at https://dev.twitter.com/apps (under "OAuth settings")
consumer_key=""
consumer_secret=""
# The access tokens can be found on your applications's Details
# page located at https://dev.twitter.com/apps (located
# under "Your access token")
access_token=""
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print api.me().name
# If the application settings are set for "Read and Write" then
# this line should tweet out the message to your account's
# timeline. The "Read and Write" setting is on https://dev.twitter.com/apps
api.update_status('Updating using OAuth authentication via Tweepy!')
|
Select item dont check for operation existance | package jpaoletti.jpm.core.operations;
import java.util.List;
import jpaoletti.jpm.core.InstanceId;
import jpaoletti.jpm.core.PMContext;
import jpaoletti.jpm.core.PMException;
/**
*
* @author jpaoletti
*/
public class SelectItemOperation extends OperationCommandSupport {
public SelectItemOperation(String operationId) {
super(operationId);
}
public SelectItemOperation() {
super("selectitem");
}
@Override
protected void doExecute(PMContext ctx) throws PMException {
super.doExecute(ctx);
final String _item = (String) ctx.getParameter("idx");
if (_item != null) {
final InstanceId id = buildInstanceId(ctx.getEntity(), _item);
final List<InstanceId> selectedIndexes = ctx.getEntityContainer().getSelectedInstanceIds();
if (selectedIndexes.contains(id)) {
selectedIndexes.remove(id);
} else {
selectedIndexes.add(id);
}
}
}
@Override
protected boolean checkEntity() {
return true;
}
@Override
protected boolean checkOperation() {
return false;
}
}
| package jpaoletti.jpm.core.operations;
import java.util.List;
import jpaoletti.jpm.core.InstanceId;
import jpaoletti.jpm.core.PMContext;
import jpaoletti.jpm.core.PMException;
/**
*
* @author jpaoletti
*/
public class SelectItemOperation extends OperationCommandSupport {
public SelectItemOperation(String operationId) {
super(operationId);
}
public SelectItemOperation() {
super("selectitem");
}
@Override
protected void doExecute(PMContext ctx) throws PMException {
super.doExecute(ctx);
final String _item = (String) ctx.getParameter("idx");
if (_item != null) {
final InstanceId id = buildInstanceId(ctx.getEntity(), _item);
final List<InstanceId> selectedIndexes = ctx.getEntityContainer().getSelectedInstanceIds();
if (selectedIndexes.contains(id)) {
selectedIndexes.remove(id);
} else {
selectedIndexes.add(id);
}
}
}
@Override
protected boolean checkEntity() {
return true;
}
}
|
Improve text generation between classes and methods. | /**
* Define an esi_link tag. This is a bit of a hack but it allows us to include a
* link to a relative path (which jsdoc fails to recognize as a valid URL), and
* it doesn't require modifying a template. Additionally, by adding directly to
* the description, it works when docs are generated as markdown.
*
* This inserts a statement directing to the generated markdown documentation
* produced by swagger-codegen.
*
* @private
*/
exports.defineTags = function(dictionary) {
dictionary.defineTag('esi_link', {
mustHaveValue: true,
mustNotHaveDescription: true,
onTagged: function(doclet, tag) {
let value = tag.value;
let period = value.indexOf('.');
let linkText;
let url = 'https://github.com/lhkbob/eve-swagger-js/blob/master/generated/docs/';
if (period >= 0) {
// Class and method name provided
let base = value.substring(0, period);
let method = value.substring(period + 1);
url = url + base + '.md#' + method;
linkText = '\nThis promisifies a call to the generated [' + value
+ '](' + url + ').';
} else {
// Assume it's just a class
url = url + value + '.md';
linkText = '\nThis wraps the generated [' + value + '](' + url + ').';
}
doclet.description = doclet.description + linkText;
}
});
};
| /**
* Define an esi_link tag. This is a bit of a hack but it allows us to include a
* link to a relative path (which jsdoc fails to recognize as a valid URL), and
* it doesn't require modifying a template. Additionally, by adding directly to
* the description, it works when docs are generated as markdown.
*
* This inserts a statement directing to the generated markdown documentation
* produced by swagger-codegen.
*
* @private
*/
exports.defineTags = function(dictionary) {
dictionary.defineTag('esi_link', {
mustHaveValue: true,
mustNotHaveDescription: true,
onTagged: function(doclet, tag) {
let value = tag.value;
let period = value.indexOf('.');
let url = 'https://github.com/lhkbob/eve-swagger-js/blob/master/generated/docs/';
if (period >= 0) {
// Class and method name provided
let base = value.substring(0, period);
let method = value.substring(period + 1);
url = url + base + '.md#' + method;
} else {
// Assume it's just a class
url = url + value + '.md';
}
let linkText = '\nThis promisifies a call to the generated [' + value
+ '](' + url + ').';
doclet.description = doclet.description + linkText;
}
});
};
|
Add a new row when the last visible row is deleted
since the table should always have at least one row available at
any given time | ManageIQ.angular.app.component('genericObjectTableComponent', {
bindings: {
keys: '=',
values: '=',
keyType: '@',
tableHeaders: '=',
valueOptions: '=',
noOfRows: '=',
angularForm: '=',
},
controllerAs: 'vm',
controller: genericObjectTableController,
templateUrl: '/static/generic_object/generic_object_table.html.haml',
});
genericObjectTableController.$inject = ['$timeout'];
function genericObjectTableController($timeout) {
var vm = this;
vm.$onInit = function() {
vm.tableHeaders.push('', '');
};
vm.addRow = function(_currentRow, element, fromDelete) {
vm.keys.push('');
vm.noOfRows = _.size(vm.keys);
if (!fromDelete) {
$timeout(function () {
angular.element('#' + element).focus();
}, -1);
}
};
vm.deleteRow = function(currentRow) {
_.pullAt(vm.keys, [currentRow]);
if (vm.values) {
_.pullAt(vm.values, [currentRow]);
}
vm.noOfRows = _.size(vm.keys);
if (vm.noOfRows === 0) {
vm.addRow(0, vm.keyType + '0', true);
}
};
}
| ManageIQ.angular.app.component('genericObjectTableComponent', {
bindings: {
keys: '=',
values: '=',
keyType: '@',
tableHeaders: '=',
valueOptions: '=',
noOfRows: '=',
angularForm: '=',
},
controllerAs: 'vm',
controller: genericObjectTableController,
templateUrl: '/static/generic_object/generic_object_table.html.haml',
});
genericObjectTableController.$inject = ['$timeout'];
function genericObjectTableController($timeout) {
var vm = this;
vm.$onInit = function() {
vm.tableHeaders.push('', '');
};
vm.addRow = function(_currentRow, element) {
vm.keys.push('');
vm.noOfRows = _.size(vm.keys);
$timeout(function() {
angular.element('#' + element).focus();
}, -1);
};
vm.deleteRow = function(currentRow) {
_.pullAt(vm.keys, [currentRow]);
if (vm.values) {
_.pullAt(vm.values, [currentRow]);
}
vm.noOfRows = _.size(vm.keys);
};
}
|
Ch05: Add name parameter to Tag Detail URL. | """suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from organizer.views import homepage, tag_detail
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', homepage),
url(r'^tag/(?P<slug>[\w\-]+)/$',
tag_detail,
name='organizer_tag_detail'),
]
| """suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from organizer.views import homepage, tag_detail
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', homepage),
url(r'^tag/(?P<slug>[\w\-]+)/$',
tag_detail,
),
]
|
Use send so no templates are evald by python. | # Run with `python viewer.py PATH_TO_RECORD_JSON.
import json
import sys
from flask import Flask, jsonify
from flask.helpers import send_from_directory
app = Flask(__name__)
# `main` inits these.
# File containing `record` output.
record_path = None
# 0: source, 1: state
record_data = []
@app.route("/")
def hello():
return send_from_directory('.', 'index.html')
@app.route("/source.json")
def source():
return jsonify(record_data[0])
@app.route("/state.json")
def state():
return jsonify(record_data[1])
def main():
record_path = sys.argv[1]
with open(record_path) as f:
record_data.append(json.loads(f.readline()))
record_data.append(json.loads(f.readline()))
app.run()
if __name__ == "__main__":
main()
| # Run with `python viewer.py PATH_TO_RECORD_JSON.
import json
import sys
from flask import Flask, jsonify
from flask.templating import render_template
app = Flask(__name__, template_folder='.')
# app.debug = True
# `main` inits these.
# File containing `record` output.
record_path = None
# 0: source, 1: state
record_data = []
@app.route("/")
def hello():
return render_template('index.html')
@app.route("/source.json")
def source():
return jsonify(record_data[0])
@app.route("/state.json")
def state():
return jsonify(record_data[1])
def main():
record_path = sys.argv[1]
with open(record_path) as f:
record_data.append(json.loads(f.readline()))
record_data.append(json.loads(f.readline()))
app.run()
if __name__ == "__main__":
main()
|
Add test for adding JSON-LD to guess_format()
This is a follow-on patch to:
e778e9413510721c2fedaae56d4ff826df265c30
Test was confirmed to pass by running this on the current `master`
branch, and confirmed to fail with e778e941 reverted.
nosetests test/test_parse_file_guess_format.py
Signed-off-by: Alex Nelson <d5aca716d6ed55a86fa350cb5231ca56b21085ca@nist.gov> | import unittest
import logging
from pathlib import Path
from shutil import copyfile
from tempfile import TemporaryDirectory
from rdflib.exceptions import ParserError
from rdflib import Graph
class FileParserGuessFormatTest(unittest.TestCase):
def test_jsonld(self):
g = Graph()
self.assertIsInstance(g.parse("test/jsonld/1.1/manifest.jsonld"), Graph)
def test_ttl(self):
g = Graph()
self.assertIsInstance(g.parse("test/w3c/turtle/IRI_subject.ttl"), Graph)
def test_n3(self):
g = Graph()
self.assertIsInstance(g.parse("test/n3/example-lots_of_graphs.n3"), Graph)
def test_warning(self):
g = Graph()
graph_logger = logging.getLogger("rdflib")
with TemporaryDirectory() as tmpdirname:
newpath = Path(tmpdirname).joinpath("no_file_ext")
copyfile("test/rdf/Manifest.rdf", str(newpath))
with self.assertLogs(graph_logger, "WARNING"):
with self.assertRaises(ParserError):
g.parse(str(newpath))
if __name__ == "__main__":
unittest.main()
| import unittest
import logging
from pathlib import Path
from shutil import copyfile
from tempfile import TemporaryDirectory
from rdflib.exceptions import ParserError
from rdflib import Graph
class FileParserGuessFormatTest(unittest.TestCase):
def test_ttl(self):
g = Graph()
self.assertIsInstance(g.parse("test/w3c/turtle/IRI_subject.ttl"), Graph)
def test_n3(self):
g = Graph()
self.assertIsInstance(g.parse("test/n3/example-lots_of_graphs.n3"), Graph)
def test_warning(self):
g = Graph()
graph_logger = logging.getLogger("rdflib")
with TemporaryDirectory() as tmpdirname:
newpath = Path(tmpdirname).joinpath("no_file_ext")
copyfile("test/rdf/Manifest.rdf", str(newpath))
with self.assertLogs(graph_logger, "WARNING"):
with self.assertRaises(ParserError):
g.parse(str(newpath))
if __name__ == "__main__":
unittest.main()
|
Add documentation for customising emails per channel | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\EmailManager;
use Sylius\Bundle\CoreBundle\Mailer\Emails;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;
final class ShipmentEmailManager implements ShipmentEmailManagerInterface
{
/** @var SenderInterface */
private $emailSender;
public function __construct(SenderInterface $emailSender)
{
$this->emailSender = $emailSender;
}
/**
* {@inheritdoc}
*/
public function sendConfirmationEmail(ShipmentInterface $shipment): void
{
/** @var OrderInterface $order */
$order = $shipment->getOrder();
$this->emailSender->send(Emails::SHIPMENT_CONFIRMATION, [$order->getCustomer()->getEmail()], [
'shipment' => $shipment,
'order' => $order,
'channel' => $order->getChannel(),
]);
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\EmailManager;
use Sylius\Bundle\CoreBundle\Mailer\Emails;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;
final class ShipmentEmailManager implements ShipmentEmailManagerInterface
{
/** @var SenderInterface */
private $emailSender;
public function __construct(SenderInterface $emailSender)
{
$this->emailSender = $emailSender;
}
/**
* {@inheritdoc}
*/
public function sendConfirmationEmail(ShipmentInterface $shipment): void
{
/** @var OrderInterface $order */
$order = $shipment->getOrder();
$this->emailSender->send(Emails::SHIPMENT_CONFIRMATION, [$order->getCustomer()->getEmail()], [
'shipment' => $shipment,
'order' => $order,
]);
}
}
|
Disable browser cache for builder page
This is to avoid user uses back button after logout | <?php
namespace Meot\FormBundle\Controller;
use Meot\FormBundle\Entity\Question,
Meot\FormBundle\Entity\Response,
Meot\FormBundle\Form\ResponseType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
class DefaultController extends Controller
{
/**
* @Route("/")
* @Template(engine="twig")
*/
public function indexAction()
{
return array();
}
/**
* @Route("/builder")
* @Template(engine="twig")
*/
public function builderAction()
{
// force browser not to cache the builder page so that when user logout
// and click back button, he/she will not see the previous page
header("Cache-Control: no-store, no-cache, must-revalidate");
return array();
}
}
| <?php
namespace Meot\FormBundle\Controller;
use Meot\FormBundle\Entity\Question,
Meot\FormBundle\Entity\Response,
Meot\FormBundle\Form\ResponseType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class DefaultController extends Controller
{
/**
* @Route("/")
* @Template(engine="twig")
*/
public function indexAction()
{
return array();
}
/**
* @Route("/builder")
* @Template(engine="twig")
*/
public function builderAction()
{
return array();
}
}
|
Change the text on the test | /*
* Copyright 2015 Bridje Framework.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bridje.core.ioc.test;
import org.bridje.core.ioc.ContextListener;
import org.bridje.core.ioc.annotations.Component;
@Component
public class ContextListenerDummy implements ContextListener<DummyComponent>
{
@Override
public void preCreateComponent(Class<DummyComponent> clazz)
{
System.out.println("This method is called only when DummyComponent is preCreate");
}
@Override
public void preInitComponent(Class<DummyComponent> clazz)
{
System.out.println("This method is called only when DummyComponent is preInit");
}
@Override
public void postInitComponent(Class<DummyComponent> clazz)
{
System.out.println("This method is called only when DummyComponent is postInit");
}
}
| /*
* Copyright 2015 Bridje Framework.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bridje.core.ioc.test;
import org.bridje.core.ioc.ContextListener;
import org.bridje.core.ioc.annotations.Component;
@Component
public class ContextListenerDummy implements ContextListener<DummyComponent>
{
@Override
public void preCreateComponent(Class<DummyComponent> clazz)
{
System.out.println("preCreate: " + clazz.getName());
}
@Override
public void preInitComponent(Class<DummyComponent> clazz)
{
System.out.println("preInit: " + clazz.getName());
}
@Override
public void postInitComponent(Class<DummyComponent> clazz)
{
System.out.println("postInit: " + clazz.getName());
}
}
|
Change choice_id field to choice | from django.db import models
from rest_framework import serializers
class Choice(models.Model):
text = models.CharField(max_length=255)
version = models.CharField(max_length=4)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Model):
choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
user_id = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('id', 'text', 'season', 'created_on', 'updated_on',)
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('id', 'choice_id', 'user_id', 'created_on',)
| from django.db import models
from rest_framework import serializers
class Choice(models.Model):
text = models.CharField(max_length=255)
version = models.CharField(max_length=4)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Model):
choice_id = models.ForeignKey(Choice, on_delete=models.CASCADE)
user_id = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('id', 'text', 'season', 'created_on', 'updated_on',)
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('id', 'choice_id', 'user_id', 'created_on',)
|
Fix testing error when IPython not installed | """
A print function that pretty prints SymPy objects.
:moduleauthor: Brian Granger
Usage
=====
To use this extension, execute:
%load_ext sympy.interactive.ipythonprinting
Once the extension is loaded, SymPy Basic objects are automatically
pretty-printed in the terminal and rendered in LaTeX in the Qt console and
notebook.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from sympy.interactive.printing import init_printing
#-----------------------------------------------------------------------------
# Definitions of special display functions for use with IPython
#-----------------------------------------------------------------------------
_loaded = False
def load_ipython_extension(ip):
"""Load the extension in IPython."""
import IPython
global _loaded
# Use extension manager to track loaded status if available
# This is currently in IPython 0.14.dev
if hasattr(ip.extension_manager, 'loaded'):
loaded = 'sympy.interactive.ipythonprinting' not in ip.extension_manager.loaded
else:
loaded = _loaded
if not loaded:
if isinstance(ip, IPython.frontend.terminal.interactiveshell.TerminalInteractiveShell):
init_printing(ip=ip)
else:
init_printing(use_unicode=True, use_latex=True, ip=ip)
_loaded = True
| """
A print function that pretty prints SymPy objects.
:moduleauthor: Brian Granger
Usage
=====
To use this extension, execute:
%load_ext sympy.interactive.ipythonprinting
Once the extension is loaded, SymPy Basic objects are automatically
pretty-printed in the terminal and rendered in LaTeX in the Qt console and
notebook.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import IPython
from sympy.interactive.printing import init_printing
#-----------------------------------------------------------------------------
# Definitions of special display functions for use with IPython
#-----------------------------------------------------------------------------
_loaded = False
def load_ipython_extension(ip):
"""Load the extension in IPython."""
global _loaded
# Use extension manager to track loaded status if available
# This is currently in IPython 0.14.dev
if hasattr(ip.extension_manager, 'loaded'):
loaded = 'sympy.interactive.ipythonprinting' not in ip.extension_manager.loaded
else:
loaded = _loaded
if not loaded:
if isinstance(ip, IPython.frontend.terminal.interactiveshell.TerminalInteractiveShell):
init_printing(ip=ip)
else:
init_printing(use_unicode=True, use_latex=True, ip=ip)
_loaded = True
|
Add $why var for parse exceptions.
git-svn-id: 71b65f7ff3646a85e1ba76c778efde6466075005@285075 c90b9560-bf6c-de11-be94-00142212c4b1 | <?php
/**
* PEAR2_Pyrus_ChannelRegistry_ParseException
*
* PHP version 5
*
* @category PEAR2
* @package PEAR2_Pyrus
* @author Greg Beaver <cellog@php.net>
* @copyright 2008 The PEAR Group
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id$
* @link http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
*/
/**
* Base class for Exceptions when parsing channel registry.
*
* @category PEAR2
* @package PEAR2_Pyrus
* @author Greg Beaver <cellog@php.net>
* @copyright 2008 The PEAR Group
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @link http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
*/
class PEAR2_Pyrus_ChannelRegistry_ParseException extends PEAR2_Exception
{
public $why;
function __construct($message, $why)
{
$this->why = $why;
parent::__construct($message);
}
} | <?php
/**
* PEAR2_Pyrus_ChannelRegistry_ParseException
*
* PHP version 5
*
* @category PEAR2
* @package PEAR2_Pyrus
* @author Greg Beaver <cellog@php.net>
* @copyright 2008 The PEAR Group
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id$
* @link http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
*/
/**
* Base class for Exceptions when parsing channel registry.
*
* @category PEAR2
* @package PEAR2_Pyrus
* @author Greg Beaver <cellog@php.net>
* @copyright 2008 The PEAR Group
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @link http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
*/
class PEAR2_Pyrus_ChannelRegistry_Exception extends PEAR2_Exception
{
} |
Edit wrong test that make build fail | package de.fau.amos.virtualledger.server;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.core.Response;
public class TestRestProviderTest {
private final TestRestProvider testRestProvider = new TestRestProvider();
@Test
public void helloWorld_noInput_200Status() {
//arrange
//act
final Response result = testRestProvider.helloWorld();
//assert
Assert.assertEquals(200, result.getStatus());
}
@Test
public void helloWorld_noInput_helloWorldEntity() {
//arrange
//act
final Response result = testRestProvider.helloWorld();
//assert
Assert.assertEquals("hallo!", result.getEntity());
}
}
| package de.fau.amos.virtualledger.server;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.core.Response;
public class TestRestProviderTest {
private final TestRestProvider testRestProvider = new TestRestProvider();
@Test
public void helloWorld_noInput_200Status() {
//arrange
//act
final Response result = testRestProvider.helloWorld();
//assert
Assert.assertEquals(200, result.getStatus());
}
@Test
public void helloWorld_noInput_helloWorldEntity() {
//arrange
//act
final Response result = testRestProvider.helloWorld();
//assert
Assert.assertEquals("Hello World", result.getEntity());
}
}
|
Fix leaking file descriptor in NetNs strategy
Docker-DCO-1.1-Signed-off-by: Hugo Duncan <hugo@hugoduncan.org> (github: hugoduncan) | // +build linux
package network
import (
"fmt"
"os"
"syscall"
"github.com/docker/libcontainer/system"
)
// crosbymichael: could make a network strategy that instead of returning veth pair names it returns a pid to an existing network namespace
type NetNS struct {
}
func (v *NetNS) Create(n *Network, nspid int, networkState *NetworkState) error {
networkState.NsPath = n.NsPath
return nil
}
func (v *NetNS) Initialize(config *Network, networkState *NetworkState) error {
if networkState.NsPath == "" {
return fmt.Errorf("nspath does is not specified in NetworkState")
}
f, err := os.OpenFile(networkState.NsPath, os.O_RDONLY, 0)
if err != nil {
return fmt.Errorf("failed get network namespace fd: %v", err)
}
if err := system.Setns(f.Fd(), syscall.CLONE_NEWNET); err != nil {
f.Close()
return fmt.Errorf("failed to setns current network namespace: %v", err)
}
f.Close()
return nil
}
| // +build linux
package network
import (
"fmt"
"os"
"syscall"
"github.com/docker/libcontainer/system"
)
// crosbymichael: could make a network strategy that instead of returning veth pair names it returns a pid to an existing network namespace
type NetNS struct {
}
func (v *NetNS) Create(n *Network, nspid int, networkState *NetworkState) error {
networkState.NsPath = n.NsPath
return nil
}
func (v *NetNS) Initialize(config *Network, networkState *NetworkState) error {
if networkState.NsPath == "" {
return fmt.Errorf("nspath does is not specified in NetworkState")
}
f, err := os.OpenFile(networkState.NsPath, os.O_RDONLY, 0)
if err != nil {
return fmt.Errorf("failed get network namespace fd: %v", err)
}
if err := system.Setns(f.Fd(), syscall.CLONE_NEWNET); err != nil {
return fmt.Errorf("failed to setns current network namespace: %v", err)
}
return nil
}
|
Add message command because y not? | package me.rbrickis.mojo.bukkit;
import me.rbrickis.mojo.annotations.Command;
import me.rbrickis.mojo.annotations.Default;
import me.rbrickis.mojo.annotations.Text;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ExampleCommands {
@Command(aliases = "hello")
@me.rbrickis.mojo.bukkit.annotations.Player
public void helloWorld(Player player) {
player.sendMessage(ChatColor.GOLD + "Hello, " + player.getName());
}
@Command(aliases = {"broadcast", "bc"})
public void broadcast(CommandSender sender, @Text @Default("&6Hello World!") String message) {
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', message));
}
@Command(aliases = {"message", "msg"})
public void message(Player sender, Player receiver, @Text String message) {
if (receiver == null) {
sender.sendMessage(ChatColor.RED + "Could not find player!");
} else {
receiver.sendMessage(ChatColor.GRAY + "(From " + sender.getDisplayName() + ChatColor.GRAY + "): "
+ ChatColor.WHITE + message);
}
}
}
| package me.rbrickis.mojo.bukkit;
import me.rbrickis.mojo.annotations.Command;
import me.rbrickis.mojo.annotations.Default;
import me.rbrickis.mojo.annotations.Text;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ExampleCommands {
@Command(aliases = "hello")
@me.rbrickis.mojo.bukkit.annotations.Player
public void helloWorld(Player player) {
player.sendMessage(ChatColor.GOLD + "Hello, " + player.getName());
}
@Command(aliases = {"broadcast", "bc"})
public void broadcast(CommandSender sender, @Text @Default("&6Hello World!") String message) {
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', message));
}
}
|
Enable PHPUnit exception expecting test | <?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
/**
* @covers Email
*/
final class EmailTest extends TestCase
{
public function testCanBeCreatedFromValidEmailAddress(): void
{
$this->assertInstanceOf(
Email::class,
Email::fromString('user@example.com')
);
}
public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
$this->expectException(InvalidArgumentException::class);
Email::fromString('invalid');
}
public function testCanBeUsedAsString(): void
{
$this->assertEquals(
'user@example.com',
Email::fromString('user@example.com')
);
}
}
| <?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
/**
* @covers Email
*/
final class EmailTest extends TestCase
{
public function testCanBeCreatedFromValidEmailAddress(): void
{
$this->assertInstanceOf(
Email::class,
Email::fromString('user@example.com')
);
}
// TODO: Enable when the problem with interface catching is solved
// public function testCannotBeCreatedFromInvalidEmailAddress(): void
// {
// $this->expectException(InvalidArgumentException::class);
// Email::fromString('invalid');
// }
public function testCanBeUsedAsString(): void
{
$this->assertEquals(
'user@example.com',
Email::fromString('user@example.com')
);
}
}
|
Fix applying of the custom theme object. | import React from 'react';
import lodash from 'lodash';
import refractToComponentsMap from 'refractToComponentMap';
import theme from 'theme';
class Attribute extends React.Component {
static propTypes = {
theme: React.PropTypes.object,
element: React.PropTypes.object,
expandableCollapsible: React.PropTypes.bool,
parentElement: React.PropTypes.object,
}
static childContextTypes = {
theme: React.PropTypes.object,
}
constructor(props) {
super(props);
}
getChildContext() {
return {
theme: lodash.merge(theme, this.props.theme || {}),
};
}
render() {
if (!this.props.element) {
return false;
}
const reactComponent = refractToComponentsMap[this.props.element.element];
if (typeof reactComponent === 'undefined') {
return new Error(`Unable to find a rendering component for ${this.props.element.element}`);
}
return React.createElement(reactComponent, {
element: this.props.element,
expandableCollapsible: this.props.expandableCollapsible,
parentElement: this.props.parentElement,
});
}
}
export default Attribute;
| import React from 'react';
import lodash from 'lodash';
import refractToComponentsMap from 'refractToComponentMap';
import theme from 'theme';
class Attribute extends React.Component {
static propTypes = {
theme: React.PropTypes.object,
element: React.PropTypes.object,
expandableCollapsible: React.PropTypes.bool,
parentElement: React.PropTypes.object,
}
static childContextTypes = {
theme: React.PropTypes.object,
}
constructor(props) {
super(props);
}
getChildContext() {
return {
theme: lodash.merge(this.props.theme || {}, theme),
};
}
render() {
if (!this.props.element) {
return false;
}
const reactComponent = refractToComponentsMap[this.props.element.element];
if (typeof reactComponent === 'undefined') {
return new Error(`Unable to find a rendering component for ${this.props.element.element}`);
}
return React.createElement(reactComponent, {
element: this.props.element,
expandableCollapsible: this.props.expandableCollapsible,
parentElement: this.props.parentElement,
});
}
}
export default Attribute;
|
Make devices discovered unique in example app | import * as types from '../actions/DiscoveryActionTypes';
import _ from 'lodash';
const initialState = {
devicesDiscovered: [],
discoveryStatus: "",
};
export default function discovery(state = initialState, action) {
switch (action.type) {
case types.DEVICEDISCOVERED:
return {
...state,
devicesDiscovered: _.uniq([...state.devicesDiscovered, action.device]),
};
case types.DISCOVERYSTATUSCHANGE:
return {
...state,
discoveryStatus: action.status,
};
case types.RESETDEVICES:
return {
...state,
devicesDiscovered: [],
};
default:
return state;
}
}
| import * as types from '../actions/DiscoveryActionTypes';
const initialState = {
devicesDiscovered: [],
discoveryStatus: "",
};
export default function discovery(state = initialState, action) {
switch (action.type) {
case types.DEVICEDISCOVERED:
return {
...state,
devicesDiscovered: [...state.devicesDiscovered, action.device]
};
case types.DISCOVERYSTATUSCHANGE:
return {
...state,
discoveryStatus: action.status,
};
case types.RESETDEVICES:
return {
...state,
devicesDiscovered: [],
};
default:
return state;
}
}
|
Fix possible mix of ProxyFactory instances. | /*
* Created on 04-Feb-2004
*
* (c) 2003-2004 ThoughtWorks
*
* See license.txt for licence details
*/
package com.thoughtworks.proxy.toys.delegate;
import com.thoughtworks.proxy.ProxyFactory;
import com.thoughtworks.proxy.factory.StandardProxyFactory;
/**
* @author <a href="mailto:dan.north@thoughtworks.com">Dan North</a>
*/
public class Delegating {
/** delegate must implement the method's interface */
public static final boolean STATIC_TYPING = DelegatingInvoker.EXACT_METHOD;
/** delegate must have method with matching signature - not necessarily the same */
public static final boolean DYNAMIC_TYPING = DelegatingInvoker.SAME_SIGNATURE_METHOD;
public static Object object(Class type, Object delegate) {
return object(type, delegate, new StandardProxyFactory());
}
public static Object object(Class type, Object delegate, ProxyFactory factory) {
return factory.createProxy(
new Class[] {type},
new DelegatingInvoker(factory, new SimpleReference(delegate), DYNAMIC_TYPING));
}
/** It's a factory, stupid */
private Delegating(){}
}
| /*
* Created on 04-Feb-2004
*
* (c) 2003-2004 ThoughtWorks
*
* See license.txt for licence details
*/
package com.thoughtworks.proxy.toys.delegate;
import com.thoughtworks.proxy.ProxyFactory;
import com.thoughtworks.proxy.factory.StandardProxyFactory;
/**
* @author <a href="mailto:dan.north@thoughtworks.com">Dan North</a>
*/
public class Delegating {
/** delegate must implement the method's interface */
public static final boolean STATIC_TYPING = DelegatingInvoker.EXACT_METHOD;
/** delegate must have method with matching signature - not necessarily the same */
public static final boolean DYNAMIC_TYPING = DelegatingInvoker.SAME_SIGNATURE_METHOD;
public static Object object(Class type, Object delegate) {
return object(type, delegate, new StandardProxyFactory());
}
public static Object object(Class type, Object delegate, ProxyFactory factory) {
return factory.createProxy(new Class[] {type}, new DelegatingInvoker(delegate));
}
/** It's a factory, stupid */
private Delegating(){}
}
|
Make HTTP method of custom routing and URL redirection case insensitive | import { join } from 'path';
import Router from 'express/lib/router';
import cookieMiddleware from 'universal-cookie-express';
import createLocaleMiddleware from './createLocaleMiddleware';
const defaultOptions = {
routes: {},
redirects: [],
};
export default (app, {
routes = defaultOptions.routes,
redirects = defaultOptions.redirects,
defaultLocale,
siteLocales,
compression,
} = defaultOptions) => {
const router = Router();
const handle = app.getRequestHandler();
if (!app.dev) {
router.use(require('compression')(compression));
}
router.use(cookieMiddleware());
if (defaultLocale && siteLocales) {
router.use(createLocaleMiddleware({ defaultLocale, siteLocales }));
}
router.get('/_soya/:path(*)', async (req, res) => {
const p = join(app.dir, app.dist, 'dist', 'static', req.params.path);
await app.serveStatic(req, res, p);
});
redirects.forEach(({ from, to, method = 'GET', type = 301 }) => {
router[method.toLowerCase()](from, (req, res) => res.redirect(type, to));
});
Object.keys(routes).forEach(path => {
const { method = 'GET', page } = routes[path];
router[method.toLowerCase()](path, (req, res) => {
app.render(req, res, page, Object.assign({}, req.query, req.params));
});
});
router.get('*', (req, res) => handle(req, res));
return router;
};
| import { join } from 'path';
import Router from 'express/lib/router';
import cookieMiddleware from 'universal-cookie-express';
import createLocaleMiddleware from './createLocaleMiddleware';
const defaultOptions = {
routes: {},
redirects: [],
};
export default (app, {
routes = defaultOptions.routes,
redirects = defaultOptions.redirects,
defaultLocale,
siteLocales,
compression,
} = defaultOptions) => {
const router = Router();
const handle = app.getRequestHandler();
if (!app.dev) {
router.use(require('compression')(compression));
}
router.use(cookieMiddleware());
if (defaultLocale && siteLocales) {
router.use(createLocaleMiddleware({ defaultLocale, siteLocales }));
}
router.get('/_soya/:path(*)', async (req, res) => {
const p = join(app.dir, app.dist, 'dist', 'static', req.params.path);
await app.serveStatic(req, res, p);
});
redirects.forEach(({ from, to, method = 'get', type = 301 }) => {
router[method](from, (req, res) => res.redirect(type, to));
});
Object.keys(routes).forEach(path => {
const { method = 'get', page } = routes[path];
router[method](path, (req, res) => {
app.render(req, res, page, Object.assign({}, req.query, req.params));
});
});
router.get('*', (req, res) => handle(req, res));
return router;
};
|
Check if the exact item already exists, and don't correct it. | package Debrief.Wrappers.Track;
import java.util.Enumeration;
import Debrief.Wrappers.FixWrapper;
import MWC.GUI.Editable;
import MWC.GUI.Plottables;
import MWC.GenericData.HiResDate;
public class FixWrapperCollisionCheck {
/**
* We are creating this method because the following ticket
* https://github.com/debrief/debrief/issues/4894
*
* FixWrapper were initially adding with a +1 time delay to avoid collisions.
*
* Collision check modifies the time in the fixWrapper given to adapt it to
* avoid collision.
*
* @param _fixWrapper FixWrapper to modify
* @param _currentPlotables List of all the Editables
*/
public static void correctTimeCollision(final FixWrapper _fixWrapper, final Plottables _currentPlotables) {
long timeToAdd = _fixWrapper.getTime().getMicros();
// First check if the exact instance is the list.
final Enumeration<Editable> elementsEnum = _currentPlotables.elements();
while (elementsEnum.hasMoreElements()) {
if (elementsEnum.nextElement() == _fixWrapper) {
// We have found it.
return;
}
}
while (_currentPlotables.contains(_fixWrapper)) {
timeToAdd += 1000; // add 1 second
_fixWrapper.getFix().setTime(new HiResDate(timeToAdd / 1000L));
}
}
}
| package Debrief.Wrappers.Track;
import Debrief.Wrappers.FixWrapper;
import MWC.GUI.Plottables;
import MWC.GenericData.HiResDate;
public class FixWrapperCollisionCheck {
/**
* We are creating this method because the following ticket
* https://github.com/debrief/debrief/issues/4894
*
* FixWrapper were initially adding with a +1 time delay to avoid collisions.
*
* Collision check modifies the time in the fixWrapper given to adapt it to
* avoid collision.
*
* @param _fixWrapper FixWrapper to modify
* @param _currentPlotables List of all the Editables
*/
public static void correctTimeCollision(final FixWrapper _fixWrapper, final Plottables _currentPlotables) {
long timeToAdd = _fixWrapper.getTime().getMicros();
while (_currentPlotables.contains(_fixWrapper)) {
timeToAdd += 1000; // add 1 second
_fixWrapper.getFix().setTime(new HiResDate(timeToAdd / 1000L));
}
}
}
|
Set python classifiers to py34 | import setuptools
setuptools.setup(
name="inidiff",
version="0.1.0",
url="https://github.com/kragniz/inidiff",
author="Louis Taylor",
author_email="louis@kragniz.eu",
description="Find the differences between two ini config files",
long_description=open('README.rst').read(),
packages=setuptools.find_packages(),
install_requires=[
'six',
'ordered-set'
],
entry_points = {
'console_scripts': ['inidiff=inidiff:main'],
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
| import setuptools
setuptools.setup(
name="inidiff",
version="0.1.0",
url="https://github.com/kragniz/inidiff",
author="Louis Taylor",
author_email="louis@kragniz.eu",
description="Find the differences between two ini config files",
long_description=open('README.rst').read(),
packages=setuptools.find_packages(),
install_requires=[
'six',
'ordered-set'
],
entry_points = {
'console_scripts': ['inidiff=inidiff:main'],
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
Make the springCacheRegionFactoryBeanPostProcessor bean definition static so CacheManager beans are eligible for getting processed by all BeanPostProcessors | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package com.integralblue.hibernate.cache.springcache;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnProperty(name="spring.jpa.properties.hibernate.cache.region.factory_class", havingValue="com.integralblue.hibernate.cache.springcache.SpringCacheRegionFactory")
public class SpringCacheRegionFactoryAutoConfigure {
@Bean
protected static SpringCacheRegionFactoryBeanPostProcessor springCacheRegionFactoryBeanPostProcessor(){
return new SpringCacheRegionFactoryBeanPostProcessor();
}
}
| /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package com.integralblue.hibernate.cache.springcache;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnProperty(name="spring.jpa.properties.hibernate.cache.region.factory_class", havingValue="com.integralblue.hibernate.cache.springcache.SpringCacheRegionFactory")
public class SpringCacheRegionFactoryAutoConfigure {
@Bean
protected SpringCacheRegionFactoryBeanPostProcessor springCacheRegionFactoryBeanPostProcessor(){
return new SpringCacheRegionFactoryBeanPostProcessor();
}
}
|
Mark package as a stable | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A LMTP server class',
'long_description': 'A LMTP counterpart to smtpd in the Python standard library',
'author': 'Matt Molyneaux',
'url': 'https://github.com/moggers87/lmtpd',
'download_url': 'http://pypi.python.org/pypi/lmtpd',
'author_email': 'moggers87+git@moggers87.co.uk',
'version': '6.1.0',
'license': 'MIT', # apparently nothing searches classifiers :(
'packages': ['lmtpd'],
'data_files': [('share/lmtpd', ['LICENSE', 'PY-LIC'])],
'name': 'lmtpd',
'classifiers': [
'License :: OSI Approved :: MIT License',
'License :: OSI Approved :: Python Software Foundation License',
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Intended Audience :: Developers',
'Topic :: Communications :: Email'],
'test_suite': 'lmtpd.tests'
}
setup(**config)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A LMTP server class',
'long_description': 'A LMTP counterpart to smtpd in the Python standard library',
'author': 'Matt Molyneaux',
'url': 'https://github.com/moggers87/lmtpd',
'download_url': 'http://pypi.python.org/pypi/lmtpd',
'author_email': 'moggers87+git@moggers87.co.uk',
'version': '6.1.0',
'license': 'MIT', # apparently nothing searches classifiers :(
'packages': ['lmtpd'],
'data_files': [('share/lmtpd', ['LICENSE', 'PY-LIC'])],
'name': 'lmtpd',
'classifiers': [
'License :: OSI Approved :: MIT License',
'License :: OSI Approved :: Python Software Foundation License',
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Intended Audience :: Developers',
'Topic :: Communications :: Email'],
'test_suite': 'lmtpd.tests'
}
setup(**config)
|
Increment version after fix to frozendict version | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis-metadata-parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.6',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict==1.2', 'parserutils>=1.2.3', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
| import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis-metadata-parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.5',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict==1.2', 'parserutils>=1.2.3', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
Fix mapping for codon keys for Serine | # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UAA, UAG, UGA | STOP
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
| # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCC, UCC | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UAA, UAG, UGA | STOP
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCC": "Serine",
"UCC": "Serine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
|
Update Server back to local | var Backbone = require('backbone');
module.exports = Backbone.Model.extend({
defaults: {
beenSet: true, //set this back to false when done testing
guid: "8f9c3e25c0e196647f83fa704a59c6b76f15b686", //for testing with test server only
name: "Your Name",
handle: "Blockchain ID",
avatar_hash: "",
tempAvatar: "",
bitcoinAddress: "",
currency: "US Dollar",
currencyCode: "USD",
country: "UNITED_STATES", //set to blank when done testing //this is the country code, like UNITED_STATES
language: "en",
timeZome: "",
notifications: true,
shipToName: "",
shipToStreet: "",
shipToCity: "",
shipToState: "",
shipToPostalCode: "",
shipToCountry: "",
blocked: ["handle1", "handle2", "handle3"],
libbitcoinServer: "",
SSL: false,
seedPhrase: "",
server: "http://localhost:18469/api/v1/"
//values below for testing. Real value should be dynamically set
//server: "http://seed.openbazaar.org:18469/api/v1/"
//server: "http://bitcoinauthenticator.org:18469/api/v1/"
}
});
| var Backbone = require('backbone');
module.exports = Backbone.Model.extend({
defaults: {
beenSet: true, //set this back to false when done testing
guid: "8f9c3e25c0e196647f83fa704a59c6b76f15b686", //for testing with test server only
name: "Your Name",
handle: "Blockchain ID",
avatar_hash: "",
tempAvatar: "",
bitcoinAddress: "",
currency: "US Dollar",
currencyCode: "USD",
country: "UNITED_STATES", //set to blank when done testing //this is the country code, like UNITED_STATES
language: "en",
timeZome: "",
notifications: true,
shipToName: "",
shipToStreet: "",
shipToCity: "",
shipToState: "",
shipToPostalCode: "",
shipToCountry: "",
blocked: ["handle1", "handle2", "handle3"],
libbitcoinServer: "",
SSL: false,
seedPhrase: "",
//server: "http://localhost:18469/api/v1/"
//values below for testing. Real value should be dynamically set
server: "http://seed.openbazaar.org:18469/api/v1/"
//server: "http://bitcoinauthenticator.org:18469/api/v1/"
}
});
|
Include swagger definition in the implementation | package org.mskcc.cbio.oncokb.api.pub.v1;
import io.swagger.annotations.ApiParam;
import org.mskcc.cbio.oncokb.model.Geneset;
import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* Created by Hongxin Zhang on 2019-08-09.
*/
@Controller
public class GenesetsApiController implements GenesetsApi {
@Override
public ResponseEntity<List<Geneset>> genesetsGet() {
return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findAll(), HttpStatus.OK);
}
@Override
public ResponseEntity<Geneset> genesetsIdGet(
@ApiParam(value = "Geneset ID", required = true) @PathVariable(value = "id") Integer id
) {
return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findGenesetById(id), HttpStatus.OK);
}
}
| package org.mskcc.cbio.oncokb.api.pub.v1;
import org.mskcc.cbio.oncokb.model.Geneset;
import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import java.util.List;
/**
* Created by Hongxin Zhang on 2019-08-09.
*/
@Controller
public class GenesetsApiController implements GenesetsApi {
@Override
public ResponseEntity<List<Geneset>> genesetsGet() {
return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findAll(), HttpStatus.OK);
}
@Override
public ResponseEntity<Geneset> genesetsIdGet(Integer id) {
return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findGenesetById(id), HttpStatus.OK);
}
}
|
Fix format issue with `__repr__` | import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(str, enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
class Upload(Base):
__tablename__ = "uploads"
id = Column(Integer, primary_key=True)
created_at = Column(DateTime)
name = Column(String)
name_on_disk = Column(String, unique=True)
ready = Column(Boolean)
removed = Column(Boolean)
removed_at = Column(DateTime)
reserved = Column(Boolean)
size = Column(Integer)
type = Column(Enum(UploadType))
user = Column(String)
uploaded_at = Column(DateTime)
def __repr__(self):
return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \
f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \
f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \
f"uploaded_at={self.uploaded_at})>"
| import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(str, enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
class Upload(Base):
__tablename__ = "uploads"
id = Column(Integer, primary_key=True)
created_at = Column(DateTime)
name = Column(String)
name_on_disk = Column(String, unique=True)
ready = Column(Boolean)
removed = Column(Boolean)
removed_at = Column(DateTime)
reserved = Column(Boolean)
size = Column(Integer)
type = Column(Enum(UploadType))
user = Column(String)
uploaded_at = Column(DateTime)
def __repr__(self):
return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \
f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \
f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \
f"uploaded_at={self.uploaded_at}>"
|
Add type switch evaluation example | package main
import "fmt"
func main() {
for _, wolf := range WolfEnumValues() {
fmt.Println("Enum value: ", wolf)
}
ev1 := Wolf1{}.New()
ev2 := Wolf2{}.New()
if ev1 != ev2 {
fmt.Println(ev1, " differs from ", ev2)
} else {
fmt.Println(ev1, " is the same as ", ev2)
}
ev1 = Wolf3{}.New()
ev2 = Wolf3{}.New()
if ev1 != ev2 {
fmt.Println(ev1, " differs from ", ev2)
} else {
fmt.Println(ev1, " is the same as ", ev2)
}
ev1 = NewWolfFromValue(1)
if ev1 == nil {
panic("could not create wolf!")
}
ev2 = Wolf2{}.New()
if ev1 != ev2 {
fmt.Println(ev1, " differs from ", ev2)
} else {
fmt.Println(ev1, " is the same as ", ev2)
}
ev1 = NewWolfFromValue(100)
if ev1 != nil {
panic("imaginary wolf created!")
}
// example of safer evaluation with a type switch
// loop will pick only odd wolfs
for _, wolf := range WolfEnumValues() {
switch wolf.(type) {
case Wolf1, Wolf3:
fmt.Println("Found an odd wolf:", wolf)
default:
// ignore all other wolves
}
}
}
| package main
import "fmt"
func main() {
for _, ev := range WolfEnumValues() {
fmt.Println("Enum value: ", ev)
}
ev1 := Wolf1{}.New()
ev2 := Wolf2{}.New()
if ev1 != ev2 {
fmt.Println(ev1, " differs from ", ev2)
} else {
fmt.Println(ev1, " is the same as ", ev2)
}
ev1 = Wolf3{}.New()
ev2 = Wolf3{}.New()
if ev1 != ev2 {
fmt.Println(ev1, " differs from ", ev2)
} else {
fmt.Println(ev1, " is the same as ", ev2)
}
ev1 = NewWolfFromValue(1)
if ev1 == nil {
panic("could not create wolf!")
}
ev2 = Wolf2{}.New()
if ev1 != ev2 {
fmt.Println(ev1, " differs from ", ev2)
} else {
fmt.Println(ev1, " is the same as ", ev2)
}
ev1 = NewWolfFromValue(100)
if ev1 != nil {
panic("imaginary wolf created!")
}
}
|
Fix leaked mmap storage in test | //go:build !wasm
// +build !wasm
package torrent
import (
"io"
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/time/rate"
"github.com/anacrolix/torrent/internal/testutil"
"github.com/anacrolix/torrent/storage"
)
func TestDropTorrentWithMmapStorageWhileHashing(t *testing.T) {
cfg := TestingConfig(t)
// Ensure the data is present when the torrent is added, and not obtained
// over the network as the test runs.
cfg.DownloadRateLimiter = rate.NewLimiter(0, 0)
cl, err := NewClient(cfg)
require.NoError(t, err)
defer cl.Close()
td, mi := testutil.GreetingTestTorrent()
mms := storage.NewMMap(td)
defer mms.Close()
tt, new, err := cl.AddTorrentSpec(&TorrentSpec{
Storage: mms,
InfoHash: mi.HashInfoBytes(),
InfoBytes: mi.InfoBytes,
})
require.NoError(t, err)
assert.True(t, new)
r := tt.NewReader()
go tt.Drop()
io.Copy(ioutil.Discard, r)
}
| //go:build !wasm
// +build !wasm
package torrent
import (
"io"
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/time/rate"
"github.com/anacrolix/torrent/internal/testutil"
"github.com/anacrolix/torrent/storage"
)
func TestDropTorrentWithMmapStorageWhileHashing(t *testing.T) {
cfg := TestingConfig(t)
// Ensure the data is present when the torrent is added, and not obtained
// over the network as the test runs.
cfg.DownloadRateLimiter = rate.NewLimiter(0, 0)
cl, err := NewClient(cfg)
require.NoError(t, err)
defer cl.Close()
td, mi := testutil.GreetingTestTorrent()
tt, new, err := cl.AddTorrentSpec(&TorrentSpec{
Storage: storage.NewMMap(td),
InfoHash: mi.HashInfoBytes(),
InfoBytes: mi.InfoBytes,
})
require.NoError(t, err)
assert.True(t, new)
r := tt.NewReader()
go tt.Drop()
io.Copy(ioutil.Discard, r)
}
|
Fix package name in doc. | // Package tor supplies helper functions to start a tor binary as a slave process.
package tor
import (
"os/exec"
// "bufio"
// "regexp"
)
// Cmd represents an tor executable to be run as a slave process.
type Cmd struct {
Config *Config
Cmd *exec.Cmd // TODO: We probably shouldn't expose the exec.Cmd
}
// NewCmd returns a Cmd to run a tor process using the configuration values in config.
// The argument path is the path to the tor program to be run. If path is the empty string,
// $PATH is used to search for a tor executable.
func NewCmd(path string, config *Config) (*Cmd, error) {
if path == "" {
file, err := exec.LookPath("tor")
if err != nil {
return nil, err
}
path = file
}
return &Cmd{Config: config, Cmd: exec.Command(path, config.ToCmdLineFormat()...)}, nil
}
func (c *Cmd) Start() error {
err := c.Cmd.Start()
if err != nil {
return err
}
// TODO: read output until one gets a "Bootstrapped 100%: Done" notice.
return nil
}
func (c *Cmd) Wait() error {
return c.Cmd.Wait()
}
| // Package process supplies helper functions to start a tor binary as a slave process.
package tor
import (
"os/exec"
// "bufio"
// "regexp"
)
// Cmd represents an tor executable to be run as a slave process.
type Cmd struct {
Config *Config
Cmd *exec.Cmd // TODO: We probably shouldn't expose the exec.Cmd
}
// NewCmd returns a Cmd to run a tor process using the configuration values in config.
// The argument path is the path to the tor program to be run. If path is the empty string,
// $PATH is used to search for a tor executable.
func NewCmd(path string, config *Config) (*Cmd, error) {
if path == "" {
file, err := exec.LookPath("tor")
if err != nil {
return nil, err
}
path = file
}
return &Cmd{Config: config, Cmd: exec.Command(path, config.ToCmdLineFormat()...)}, nil
}
func (c *Cmd) Start() error {
err := c.Cmd.Start()
if err != nil {
return err
}
// TODO: read output until one gets a "Bootstrapped 100%: Done" notice.
return nil
}
func (c *Cmd) Wait() error {
return c.Cmd.Wait()
}
|
Revert "Clean up a bit"
This reverts commit 4500b571e2fd7a35cf722c3c9cc2fab7ea942cba. | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User, Group
from django.contrib import admin
from gmmp.models import Monitor
from forms.admin import (
RadioSheetAdmin, TwitterSheetAdmin, InternetNewsSheetAdmin,
NewspaperSheetAdmin, TelevisionSheetAdmin)
from forms.models import (
RadioSheet, TwitterSheet, InternetNewsSheet, NewspaperSheet,
TelevisionSheet)
from sheets import (radio_sheets, twitter_sheets, internetnews_sheets,
newspaper_sheets, television_sheets)
sheet_types = [
(RadioSheet, RadioSheetAdmin, radio_sheets),
(TwitterSheet, TwitterSheetAdmin, twitter_sheets),
(InternetnewsSheet, InternetNewsSheetAdmin, internetnews_sheets),
(NewspaperSheet, NewspaperSheetAdmin, newspaper_sheets),
(TelevisionSheet, TelevisionSheetAdmin, television_sheets)
]
class Command(BaseCommand):
def handle(self, *args, **options):
for model, model_admin, sheet_monitor_list in sheet_types:
admin_obj =model_admin(model, admin.site)
for sheet_id, monitor_id in sheet_monitor_list:
user = User.objects.get(monitor__id=monitor_id)
sheet_obj = model.objects.get(id=sheet_id)
admin_obj.assign_permissions(user, sheet_obj)
| from django.core.management.base import BaseCommand
from django.contrib.auth.models import User, Group
from django.contrib import admin
from gmmp.models import Monitor
from forms.admin import (
RadioSheetAdmin, TwitterSheetAdmin, InternetNewsSheetAdmin,
NewspaperSheetAdmin, TelevisionSheetAdmin)
from forms.models import (
RadioSheet, TwitterSheet, InternetNewsSheet, NewspaperSheet,
TelevisionSheet)
from sheets import (radio_sheets, twitter_sheets, internetnews_sheets,
newspaper_sheets, television_sheets)
class Command(BaseCommand):
def handle(self, *args, **options):
sheet_types = [
(RadioSheet, RadioSheetAdmin, radio_sheets),
(TwitterSheet, TwitterSheetAdmin, twitter_sheets),
(InternetnewsSheet, InternetNewsSheetAdmin, internetnews_sheets),
(NewspaperSheet, NewspaperSheetAdmin, newspaper_sheets),
(TelevisionSheet, TelevisionSheetAdmin, television_sheets)
]
for model, model_admin, sheet_monitor_list in sheet_types:
admin_obj =model_admin(model, admin.site)
for sheet_id, monitor_id in sheet_monitor_list:
user = User.objects.get(monitor__id=monitor_id)
sheet_obj = model.objects.get(id=sheet_id)
admin_obj.assign_permissions(user, sheet_obj)
|
Resolve deprecation warning for React Router 2.0 | import App from '../containers/App'
function createRedirect(from, to) {
return {
path: from,
onEnter(nextState, replace) {
replace({ pathname: to, state: nextState })
},
}
}
const routes = [
createRedirect('/', '/explore'),
{
path: '/',
component: App,
// order matters, so less specific routes should go at the bottom
childRoutes: [
require('./post_detail').default,
...require('./authentication').default,
...require('./discover').default,
...require('./streams').default,
require('./notifications').default,
...require('./invitations').default,
...require('./settings').default,
...require('./invitations').default,
createRedirect('onboarding', '/onboarding/communities'),
require('./onboarding').default,
...require('./search').default,
require('./user_detail').default,
],
},
]
export default routes
| import App from '../containers/App'
function createRedirect(from, to) {
return {
path: from,
onEnter(nextState, replaceState) {
replaceState(nextState, to)
},
}
}
const routes = [
createRedirect('/', '/explore'),
{
path: '/',
component: App,
// order matters, so less specific routes should go at the bottom
childRoutes: [
require('./post_detail').default,
...require('./authentication').default,
...require('./discover').default,
...require('./streams').default,
require('./notifications').default,
...require('./invitations').default,
...require('./settings').default,
...require('./invitations').default,
createRedirect('onboarding', '/onboarding/communities'),
require('./onboarding').default,
...require('./search').default,
require('./user_detail').default,
],
},
]
export default routes
|
Use injected Imagick instance for loading | <?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace Imbo\Image\Loader;
/**
* Basic image loader / fallback image loader
*
* @author Mats Lindh <mats@lindh.no>
* @package Image\Loaders
*/
class Basic implements LoaderInterface {
public function getMimeTypeCallbacks() {
return [
'image/png' => [
'extension' => 'png',
'callback' => [$this, 'load'],
],
'image/jpeg' => [
'extension' => 'jpg',
'callback' => [$this, 'load'],
],
'image/gif' => [
'extension' => 'gif',
'callback' => [$this, 'load'],
],
];
}
public function load($imagick, $blob) {
$imagick->readImageBlob($blob);
return $imagick;
}
} | <?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace Imbo\Image\Loader;
/**
* Basic image loader / fallback image loader
*
* @author Mats Lindh <mats@lindh.no>
* @package Image\Loaders
*/
class Basic implements LoaderInterface {
public function getMimeTypeCallbacks() {
return [
'image/png' => [
'extension' => 'png',
'callback' => [$this, 'load'],
],
'image/jpeg' => [
'extension' => 'jpg',
'callback' => [$this, 'load'],
],
'image/gif' => [
'extension' => 'gif',
'callback' => [$this, 'load'],
],
];
}
public function load($blob) {
$imagick = new \Imagick();
$imagick->readImageBlob($blob);
return $imagick;
}
} |
Delete `requires` and `wxPython` dependency
`wxPython` is not easily installable via pip on all Linux distributions without explicitly providing the path to the wheel, yet.
`requires` is obsolete, because of the use of `install_requires` | from setuptools import setup, find_packages
import os
scriptnames = ['runElegant.sh',
'sddsprintdata.sh',
'renametolower.sh',
'file2lower.sh',
'lte2json',
'json2lte',
'latticeviewer',
'lv']
def readme():
with open('README.rst') as f:
return f.read()
requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics']
setup(
name = "beamline",
version = "1.3.6",
description = "online model package for electron accelerator",
long_description = readme() + '\n\n',
author = "Tong Zhang",
author_email = "warriorlance@gmail.com",
platforms = ["Linux"],
license = "MIT",
packages = find_packages(),
url = "http://archman.github.io/beamline/",
scripts = [os.path.join('scripts',sn) for sn in scriptnames],
install_requires = requiredpackages,
extras_require = {'sdds': ['sddswhl']},
)
| from setuptools import setup, find_packages
import os
scriptnames = ['runElegant.sh',
'sddsprintdata.sh',
'renametolower.sh',
'file2lower.sh',
'lte2json',
'json2lte',
'latticeviewer',
'lv']
def readme():
with open('README.rst') as f:
return f.read()
requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics', 'wxPython']
setup(
name = "beamline",
version = "1.3.6",
description = "online model package for electron accelerator",
long_description = readme() + '\n\n',
author = "Tong Zhang",
author_email = "warriorlance@gmail.com",
platforms = ["Linux"],
license = "MIT",
packages = find_packages(),
url = "http://archman.github.io/beamline/",
scripts = [os.path.join('scripts',sn) for sn in scriptnames],
requires = requiredpackages,
install_requires = requiredpackages,
extras_require = {'sdds': ['sddswhl']},
)
|
Set version to mercurial in trunk | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import os.path
__version__ = 'mercurial'
package_dir = os.path.abspath(os.path.dirname(__file__))
def embed(locals_=None, args=['-i', '-q'], banner=None):
from bpython.cli import main
return main(args, locals_, banner)
| # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import os.path
__version__ = '0.11'
package_dir = os.path.abspath(os.path.dirname(__file__))
def embed(locals_=None, args=['-i', '-q'], banner=None):
from bpython.cli import main
return main(args, locals_, banner)
|
Remove var declaration from abstract base class | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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.
#
# Requires Python 2.7+
#
from collections import namedtuple
class OSEncryptionState(object):
def __init__(self, context):
super(OSEncryptionState, self).__init__()
def enter(self):
assert 0, "implement enter"
def should_exit(self):
assert 0, "implement should_exit"
OSEncryptionStateContext = namedtuple('OSEncryptionStateContext',
['hutil',
'distro_patcher',
'logger',
'encryption_environment'])
| #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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.
#
# Requires Python 2.7+
#
from collections import namedtuple
class OSEncryptionState(object):
def __init__(self, context):
super(OSEncryptionState, self).__init__()
self.state_executed = False
def enter(self):
assert 0, "implement enter"
def should_exit(self):
assert 0, "implement should_exit"
OSEncryptionStateContext = namedtuple('OSEncryptionStateContext',
['hutil',
'distro_patcher',
'logger',
'encryption_environment'])
|
Use "done" helper to marke the process finished | var chai = require('chai'),
runSequence = require('run-sequence');
chai.config.includeStack = true;
global.expect = chai.expect;
global.AssertionError = chai.AssertionError;
global.Assertion = chai.Assertion;
global.assert = chai.assert;
var styleguide = require("../lib/styleguide.js");
var gulp = require('gulp');
gulp.task("testStyleguide", function(done, cb) {
return gulp.src(["./demo/source/**/*.scss"])
.pipe(styleguide({
outputPath: "./demo/tmp",
overviewPath: "./demo/source/overview.md",
extraHead: [
"<link rel=\"stylesheet\" type=\"text/css\" href=\"your/custom/style.css\">",
"<script src=\"your/custom/script.js\"></script>"
],
sass: {
// Options passed to gulp-ruby-sass
},
}))
});
describe('structure', function() {
it('test', function(done) {
runSequence("testStyleguide", function() {
done()
});
})
})
| var chai = require('chai');
chai.config.includeStack = true;
global.expect = chai.expect;
global.AssertionError = chai.AssertionError;
global.Assertion = chai.Assertion;
global.assert = chai.assert;
var styleguide = require("../lib/styleguide.js");
var gulp = require('gulp');
gulp.task("testStyleguide", function() {
return gulp.src(["./demo/source/**/*.scss"])
.pipe(styleguide({
outputPath: "./demo/tmp",
overviewPath: "./demo/source/overview.md",
extraHead: [
"<link rel=\"stylesheet\" type=\"text/css\" href=\"your/custom/style.css\">",
"<script src=\"your/custom/script.js\"></script>"
],
sass: {
// Options passed to gulp-ruby-sass
},
}));
});
describe('structure', function() {
it('test', function() {
gulp.tasks.testStyleguide.fn();
})
})
|
Set Autonomous to maintain its 3 second delay for shooter lowering. | package com.edinarobotics.zeke.commands;
import com.edinarobotics.zeke.subsystems.Collector;
import com.edinarobotics.zeke.subsystems.Shooter;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.StartCommand;
public class ShootingSequenceCommand extends CommandGroup {
public ShootingSequenceCommand(boolean lowerAfterShoot) {
this.setInterruptible(false);
this.addSequential(new SetCollectorCommand(Collector.CollectorState.RETRACTED,
Collector.CollectorWheelState.STOPPED));
this.addSequential(new WaitForCollectorUndeployedCommand());
this.addSequential(new SetShooterCommand(Shooter.WinchState.FREE));
if(lowerAfterShoot) {
this.addSequential(new StartCommand(new LowerShooterAfterWaitCommand(3)));
}
}
}
| package com.edinarobotics.zeke.commands;
import com.edinarobotics.zeke.subsystems.Collector;
import com.edinarobotics.zeke.subsystems.Shooter;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.StartCommand;
public class ShootingSequenceCommand extends CommandGroup {
public ShootingSequenceCommand(boolean lowerAfterShoot) {
this.setInterruptible(false);
this.addSequential(new SetCollectorCommand(Collector.CollectorState.RETRACTED,
Collector.CollectorWheelState.STOPPED));
this.addSequential(new WaitForCollectorUndeployedCommand());
this.addSequential(new SetShooterCommand(Shooter.WinchState.FREE));
if(lowerAfterShoot) {
this.addSequential(new StartCommand(new LowerShooterAfterWaitCommand()));
}
}
}
|
Add condition to only launch client if -c or --client is specified | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import update
from arguments import parse
from settings import HONEYPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfhclient_process",
target=mfhclient.main,
)
if args.client is not None:
mfhclient_process.start()
trigger_process = Process(
args=(update_event,),
name="trigger_process",
target=update.trigger,
)
trigger_process.start()
trigger_process.join()
while mfhclient_process.is_alive():
time.sleep(5)
else:
update.pull("origin", "master")
sys.stdout.flush()
os.execl(sys.executable, sys.executable, *sys.argv)
if __name__ == '__main__':
# Parse arguments
args = parse()
if args.c:
args.client = HONEYPORT
main()
| import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import update
from arguments import parse
def main():
q = Event()
mfhclient_process = Process(
args=(args, q,),
name="mfhclient_process",
target=mfhclient.main,
)
mfhclient_process.start()
trigger_process = Process(
args=(q,),
name="trigger_process",
target=update.trigger,
)
trigger_process.start()
trigger_process.join()
while mfhclient_process.is_alive():
time.sleep(5)
else:
update.pull("origin", "master")
sys.stdout.flush()
os.execl(sys.executable, sys.executable, *sys.argv)
if __name__ == '__main__':
# Parse arguments
args = parse()
main()
|
Fix Gulp not watching subdirectories of client | var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var nodemon = require('nodemon');
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
gulp.task('compile-js', function() {
return browserify('client/main.js')
.transform(babelify)
.bundle()
.pipe(source('scripts.min.js'))
.pipe(buffer())
.pipe(gulpif(process.env.NODE_ENV === 'production', uglify()))
.pipe(gulp.dest('public'))
}
);
gulp.task('server', ['compile-js'], function() {
browserSync.create().init({
files: ['public/**'],
port: 3001,
proxy: 'http://localhost:3000',
ui: { port: 3002 },
open: false,
});
gulp.watch(['client/**/*.js'], ['compile-js']);
return nodemon({
script: 'server/index.js',
env: { 'NODE_ENV': 'development' },
watch: ['server/**/*'],
});
});
| var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var nodemon = require('nodemon');
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
gulp.task('compile-js', function() {
return browserify('client/main.js')
.transform(babelify)
.bundle()
.pipe(source('scripts.min.js'))
.pipe(buffer())
.pipe(gulpif(process.env.NODE_ENV === 'production', uglify()))
.pipe(gulp.dest('public'))
}
);
gulp.task('server', ['compile-js'], function() {
browserSync.create().init({
files: ['public/**'],
port: 3001,
proxy: 'http://localhost:3000',
ui: { port: 3002 },
open: false,
});
gulp.watch(['client/*.js'], ['compile-js']);
return nodemon({
script: 'server/index.js',
env: { 'NODE_ENV': 'development' },
watch: ['server/**/*'],
});
});
|
Add bin to the phpcs path. | #!/usr/bin/env php
<?php
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['bin', 'src', 'tests', 'build.php']]);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration];
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
file_put_contents('php://stderr', "Code coverage was 100%\n");
| #!/usr/bin/env php
<?php
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php']]);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration];
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
file_put_contents('php://stderr', "Code coverage was 100%\n");
|
Add support for formated text to /echo
Runs unformat aka tomd before echoing to replace formatting
with markdown producing that formatting,
which allows the bot to reproduce that formatting. | 'use strict'
const {unformat} = require('./unformat')
exports.init = (bot, prefs) => {
bot.register.command('echo', {
format: true,
fn: message => {
if (!message.args) {
return "Supply some text to echo in markdown. (For example: <code>/echo *bold text*</code>.)";
}
const cut = message.entities[0].length + 1;
// we run unformat with the command intact, to not mess up entity offsets,
// only after that we get rid of command
let response = unformat(message).slice(cut);
bot.api.sendMessage(message.chat.id, response, {
parseMode: 'markdown',
reply: (message.reply_to_message || message).message_id
}).catch(e =>
e.description.includes('entity')
? message.tag(response)
: message.error(e.error_code, e.description)
);
}
});
}
| 'use strict'
exports.init = (bot, prefs) => {
bot.register.command('echo', {
format: true,
fn: message => {
var response = message.text.replace('/echo', "");
if (!response)
return "Supply some text to echo in markdown. (For example: <code>/echo *bold text*</code>.)";
bot.api.sendMessage(message.chat.id, response, {
parseMode: 'markdown',
reply: (message.reply_to_message || message).message_id
}).catch(e =>
e.description.includes('entity')
? message.tag(response)
: message.error(e.error_code, e.description)
);
}
});
}
|
Move common behaviour into selectItem function | // ==UserScript==
// @name Rightmove Enhancement Suite
// @namespace https://github.com/chigley/
// @description Keyboard shortcuts
// @include http://www.rightmove.co.uk/*
// @version 1
// @grant GM_addStyle
// @grant GM_getResourceText
// @resource style style.css
// ==/UserScript==
var $ = unsafeWindow.jQuery;
GM_addStyle(GM_getResourceText("style"));
var listItems = $("[name=summary-list-item]");
var currentlySelected;
// Remove grey background on premium listings. Otherwise, my active item doesn't
// stand out against such listings
$(".premium").css("background", "white");
function selectItem(item) {
listItems.removeClass("RES-active-list-item");
item.addClass("RES-active-list-item");
currentlySelected = item;
}
listItems.click(function () {
selectItem($(this));
});
$('body').bind('keyup', function(e) {
var code = e.keyCode || e.which;
if (e.keyCode == 74) {
// j
var next = currentlySelected.next("[name=summary-list-item]");
if (next.length == 1)
selectItem(next);
}
});
| // ==UserScript==
// @name Rightmove Enhancement Suite
// @namespace https://github.com/chigley/
// @description Keyboard shortcuts
// @include http://www.rightmove.co.uk/*
// @version 1
// @grant GM_addStyle
// @grant GM_getResourceText
// @resource style style.css
// ==/UserScript==
var $ = unsafeWindow.jQuery;
GM_addStyle(GM_getResourceText("style"));
var listItems = $("[name=summary-list-item]");
var currentlySelected;
// Remove grey background on premium listings. Otherwise, my active item doesn't
// stand out against such listings
$(".premium").css("background", "white");
listItems.click(function () {
listItems.removeClass("RES-active-list-item");
$(this).addClass("RES-active-list-item");
currentlySelected = $(this);
});
$('body').bind('keyup', function(e) {
var code = e.keyCode || e.which;
if (e.keyCode == 74) {
// j
var next = currentlySelected.next("[name=summary-list-item]");
if (next.length == 1) {
listItems.removeClass("RES-active-list-item");
next.addClass("RES-active-list-item");
currentlySelected = next;
}
}
});
|
Change attributes order on constructor | from infosystem.database import db
from infosystem.common.subsystem import entity
class Domain(entity.Entity, db.Model):
attributes = ['name', 'parent_id']
attributes += entity.Entity.attributes
name = db.Column(db.String(60), nullable=False, unique=True)
parent_id = db.Column(
db.CHAR(32), db.ForeignKey("domain.id"), nullable=True)
def __init__(self, id, name, parent_id=None,
active=True, created_at=None, created_by=None,
updated_at=None, updated_by=None):
super().__init__(id, active, created_at, created_by,
updated_at, updated_by)
self.name = name
self.parent_id = parent_id
| from infosystem.database import db
from infosystem.common.subsystem import entity
class Domain(entity.Entity, db.Model):
attributes = ['name', 'parent_id']
attributes += entity.Entity.attributes
name = db.Column(db.String(60), nullable=False, unique=True)
parent_id = db.Column(
db.CHAR(32), db.ForeignKey("domain.id"), nullable=True)
def __init__(self, id, name, active=True, parent_id=None,
created_at=None, created_by=None,
updated_at=None, updated_by=None):
super().__init__(id, active, created_at, created_by,
updated_at, updated_by)
self.name = name
self.parent_id = parent_id
|
Use os.system to initialise db in tests | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from time import sleep
import unittest
import os
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh"
os.system(cmd)
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
| # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from time import sleep
import unittest
import os
from subprocess import call
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
# call([os.environ['CAIRIS_SRC'] + "/test/initdb.sh"])
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
|
Remove add new flowchart page from modeladmin | <?php
/**
* Graphical interface for creating basic flowcharts
*/
class FlowchartAdmin extends ModelAdmin {
private static $managed_models = array('FlowchartPage','FlowState');
private static $url_segment = 'flowcharts';
private static $menu_title = 'Flowcharts';
private static $menu_icon = "flowchart/images/flowchart.png";
private static $tree_class = 'SS_Flowchart';
public function getEditForm($id = null, $fields = null){
$form = parent::getEditForm($id, $fields);
$gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass));
$config = $gridField->getConfig();
if($this->sanitiseClassName($this->modelClass) == "FlowchartPage"){
$config->removeComponentsByType('GridFieldDetailForm');
$config->removeComponentsByType('GridFieldAddNewButton');
$config->addComponent(new GridFieldFlowchartDetailForm());
} else if($this->sanitiseClassName($this->modelClass) == "FlowState"){
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(
singleton($this->sanitiseClassName($this->modelClass))->getCurrentDisplayFields()
);
}
return $form;
}
}
| <?php
/**
* Graphical interface for creating basic flowcharts
*/
class FlowchartAdmin extends ModelAdmin {
private static $managed_models = array('FlowchartPage','FlowState');
private static $url_segment = 'flowcharts';
private static $menu_title = 'Flowcharts';
private static $menu_icon = "flowchart/images/flowchart.png";
private static $tree_class = 'SS_Flowchart';
public function getEditForm($id = null, $fields = null){
$form = parent::getEditForm($id, $fields);
$gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass));
$config = $gridField->getConfig();
if($this->sanitiseClassName($this->modelClass) == "FlowchartPage"){
$config->removeComponentsByType('GridFieldDetailForm');
$config->addComponent(new GridFieldFlowchartDetailForm());
} else if($this->sanitiseClassName($this->modelClass) == "FlowState"){
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(
singleton($this->sanitiseClassName($this->modelClass))->getCurrentDisplayFields()
);
}
return $form;
}
}
|
Update script for the beauty of it |
requirejs.config({
paths: {
'jquery': './lib/components/jquery/dist/jquery.min'
}
});
require( [ 'src/graph' ] , function( Graph ) {
var functions = [
function( domGraph ) {
var graph = new Graph( domGraph );
graph.newSerie("serieTest")
.setLabel( "My serie" )
.autoAxis()
.setData( [ [1, 2], [2, 5], [3, 10] ] )
.showMarkers( true )
.setMarkerType( 1 );
graph.newSerie("serieTest")
.setLabel( "My serie 2" )
.autoAxis()
.setData( [ [2, 4], [3, 1], [5, 20] ] )
.setLineColor('red');
graph.makeLegend({
frame: true,
frameWidth: 1,
frameColor: "green",
backgroundColor: "blue"
});
graph.redraw( );
graph.drawSeries();
}
]
for( var i = 0, l = functions.length ; i < l ; i ++ ) {
functions[ i ]("example-1-graph");
$("#example-1-source").html( functions[ i ].toString() );
}
} ); |
requirejs.config({
paths: {
'jquery': './lib/components/jquery/dist/jquery.min'
}
});
require( [ 'src/graph' ] , function( Graph ) {
var functions = [
function( domGraph, domSource ) {
var g1 = new Graph( domGraph );
var serie = g1.newSerie("serieTest")
.setLabel( "My serie" )
.autoAxis()
.setData( [ [1, 2], [2, 5], [3, 10] ] )
.showMarkers( true )
.setMarkerType( 1 );
var serie = g1.newSerie("serieTest")
.setLabel( "My serie 2" )
.autoAxis()
.setData( [ [2, 4], [3, 1], [5, 20] ] )
.setLineColor('red');
var legend = g1.makeLegend({
frame: true,
frameWidth: 1,
frameColor: "green",
backgroundColor: "blue"
});
g1.redraw( );
g1.drawSeries();
}
]
for( var i = 0, l = functions.length ; i < l ; i ++ ) {
functions[ i ]("example-1-graph");
$("#example-1-source").html( functions[ i ].toString() );
}
} ); |
Increase time of Drinker swop | //BG Color Change
var colors = ["red", "green", "blue", "purple", "yellow", "orange"];
var currentColor = 0;
function switchColor() {
if (currentColor >= colors.length) currentColor = 0;
$('#outer').css('background-color', colors[currentColor++]);
setTimeout(switchColor, 400);
}
switchColor();
//Rotate Drinker
var angle = 0;
setInterval(function(){
angle+=3;
$("#drinker").rotate(angle);
},50);
//Swop Drinker
var drinker = ["img/ED_PINT.png", "img/NF_PINT.png", "img/PINT.png", "img/ED_PINT2.png"];
var currentDrinker = 0;
function switchDrinker(){
if (currentDrinker >= drinker.length) currentDrinker = 0;
$("#drinker").attr('src', drinker[currentDrinker++]);
setTimeout(switchDrinker, 1400);
}
switchDrinker();
| //BG Color Change
var colors = ["red", "green", "blue", "purple", "yellow", "orange"];
var currentColor = 0;
function switchColor() {
if (currentColor >= colors.length) currentColor = 0;
$('#outer').css('background-color', colors[currentColor++]);
setTimeout(switchColor, 400);
}
switchColor();
//Rotate Drinker
var angle = 0;
setInterval(function(){
angle+=3;
$("#drinker").rotate(angle);
},50);
//Swop Drinker
var drinker = ["img/ED_PINT.png", "img/NF_PINT.png", "img/PINT.png", "img/ED_PINT2.png"];
var currentDrinker = 0;
function switchDrinker(){
if (currentDrinker >= drinker.length) currentDrinker = 0;
$("#drinker").attr('src', drinker[currentDrinker++]);
setTimeout(switchDrinker, 1000);
}
switchDrinker();
|
Document another possible argument type
This class is sometimes instanciated in the codebase with objects rather
than strings, and used in phpspec by php functions able to deal with
both types.
See #369
See https://github.com/phpspec/phpspec/pull/1180 | <?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Exception\Doubler;
class MethodNotFoundException extends DoubleException
{
/**
* @var string|object
*/
private $classname;
/**
* @var string
*/
private $methodName;
/**
* @var array
*/
private $arguments;
/**
* @param string $message
* @param string|object $classname
* @param string $methodName
* @param null|Argument\ArgumentsWildcard|array $arguments
*/
public function __construct($message, $classname, $methodName, $arguments = null)
{
parent::__construct($message);
$this->classname = $classname;
$this->methodName = $methodName;
$this->arguments = $arguments;
}
public function getClassname()
{
return $this->classname;
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
}
| <?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Exception\Doubler;
class MethodNotFoundException extends DoubleException
{
/**
* @var string
*/
private $classname;
/**
* @var string
*/
private $methodName;
/**
* @var array
*/
private $arguments;
/**
* @param string $message
* @param string $classname
* @param string $methodName
* @param null|Argument\ArgumentsWildcard|array $arguments
*/
public function __construct($message, $classname, $methodName, $arguments = null)
{
parent::__construct($message);
$this->classname = $classname;
$this->methodName = $methodName;
$this->arguments = $arguments;
}
public function getClassname()
{
return $this->classname;
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
}
|
Use correct version checker url | package org.cyclops.cyclopscore;
/**
* Class that can hold basic static things that are better not hard-coded
* like mod details, texture paths, ID's...
* @author rubensworks
*/
public final class Reference {
// Mod info
public static final String MOD_ID = "cyclopscore";
public static final String MOD_NAME = "Cyclops Core";
public static final String MOD_VERSION = "@VERSION@";
public static final String MOD_BUILD_NUMBER = "@BUILD_NUMBER@";
public static final String MOD_MC_VERSION = "@MC_VERSION@";
public static final String GA_TRACKING_ID = "UA-65307010-1";
public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/1.9/CyclopsCore.txt";
// Mod ID's
public static final String MOD_VANILLA = "Minecraft";
public static final String MOD_BAUBLES = "Baubles";
public static final String MOD_VERSION_CHECKER = "VersionChecker";
// Dependencies
public static final String MOD_DEPENDENCIES =
"required-after:Forge@[12.16.0.1767,);";
}
| package org.cyclops.cyclopscore;
/**
* Class that can hold basic static things that are better not hard-coded
* like mod details, texture paths, ID's...
* @author rubensworks
*/
public final class Reference {
// Mod info
public static final String MOD_ID = "cyclopscore";
public static final String MOD_NAME = "Cyclops Core";
public static final String MOD_VERSION = "@VERSION@";
public static final String MOD_BUILD_NUMBER = "@BUILD_NUMBER@";
public static final String MOD_MC_VERSION = "@MC_VERSION@";
public static final String GA_TRACKING_ID = "UA-65307010-1";
public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/1.8/CyclopsCore.txt";
// Mod ID's
public static final String MOD_VANILLA = "Minecraft";
public static final String MOD_BAUBLES = "Baubles";
public static final String MOD_VERSION_CHECKER = "VersionChecker";
// Dependencies
public static final String MOD_DEPENDENCIES =
"required-after:Forge@[12.16.0.1767,);";
}
|
js: Move into base JS library one more function.
* Move the setXhrHeader function into the base library.
Change-Id: Id54c0486aeb8ae1d49fc934ba60177a66bfa4187 | var csrftoken = $('meta[name=csrf-token]').attr('content');
function setErrorAlert (id, code, reason) {
/*
* Pass code (int) and id (string) to alert an error on the page.
* Optionally pass a reason (string) for the error.
*/
'use strict';
var localId = id,
text = '';
if (id[0] !== '#') {
localId = '#' + id;
}
text = '<div id="' + localId + '" ' +
'class="alert alert-danger alert-dismissable">' +
'<button type="button" class="close" ' +
'data-dismiss="alert" aria-hidden="true">×</button>';
if (reason !== undefined) {
text += reason + '<br/>';
}
text += 'Error while loading data from the server (error code: ' +
code + '). ' +
'Please contact the website administrators.';
text += '</div>';
$('#errors-container').append(text);
$(localId).alert();
}
function setXhrHeader (xhr) {
/*
Set the CSRF token header for ajax request.
xhr: The xhr object to add the header to.
*/
'use strict';
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
| function setErrorAlert (id, code, reason) {
/*
* Pass code (int) and id (string) to alert an error on the page.
* Optionally pass a reason (string) for the error.
*/
'use strict';
var localId = id,
text = '';
if (id[0] !== '#') {
localId = '#' + id;
}
text = '<div id="' + localId + '" ' +
'class="alert alert-danger alert-dismissable">' +
'<button type="button" class="close" ' +
'data-dismiss="alert" aria-hidden="true">×</button>';
if (reason !== undefined) {
text += reason + '<br/>';
}
text += 'Error while loading data from the server (error code: ' +
code + '). ' +
'Please contact the website administrators.';
text += '</div>';
$('#errors-container').append(text);
$(localId).alert();
}
|
Put space between master and hash | package cmd
import (
"fmt"
"github.com/s3git/s3git-go"
"github.com/spf13/cobra"
)
var message string
// commitCmd represents the commit command
var commitCmd = &cobra.Command{
Use: "commit",
Short: "Commit the changes in the repository",
Long: "Commit the changes in the repository",
Run: func(cmd *cobra.Command, args []string) {
repo, err := s3git.OpenRepository(".")
if err != nil {
er(err)
}
key, nothing, err := repo.Commit(message)
if err != nil {
er(err)
}
if nothing {
fmt.Println("Nothing to commit")
} else {
fmt.Printf("[master %s]\n", key)
fmt.Printf("X files added, Y files removed\n")
}
},
}
func init() {
RootCmd.AddCommand(commitCmd)
// Add local message flags
commitCmd.Flags().StringVarP(&message, "message", "m", "", "Message for the commit")
}
| package cmd
import (
"fmt"
"github.com/s3git/s3git-go"
"github.com/spf13/cobra"
)
var message string
// commitCmd represents the commit command
var commitCmd = &cobra.Command{
Use: "commit",
Short: "Commit the changes in the repository",
Long: "Commit the changes in the repository",
Run: func(cmd *cobra.Command, args []string) {
repo, err := s3git.OpenRepository(".")
if err != nil {
er(err)
}
key, nothing, err := repo.Commit(message)
if err != nil {
er(err)
}
if nothing {
fmt.Println("Nothing to commit")
} else {
fmt.Printf("[master%s]\n", key)
fmt.Printf("X files added, Y files removed\n")
}
},
}
func init() {
RootCmd.AddCommand(commitCmd)
// Add local message flags
commitCmd.Flags().StringVarP(&message, "message", "m", "", "Message for the commit")
}
|
Use Jython dont import site flag
The purpose of this change is to improve startup performance of the cslang CLI
According to jython java docs when this property is set to false site.py will not be imported
AFAIK this site packages doesn't exist unless you install jython (and not embedding)
Signed-off-by: Eliya Sadan <ee72bd64a89bf65c610af864999dbed3edbad28e@gmail.com> | package io.cloudslang.lang.runtime.configuration;
/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
import org.python.core.Options;
import org.python.util.PythonInterpreter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
@Configuration
@ComponentScan("io.cloudslang.lang.runtime")
public class SlangRuntimeSpringConfig {
static {
Options.importSite = false;
}
@Bean
public PythonInterpreter interpreter(){
return new PythonInterpreter();
}
@Bean
public ScriptEngine scriptEngine(){
return new ScriptEngineManager().getEngineByName("python");
}
}
| package io.cloudslang.lang.runtime.configuration;
/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
import org.python.util.PythonInterpreter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
@Configuration
@ComponentScan("io.cloudslang.lang.runtime")
public class SlangRuntimeSpringConfig {
@Bean
public PythonInterpreter interpreter(){
return new PythonInterpreter();
}
@Bean
public ScriptEngine scriptEngine(){
return new ScriptEngineManager().getEngineByName("python");
}
}
|
Include templates and static at the installing process too | from setuptools import setup
setup(
name='django-setmagic',
version='0.2.1',
author='Evandro Myller',
author_email='emyller@7ws.co',
description='Magically editable settings for winged pony lovers',
url='https://github.com/7ws/django-setmagic',
install_requires=[
'django >= 1.5',
],
packages=['setmagic'],
include_package_data=True,
keywords=['django', 'settings'],
classifiers=[
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
],
)
| from setuptools import setup
setup(
name='django-setmagic',
version='0.2',
author='Evandro Myller',
author_email='emyller@7ws.co',
description='Magically editable settings for winged pony lovers',
url='https://github.com/7ws/django-setmagic',
install_requires=[
'django >= 1.5',
],
packages=['setmagic'],
keywords=['django', 'settings'],
classifiers=[
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
],
)
|
Use the UTF-8 ellipsis character
svn commit r15188 | <?php
/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
require_once 'Swat/SwatEntry.php';
/**
* A single line search entry widget
*
* @package Swat
* @copyright 2004-2007 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatSearch extends SwatEntry
{
// {{{ public properties
/**
* SwatSearch title value
*
* Text content of the widget, or defaults to 'Enter Search …'.
*
* @var string
*/
public $title;
// }}}
// {{{ public function __construct()
public function __construct($id = null)
{
parent::__construct($id);
$this->title = Swat::_('Enter Search …');
}
// }}}
// {{{ protected function getDisplayValue()
/**
* Displays a value for SwatSearch
*
* The methond returns either the title or the correct search entry.
*
* @return string the display value
*/
protected function getDisplayValue()
{
$value = '';
if ($this->value === null) {
$value = $this->title;
} else {
$value = parent::getDisplayValue();
}
return $value;
}
// }}}
}
?>
| <?php
/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
require_once 'Swat/SwatEntry.php';
/**
* A single line search entry widget
*
* @package Swat
* @copyright 2004-2007 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatSearch extends SwatEntry
{
// {{{ public properties
/**
* SwatSearch title value
*
* Text content of the widget, or defaults to 'Enter Search'.
*
* @var string
*/
public $title;
// }}}
// {{{ public function __construct()
public function __construct($id = null)
{
parent::__construct($id);
$this->title = Swat::_('Enter Search...');
}
// }}}
// {{{ protected function getDisplayValue()
/**
* Displays a value for SwatSearch
*
* The methond returns either the title or the correct search entry.
*
* @return string the display value
*/
protected function getDisplayValue()
{
$value = '';
if ($this->value === null) {
$value = $this->title;
} else {
$value = parent::getDisplayValue();
}
return $value;
}
// }}}
}
?>
|
Fix theme changer.
Use cms-theme as query param.
Set default theme on config. | <?php
namespace Yajra\CMS\Themes;
use Closure;
class ThemeChanger
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($theme = $request->query('cms-theme')) {
$finder = app('themes.view.finder');
$basePath = config('themes.path.frontend', base_path('themes/frontend'));
$finder->removeBasePath();
$finder->setBasePath($basePath . DIRECTORY_SEPARATOR . $theme);
config(['themes.frontend' => $theme]);
}
return $next($request);
}
}
| <?php
namespace Yajra\CMS\Themes;
use Closure;
class ThemeChanger
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->query('tmpl')) {
$finder = app('themes.view.finder');
$basePath = config('themes.path.frontend', base_path('themes')) . DIRECTORY_SEPARATOR . $request->query('tmpl');
$finder->setBasePath($basePath);
}
return $next($request);
}
}
|
Revert unnecessary change to original | """Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks."""
import sys
OPENCV_FOUND = False
OPENCV_VERSION_COMPATIBLE = False
try:
import cv2
OPENCV_FOUND = True
except ModuleNotFoundError:
print('OpenCV is not found (tried importing cv2).', file=sys.stderr)
print('''
Is OpenCV installed and properly added to your path?
you are using a virtual environment, make sure to add the path
to the OpenCV bindings to the environment\'s site-packages.
For example (MacOSX with brew):
echo /usr/local/Cellar/opencv3/HEAD-8d662a1_4/lib/python3.6/site-packages > ./.venv/lib/python3.6/site-packages/opencv.pth
Make sure that the first path contains your cv2.so!
See https://docs.python.org/3/library/site.html
''')
if OPENCV_FOUND:
MAJOR, MINOR, PATCH = cv2.__version__.split('.')
OPENCV_VERSION_COMPATIBLE = int(MAJOR) >= 3 and int(MINOR) >= 1
if not OPENCV_VERSION_COMPATIBLE:
print('OpenCV version {} is lower than 3.1!'.format(cv2.__version__), file=sys.stderr)
if OPENCV_FOUND and OPENCV_VERSION_COMPATIBLE:
from .cvloop import cvloop
from .functions import *
| """Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks."""
import sys
OPENCV_FOUND = False
OPENCV_VERSION_COMPATIBLE = False
try:
import cv2
OPENCV_FOUND = True
except Exception as e:
# print ("Error:", e)
print('OpenCV is not found (tried importing cv2).', file=sys.stderr)
print('''
Is OpenCV installed and properly added to your path?
you are using a virtual environment, make sure to add the path
to the OpenCV bindings to the environment\'s site-packages.
For example (MacOSX with brew):
echo /usr/local/Cellar/opencv3/HEAD-8d662a1_4/lib/python3.6/site-packages > ./.venv/lib/python3.6/site-packages/opencv.pth
Make sure that the first path contains your cv2.so!
See https://docs.python.org/3/library/site.html
''')
if OPENCV_FOUND:
MAJOR, MINOR, PATCH = cv2.__version__.split('.')
OPENCV_VERSION_COMPATIBLE = int(MAJOR) >= 3 and int(MINOR) >= 1
if not OPENCV_VERSION_COMPATIBLE:
print('OpenCV version {} is lower than 3.1!'.format(cv2.__version__), file=sys.stderr)
if OPENCV_FOUND and OPENCV_VERSION_COMPATIBLE:
from .cvloop import cvloop
from .functions import *
|
Improve sanity checking for signin "from" param | /**
* The signin page, it renders a page with a username and password input form.
*
* This is decoupled from the main app (in the "App/" folder) because we inject
* lots of data into the other screens (like the lists that exist) that we don't
* want to have injected here, so this is a completely separate route and template.
*/
import qs from 'qs';
import React from 'react';
import ReactDOM from 'react-dom';
import Signin from './Signin';
// Sanitize from param
const internalFromRegex = /^\/[^\/\\]\w+/;
const params = qs.parse(window.location.search.replace(/^\?/, ''));
const from = internalFromRegex.test(params.from) ? params.from : undefined;
ReactDOM.render(
<Signin
brand={Keystone.brand}
from={from}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>,
document.getElementById('signin-view')
);
| /**
* The signin page, it renders a page with a username and password input form.
*
* This is decoupled from the main app (in the "App/" folder) because we inject
* lots of data into the other screens (like the lists that exist) that we don't
* want to have injected here, so this is a completely separate route and template.
*/
import qs from 'qs';
import React from 'react';
import ReactDOM from 'react-dom';
import Signin from './Signin';
const params = qs.parse(window.location.search.replace(/^\?/, ''));
const from = typeof params.from === 'string' && params.from.charAt(0) === '/'
? params.from : undefined;
ReactDOM.render(
<Signin
brand={Keystone.brand}
from={from}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>,
document.getElementById('signin-view')
);
|
Change this to use Clock in case people are relying on this function to advance the Clock abstraction | package org.threadly.test.concurrent;
import org.threadly.util.Clock;
/**
* Generic tools to be used in unit testing.
*
* @author jent - Mike Jensen
*/
public class TestUtils {
private TestUtils() {
// don't construct
}
/**
* Since sleeps are sometimes necessary, this makes
* an easy way to ignore InterruptedException's.
*
* @param time time in milliseconds to make the thread to sleep
*/
public static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// ignored
}
}
/**
* Blocks until the System clock advances at least 1 millisecond.
*/
public static void blockTillClockAdvances() {
new TestCondition() {
private static final int TIMEOUT_IN_MS = 1000;
private static final int POLL_INTERVAL_IN_MS = 1;
private final long startTime = Clock.accurateTime();
@Override
public boolean get() {
return Clock.accurateTime() != startTime;
}
@Override
public void blockTillTrue() {
blockTillTrue(TIMEOUT_IN_MS, POLL_INTERVAL_IN_MS);
}
}.blockTillTrue();
}
}
| package org.threadly.test.concurrent;
/**
* Generic tools to be used in unit testing.
*
* @author jent - Mike Jensen
*/
public class TestUtils {
private TestUtils() {
// don't construct
}
/**
* Since sleeps are sometimes necessary, this makes
* an easy way to ignore InterruptedException's.
*
* @param time time in milliseconds to make the thread to sleep
*/
public static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// ignored
}
}
/**
* Blocks until the System clock advances at least 1 millisecond.
*/
public static void blockTillClockAdvances() {
new TestCondition() {
private static final int TIMEOUT_IN_MS = 1000;
private static final int POLL_INTERVAL_IN_MS = 1;
private final long startTime = System.currentTimeMillis();
@Override
public boolean get() {
return System.currentTimeMillis() != startTime;
}
@Override
public void blockTillTrue() {
blockTillTrue(TIMEOUT_IN_MS, POLL_INTERVAL_IN_MS);
}
}.blockTillTrue();
}
}
|
Add file to JS tree for comparison | /* jshint node: true */
'use strict';
var fs = require('fs');
var Plugin = require('broccoli-plugin');
var mergeTrees = require('broccoli-merge-trees');
var path = require('path');
var log = require('broccoli-stew').log;
var customTestFilePath = 'my-custom-test-files/test-file.js';
var customJsFilePath = 'my-custom-test-files/js-file.js';
AddCustomFile.prototype = Object.create(Plugin.prototype);
AddCustomFile.prototype.constructor = AddCustomFile;
function AddCustomFile(inputNodes, options) {
this.path = options.path;
Plugin.call(this, inputNodes);
}
AddCustomFile.prototype.build = function() {
var outPath = path.join(this.outputPath, this.path);
fs.mkdirSync(path.dirname(outPath));
fs.writeFileSync(outPath, 'window.testing123 = true;');
};
module.exports = {
name: 'addon-test-bug',
included: function(app) {
app.import({
test: customTestFilePath
});
app.import(customJsFilePath);
},
postprocessTree: function(type, tree){
if (type === 'test') {
return mergeTrees([tree, log(new AddCustomFile([tree], {
path: customTestFilePath
}))]);
} else if (type === 'js') {
return mergeTrees([tree, log(new AddCustomFile([tree], {
path: customJsFilePath
}))]);
}
return tree;
}
};
| /* jshint node: true */
'use strict';
var fs = require('fs');
var Plugin = require('broccoli-plugin');
var mergeTrees = require('broccoli-merge-trees');
var path = require('path');
var log = require('broccoli-stew').log;
var customTestFilePath = 'my-custom-test-files/foo.js';
AddCustomTestFile.prototype = Object.create(Plugin.prototype);
AddCustomTestFile.prototype.constructor = AddCustomTestFile;
function AddCustomTestFile(inputNodes) {
Plugin.call(this, inputNodes);
}
AddCustomTestFile.prototype.build = function() {
var outPath = path.join(this.outputPath, customTestFilePath);
fs.mkdirSync(path.dirname(outPath));
fs.writeFileSync(outPath, 'window.testing123 = true;');
};
module.exports = {
name: 'addon-test-bug',
included: function(app) {
app.import({
test: customTestFilePath
});
},
postprocessTree: function(type, tree){
if (type === 'test') {
return mergeTrees([tree, log(new AddCustomTestFile([tree]))]);
}
return tree;
}
};
|
Use an EnumMap rather than a HashMap. | /**
* Copyright 2011 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.android;
import android.graphics.Typeface;
import java.util.EnumMap;
import java.util.Map;
import playn.core.AbstractFont;
class AndroidFont extends AbstractFont {
public final Typeface typeface;
public AndroidFont(String name, Style style, float size) {
super(name, style, size);
this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
}
protected static final Map<Style,Integer> TO_ANDROID_STYLE =
new EnumMap<Style,Integer>(Style.class);
static {
TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL);
TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD);
TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC);
TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
}
}
| /**
* Copyright 2011 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.android;
import android.graphics.Typeface;
import java.util.HashMap;
import java.util.Map;
import playn.core.AbstractFont;
class AndroidFont extends AbstractFont {
public final Typeface typeface;
public AndroidFont(String name, Style style, float size) {
super(name, style, size);
this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
}
protected static final Map<Style,Integer> TO_ANDROID_STYLE = new HashMap<Style,Integer>();
static {
TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL);
TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD);
TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC);
TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
}
}
|
Throw an exception when the request times out | /*
* Copyright (C) 2012 Pixmob (http://github.com/pixmob)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pixmob.hcl;
import java.io.File;
/**
* This handler is notified when an Http response is received.
* @author Pixmob
*/
public class HttpResponseHandler {
/**
* Create an {@link HttpResponseHandler} instance for writing the response
* to a file.
*/
public static HttpResponseHandler toFile(File file) {
return new WriteToFileHandler(file);
}
/**
* The request failed to connect or read data in time.
*/
public void onTimeout() throws HttpClientException {
throw new HttpClientException("Timeout");
}
/**
* The request was successfully sent and a response is available.
*/
public void onResponse(HttpResponse response) throws HttpClientException {
}
}
| /*
* Copyright (C) 2012 Pixmob (http://github.com/pixmob)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pixmob.hcl;
import java.io.File;
/**
* This handler is notified when an Http response is received.
* @author Pixmob
*/
public class HttpResponseHandler {
/**
* Create an {@link HttpResponseHandler} instance for writing the response
* to a file.
*/
public static HttpResponseHandler toFile(File file) {
return new WriteToFileHandler(file);
}
/**
* The request failed to connect or read data in time.
*/
public void onTimeout() throws HttpClientException {
}
/**
* The request was successfully sent and a response is available.
*/
public void onResponse(HttpResponse response) throws HttpClientException {
}
}
|
Add asBuffer() for converting a DataTester to a byte buffer | package se.fnord.katydid;
import se.fnord.katydid.internal.TestingContext;
import java.nio.ByteBuffer;
public class DataAsserts {
public static void assertNext(DataTester dataTester, ByteBuffer bb) {
int m = dataTester.passCount();
TestingContext tc = new TestingContext(bb);
int pos = bb.position();
for (int i = 0; i < m; i++) {
bb.position(pos);
dataTester.compareTo(i, tc);
}
}
public static void assertExact(DataTester dataTester, ByteBuffer bb) {
ByteBuffer bb2 = bb.slice();
assertNext(dataTester, bb2);
if (bb2.hasRemaining())
throw new AssertionError(String.format("Expected %d bytes, was %d bytes", dataTester.length(), bb.remaining()));
}
public static void assertExact(DataTester dataTester, byte[] bytes) {
assertExact(dataTester, ByteBuffer.wrap(bytes));
}
public static ByteBuffer asBuffer(DataTester dataTester) {
int length = dataTester.length();
ByteBuffer bb = ByteBuffer.allocate(length);
dataTester.toBuffer(bb);
bb.flip();
return bb;
}
}
| package se.fnord.katydid;
import se.fnord.katydid.internal.TestingContext;
import java.nio.ByteBuffer;
public class DataAsserts {
public static void assertNext(DataTester dataTester, ByteBuffer bb) {
int m = dataTester.passCount();
TestingContext tc = new TestingContext(bb);
int pos = bb.position();
for (int i = 0; i < m; i++) {
bb.position(pos);
dataTester.compareTo(i, tc);
}
}
public static void assertExact(DataTester dataTester, ByteBuffer bb) {
ByteBuffer bb2 = bb.slice();
assertNext(dataTester, bb2);
if (bb2.hasRemaining())
throw new AssertionError(String.format("Expected %d bytes, was %d bytes", dataTester.length(), bb.remaining()));
}
public static void assertExact(DataTester dataTester, byte[] bytes) {
assertExact(dataTester, ByteBuffer.wrap(bytes));
}
}
|
Switch from SF to Github for canonical links. | from setuptools import setup, find_packages
version = '1.2.4'
setup(name='switchboard',
version=version,
description="Feature flipper for Pyramid, Pylons, or TurboGears apps.",
# http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='switches feature flipper pyramid pylons turbogears',
author='Kyle Adams',
author_email='kadams54@users.noreply.github.com',
url='https://github.com/switchboardpy/switchboard/',
download_url='https://github.com/switchboardpy/switchboard/releases',
license='Apache License',
packages=find_packages(exclude=['ez_setup']),
include_package_data=True,
install_requires=[
'pymongo == 2.3',
'blinker >= 1.2',
'WebOb >= 0.9',
'Mako >= 0.9',
],
zip_safe=False,
tests_require=[
'nose',
'mock',
'bottle',
],
test_suite='nose.collector',
)
| from setuptools import setup, find_packages
version = '1.2.4'
setup(name='switchboard',
version=version,
description="Feature flipper for Pyramid, Pylons, or TurboGears apps.",
# http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='switches feature flipper pyramid pylons turbogears',
author='Kyle Adams',
author_email='kadams54@users.sourceforge.net',
url='http://sf.net/projects/switchboardpy',
download_url='https://sf.net/projects/switchboardpy/files/latest',
license='Apache License',
packages=find_packages(exclude=['ez_setup']),
include_package_data=True,
install_requires=[
'pymongo == 2.3',
'blinker >= 1.2',
'WebOb >= 0.9',
'Mako >= 0.9',
],
zip_safe=False,
tests_require=[
'nose',
'mock',
'bottle',
],
test_suite='nose.collector',
)
|
Use __file__ for static and templates | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""
pystil - An elegant site web traffic analyzer
"""
from flask import Flask
from logging import getLogger, INFO
from pystil.log import get_default_handler
from pystil.routes import register_common_routes
from pystil.routes.data import register_data_routes
import pystil
import os
def app():
"""Create Flask app"""
root = os.path.dirname(pystil.__file__)
static_folder = os.path.join(root, 'static')
template_folder = os.path.join(root, 'templates')
app = Flask(__name__,
static_folder=static_folder, template_folder=template_folder)
handler = get_default_handler()
getLogger('werkzeug').addHandler(handler)
getLogger('werkzeug').setLevel(INFO)
app.logger.handlers = []
app.logger.addHandler(handler)
register_common_routes(app)
register_data_routes(app)
return app
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""
pystil - An elegant site web traffic analyzer
"""
from flask import Flask
from logging import getLogger, INFO
from pystil.log import get_default_handler
from pystil.routes import register_common_routes
from pystil.routes.data import register_data_routes
def app():
"""Create Flask app"""
app = Flask(__name__)
handler = get_default_handler()
getLogger('werkzeug').addHandler(handler)
getLogger('werkzeug').setLevel(INFO)
app.logger.handlers = []
app.logger.addHandler(handler)
register_common_routes(app)
register_data_routes(app)
return app
|
Remove tags from list_filter and filter_horizontal | from django.contrib import admin
from geartracker.models import *
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("make", "model", "size")}
list_display = ('__unicode__', 'type', 'metric_weight', 'acquired')
list_filter = ('archived', 'category', 'type', 'make')
search_fields = ('make', 'model')
filter_horizontal = ('related',)
admin.site.register(Item, ItemAdmin)
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('__unicode__', 'number_items')
admin.site.register(Category, CategoryAdmin)
class TypeAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('category', 'name', 'number_items')
list_filter = ('category',)
admin.site.register(Type, TypeAdmin)
class ListItemRelationshipInline(admin.TabularInline):
model = ListItem
extra = 1
class ListAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
inlines = (ListItemRelationshipInline,)
list_display = ('name', 'total_metric_weight', 'start_date', 'end_date',
'public')
list_filter = ('public',)
admin.site.register(List, ListAdmin)
| from django.contrib import admin
from geartracker.models import *
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("make", "model", "size")}
list_display = ('__unicode__', 'type', 'metric_weight', 'acquired')
list_filter = ('archived', 'category', 'type', 'make', 'tags')
search_fields = ('make', 'model')
filter_horizontal = ('related', 'tags')
admin.site.register(Item, ItemAdmin)
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('__unicode__', 'number_items')
admin.site.register(Category, CategoryAdmin)
class TypeAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('category', 'name', 'number_items')
list_filter = ('category',)
admin.site.register(Type, TypeAdmin)
class ListItemRelationshipInline(admin.TabularInline):
model = ListItem
extra = 1
class ListAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
inlines = (ListItemRelationshipInline,)
list_display = ('name', 'total_metric_weight', 'start_date', 'end_date',
'public')
list_filter = ('public',)
admin.site.register(List, ListAdmin)
|
Include timestamp in version when building SNAPSHOTS | package com.jamierf.dropwizard.config;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.vafer.jdeb.utils.Utils;
public class DebConfiguration {
private MavenProject project;
private MavenSession session;
public void setProject(MavenProject project) {
this.project = project;
}
public void setSession(MavenSession session) {
this.session = session;
}
@Parameter
private String maintainer = "Unspecified";
@SuppressWarnings("unused")
public String getName() {
return project.getArtifactId();
}
@SuppressWarnings("unused")
public String getVersion() {
return Utils.convertToDebianVersion(project.getVersion(), true, null, session.getStartTime());
}
@SuppressWarnings("unused")
public String getMaintainer() {
return maintainer;
}
}
| package com.jamierf.dropwizard.config;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.vafer.jdeb.utils.Utils;
public class DebConfiguration {
private MavenProject project;
private MavenSession session;
public void setProject(MavenProject project) {
this.project = project;
}
public void setSession(MavenSession session) {
this.session = session;
}
@Parameter
private String maintainer = "Unspecified";
@SuppressWarnings("unused")
public String getName() {
return project.getArtifactId();
}
@SuppressWarnings("unused")
public String getVersion() {
return Utils.convertToDebianVersion(project.getVersion(), false, null, session.getStartTime());
}
@SuppressWarnings("unused")
public String getMaintainer() {
return maintainer;
}
}
|
Improve SEO for Atmosphere. Uniform quoting.
Right now the package doesn't show up at https://atmospherejs.com?q=d3 | Package.describe({
summary: 'Graph / network visualization library',
version: '1.0.7',
name: 'futurescaper:futuregrapher',
git: 'https://github.com/Futurescaper/futuregrapher.git'
});
Package.onUse(function(api, where) {
api.versionsFrom('METEOR@0.9.0');
api.use(['d3', 'jquery'], 'client');
api.addFiles(['dist/futuregrapher.js'], 'client');
api.export('futuregrapher');
});
Package.onTest(function (api) {
api.use(['d3', 'tinytest', 'test-helpers']);
api.addFiles(['dist/futuregrapher.js'], 'client');
api.addFiles([
'test/jquery-simulate/jquery.simulate.js',
'test/stubs.js', 'test/helpers.js',
'test/graphvis-tests.js'
], 'client');
});
| Package.describe({
summary: "Network visualization library",
version: "1.0.6",
name: "futurescaper:futuregrapher",
git: "https://github.com/Futurescaper/futuregrapher.git"
});
Package.onUse(function(api, where) {
api.versionsFrom('METEOR@0.9.0');
api.use(['d3', 'jquery'], 'client');
api.addFiles(['dist/futuregrapher.js'], ['client']);
api.export('futuregrapher');
});
Package.on_test(function (api) {
api.use(["d3", "tinytest", "test-helpers"]);
api.addFiles(['dist/futuregrapher.js'], ["client"]);
api.addFiles([
"test/jquery-simulate/jquery.simulate.js",
"test/stubs.js", "test/helpers.js",
"test/graphvis-tests.js"
], ["client"]);
});
|
Fix unit test for JDK 1.3.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@701 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
static class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
| package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
|
Normalize strings for per object settings | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Per Object Settings"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml"
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
| # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Settings Per Object Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Settings Per Object"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml"
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
|
Update description for consistency with readme | import os
from setuptools import setup
PROJECT_DIR = os.path.dirname(__file__)
setup(
name = 'django-right-to-left',
packages = ['rtl'],
version = '0.1',
license = 'BSD',
keywords = 'Django, translation, internationalization, righ to left, bidi',
description = 'A Django template loader that looks for an alternative right to left version of a template file if the activated language is a right to left language such as Arabic or Hebrew.',
long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(),
author='Mohammad Abbas',
author_email='mohammad.abbas86@gmail.com',
url='https://github.com/abbas123456/django-right-to-left',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internationalization'],
)
| import os
from setuptools import setup
PROJECT_DIR = os.path.dirname(__file__)
setup(
name = 'django-right-to-left',
packages = ['rtl'],
version = '0.1',
license = 'BSD',
keywords = 'Django, translation, internationalization, righ to left, bidi',
description = 'A django template loader that looks for a right to left version of a template if the activated language is a right to left language (e.g Arabic, Hebrew)',
long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(),
author='Mohammad Abbas',
author_email='mohammad.abbas86@gmail.com',
url='https://github.com/abbas123456/django-right-to-left',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internationalization'],
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.