text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
qa: Remove race between connecting and shutdown on separate connections | #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy, wait_until
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
# Force connection establishment by executing a dummy command.
node.getblockcount()
Thread(target=test_long_call, args=(node,)).start()
# Wait until the server is executing the above `waitfornewblock`.
wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2)
# Wait 1 second after requesting shutdown but not before the `stop` call
# finishes. This is to ensure event loop waits for current connections
# to close.
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
| #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
Thread(target=test_long_call, args=(node,)).start()
# wait 1 second to ensure event loop waits for current connections to close
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
|
Update manager for Person requirement | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', person, **kwargs):
user = self.model(
email=email,
password='',
person=person,
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, person, **kwargs):
user = self.model(
email=email,
person=person,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
|
Use git tags prepended with v
This makes the script behave like other imagemin binary projects.
Pull Request URL:
https://github.com/imagemin/gifsicle-bin/pull/56 | 'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.githubusercontent.com/imagemin/gifsicle-bin/v' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'osx/gifsicle', 'darwin')
.src(url + 'linux/x86/gifsicle', 'linux', 'x86')
.src(url + 'linux/x64/gifsicle', 'linux', 'x64')
.src(url + 'freebsd/x86/gifsicle', 'freebsd', 'x86')
.src(url + 'freebsd/x64/gifsicle', 'freebsd', 'x64')
.src(url + 'win/x86/gifsicle.exe', 'win32', 'x86')
.src(url + 'win/x64/gifsicle.exe', 'win32', 'x64')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
| 'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.githubusercontent.com/imagemin/gifsicle-bin/' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'osx/gifsicle', 'darwin')
.src(url + 'linux/x86/gifsicle', 'linux', 'x86')
.src(url + 'linux/x64/gifsicle', 'linux', 'x64')
.src(url + 'freebsd/x86/gifsicle', 'freebsd', 'x86')
.src(url + 'freebsd/x64/gifsicle', 'freebsd', 'x64')
.src(url + 'win/x86/gifsicle.exe', 'win32', 'x86')
.src(url + 'win/x64/gifsicle.exe', 'win32', 'x64')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
|
Add 'full' option to get all package details not just version number. | 'use strict';
const semver = require('semver');
const fetch = require('node-fetch');
const url = require('url');
module.exports = pkg => {
if (typeof pkg === 'string') {
pkg = {
name: pkg
}
}
if (!pkg || !pkg.name) {
throw new Error('You must provide a package name');
}
pkg.version = pkg.version || '*';
if (!semver.validRange(pkg.version)) {
throw new Error('That is not a valid package version range');
}
pkg.registry = pkg.registry || 'http://registry.npmjs.com/';
return fetch(url.resolve(pkg.registry, pkg.name))
.then(response => response.json())
.then(data => {
let v = semver.maxSatisfying(Object.keys(data.versions || {}), pkg.version);
return (pkg.full) ? data.versions[v] : v;
})
.catch(err => { throw new Error(err); });
}
| 'use strict';
const semver = require('semver');
const fetch = require('node-fetch');
const url = require('url');
module.exports = pkg => {
if (typeof pkg === 'string') {
pkg = {
name: pkg
}
}
if (!pkg || !pkg.name) {
throw new Error('You must provide a package name');
}
pkg.version = pkg.version || '*';
if (!semver.validRange(pkg.version)) {
throw new Error('That is not a valid package version range');
}
pkg.registry = pkg.registry || 'http://registry.npmjs.com/';
return fetch(url.resolve(pkg.registry, pkg.name))
.then(response => response.json())
.then(data => semver.maxSatisfying(Object.keys(data.versions || {}), pkg.version))
.catch(err => { throw new Error(err); });
} |
Update streaming message repository to deal with heart beats | 'use strict';
var glimpse = require('glimpse');
var polyfill = require('event-source')
var socket = (function() {
var connection;
var setup = function() {
connection = new polyfill.EventSource('/Glimpse/MessageStream');
connection.addEventListener('message', function(e) {
if (!FAKE_SERVER) {
glimpse.emit('data.message.summary.found.stream', JSON.parse(e.data));
}
});
connection.addEventListener('ping', function(e) {
if (!DIAGNOSTICS) {
console.log('[repo] Server is still alive');
}
});
};
return {
check: function() {
if (!connection) {
setup();
}
}
};
})();
module.exports = {
subscribeToLastestSummaries: function () {
socket.check();
},
subscribeToDetailsFor: function (requestId) {
// TODO: Setup SSE code
}
};
| 'use strict';
var glimpse = require('glimpse');
var polyfill = require('event-source')
var socket = (function() {
var connection;
var setup = function() {
connection = new polyfill.EventSource('/Glimpse/MessageStream');
connection.onmessage = function(e) {
if (!FAKE_SERVER) {
glimpse.emit('data.message.summary.found.stream', JSON.parse(e.data));
}
};
};
return {
check: function() {
if (!connection) {
setup();
}
}
};
})();
module.exports = {
subscribeToLastestSummaries: function () {
socket.check();
},
subscribeToDetailsFor: function (requestId) {
// TODO: Setup SSE code
}
};
|
Fix variable in testcase from previous commit change | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from nose.tools import raises
from spec_cleaner.fileutils import FileUtils
from spec_cleaner import RpmException
class TestFileutils(unittest.TestCase):
"""
We run few tests to ensure fileutils class works fine
"""
def setUp(self):
"""
Declare global scope variables for further use.
"""
self.fileutils = FileUtils()
@raises(RpmException)
def test_open_assertion(self):
self.fileutils.open('missing-file.txt', 'r')
@raises(RpmException)
def test_open_datafile_assertion(self):
self.fileutils.open_datafile('missing-file.txt')
def test_open(self):
self.fileutils.open('tests/fileutils-tests.py', 'r')
self.fileutils.close()
self.assertEqual(None, self.fileutils.f)
def test_open_datafile(self):
self.fileutils.open_datafile('excludes-bracketing.txt')
self.fileutils.close()
self.assertEqual(None, self.fileutils.f)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from nose.tools import raises
from spec_cleaner.fileutils import FileUtils
from spec_cleaner import RpmException
class TestFileutils(unittest.TestCase):
"""
We run few tests to ensure fileutils class works fine
"""
def setUp(self):
"""
Declare global scope variables for further use.
"""
self.fileutils = FileUtils()
@raises(RpmException)
def test_open_assertion(self):
self.fileutils.open('missing-file.txt', 'r')
@raises(RpmException)
def test_open_datafile_assertion(self):
self.fileutils.open_datafile('missing-file.txt')
def test_open(self):
self.fileutils.open('tests/fileutils-tests.py', 'r')
self.fileutils.close()
self.assertEqual(None, self.fileutils._file)
def test_open_datafile(self):
self.fileutils.open_datafile('excludes-bracketing.txt')
self.fileutils.close()
self.assertEqual(None, self.fileutils._file)
|
Remove spaces from hash tag links | from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('(^|\s)(#\S+)')
@register.filter
def buglise(s):
s = unicode(s)
usernames = set(User.objects.values_list('username', flat=True))
def replace_username(match):
username = match.group(0)[1:]
if username.lower() == 'all':
return '<strong>@all</strong>'
if username in usernames:
return '<a href="/%s/">@%s</a>' % (username, username)
else:
return '@' + username
s = username_re.sub(replace_username, s)
s = hashtag_re.sub(
lambda m: '%s<a href="/search/?q=%s">%s</a>' % (
m.group(1),
urllib.quote(m.group(2)),
m.group(2),
),
s
)
return mark_safe(s)
| from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('(?:^|\s)(#\S+)')
@register.filter
def buglise(s):
s = unicode(s)
usernames = set(User.objects.values_list('username', flat=True))
def replace_username(match):
username = match.group(0)[1:]
if username.lower() == 'all':
return '<strong>@all</strong>'
if username in usernames:
return '<a href="/%s/">@%s</a>' % (username, username)
else:
return '@' + username
s = username_re.sub(replace_username, s)
s = hashtag_re.sub(
lambda m: '<a href="/search/?q=%s">%s</a>' % (
urllib.quote(m.group(0)),
m.group(0),
),
s
)
return mark_safe(s)
|
Change the order of the Web_Alltests suite | <?php
require_once dirname(__FILE__).'/../phpunit.php';
if(!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Web_AllTests::main');
}
require_once 'TAssetManagerTest.php';
require_once 'THttpCookieCollectionTest.php';
require_once 'THttpCookieTest.php';
require_once 'THttpRequestTest.php';
require_once 'THttpResponseTest.php';
require_once 'THttpSessionTest.php';
require_once 'THttpUtilityTest.php';
require_once 'TUriTest.php';
require_once 'UI/AllTests.php';
class Web_AllTests {
public static function main() {
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('System.Web');
$suite->addTestSuite('THttpRequestTest');
$suite->addTestSuite('TAssetManagerTest');
$suite->addTestSuite('THttpCookieCollectionTest');
$suite->addTestSuite('THttpCookieTest');
$suite->addTestSuite('THttpResponseTest');
$suite->addTestSuite('THttpSessionTest');
$suite->addTestSuite('THttpUtilityTest');
$suite->addTestSuite('TUriTest');
$suite->addTest(Web_UI_AllTests::suite());
return $suite;
}
}
if(PHPUnit_MAIN_METHOD == 'Web_AllTests::main') {
Web_AllTests::main();
}
?>
| <?php
require_once dirname(__FILE__).'/../phpunit.php';
if(!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Web_AllTests::main');
}
require_once 'TAssetManagerTest.php';
require_once 'THttpCookieCollectionTest.php';
require_once 'THttpCookieTest.php';
require_once 'THttpRequestTest.php';
require_once 'THttpResponseTest.php';
require_once 'THttpSessionTest.php';
require_once 'THttpUtilityTest.php';
require_once 'TUriTest.php';
require_once 'UI/AllTests.php';
class Web_AllTests {
public static function main() {
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('System.Web');
$suite->addTestSuite('TAssetManagerTest');
$suite->addTestSuite('THttpCookieCollectionTest');
$suite->addTestSuite('THttpCookieTest');
$suite->addTestSuite('THttpRequestTest');
$suite->addTestSuite('THttpResponseTest');
$suite->addTestSuite('THttpSessionTest');
$suite->addTestSuite('THttpUtilityTest');
$suite->addTestSuite('TUriTest');
$suite->addTest(Web_UI_AllTests::suite());
return $suite;
}
}
if(PHPUnit_MAIN_METHOD == 'Web_AllTests::main') {
Web_AllTests::main();
}
?>
|
Improve report format and information
Include total number of files. | #!/usr/bin/env python
import rethinkdb as r
from optparse import OptionParser
def compute_project_size(project_id, conn):
total = 0
count = 0
for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table(
'datafiles')).zip().run(conn):
total = total + f['size']
count = count + 1
print "Total files : %s" % "{:,}".format(count)
print "Project size: %s" % sizeof_fmt(total)
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-P", "--port", dest="port", type="int", help="rethinkdb port", default=30815)
parser.add_option("-p", "--project-id", dest="project_id", type="string", help="project id")
(options, args) = parser.parse_args()
conn = r.connect('localhost', options.port, db="materialscommons")
compute_project_size(options.project_id, conn)
| #!/usr/bin/env python
import rethinkdb as r
from optparse import OptionParser
def compute_project_size(project_id, conn):
total = 0
for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table(
'datafiles')).zip().run(conn):
total = total + f['size']
print "Total size %s" % sizeof_fmt(total)
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-P", "--port", dest="port", type="int", help="rethinkdb port", default=30815)
parser.add_option("-p", "--project-id", dest="project_id", type="string", help="project id")
(options, args) = parser.parse_args()
conn = r.connect('localhost', options.port, db="materialscommons")
compute_project_size(options.project_id, conn)
|
Make numpy test clearer and ensure unstub | import mockito
from mockito import when, patch
import pytest
import numpy as np
from . import module
pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.array([1, 2, 3])
when(module).one_arg(array).thenReturn('yep')
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
assert module.one_arg(array) == 'yep'
def testEnsureNumpyArrayAllowedWhenCalling(self):
array = np.array([1, 2, 3])
when(module).one_arg(Ellipsis).thenReturn('yep')
assert module.one_arg(array) == 'yep'
| import mockito
from mockito import when, patch
import numpy as np
from . import module
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = np.array([1, 2, 3])
with patch(mockito.invocation.MatchingInvocation.compare, xcompare):
when(module).one_arg(array).thenReturn('yep')
assert module.one_arg(array) == 'yep'
def testEnsureNumpyArrayAllowedWhenCalling(self):
array = np.array([1, 2, 3])
when(module).one_arg(Ellipsis).thenReturn('yep')
assert module.one_arg(array) == 'yep'
|
Fix resume operation, intialize session | package org.swellrt.beta.client.rest.operations;
import org.swellrt.beta.client.ServiceContext;
import org.swellrt.beta.client.rest.ServerOperation;
import org.swellrt.beta.client.rest.ServiceOperation;
import org.swellrt.beta.client.rest.operations.params.Account;
import org.swellrt.beta.client.rest.operations.params.AccountImpl;
import org.swellrt.beta.client.rest.operations.params.Credential;
import org.swellrt.beta.common.SException;
public final class ResumeOperation
extends ServerOperation<Credential, Account> {
public ResumeOperation(ServiceContext context, Credential options,
ServiceOperation.Callback<Account> callback) {
super(context, options, callback, AccountImpl.class);
}
@Override
public ServerOperation.Method getMethod() {
return ServerOperation.Method.POST;
}
@Override
protected void doSuccess(Account response) {
context.initSession(response);
super.doSuccess(response);
}
@Override
protected void buildRestParams() throws SException {
addPathElement("auth");
addPathElement(options.getId());
}
}
| package org.swellrt.beta.client.rest.operations;
import org.swellrt.beta.client.ServiceContext;
import org.swellrt.beta.client.rest.ServerOperation;
import org.swellrt.beta.client.rest.ServiceOperation;
import org.swellrt.beta.client.rest.operations.params.Account;
import org.swellrt.beta.client.rest.operations.params.AccountImpl;
import org.swellrt.beta.client.rest.operations.params.Credential;
import org.swellrt.beta.common.SException;
public final class ResumeOperation
extends ServerOperation<Credential, Account> {
public ResumeOperation(ServiceContext context, Credential options,
ServiceOperation.Callback<Account> callback) {
super(context, options, callback, AccountImpl.class);
}
@Override
public ServerOperation.Method getMethod() {
return ServerOperation.Method.POST;
}
@Override
protected void buildRestParams() throws SException {
addPathElement("auth");
addPathElement(options.getId());
}
}
|
Change karma to run both Firefox and Chrome.
I have both, I care about both, so run both! | module.exports = function(config){
config.set({
basePath : './',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/components/**/*.js',
'app/view*/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome', 'Firefox'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
| module.exports = function(config){
config.set({
basePath : './',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/components/**/*.js',
'app/view*/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
Make image preview slightly wider for mockup | import React, { Component } from 'react';
class MembersPreview extends Component {
render() {
const {displayName, image, intro, slug} = this.props;
// TODO: remove inline styles and implement a system
return (
<div style={{
height: '200px',
}}>
<img src={image.uri} style={{
maxHeight: '75px',
float: 'left',
}} />
<div style={{
float: 'right',
width: 'calc(100% - 150px);',
}}>
<p>
<a href={slug}>{displayName}</a>
</p>
<p>{intro}</p>
</div>
</div>
);
}
}
MembersPreview.propTypes = {
displayName: React.PropTypes.string.isRequired,
image: React.PropTypes.shape({
uri: React.PropTypes.string.isRequired,
height: React.PropTypes.number,
width: React.PropTypes.number,
}),
intro: React.PropTypes.string,
slug: React.PropTypes.string.isRequired,
usState: React.PropTypes.string,
};
export default MembersPreview;
| import React, { Component } from 'react';
class MembersPreview extends Component {
render() {
const {displayName, image, intro, slug} = this.props;
// TODO: remove inline styles and implement a system
return (
<div style={{
height: '200px',
}}>
<img src={image.uri} style={{
maxHeight: '75px',
float: 'left',
}} />
<div style={{
float: 'right',
width: 'calc(100% - 100px);',
}}>
<p>
<a href={slug}>{displayName}</a>
</p>
<p>{intro}</p>
</div>
</div>
);
}
}
MembersPreview.propTypes = {
displayName: React.PropTypes.string.isRequired,
image: React.PropTypes.shape({
uri: React.PropTypes.string.isRequired,
height: React.PropTypes.number,
width: React.PropTypes.number,
}),
intro: React.PropTypes.string,
slug: React.PropTypes.string.isRequired,
usState: React.PropTypes.string,
};
export default MembersPreview;
|
Allow all methods as allowed methods for CORS | var express = require('express');
var app = express();
var cors = require('cors')
var Notes = require('./domain/Notes');
var notes = new Notes();
var Users = require('./domain/Users');
var users = new Users();
/* enable cors */
app.use(cors({
"credentials": true,
"origin": true,
"methods": ["GET","HEAD","PUT","PATCH","POST","DELETE", "OPTIONS"]
}));
/* inject test data */
var TestData = require('./TestData');
TestData(notes, users);
/* HAL Api */
var halApi = require('./api/HalApi');
app.use('/api/hal', halApi(notes, users));
/* HTML Api */
var htmlApi = require('./api/HtmlApi');
app.use('/api/html', htmlApi(notes, users));
app.set('views', __dirname + '/api/html');
app.set('view engine', 'twig');
app.set('twig options', {
strict_variables: false
});
/* Redirect all other Users to github */
app.get('/', function(req, res) {
res.statusCode = 302;
res.setHeader('Location', '/api/html');
res.end();
});
app.get('/robots.txt', function(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send([
'User-Agent: *',
'Allow: /'
].join("\n"));
});
module.exports = app; | var express = require('express');
var app = express();
var cors = require('cors')
var Notes = require('./domain/Notes');
var notes = new Notes();
var Users = require('./domain/Users');
var users = new Users();
/* enable cors */
app.use(cors({
"credentials": true,
"origin": true
}));
/* inject test data */
var TestData = require('./TestData');
TestData(notes, users);
/* HAL Api */
var halApi = require('./api/HalApi');
app.use('/api/hal', halApi(notes, users));
/* HTML Api */
var htmlApi = require('./api/HtmlApi');
app.use('/api/html', htmlApi(notes, users));
app.set('views', __dirname + '/api/html');
app.set('view engine', 'twig');
app.set('twig options', {
strict_variables: false
});
/* Redirect all other Users to github */
app.get('/', function(req, res) {
res.statusCode = 302;
res.setHeader('Location', '/api/html');
res.end();
});
app.get('/robots.txt', function(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send([
'User-Agent: *',
'Allow: /'
].join("\n"));
});
module.exports = app; |
Fix for 'no writecb in Transform' error.
The clue came from the discussion here:
https://github.com/rvagg/through2/issues/1 | 'use strict';
var jest = require('jest-cli'),
gutil = require('gulp-util'),
through = require('through2');
module.exports = function (options) {
options = options || {};
return through.obj(function (file, enc, cb) {
options.rootDir = options.rootDir || file.path;
jest.runCLI({
config: options
}, options.rootDir, function (success) {
if(!success) {
cb(new gutil.PluginError('gulp-jest', { message: "Tests Failed" }));
} else {
cb();
}
}.bind(this));
});
};
| 'use strict';
var jest = require('jest-cli'),
gutil = require('gulp-util'),
through = require('through2');
module.exports = function (options) {
options = options || {};
return through.obj(function (file, enc, cb) {
options.rootDir = options.rootDir || file.path;
jest.runCLI({
config: options
}, options.rootDir, function (success) {
if(!success) {
cb(new gutil.PluginError('gulp-jest', { message: "Tests Failed" }));
}
cb();
}.bind(this));
});
};
|
[ADD] Change the icon on instructions view to chevrons | import React from 'react';
import autobind from 'core-decorators/es/autobind';
import { Button, Intent, Collapse } from '@blueprintjs/core';
import MarkdownRenderer from '../../../../../../lib/react/components/MarkdownRenderer';
import '../../scss/components/_instruction-panel.scss';
@autobind
class InstructionCollapse extends React.Component {
state = {
isOpen: false,
}
toggleOpen() {
this.setState((prevState) => {
return { isOpen: !prevState.isOpen }
});
}
render() {
const { title, content } = this.props.article;
return (
<div className='instruction-collapse'>
<Button className='pt-fill ' text={title}
iconName={this.state.isOpen?'chevron-up':'chevron-down'} onClick={this.toggleOpen}/>
<Collapse isOpen={this.state.isOpen}>
<div className='instruction-panel'>
<MarkdownRenderer className='markdown-content' src={content}/>
</div>
</Collapse>
</div>
);
}
}
export default InstructionCollapse;
| import React from 'react';
import autobind from 'core-decorators/es/autobind';
import { Button, Intent, Collapse } from '@blueprintjs/core';
import MarkdownRenderer from '../../../../../../lib/react/components/MarkdownRenderer';
import '../../scss/components/_instruction-panel.scss';
@autobind
class InstructionCollapse extends React.Component {
state = {
isOpen: false,
}
toggleOpen() {
this.setState((prevState) => {
return { isOpen: !prevState.isOpen }
});
}
render() {
const { title, content } = this.props.article;
return (
<div className='instruction-collapse'>
<Button className='pt-fill ' text={title}
iconName={this.state.isOpen?'remove':'add'} onClick={this.toggleOpen}/>
<Collapse isOpen={this.state.isOpen}>
<div className='instruction-panel'>
<MarkdownRenderer className='markdown-content' src={content}/>
</div>
</Collapse>
</div>
);
}
}
export default InstructionCollapse;
|
Fix the test with a good js
The promise API of watt is very limited. It's better to use the
callback way.
See https://github.com/mappum/watt/issues/15 | 'use strict';
const path = require ('path');
const {expect} = require ('chai');
const wannabe = require ('../lib/index.js');
describe ('index', function () {
it ('#default (good js)', function (done) {
wannabe (path.join (__dirname, './sample.js'), null, 'it', 'a.1', (err, frames) => {
expect (err).to.be.null;
expect (frames).to.be.eql ({
'12': [{
name: 'test',
value: 'foo'
}, {
name: 'a1',
value: undefined
}],
'13': [{
name: 'test',
value: 'foo'
}, {
name: 'a1',
value: 'foo - bar'
}]
});
done ();
});
});
it ('#default (bad js)', function (done) {
wannabe (path.join (__dirname, './other.txt'), null, 'it', 'a.1', (err, frames) => {
expect (err).to.be.not.null;
done ();
});
});
});
| 'use strict';
const path = require ('path');
const {expect} = require ('chai');
const wannabe = require ('../lib/index.js');
describe ('index', function () {
it ('#default', function (done) {
wannabe (path.join (__dirname, './sample.js'), null, 'it', 'a.1')
.then ((frames, err) => {
expect (err).to.be.undefined;
expect (frames).to.be.eql ({
'12': [{
name: 'test',
value: 'foo'
}, {
name: 'a1',
value: undefined
}],
'13': [{
name: 'test',
value: 'foo'
}, {
name: 'a1',
value: 'foo - bar'
}]
});
done ();
});
});
it ('#default (bad js)', function (done) {
wannabe (path.join (__dirname, './other.txt'), null, 'it', 'a.1', (err, frames) => {
expect (err).to.be.not.null;
done ();
});
});
});
|
Fix to return obj in reduce operation | const fs = require('fs')
module.exports.init = function init(config, cb) {
const path = config.path
const readF = (cb) => {
fs.readFile(path, 'utf8', (err, data) => {
if(err) {
return cb(err)
}
const dataArray = data.split('\n')
if(dataArray.some(entry => entry === undefined || entry.split('=').length < 2)) {
return cb(new Error(`File ${path} contains malformed entries.`))
}
const variables = dataArray.reduce((obj, entry) => {
const splitEntry = entry.split('=')
obj[splitEntry[0]] = splitEntry[1]
return obj
}, {})
cb(null, variables)
})
}
cb(null, {read: readF})
}
| const fs = require('fs')
module.exports.init = function init(config, cb) {
const path = config.path
const readF = (cb) => {
fs.readFile(path, 'utf8', (err, data) => {
if(err) {
return cb(err)
}
const dataArray = data.split('\n')
if(dataArray.some(entry => entry === undefined || entry.split('=').length < 2)) {
return cb(new Error(`File ${path} contains malformed entries.`))
}
const variables = dataArray.reduce((obj, entry) => {
const splitEntry = entry.split('=')
obj[splitEntry[0]] = splitEntry[1]
}, {})
cb(null, variables)
})
}
cb(null, {read: readF})
}
|
Print out ENVys with newlines for envy list | from cloudenvy.envy import Envy
class EnvyList(object):
"""List all ENVys in context of your current project"""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('list', help='list help')
subparser.set_defaults(func=self.run)
subparser.add_argument('-n', '--name', action='store', default='',
help='specify custom name for an ENVy')
return subparser
def run(self, config, args):
envy = Envy(config)
for server in envy.list_servers():
if server.name.startswith(envy.name):
print server.name
| from cloudenvy.envy import Envy
class EnvyList(object):
"""List all ENVys in context of your current project"""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('list', help='list help')
subparser.set_defaults(func=self.run)
subparser.add_argument('-n', '--name', action='store', default='',
help='specify custom name for an ENVy')
return subparser
#TODO(jakedahn): The way this works is just silly. This should be totally
# refactored to use nova's server metadata attributes.
def run(self, config, args):
envy = Envy(config)
envys = []
servers = envy.list_servers()
for server in servers:
if len(server.name.split(envy.name)) > 1:
envys.append(str(server.name))
print "ENVys for your project: %s" % str(envys)
|
Fix error on view using column alias to order by | const knex = require('../../../knex').web
const orgUnitFinder = require('../helpers/org-unit-finder')
const orgUnitConstants = require('../../constants/organisation-unit')
module.exports = function (id, type) {
var orgUnit = orgUnitFinder('name', type)
var table = 'individual_case_overview'
var whereClause = ''
var orderBy = 'lduCluster, teamName'
if (id !== undefined) {
whereClause = 'WHERE ' + orgUnit.name + '_id = ' + id
}
var selectColumns = [
'ldu_name AS lduCluster',
'team_name AS teamName',
'of_name AS offenderManager',
'total_cases AS totalCases',
'available_points AS availablePoints',
'total_points AS totalPoints',
'contracted_hours AS contractedHours',
'reduction_hours AS reductionHours',
'grade_code AS gradeCode'
]
if (orgUnit.name === orgUnitConstants.REGION.name || orgUnit.name === orgUnitConstants.NATIONAL.name) {
selectColumns.unshift('region_name AS regionName')
orderBy = 'regionName,' + orderBy
}
return knex.raw(
'SELECT ' + selectColumns.join(', ') +
' FROM ' + table + ' WITH (NOEXPAND)' +
whereClause + ' ORDER BY ' + orderBy)
.then(function (results) {
return results
})
}
| const knex = require('../../../knex').web
const orgUnitFinder = require('../helpers/org-unit-finder')
const orgUnitConstants = require('../../constants/organisation-unit')
module.exports = function (id, type) {
var orgUnit = orgUnitFinder('name', type)
var table = 'individual_case_overview'
var whereClause = ''
var orderBy = 'ldu_name, team_name'
if (id !== undefined) {
whereClause = 'WHERE ' + orgUnit.name + '_id = ' + id
}
var selectColumns = [
'ldu_name AS lduCluster',
'team_name AS teamName',
'of_name AS offenderManager',
'total_cases AS totalCases',
'available_points AS availablePoints',
'total_points AS totalPoints',
'contracted_hours AS contractedHours',
'reduction_hours AS reductionHours',
'grade_code AS gradeCode'
]
if (orgUnit.name === orgUnitConstants.REGION.name || orgUnit.name === orgUnitConstants.NATIONAL.name) {
selectColumns.unshift('region_name AS regionName')
orderBy = 'region_name,' + orderBy
}
return knex.raw(
'SELECT ' + selectColumns.join(', ') +
' FROM ' + table + ' WITH (NOEXPAND)' +
whereClause + ' ORDER BY ' + orderBy)
.then(function (results) {
return results
})
}
|
Use the build in static() method instead of building a static URL manually | # -*- coding: utf-8 -*-
# Copyright 2016, Digital Reasoning
#
# 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.
#
# Need this so the stackdio import below doesn't get confused
from __future__ import absolute_import
from django import template
from django.conf import settings
from django.shortcuts import resolve_url
from django.contrib.staticfiles.templatetags.staticfiles import static
from stackdio.server import __version__
register = template.Library()
@register.simple_tag
def stackdio_version():
return '<span class="version">{0}</span>'.format(__version__)
@register.simple_tag
def main_file():
if settings.JAVASCRIPT_DEBUG:
return resolve_url('ui:js-main')
else:
return static('stackdio/build/main.js')
| # -*- coding: utf-8 -*-
# Copyright 2016, Digital Reasoning
#
# 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.
#
# Need this so the stackdio import below doesn't get confused
from __future__ import absolute_import
from django import template
from django.conf import settings
from django.shortcuts import resolve_url
from stackdio.server import __version__
register = template.Library()
@register.simple_tag
def stackdio_version():
return '<span class="version">{0}</span>'.format(__version__)
@register.simple_tag
def main_file():
if settings.JAVASCRIPT_DEBUG:
return resolve_url('ui:js-main')
else:
return '{0}stackdio/build/main.js'.format(settings.STATIC_URL)
|
Use max representation for smaller space usage. | import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state):
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = max(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
| import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state): # Test code only
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = min(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
|
Fix for T2-674: Hardcoded default locations. Added loading of service descriptions from a URL.
git-svn-id: 10833e805afea9e5a6509b27c1b8b6924566be5c@10140 bf327186-88b3-11dd-a302-d386e5130c1c | package net.sf.taverna.t2.servicedescriptions;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Set;
import net.sf.taverna.t2.lang.observer.Observable;
import net.sf.taverna.t2.servicedescriptions.events.ServiceDescriptionRegistryEvent;
import net.sf.taverna.t2.workflowmodel.serialization.DeserializationException;
public interface ServiceDescriptionRegistry extends
Observable<ServiceDescriptionRegistryEvent> {
public void addServiceDescriptionProvider(
ServiceDescriptionProvider provider);
public Set<ServiceDescriptionProvider> getDefaultServiceDescriptionProviders();
public Set<ServiceDescriptionProvider> getServiceDescriptionProviders();
public Set<ServiceDescriptionProvider> getServiceDescriptionProviders(ServiceDescription sd);
@SuppressWarnings("unchecked")
public Set<ServiceDescription> getServiceDescriptions();
@SuppressWarnings("unchecked")
public List<ConfigurableServiceProvider> getUnconfiguredServiceProviders();
public Set<ServiceDescriptionProvider> getUserAddedServiceProviders();
public Set<ServiceDescriptionProvider> getUserRemovedServiceProviders();
public void loadServiceProviders() throws DeserializationException;
public void loadServiceProviders(File serviceProvidersURL)
throws DeserializationException;
public void loadServiceProviders(URL serviceProvidersURL)
throws DeserializationException;
public void refresh();
public void removeServiceDescriptionProvider(
ServiceDescriptionProvider provider);
public void saveServiceDescriptions();
public void saveServiceDescriptions(File serviceDescriptionsFile);
public void exportCurrentServiceDescriptions(File serviceDescriptionsFile);
}
| package net.sf.taverna.t2.servicedescriptions;
import java.io.File;
import java.util.List;
import java.util.Set;
import net.sf.taverna.t2.lang.observer.Observable;
import net.sf.taverna.t2.servicedescriptions.events.ServiceDescriptionRegistryEvent;
import net.sf.taverna.t2.workflowmodel.serialization.DeserializationException;
public interface ServiceDescriptionRegistry extends
Observable<ServiceDescriptionRegistryEvent> {
public void addServiceDescriptionProvider(
ServiceDescriptionProvider provider);
public Set<ServiceDescriptionProvider> getDefaultServiceDescriptionProviders();
public Set<ServiceDescriptionProvider> getServiceDescriptionProviders();
public Set<ServiceDescriptionProvider> getServiceDescriptionProviders(ServiceDescription sd);
@SuppressWarnings("unchecked")
public Set<ServiceDescription> getServiceDescriptions();
@SuppressWarnings("unchecked")
public List<ConfigurableServiceProvider> getUnconfiguredServiceProviders();
public Set<ServiceDescriptionProvider> getUserAddedServiceProviders();
public Set<ServiceDescriptionProvider> getUserRemovedServiceProviders();
public void loadServiceProviders() throws DeserializationException;
public void loadServiceProviders(File serviceProviderFile)
throws DeserializationException;
public void refresh();
public void removeServiceDescriptionProvider(
ServiceDescriptionProvider provider);
public void saveServiceDescriptions();
public void saveServiceDescriptions(File serviceDescriptionsFile);
public void exportCurrentServiceDescriptions(File serviceDescriptionsFile);
}
|
Improve type checking in ol.ImageUrlFunction | goog.provide('ol.ImageUrlFunction');
goog.provide('ol.ImageUrlFunctionType');
goog.require('ol.Size');
/**
* @typedef {function(this:ol.source.Source, ol.Extent, ol.Size, ol.Projection):
* (string|undefined)}
*/
ol.ImageUrlFunctionType;
/**
* @param {string} baseUrl Base URL (may have query data).
* @param {Object.<string,*>} params to encode in the url.
* @param {function(string, Object.<string,*>, ol.Extent, ol.Size,
* ol.Projection): (string|undefined)} paramsFunction params function.
* @return {ol.ImageUrlFunctionType} Image URL function.
*/
ol.ImageUrlFunction.createFromParamsFunction =
function(baseUrl, params, paramsFunction) {
return (
/**
* @param {ol.Extent} extent Extent.
* @param {ol.Size} size Size.
* @param {ol.Projection} projection Projection.
* @return {string|undefined} URL.
*/
function(extent, size, projection) {
return paramsFunction(baseUrl, params, extent, size, projection);
});
};
/**
* @param {ol.Extent} extent Extent.
* @param {ol.Size} size Size.
* @return {string|undefined} Image URL.
*/
ol.ImageUrlFunction.nullImageUrlFunction =
function(extent, size) {
return undefined;
};
| goog.provide('ol.ImageUrlFunction');
goog.provide('ol.ImageUrlFunctionType');
goog.require('ol.Size');
/**
* @typedef {function(this:ol.source.Source, ol.Extent, ol.Size, ol.Projection):
* (string|undefined)}
*/
ol.ImageUrlFunctionType;
/**
* @param {string} baseUrl Base URL (may have query data).
* @param {Object.<string,*>} params to encode in the url.
* @param {function(string, Object.<string,*>, ol.Extent, ol.Size,
* ol.Projection)} paramsFunction params function.
* @return {ol.ImageUrlFunctionType} Image URL function.
*/
ol.ImageUrlFunction.createFromParamsFunction =
function(baseUrl, params, paramsFunction) {
return function(extent, size, projection) {
return paramsFunction(
baseUrl, params, extent, size, projection);
};
};
/**
* @param {ol.Extent} extent Extent.
* @param {ol.Size} size Size.
* @return {string|undefined} Image URL.
*/
ol.ImageUrlFunction.nullImageUrlFunction =
function(extent, size) {
return undefined;
};
|
Set the container in the constructor | <?php
/*
* This file is part of the awurth/silex-user package.
*
* (c) Alexis Wurth <awurth.dev@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AWurth\SilexUser\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Command\Command;
/**
* Command.
*
* @author Alexis Wurth <awurth.dev@gmail.com>
*/
abstract class ContainerAwareCommand extends Command
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* Constructor.
*
* @param ContainerInterface $container
* @param string|null $name
*/
public function __construct(ContainerInterface $container, $name = null)
{
parent::__construct($name);
$this->container = $container;
}
/**
* Gets the container.
*
* @return ContainerInterface
*/
public function getContainer()
{
return $this->container;
}
/**
* Sets the container.
*
* @param ContainerInterface $container
*/
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}
}
| <?php
/*
* This file is part of the awurth/silex-user package.
*
* (c) Alexis Wurth <awurth.dev@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AWurth\SilexUser\Command;
use LogicException;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Command\Command;
/**
* Command.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class ContainerAwareCommand extends Command
{
/**
* @var ContainerInterface|null
*/
private $container;
/**
* @return ContainerInterface
*
* @throws LogicException
*/
protected function getContainer()
{
if (null === $this->container) {
$application = $this->getApplication();
if (null === $application) {
throw new LogicException('The container cannot be retrieved as the application instance is not yet set.');
}
$this->container = $application->getKernel()->getContainer();
}
return $this->container;
}
/**
* Sets the container.
*
* @param ContainerInterface|null $container A ContainerInterface instance or null
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}
|
Update module name as changed in last module version. | # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Excerpt + Image in Events",
"summary": "New layout for event summary, including an excerpt and image",
"version": "8.0.1.0.0",
"category": "Website",
"website": "http://www.antiun.com",
"author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": [
"website_event",
"html_image_url_extractor",
"html_text",
],
"data": [
"views/assets.xml",
"views/event.xml",
"views/event_event_view.xml",
],
"images": [
"images/frontend.png",
"images/backend.png",
"images/customize.png",
],
}
| # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Excerpt + Image in Events",
"summary": "New layout for event summary, including an excerpt and image",
"version": "8.0.1.0.0",
"category": "Website",
"website": "http://www.antiun.com",
"author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": [
"website_event",
"html_imgs",
"html_text",
],
"data": [
"views/assets.xml",
"views/event.xml",
"views/event_event_view.xml",
],
"images": [
"images/frontend.png",
"images/backend.png",
"images/customize.png",
],
}
|
Define the menu size dynamically | <!--
var browser = '';
var version = '';
var entrance = '';
var cond = '';
// BROWSER?
if (browser == '') {
if (navigator.appName.indexOf('Microsoft') != -1)
browser = 'IE'
else if (navigator.appName.indexOf('Netscape') != -1)
browser = 'Netscape'
else
browser = 'IE';
}
if (version == '') {
version= navigator.appVersion;
paren = version.indexOf('(');
whole_version = navigator.appVersion.substring(0,paren-1);
version = parseInt(whole_version);
}
if (browser == 'IE' && version < 7) {
document.write('<script type="text/javascript" src="/themes/nervecenter/javascript/ie7/ie7-standard-p.js"></scr'+'ipt>');
}
document.write('<script type="text/javascript" src="/themes/nervecenter/javascript/niftyjsCode.js"></scr'+'ipt>');
// jQuery function to define dropdown menu size
jQuery(document).ready(function () {
var hwindow = '';
hwindow = (jQuery(window).height()-100);
// Force the size dropdown menu
jQuery('#navigation ul li ul').css('max-height', hwindow);
});
// -->
| <!--
var browser = '';
var version = '';
var entrance = '';
var cond = '';
// BROWSER?
if (browser == '') {
if (navigator.appName.indexOf('Microsoft') != -1)
browser = 'IE'
else if (navigator.appName.indexOf('Netscape') != -1)
browser = 'Netscape'
else
browser = 'IE';
}
if (version == '') {
version= navigator.appVersion;
paren = version.indexOf('(');
whole_version = navigator.appVersion.substring(0,paren-1);
version = parseInt(whole_version);
}
if (browser == 'IE' && version < 7) {
document.write('<script type="text/javascript" src="/themes/nervecenter/javascript/ie7/ie7-standard-p.js"></scr'+'ipt>');
}
document.write('<script type="text/javascript" src="/themes/nervecenter/javascript/niftyjsCode.js"></scr'+'ipt>');
// -->
|
Rename default connection name property | <?php
namespace Veles\DataBase\ConnectionPools;
use Veles\DataBase\Connections\PdoConnection;
/**
* Class ConnectionPool
*
* @author Alexander Yancharuk <alex at itvault dot info>
*/
class ConnectionPool
{
/** @var array */
protected $pool;
/** @var string */
protected $conn_name;
/**
* @return string
*/
public function getDefaultConnectionName()
{
return $this->conn_name;
}
/**
* Add connection to connection pool
*
* @param PdoConnection $conn
* @param bool $default Flag is this connection default or not
* @return $this
* @see DbConnection
*/
public function addConnection(PdoConnection $conn, $default = false)
{
$this->pool[$conn->getName()] = $conn;
if ($default) {
$this->conn_name = $conn->getName();
}
return $this;
}
/**
* Get connection class by name
*
* @param string $name Connection name
* @return PdoConnection|null
* @see DbConnection
*/
public function getConnection($name)
{
return isset($this->pool[$name]) ? $this->pool[$name] : null;
}
}
| <?php
namespace Veles\DataBase\ConnectionPools;
use Veles\DataBase\Connections\PdoConnection;
/**
* Class ConnectionPool
*
* @author Alexander Yancharuk <alex at itvault dot info>
*/
class ConnectionPool
{
/** @var array */
protected $pool;
/** @var string */
protected $default_connection_name;
/**
* @return string
*/
public function getDefaultConnectionName()
{
return $this->default_connection_name;
}
/**
* Add connection to connection pool
*
* @param PdoConnection $conn
* @param bool $default Flag is this connection default or not
* @return $this
* @see DbConnection
*/
public function addConnection(PdoConnection $conn, $default = false)
{
$this->pool[$conn->getName()] = $conn;
if ($default) {
$this->default_connection_name = $conn->getName();
}
return $this;
}
/**
* Get connection class by name
*
* @param string $name Connection name
* @return PdoConnection|null
* @see DbConnection
*/
public function getConnection($name)
{
return isset($this->pool[$name]) ? $this->pool[$name] : null;
}
}
|
Save token to localStorage only if it changes | // TODO consider using https://babeljs.io/docs/plugins/transform-runtime/ instead of babel-polyfill
import "babel-polyfill"
import React from "react"
import { render } from "react-dom"
import { createStore, applyMiddleware } from "redux"
import { Provider } from "react-redux"
import createSagaMiddleware from "redux-saga"
import debounce from "lodash.debounce"
import { getToken, setToken } from "./lib/auth"
import { loginSuccess } from "./actions"
import reducers from "./reducers"
import { rootSaga } from "./sagas"
import "./main.scss"
import App from "./containers/App"
const container = document.getElementById("app")
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducers,
// eslint-disable-next-line
process.env.NODE_ENV !== "production" && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(sagaMiddleware),
)
sagaMiddleware.run(rootSaga)
let token = getToken()
if (token) {
store.dispatch(loginSuccess(token))
}
store.subscribe(debounce(() => {
const newToken = store.getState().auth.token
if (newToken !== token) {
token = newToken
setToken(newToken)
}
}, 500, {
leading: true,
trailing: false,
}))
render(
<Provider store={store}>
<App />
</Provider>,
container,
)
| // TODO consider using https://babeljs.io/docs/plugins/transform-runtime/ instead of babel-polyfill
import "babel-polyfill"
import React from "react"
import { render } from "react-dom"
import { createStore, applyMiddleware } from "redux"
import { Provider } from "react-redux"
import createSagaMiddleware from "redux-saga"
import debounce from "lodash.debounce"
import { getToken, setToken } from "./lib/auth"
import { loginSuccess } from "./actions"
import reducers from "./reducers"
import { rootSaga } from "./sagas"
import "./main.scss"
import App from "./containers/App"
const container = document.getElementById("app")
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducers,
// eslint-disable-next-line
process.env.NODE_ENV !== "production" && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(sagaMiddleware),
)
sagaMiddleware.run(rootSaga)
const token = getToken()
if (token) {
store.dispatch(loginSuccess(token))
}
store.subscribe(debounce(() => {
console.log("setting token", store.getState().auth.token)
setToken(store.getState().auth.token)
}, 500, {
leading: true,
trailing: false,
}))
render(
<Provider store={store}>
<App />
</Provider>,
container,
)
|
Use second argument to test command as configuration filter | const pickBy = require('ramda/src/pickBy');
const minimist = require('minimist');
const { warn } = require('../../console');
const getConfig = require('../../config');
const parseOptions = require('./parse-options');
const runTests = require('./run-tests');
function test(args) {
const argv = minimist(args);
const config = getConfig();
const options = parseOptions(args, config);
const targetFilter = new RegExp(argv['target-filter']);
const configurationFilter = new RegExp(argv['configuration-filter'] || argv._[1]);
const matchesFilters = ({ target }, name) =>
targetFilter.test(target) && configurationFilter.test(name);
const configurations = pickBy(matchesFilters, config.configurations);
if (Object.keys(configurations).length === 0) {
warn('No matching configurations');
process.exit(0);
}
return runTests(configurations, options);
}
module.exports = test;
| const pickBy = require('ramda/src/pickBy');
const minimist = require('minimist');
const { warn } = require('../../console');
const getConfig = require('../../config');
const parseOptions = require('./parse-options');
const runTests = require('./run-tests');
function test(args) {
const argv = minimist(args);
const config = getConfig();
const options = parseOptions(args, config);
const targetFilter = new RegExp(argv['target-filter']);
const configurationFilter = new RegExp(argv['configuration-filter']);
const matchesFilters = ({ target }, name) =>
targetFilter.test(target) && configurationFilter.test(name);
const configurations = pickBy(matchesFilters, config.configurations);
if (Object.keys(configurations).length === 0) {
warn('No matching configurations');
process.exit(0);
}
return runTests(configurations, options);
}
module.exports = test;
|
Add more tests around ignored names | #: Okay
def ok():
pass
#: N802
def __bad():
pass
#: N802
def bad__():
pass
#: N802
def __bad__():
pass
#: Okay
def _ok():
pass
#: Okay
def ok_ok_ok_ok():
pass
#: Okay
def _somehow_good():
pass
#: Okay
def go_od_():
pass
#: Okay
def _go_od_():
pass
#: N802
def NotOK():
pass
#: Okay
def _():
pass
#: Okay
class Foo(object):
def __method(self):
pass
#: Okay
class Foo(object):
def __method__(self):
pass
#: Okay
class ClassName(object):
def __method__(self):
pass
#: N802
class ClassName(object):
def notOk(self):
pass
#: N802
class ClassName(object):
def method(self):
def __bad():
pass
#: Okay
def setUp():
pass
#: Okay
def tearDown():
pass
#: Okay
class TestCase:
def setUp(self):
pass
def tearDown(self):
pass
| #: Okay
def ok():
pass
#: N802
def __bad():
pass
#: N802
def bad__():
pass
#: N802
def __bad__():
pass
#: Okay
def _ok():
pass
#: Okay
def ok_ok_ok_ok():
pass
#: Okay
def _somehow_good():
pass
#: Okay
def go_od_():
pass
#: Okay
def _go_od_():
pass
#: N802
def NotOK():
pass
#: Okay
def _():
pass
#: Okay
class Foo(object):
def __method(self):
pass
#: Okay
class Foo(object):
def __method__(self):
pass
#: Okay
class ClassName(object):
def __method__(self):
pass
#: N802
class ClassName(object):
def notOk(self):
pass
#: N802
class ClassName(object):
def method(self):
def __bad():
pass
#: Okay
def setUp():
pass
#: Okay
def tearDown():
pass
|
Move task starting and ending points to start of days | /**
* Parse task and return task info if
* the task is valid, otherwise throw
* error.
* @param {string} query Enetered task
* @return {object} Task info containing
* task text, start time
* and dealine
*/
function parse(query) {
/**
* Day, week or month coefficient
* @type {Object}
*/
const dwm = {
d: 1,
'': 1,
w: 7,
m: 30,
};
const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/;
const regexResult = regex.exec(query);
const text = query.slice(0, regexResult.index);
let start = Date.now() - ((Date.now() % 86400000) + (new Date().getTimezoneOffset() * 60000));
if (regexResult[3]) {
start += 86400000 * regexResult[4] * dwm[regexResult[5]];
}
const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]);
const importance = regexResult[6].length + 1;
const status = 0;
return {
text: text.trim(),
start,
end,
importance,
status,
};
}
module.exports = parse;
| /**
* Parse task and return task info if
* the task is valid, otherwise throw
* error.
* @param {string} query Enetered task
* @return {object} Task info containing
* task text, start time
* and dealine
*/
function parse(query) {
/**
* Day, week or month coefficient
* @type {Object}
*/
const dwm = {
d: 1,
'': 1,
w: 7,
m: 30,
};
const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/;
const regexResult = regex.exec(query);
const text = query.slice(0, regexResult.index);
let start = Date.now();
if (regexResult[3]) {
start += 86400000 * regexResult[4] * dwm[regexResult[5]];
}
const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]);
const importance = regexResult[6].length + 1;
const status = 0;
return {
text: text.trim(),
start,
end,
importance,
status,
};
}
module.exports = parse;
|
Use struct{} instead of int as context key
The line
val := ctx.Value(activeSpanKey)
previously allocated to pass the integer
`activeSpanKey` as an interface. With this
change, no such allocation is necessary.
This showed up during benchmarks in
cockroachdb/cockroach. | package opentracing
import "golang.org/x/net/context"
type contextKey struct{}
var activeSpanKey = contextKey{}
// ContextWithSpan returns a new `context.Context` that holds a reference to
// the given `Span`.
//
// The second return value is simply the `span` passed in:
// this can save some typing and is only provided as a convenience.
func ContextWithSpan(ctx context.Context, span Span) (context.Context, Span) {
return context.WithValue(ctx, activeSpanKey, span), span
}
// BackgroundContextWithSpan is a convenience wrapper around
// `ContextWithSpan(context.BackgroundContext(), ...)`.
//
// The second return value is simply the `span` passed in:
// this can save some typing and is only provided as a convenience.
func BackgroundContextWithSpan(span Span) (context.Context, Span) {
return context.WithValue(context.Background(), activeSpanKey, span), span
}
// SpanFromContext returns the `Span` previously associated with `ctx`, or
// `nil` if no such `Span` could be found.
func SpanFromContext(ctx context.Context) Span {
val := ctx.Value(activeSpanKey)
if span, ok := val.(Span); ok {
return span
}
return nil
}
| package opentracing
import "golang.org/x/net/context"
type contextKey int
const activeSpanKey contextKey = iota
// ContextWithSpan returns a new `context.Context` that holds a reference to
// the given `Span`.
//
// The second return value is simply the `span` passed in:
// this can save some typing and is only provided as a convenience.
func ContextWithSpan(ctx context.Context, span Span) (context.Context, Span) {
return context.WithValue(ctx, activeSpanKey, span), span
}
// BackgroundContextWithSpan is a convenience wrapper around
// `ContextWithSpan(context.BackgroundContext(), ...)`.
//
// The second return value is simply the `span` passed in:
// this can save some typing and is only provided as a convenience.
func BackgroundContextWithSpan(span Span) (context.Context, Span) {
return context.WithValue(context.Background(), activeSpanKey, span), span
}
// SpanFromContext returns the `Span` previously associated with `ctx`, or
// `nil` if no such `Span` could be found.
func SpanFromContext(ctx context.Context) Span {
val := ctx.Value(activeSpanKey)
if span, ok := val.(Span); ok {
return span
}
return nil
}
|
Test - one more reproduction for implicit phpDoc issues | <?php
namespace MethodPhpDocsNamespace;
use SomeNamespace\Amet as Dolor;
interface FooInterface
{
/**
* @return void
*/
public function phpDocVoidMethodFromInterface();
}
class FooParentParent
{
/**
* @return void
*/
public function phpDocVoidParentMethod()
{
}
}
abstract class FooParent extends FooParentParent implements FooInterface
{
/**
* @return Static
*/
public function doLorem()
{
}
/**
* @return static
*/
public function doIpsum(): self
{
}
/**
* @return $this
*/
public function doThis()
{
return $this;
}
/**
* @return $this|null
*/
public function doThisNullable()
{
return $this;
}
/**
* @return $this|Bar|null
*/
public function doThisUnion()
{
}
/**
* @return void
*/
public function phpDocVoidMethod()
{
}
/**
* {@inheritDoc}
*/
public function phpDocVoidParentMethod()
{
}
}
| <?php
namespace MethodPhpDocsNamespace;
use SomeNamespace\Amet as Dolor;
interface FooInterface
{
/**
* @return void
*/
public function phpDocVoidMethodFromInterface();
}
class FooParentParent
{
/**
* @return void
*/
public function phpDocVoidParentMethod()
{
}
}
abstract class FooParent extends FooParentParent implements FooInterface
{
/**
* @return Static
*/
public function doLorem()
{
}
/**
* @return static
*/
public function doIpsum(): self
{
}
/**
* @return $this
*/
public function doThis()
{
return $this;
}
/**
* @return $this|null
*/
public function doThisNullable()
{
return $this;
}
/**
* @return $this|Bar|null
*/
public function doThisUnion()
{
}
/**
* @return void
*/
public function phpDocVoidMethod()
{
}
}
|
Fix typo in CSS class name | import React, { PropTypes } from 'react';
import Alternative from './Alternative';
import css from './Alternatives.css';
const Alternatives = ({ disabled, alternatives, handleChange, selectedVote }) => (
<div className={css.alternatives}>
{alternatives.map(alternative => (
<Alternative
disabled={disabled && alternative.id !== selectedVote}
key={alternative.id} {...alternative}
onClick={handleChange} selected={alternative.id === selectedVote}
/>
))}
</div>
);
Alternatives.defaultProps = {
selectedVote: null,
handleChange: undefined,
disabled: false,
};
Alternatives.propTypes = {
alternatives: PropTypes.arrayOf(PropTypes.shape(Alternative.propTypes)).isRequired,
disabled: PropTypes.bool,
handleChange: PropTypes.func,
selectedVote: PropTypes.string,
};
export default Alternatives;
| import React, { PropTypes } from 'react';
import Alternative from './Alternative';
import css from './Alternatives.css';
const Alternatives = ({ disabled, alternatives, handleChange, selectedVote }) => (
<div className={css.lternatives}>
{alternatives.map(alternative => (
<Alternative
disabled={disabled && alternative.id !== selectedVote}
key={alternative.id} {...alternative}
onClick={handleChange} selected={alternative.id === selectedVote}
/>
))}
</div>
);
Alternatives.defaultProps = {
selectedVote: null,
handleChange: undefined,
disabled: false,
};
Alternatives.propTypes = {
alternatives: PropTypes.arrayOf(PropTypes.shape(Alternative.propTypes)).isRequired,
disabled: PropTypes.bool,
handleChange: PropTypes.func,
selectedVote: PropTypes.string,
};
export default Alternatives;
|
Fix normalization of tags in case is None | """
This library offers an API to use Tacyt in a python environment.
Copyright (C) 2015-2020 Eleven Paths
"""
try:
import simplejson as json
except ImportError:
import json
class TagRequest(object):
LIST_REQUEST = "LIST"
CREATE_REQUEST = "CREATE"
REMOVE_REQUEST = "REMOVE"
REMOVE_ALL_REQUEST = "REMOVE_ALL"
def __init__(self, request_type=None, tag=None, apps=None):
self.request_type = request_type
self.tag = tag.strip().lower() if tag else None
self.apps = apps if apps else []
def as_dict(self):
json_obj = dict()
if self.request_type:
json_obj["requestType"] = self.request_type
if self.tag:
json_obj["tag"] = self.tag
if self.apps:
json_obj["apps"] = self.apps
return json_obj
def get_json_encode_string(self):
return json.dumps(self.as_dict())
| """
This library offers an API to use Tacyt in a python environment.
Copyright (C) 2015-2020 Eleven Paths
"""
try:
import simplejson as json
except ImportError:
import json
class TagRequest(object):
LIST_REQUEST = "LIST"
CREATE_REQUEST = "CREATE"
REMOVE_REQUEST = "REMOVE"
REMOVE_ALL_REQUEST = "REMOVE_ALL"
def __init__(self, request_type=None, tag=None, apps=None):
self.request_type = request_type
self.tag = tag.strip().lower()
self.apps = apps if apps else []
def as_dict(self):
json_obj = dict()
if self.request_type:
json_obj["requestType"] = self.request_type
if self.tag:
json_obj["tag"] = self.tag
if self.apps:
json_obj["apps"] = self.apps
return json_obj
def get_json_encode_string(self):
return json.dumps(self.as_dict())
|
Put mouse clicks in it's own dictionary | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
buttons = {
self.tbAdd: self.addRow,
self.tbRemove: self.removeRow,
self.btnSwitchTor: self.switchTor,
}
self.evAddClick(buttons)
def evAddClick(self, obj_dict):
for obj in obj_dict:
obj.clicked.connect(obj_dict[obj])
def addRow(self):
rowPos = self.twSettings.rowCount()
self.twSettings.insertRow(rowPos)
def removeRow(self):
rows = sorted(set(index.row() for index in self.twSettings.selectedIndexes()))
rows.reverse()
for row in rows:
self.twSettings.removeRow(row)
def switchTor(self):
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
| import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
self.tbAdd.clicked.connect(self.addRow)
self.tbRemove.clicked.connect(self.removeRow)
def addRow(self):
rowPos = self.twSettings.rowCount()
self.twSettings.insertRow(rowPos)
def removeRow(self):
rows = sorted(set(index.row() for index in self.twSettings.selectedIndexes()))
rows.reverse()
for row in rows:
self.twSettings.removeRow(row)
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
|
Fix missing import in 'builtin_asset' code | // +build builtin_assets
package main
import (
"context"
"net/http"
"path"
"path/filepath"
"strings"
)
func (w *httpWorker) httpHandleAsset(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
var (
isDefault bool
ct string
)
// Stop handling assets if frontend is disabled
if !w.service.config.Frontend.Enabled {
rw.WriteHeader(http.StatusForbidden)
return
}
// Get file data from built-in assets
filePath := strings.TrimPrefix(r.URL.Path, w.service.config.RootPath+"/assets/")
if strings.HasSuffix(filePath, "/") || filepath.Ext(filePath) == "" {
filePath = httpDefaultPath
}
if filePath == httpDefaultPath {
isDefault = true
}
data, err := Asset(filePath)
if err != nil {
rw.WriteHeader(http.StatusNotFound)
return
}
// Handle default file path
if isDefault {
w.httpServeDefault(rw, string(data))
return
}
// Get asset content type
switch path.Ext(filePath) {
case ".css":
ct = "text/css"
case ".js":
ct = "text/javascript"
default:
ct = http.DetectContentType(data)
}
rw.Header().Set("Content-Type", ct)
rw.WriteHeader(http.StatusOK)
rw.Write(data)
}
| // +build builtin_assets
package main
import (
"context"
"net/http"
"path"
"strings"
)
func (w *httpWorker) httpHandleAsset(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
var (
isDefault bool
ct string
)
// Stop handling assets if frontend is disabled
if !w.service.config.Frontend.Enabled {
rw.WriteHeader(http.StatusForbidden)
return
}
// Get file data from built-in assets
filePath := strings.TrimPrefix(r.URL.Path, w.service.config.RootPath+"/assets/")
if strings.HasSuffix(filePath, "/") || filepath.Ext(filePath) == "" {
filePath = httpDefaultPath
}
if filePath == httpDefaultPath {
isDefault = true
}
data, err := Asset(filePath)
if err != nil {
rw.WriteHeader(http.StatusNotFound)
return
}
// Handle default file path
if isDefault {
w.httpServeDefault(rw, string(data))
return
}
// Get asset content type
switch path.Ext(filePath) {
case ".css":
ct = "text/css"
case ".js":
ct = "text/javascript"
default:
ct = http.DetectContentType(data)
}
rw.Header().Set("Content-Type", ct)
rw.WriteHeader(http.StatusOK)
rw.Write(data)
}
|
Use Fetch API instead of XHR | class Unsplash {
static getImage (frequency) {
return new Promise((resolve, reject) => {
// Set proper frequency in URL + screen size
var unsplashUrl = `https://source.unsplash.com/${screen.width}x${screen.height}/`;
switch (frequency) {
case 'daily':
unsplashUrl += 'daily';
break;
case 'weekly':
unsplashUrl += 'weekly';
break;
}
// Follow redirect to get actual image URL
fetch(unsplashUrl)
.then((res) => {
if (res.ok && (res.status >= 200 && res.status < 300)) {
resolve(res.url);
} else {
reject('Fetching Unsplash image failed');
}
});
});
}
}
export default Unsplash;
| class Unsplash {
static getImage (frequency) {
return new Promise((resolve, reject) => {
// Set proper frequency in URL + screen size
var unsplashUrl = `https://source.unsplash.com/${screen.width}x${screen.height}/`;
switch (frequency) {
case 'daily':
unsplashUrl += 'daily';
break;
case 'weekly':
unsplashUrl += 'weekly';
break;
}
// Follow redirect to get actual image URL
const req = new XMLHttpRequest();
req.timeout = 2000;
req.onreadystatechange = () => {
if (req.readyState === 4 && (req.status >= 200 && req.status < 300)) {
resolve(req.responseURL);
}
};
req.ontimeout = (e) => {
reject(e);
};
req.open('GET', unsplashUrl, true);
req.send(null);
});
}
}
export default Unsplash;
|
Make the personal condor config world readable | from os.path import join
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.condor as condor
import osgtest.library.osgunittest as osgunittest
import osgtest.library.service as service
personal_condor_config = '''
DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD
CONDOR_HOST = $(FULL_HOSTNAME)
'''
class TestStartCondor(osgunittest.OSGTestCase):
def test_01_start_condor(self):
core.state['condor.running-service'] = False
core.skip_ok_unless_installed('condor')
core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG')
if service.is_running('condor'):
core.state['condor.running-service'] = True
return
core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf')
files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor', chmod=0o644)
core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog'])
service.check_start('condor')
core.state['condor.started-service'] = True
core.state['condor.running-service'] = True
| from os.path import join
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.condor as condor
import osgtest.library.osgunittest as osgunittest
import osgtest.library.service as service
personal_condor_config = '''
DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD
CONDOR_HOST = $(FULL_HOSTNAME)
'''
class TestStartCondor(osgunittest.OSGTestCase):
def test_01_start_condor(self):
core.state['condor.running-service'] = False
core.skip_ok_unless_installed('condor')
core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG')
if service.is_running('condor'):
core.state['condor.running-service'] = True
return
core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf')
files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor')
core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog'])
service.check_start('condor')
core.state['condor.started-service'] = True
core.state['condor.running-service'] = True
|
Make sure flocker package can be imported even if it's not installed. | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for top-level ``flocker`` package.
"""
from sys import executable
from subprocess import check_output, STDOUT
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath
import flocker
class WarningsTests(SynchronousTestCase):
"""
Tests for warning suppression.
"""
def test_warnings_suppressed(self):
"""
Warnings are suppressed for processes that import flocker.
"""
root = FilePath(flocker.__file__)
result = check_output(
[executable, b"-c", (b"import flocker; import warnings; " +
b"warnings.warn('ohno')")],
stderr=STDOUT,
# Make sure we can import flocker package:
cwd=root.parent().parent().path)
self.assertEqual(result, b"")
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for top-level ``flocker`` package.
"""
from sys import executable
from subprocess import check_output, STDOUT
from twisted.trial.unittest import SynchronousTestCase
class WarningsTests(SynchronousTestCase):
"""
Tests for warning suppression.
"""
def test_warnings_suppressed(self):
"""
Warnings are suppressed for processes that import flocker.
"""
result = check_output(
[executable, b"-c", (b"import flocker; import warnings; " +
b"warnings.warn('ohno')")],
stderr=STDOUT)
self.assertEqual(result, b"")
|
Add protection via API_KEY in parameter | /*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';
require("babel/register");
var EventEmitter = require('eventemitter3');
var emitter = new EventEmitter();
var rx = function(req, res) {
if(req.query.api_key === process.env.API_KEY){
var data = req.body;
emitter.emit('pkg', data);
}
res.end();
};
var tx = function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// Heartbeat
var nln = () => res.write('\n');
var hbt = setInterval(nln, 15000);
var onPkg = (data) => {
res.write("retry: 500\n");
res.write(`event: pkg\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
emitter.on('pkg', onPkg);
// Clear heartbeat and listener
req.on('close', () => {
clearInterval(hbt);
emitter.removeListener('pkg', onPkg);
});
};
module.exports = {
rx: rx,
tx: tx
};
| /*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';
require("babel/register");
var EventEmitter = require('eventemitter3');
var emitter = new EventEmitter();
var rx = function(req, res) {
var data = req.body;
emitter.emit('pkg', data);
res.end();
};
var tx = function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// Heartbeat
var nln = () => res.write('\n');
var hbt = setInterval(nln, 15000);
var onPkg = (data) => {
res.write("retry: 500\n");
res.write(`event: pkg\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
emitter.on('pkg', onPkg);
// Clear heartbeat and listener
req.on('close', () => {
clearInterval(hbt);
emitter.removeListener('pkg', onPkg);
});
};
module.exports = {
rx: rx,
tx: tx
};
|
Make thumb cache key as first large preview cache key | /*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.client;
public class EhCacheKeyFactory {
public static String getThumbKey(long gid) {
return "preview:large:" + gid + ":" + 0; // "thumb:" + gid;
}
public static String getNormalPreviewKey(long gid, int index) {
return "preview:normal:" + gid + ":" + index;
}
public static String getLargePreviewKey(long gid, int index) {
return "preview:large:" + gid + ":" + index;
}
public static String getLargePreviewSetKey(long gid, int index) {
return "large_preview_set:" + gid + ":" + index;
}
public static String getImageKey(long gid, int index) {
return "image:" + gid + ":" + index;
}
}
| /*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.client;
public class EhCacheKeyFactory {
public static String getThumbKey(long gid) {
return "thumb:" + gid;
}
public static String getNormalPreviewKey(long gid, int index) {
return "preview:normal:" + gid + ":" + index;
}
public static String getLargePreviewKey(long gid, int index) {
return "preview:large:" + gid + ":" + index;
}
public static String getLargePreviewSetKey(long gid, int index) {
return "large_preview_set:" + gid + ":" + index;
}
public static String getImageKey(long gid, int index) {
return "image:" + gid + ":" + index;
}
}
|
Add hyphen to date-time pattern | package org.tinylog.impl.format.pattern.placeholders;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.tinylog.core.Framework;
import org.tinylog.core.internal.InternalLogger;
/**
* Builder for creating an instance of {@link DatePlaceholder}.
*/
public class DatePlaceholderBuilder implements PlaceholderBuilder {
private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
/** */
public DatePlaceholderBuilder() {
}
@Override
public String getName() {
return "date";
}
@Override
public Placeholder create(Framework framework, String value) {
String pattern = value == null ? DEFAULT_PATTERN : value;
Locale locale = framework.getConfiguration().getLocale();
ZoneId zone = framework.getConfiguration().getZone();
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, locale);
return new DatePlaceholder(formatter.withZone(zone), value != null);
} catch (IllegalArgumentException ex) {
InternalLogger.error(ex, "Invalid date-time pattern: \"{}\"", pattern);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DEFAULT_PATTERN, locale);
return new DatePlaceholder(formatter.withZone(zone), false);
}
}
}
| package org.tinylog.impl.format.pattern.placeholders;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.tinylog.core.Framework;
import org.tinylog.core.internal.InternalLogger;
/**
* Builder for creating an instance of {@link DatePlaceholder}.
*/
public class DatePlaceholderBuilder implements PlaceholderBuilder {
private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
/** */
public DatePlaceholderBuilder() {
}
@Override
public String getName() {
return "date";
}
@Override
public Placeholder create(Framework framework, String value) {
String pattern = value == null ? DEFAULT_PATTERN : value;
Locale locale = framework.getConfiguration().getLocale();
ZoneId zone = framework.getConfiguration().getZone();
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, locale);
return new DatePlaceholder(formatter.withZone(zone), value != null);
} catch (IllegalArgumentException ex) {
InternalLogger.error(ex, "Invalid date time pattern: \"{}\"", pattern);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DEFAULT_PATTERN, locale);
return new DatePlaceholder(formatter.withZone(zone), false);
}
}
}
|
Allow changing of villager id | package org.cyclops.cyclopscore.config.extendedconfig;
import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager;
import org.cyclops.cyclopscore.init.ModBase;
/**
* Config for villagers.
* @author rubensworks
* @see ExtendedConfig
*/
public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> {
private int id;
/**
* Make a new instance.
* @param mod The mod instance.
* @param defaultId The default ID for the configurable.
* @param namedId The unique name ID for the configurable.
* @param comment The comment to add in the config file for this configurable.
* @param element The class of this configurable.
*/
public VillagerConfig(ModBase mod, int defaultId, String namedId,
String comment, Class<? extends ConfigurableVillager> element) {
super(mod, defaultId != 0, namedId, comment, element);
this.id = defaultId;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
@Override
public String getUnlocalizedName() {
return "entity.villager." + getNamedId();
}
@Override
public ConfigurableType getHolderType() {
return ConfigurableType.VILLAGER;
}
}
| package org.cyclops.cyclopscore.config.extendedconfig;
import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager;
import org.cyclops.cyclopscore.init.ModBase;
/**
* Config for villagers.
* @author rubensworks
* @see ExtendedConfig
*/
public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> {
private final int id;
/**
* Make a new instance.
* @param mod The mod instance.
* @param defaultId The default ID for the configurable.
* @param namedId The unique name ID for the configurable.
* @param comment The comment to add in the config file for this configurable.
* @param element The class of this configurable.
*/
public VillagerConfig(ModBase mod, int defaultId, String namedId,
String comment, Class<? extends ConfigurableVillager> element) {
super(mod, defaultId != 0, namedId, comment, element);
this.id = defaultId;
}
public int getId() {
return this.id;
}
@Override
public String getUnlocalizedName() {
return "entity.villager." + getNamedId();
}
@Override
public ConfigurableType getHolderType() {
return ConfigurableType.VILLAGER;
}
}
|
[Benchmark] Update 1000 to variable for users to adjust | <?php
require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/bench.php';
$x = 1000;
if (extension_loaded('xdebug')) {
echo "Warning: xdebug is loaded, it can impact performance negatively.\n";
echo "\n";
}
$tests = array(
$x . ' one-off timers' => function ($loop) use ($x) {
for ($i = 0; $i < $x; $i++) {
$loop->addTimer(1, function ($signature, $loop) {});
}
$loop->run();
},
$x . ' periodic timers' => function ($loop) use ($x) {
for ($i = 0; $i < $x; $i++) {
$loop->addPeriodicTimer(2, function ($signature, $loop) use (&$i, $x) {
if ($i >= $x) {
$loop->cancelTimer($signature);
}
});
}
$loop->run();
},
);
benchLoops($tests);
| <?php
require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/bench.php';
if (extension_loaded('xdebug')) {
echo "Warning: xdebug is loaded, it can impact performance negatively.\n";
echo "\n";
}
$tests = array(
'1000 one-off timers' => function ($loop) {
for ($i = 0; $i < 1000; $i++) {
$loop->addTimer(1, function ($signature, $loop) {});
}
$loop->run();
},
'1000 periodic timers' => function ($loop) {
for ($i = 0; $i < 1000; $i++) {
$loop->addPeriodicTimer(2, function ($signature, $loop) use (&$i) {
if ($i >= 1000) {
$loop->cancelTimer($signature);
}
});
}
$loop->run();
},
);
benchLoops($tests);
|
Sort the database order in the inspect page. | from django.shortcuts import render
from django.utils.datastructures import SortedDict
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
database_details = SortedDict()
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
| from django.shortcuts import render
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = [name[2:] for name in conn.info() if name.startswith('db')]
database_details = {}
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
|
Remove required page key menu_title | <?php
/*
* This file is part of WordPlate.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace WordPlate\Acf;
use InvalidArgumentException;
/**
* This is the page class.
*
* @author Vincent Klaiber <hello@vinkla.com>
*/
class Page
{
/**
* Create a new page instance.
*
* @param array $settings
*
* @return void
*/
public function __construct(array $settings)
{
$keys = ['page_title', 'menu_slug'];
foreach ($keys as $key) {
if (!array_key_exists($key, $settings)) {
throw new InvalidArgumentException("Missing page setting key [$key].");
}
}
$this->settings = $settings;
}
/**
* Return the page as array.
*
* @return array
*/
public function toArray(): array
{
return $this->settings;
}
}
| <?php
/*
* This file is part of WordPlate.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace WordPlate\Acf;
use InvalidArgumentException;
/**
* This is the page class.
*
* @author Vincent Klaiber <hello@vinkla.com>
*/
class Page
{
/**
* Create a new page instance.
*
* @param array $settings
*
* @return void
*/
public function __construct(array $settings)
{
$keys = ['page_title', 'menu_title', 'menu_slug'];
foreach ($keys as $key) {
if (!array_key_exists($key, $settings)) {
throw new InvalidArgumentException("Missing page setting key [$key].");
}
}
$this->settings = $settings;
}
/**
* Return the page as array.
*
* @return array
*/
public function toArray(): array
{
return $this->settings;
}
}
|
Stop being secretive about it | """
Forms
=====
These three form subclasses will automatically add limitation by tenant
to all form fields with a ``queryset`` attribute.
.. warning::
If you customized the dropdown using ``choices`` you have to limit the
choices by the current tenant yourself.
"""
from django import forms
from towel import forms as towel_forms
from towel.utils import safe_queryset_and
def _process_fields(form, request):
for field in form.fields.values():
if getattr(field, 'queryset', None):
model = field.queryset.model
field.queryset = safe_queryset_and(
field.queryset,
model.objects.for_access(request.access),
)
class Form(forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(Form, self).__init__(*args, **kwargs)
_process_fields(self, self.request)
class ModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(ModelForm, self).__init__(*args, **kwargs)
_process_fields(self, self.request)
class SearchForm(towel_forms.SearchForm):
def post_init(self, request):
self.request = request
_process_fields(self, self.request)
| """
Forms
=====
These three form subclasses will automatically add limitation by tenant
to all form fields with a ``queryset`` attribute.
.. warning::
If you customized the dropdown using ``choices`` you have to limit the
choices by the current tenant yourself.
"""
from django import forms
from towel import forms as towel_forms
from towel.utils import safe_queryset_and
def _process_fields(form, request):
for field in form.fields.values():
if getattr(field, 'queryset', None):
model = field.queryset.model
field.queryset = safe_queryset_and(
field.queryset,
model.objects.for_access(request.access),
)
class Form(forms.Form):
def __init__(self, *args, **kwargs):
self._request = kwargs.pop('request')
super(Form, self).__init__(*args, **kwargs)
_process_fields(self, self._request)
class ModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self._request = kwargs.pop('request')
super(ModelForm, self).__init__(*args, **kwargs)
_process_fields(self, self._request)
class SearchForm(towel_forms.SearchForm):
def post_init(self, request):
self._request = request
_process_fields(self, self._request)
|
Fix linting issue with url line length | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', auth_views.LoginView.as_view(), name='login'),
url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),
url('^password_reset/$', auth_views.PasswordResetView.as_view(),
name='password_reset',),
url(r'^$', views.RootRouter.as_view(), name='root-router'),
url(r'^welcome/$', views.Welcome.as_view(), name='welcome'),
url(r'^user/settings/$', views.UserSettings.as_view(),
name='user-settings'),
url(r'', include('api.urls', namespace='api')),
url(r'', include('core.urls')),
url(r'', include('dashboard.urls')),
url(r'', include('reports.urls', namespace='reports')),
]
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', auth_views.LoginView.as_view(), name='login'),
url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),
url('^password_reset/$', auth_views.PasswordResetView.as_view(),
name='password_reset',),
url(r'^$', views.RootRouter.as_view(), name='root-router'),
url(r'^welcome/$', views.Welcome.as_view(), name='welcome'),
url(r'^user/settings/$', views.UserSettings.as_view(),
name='user-settings'),
url(r'', include('api.urls', namespace='api')),
url(r'', include('core.urls')),
url(r'', include('dashboard.urls')),
url(r'', include('reports.urls', namespace='reports')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Fix unit search suggestions bug | import {createAction} from 'redux-actions';
import values from 'lodash/values';
import {SearchActions, MAX_SUGGESTION_COUNT} from './constants';
import {Action} from '../common/constants';
import {UnitServices} from '../service/constants';
export const clearSearch = () =>
createAction(SearchActions.CLEAR)();
export const searchUnits = (input: string, params: Object): Action => {
const init = {
input,
service: `${values(UnitServices).join(',')}`
};
params = Object.assign({}, init, params);
return createAction(SearchActions.FETCH_UNITS)({params});
};
export const receiveUnits = (results: Array<Object>) =>
createAction(SearchActions.RECEIVE_UNITS)(results);
export const fetchUnitSuggestions = (input: string): Action =>
createAction(SearchActions.FETCH_UNIT_SUGGESTIONS)({params: {
input,
service: `${values(UnitServices).join(',')}`,
page_size: MAX_SUGGESTION_COUNT
}});
export const receiveUnitSuggestions = (results: Array<Object>) =>
createAction(SearchActions.RECEIVE_UNIT_SUGGESTIONS)(results);
export const receiveAddressSuggestions = (results: Array<Object>) =>
createAction(SearchActions.RECEIVE_ADDRESS_SUGGESTIONS)(results);
| import {createAction} from 'redux-actions';
import values from 'lodash/values';
import {SearchActions, MAX_SUGGESTION_COUNT} from './constants';
import {Action} from '../common/constants';
import {UnitServices} from '../unit/constants';
export const clearSearch = () =>
createAction(SearchActions.CLEAR)();
export const searchUnits = (input: string, params: Object): Action => {
const init = {
input,
service: `${values(UnitServices).join(',')}`
};
params = Object.assign({}, init, params);
return createAction(SearchActions.FETCH_UNITS)({params});
};
export const receiveUnits = (results: Array<Object>) =>
createAction(SearchActions.RECEIVE_UNITS)(results);
export const fetchUnitSuggestions = (input: string): Action =>
createAction(SearchActions.FETCH_UNIT_SUGGESTIONS)({params: {
input,
service: `${values(UnitServices).join(',')}`,
page_size: MAX_SUGGESTION_COUNT
}});
export const receiveUnitSuggestions = (results: Array<Object>) =>
createAction(SearchActions.RECEIVE_UNIT_SUGGESTIONS)(results);
export const receiveAddressSuggestions = (results: Array<Object>) =>
createAction(SearchActions.RECEIVE_ADDRESS_SUGGESTIONS)(results);
|
Change mobilization root path to /mobilizations | import DefaultConfigServer from '~server/config'
export const mobilizations = () => '/mobilizations'
export const mobilization = (mobilization, domain = DefaultConfigServer.appDomain) => {
if (domain && domain.indexOf('staging') !== -1) {
return `http://${mobilization.slug}.${domain}`
}
return mobilization.custom_domain
? `http://${mobilization.custom_domain}`
: `http://${mobilization.slug}.${domain}`
}
export const mobilizationLaunch = id => `/mobilizations/${id}/launch`
export const newMobilization = () => '/mobilizations/new'
export const editMobilization = id => `/mobilizations/${id}/edit`
export const basicsMobilization = id => `/mobilizations/${id}/basics`
export const cityMobilization = id => `/mobilizations/${id}/city`
export const cityNewMobilization = id => `/mobilizations/${id}/cityNew`
export const sharingMobilization = id => `/mobilizations/${id}/sharing`
export const analyticsMobilization = id => `/mobilizations/${id}/analytics`
export const customDomainMobilization = id => `/mobilizations/${id}/customDomain`
| import DefaultConfigServer from '~server/config'
export const mobilizations = () => '/'
export const mobilization = (mobilization, domain = DefaultConfigServer.appDomain) => {
if (domain && domain.indexOf('staging') !== -1) {
return `http://${mobilization.slug}.${domain}`
}
return mobilization.custom_domain
? `http://${mobilization.custom_domain}`
: `http://${mobilization.slug}.${domain}`
}
export const mobilizationLaunch = id => `/mobilizations/${id}/launch`
export const newMobilization = () => '/mobilizations/new'
export const editMobilization = id => `/mobilizations/${id}/edit`
export const basicsMobilization = id => `/mobilizations/${id}/basics`
export const cityMobilization = id => `/mobilizations/${id}/city`
export const cityNewMobilization = id => `/mobilizations/${id}/cityNew`
export const sharingMobilization = id => `/mobilizations/${id}/sharing`
export const analyticsMobilization = id => `/mobilizations/${id}/analytics`
export const customDomainMobilization = id => `/mobilizations/${id}/customDomain`
|
Change var from jquery to normal js var | <!--[if lt IE 9]>
document.createElement('video');
<!--[endif]-->
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
// Cool title effect for "community favorites"
$(window).load(function() {
// get the height of the hero
var pageHeight = $($('.hero')[0]).height();
// get the height including margins of the featured crops title
var titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
// On resize, recalculate the above values
$(window).resize(function() {
pageHeight = $($('.hero')[0]).height();
titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
})
$(window).scroll(function() {
updateTitleBackground($(window).scrollTop(), pageHeight, titleHeight);
})
});
// Darken the title background when the user scrolls to the featured crops header
function updateTitleBackground(scrollPos, pageHeight, titleHeight) {
var exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
// The extra 1px lets smooth scrolling still trigger the change
if (scrollPos >= (pageHeight - titleHeight - 1)) {
exploreCommunityFavoritesTitle.addClass('full-black');
}
else {
exploreCommunityFavoritesTitle.removeClass('full-black');
}
}
| <!--[if lt IE 9]>
document.createElement('video');
<!--[endif]-->
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
// Cool title effect for "community favorites"
$(window).load(function() {
// get the height of the hero
var pageHeight = $($('.hero')[0]).height();
// get the height including margins of the featured crops title
var titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
// On resize, recalculate the above values
$(window).resize(function() {
pageHeight = $($('.hero')[0]).height();
titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
})
$(window).scroll(function() {
updateTitleBackground($(window).scrollTop(), pageHeight, titleHeight);
})
});
// Darken the title background when the user scrolls to the featured crops header
function updateTitleBackground(scrollPos, pageHeight, titleHeight) {
$exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
// The extra 1px lets smooth scrolling still trigger the change
if (scrollPos >= (pageHeight - titleHeight - 1)) {
$exploreCommunityFavoritesTitle.addClass('full-black');
}
else {
$exploreCommunityFavoritesTitle.removeClass('full-black');
}
}
|
Remove fail on error and make sure to actually copy the JS files to the build dir | const gulp = require('gulp');
const eslint = require('gulp-eslint');
const srcDir = './src';
const buildDir = './lib';
gulp.task("lint", function () {
return gulp.src(`${srcDir}/**/*.js`)
.pipe(eslint({
extends: 'eslint:recommended',
ecmaFeatures: {
'modules': true
},
rules: {
'comma-dangle': ['error', 'always-multiline'],
'no-console': 'off'
},
env: {
node: true,
es6: true
}
}))
.pipe(eslint.format())
.pipe(gulp.dest(buildDir));
});
gulp.task('watch', () => {
gulp.watch(`${srcDir}/**/*.js`, ['lint']);
});
gulp.task('default', ['watch']); | const gulp = require('gulp');
const eslint = require('gulp-eslint');
const srcDir = './src';
const buildDir = './lib';
gulp.task("lint", function () {
return gulp.src(`${srcDir}/**/*.js`)
.pipe(eslint({
extends: 'eslint:recommended',
ecmaFeatures: {
'modules': true
},
rules: {
'comma-dangle': ['error', 'always-multiline'],
'no-console': 'off'
},
env: {
node: true,
es6: true
}
}))
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('watch', () => {
gulp.watch(`${srcDir}/**/*.js`, ['lint']);
});
gulp.task('default', ['watch']); |
Refactor grammar tests to be easily extensible | from .generic import GrammarTest
def add_grammar(grammar, positive_sample, negative_sample):
grammar = GrammarTest(grammar, positive_sample,
negative_sample)
grammar.check_positive()
grammar.check_negative()
def test_np():
add_grammar('grammars/test_np.fcfg',
'grammars/nounphrase.sample',
'grammars/nounphrase.sample.negative')
def test_subject():
add_grammar('grammars/test_subject.fcfg',
'grammars/subjectphrase.sample',
'grammars/subjectphrase.sample.negative')
def test_object():
add_grammar('grammars/test_object.fcfg',
'grammars/object.sample',
'grammars/object.sample.negative')
| from .generic import GrammarTest
def test_np():
grammar = GrammarTest('grammars/test_np.fcfg',
'grammars/nounphrase.sample',
'grammars/nounphrase.sample.negative')
grammar.check_positive()
grammar.check_negative()
def test_subject():
grammar = GrammarTest('grammars/test_subject.fcfg',
'grammars/subjectphrase.sample',
'grammars/subjectphrase.sample.negative')
grammar.check_positive()
grammar.check_negative()
def test_object():
grammar = GrammarTest('grammars/test_object.fcfg',
'grammars/object.sample',
'grammars/object.sample.negative')
grammar.check_positive()
grammar.check_negative()
|
[example-studio] Update custom input slider to use PatchEvent | import React, {PropTypes} from 'react'
import FormField from 'part:@sanity/components/formfields/default'
import PatchEvent, {set, unset} from '@sanity/form-builder/PatchEvent'
import styles from './styles.css'
export default class Slider extends React.Component {
static propTypes = {
type: PropTypes.shape({
title: PropTypes.string
}).isRequired,
value: PropTypes.number,
onChange: PropTypes.func.isRequired
};
handleChange = event => {
const inputValue = event.target.value
const patch = inputValue === '' ? unset() : set(Number(inputValue))
this.props.onChange(PatchEvent.from(patch))
}
render() {
const {type, value} = this.props
const {min, max, step} = type.options.range
return (
<FormField label={type.title} description={type.description}>
<input
type="range"
className={styles.slider}
min={min}
max={max}
step={step}
value={value === undefined ? '' : value}
onChange={this.handleChange}
/>
</FormField>
)
}
}
| import React, {PropTypes} from 'react'
import FormField from 'part:@sanity/components/formfields/default'
import styles from './styles.css'
const set = value => ({type: 'set', value})
const unset = () => ({type: 'unset'})
const createPatch = value => ({patch: value === '' ? unset() : set(Number(value))})
export default class Slider extends React.Component {
static propTypes = {
type: PropTypes.shape({
title: PropTypes.string
}).isRequired,
value: PropTypes.number,
onChange: PropTypes.func.isRequired
};
render() {
const {type, value, onChange} = this.props
const {min, max, step} = type.options.range
return (
<FormField label={type.title} description={type.description}>
<input
type="range"
className={styles.slider}
min={min}
max={max}
step={step}
value={value === undefined ? '' : value}
onChange={event => onChange(createPatch(event.target.value))}
/>
</FormField>
)
}
}
|
Set url target to a new window. | <?php
namespace Yajra\CMS\DataTables;
use Yajra\CMS\Entities\FileAsset;
use Yajra\Datatables\Services\DataTable;
class FileAssetsDataTable extends DataTable
{
/**
* Display ajax response.
*
* @return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->editColumn('url', function (FileAsset $asset) {
return '<small><a target="_blank" href="' . $asset->url . '">' . $asset->url . '</a></small>';
})
->addColumn('action', 'administrator.configuration.datatables.action')
->make(true);
}
/**
* Get the query object to be processed by datatables.
*
* @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder
*/
public function query()
{
$assets = FileAsset::select()->where('category', config('asset.default'))
->where('type', $this->request()->get('type'));
return $this->applyScopes($assets);
}
}
| <?php
namespace Yajra\CMS\DataTables;
use Yajra\CMS\Entities\FileAsset;
use Yajra\Datatables\Services\DataTable;
class FileAssetsDataTable extends DataTable
{
/**
* Display ajax response.
*
* @return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->editColumn('url', function (FileAsset $asset) {
return '<small><a href="' . $asset->url . '">' . $asset->url . '</a></small>';
})
->addColumn('action', 'administrator.configuration.datatables.action')
->make(true);
}
/**
* Get the query object to be processed by datatables.
*
* @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder
*/
public function query()
{
$assets = FileAsset::select()->where('category', config('asset.default'))
->where('type', $this->request()->get('type'));
return $this->applyScopes($assets);
}
}
|
Fix failing test on Windows due to path separator | import os
import pytest
import setuptools
@pytest.fixture
def example_source(tmpdir):
tmpdir.mkdir('foo')
(tmpdir / 'foo/bar.py').write('')
(tmpdir / 'readme.txt').write('')
return tmpdir
def test_findall(example_source):
found = list(setuptools.findall(str(example_source)))
expected = ['readme.txt', 'foo/bar.py']
expected = [example_source.join(fn) for fn in expected]
assert found == expected
def test_findall_curdir(example_source):
with example_source.as_cwd():
found = list(setuptools.findall())
expected = ['readme.txt', os.path.join('foo', 'bar.py')]
assert found == expected
@pytest.fixture
def can_symlink(tmpdir):
"""
Skip if cannot create a symbolic link
"""
link_fn = 'link'
target_fn = 'target'
try:
os.symlink(target_fn, link_fn)
except (OSError, NotImplementedError, AttributeError):
pytest.skip("Cannot create symbolic links")
os.remove(link_fn)
def test_findall_missing_symlink(tmpdir, can_symlink):
with tmpdir.as_cwd():
os.symlink('foo', 'bar')
found = list(setuptools.findall())
assert found == []
| import os
import pytest
import setuptools
@pytest.fixture
def example_source(tmpdir):
tmpdir.mkdir('foo')
(tmpdir / 'foo/bar.py').write('')
(tmpdir / 'readme.txt').write('')
return tmpdir
def test_findall(example_source):
found = list(setuptools.findall(str(example_source)))
expected = ['readme.txt', 'foo/bar.py']
expected = [example_source.join(fn) for fn in expected]
assert found == expected
def test_findall_curdir(example_source):
with example_source.as_cwd():
found = list(setuptools.findall())
expected = ['readme.txt', 'foo/bar.py']
assert found == expected
@pytest.fixture
def can_symlink(tmpdir):
"""
Skip if cannot create a symbolic link
"""
link_fn = 'link'
target_fn = 'target'
try:
os.symlink(target_fn, link_fn)
except (OSError, NotImplementedError, AttributeError):
pytest.skip("Cannot create symbolic links")
os.remove(link_fn)
def test_findall_missing_symlink(tmpdir, can_symlink):
with tmpdir.as_cwd():
os.symlink('foo', 'bar')
found = list(setuptools.findall())
assert found == []
|
Remove a duplicated label from the collection view | package com.intellij.debugger.streams.ui;
import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) {
super(project, value);
}
@Override
public String calcValueName() {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.calcValueName();
}
return value.type().name();
}
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.getDescriptorEvaluation(debuggerContext);
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
}
}
| package com.intellij.debugger.streams.ui;
import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) {
super(project, value);
}
@Override
public String calcValueName() {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.calcValueName();
}
return value.type().name();
}
@Override
public boolean isShowIdLabel() {
return true;
}
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.getDescriptorEvaluation(debuggerContext);
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
}
}
|
Align method arguments with laravel/framework | <?php namespace Propaganistas\LaravelFakeId;
use Illuminate\Support\Facades\App;
use Exception;
trait RoutesWithFakeIds
{
/**
* Get the value of the model's route key.
*
* @return mixed
*/
public function getRouteKey()
{
return App::make('fakeid')->encode($this->getKey());
}
/**
* Retrieve model for route model binding
*
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveRouteBinding($value)
{
try {
$value = App::make('fakeid')->decode($value);
} catch (Exception $e) {
return null;
}
return $this->where($this->getRouteKeyName(), $value)->first();
}
}
| <?php namespace Propaganistas\LaravelFakeId;
use Illuminate\Support\Facades\App;
use Exception;
trait RoutesWithFakeIds
{
/**
* Get the value of the model's route key.
*
* @return mixed
*/
public function getRouteKey()
{
return App::make('fakeid')->encode($this->getKey());
}
/**
* Retrieve model for route model binding
*
* @param mixed $routeKey
* @return null|\Illuminate\Database\Eloquent\Model
*/
public function resolveRouteBinding($routeKey)
{
try {
$key = App::make('fakeid')->decode($routeKey);
} catch (Exception $e) {
return null;
}
return $this->where($this->getRouteKeyName(), $key)->first();
}
}
|
Fix npe in syntax analyzer in logic operators. | package org.develnext.jphp.core.tokenizer.token.expr.operator;
import php.runtime.common.Association;
import org.develnext.jphp.core.tokenizer.TokenType;
import org.develnext.jphp.core.tokenizer.TokenMeta;
import org.develnext.jphp.core.tokenizer.token.Token;
import org.develnext.jphp.core.tokenizer.token.expr.ExprToken;
import org.develnext.jphp.core.tokenizer.token.expr.OperatorExprToken;
import org.develnext.jphp.core.tokenizer.token.stmt.ExprStmtToken;
public class LogicOperatorExprToken extends OperatorExprToken {
private ExprStmtToken rightValue;
@Override
public Association getAssociation() {
return Association.LEFT;
}
@Override
public boolean isBinary() {
return false;
}
public LogicOperatorExprToken(TokenMeta meta, TokenType type) {
super(meta, type);
}
public ExprStmtToken getRightValue() {
return rightValue;
}
public void setRightValue(ExprStmtToken rightValue) {
this.rightValue = rightValue;
}
@Override
public Token getLast() {
if (rightValue == null) {
return null;
}
Token token = rightValue.getLast();
if (token instanceof ExprToken)
return ((ExprToken) token).getLast();
return token;
}
}
| package org.develnext.jphp.core.tokenizer.token.expr.operator;
import php.runtime.common.Association;
import org.develnext.jphp.core.tokenizer.TokenType;
import org.develnext.jphp.core.tokenizer.TokenMeta;
import org.develnext.jphp.core.tokenizer.token.Token;
import org.develnext.jphp.core.tokenizer.token.expr.ExprToken;
import org.develnext.jphp.core.tokenizer.token.expr.OperatorExprToken;
import org.develnext.jphp.core.tokenizer.token.stmt.ExprStmtToken;
public class LogicOperatorExprToken extends OperatorExprToken {
private ExprStmtToken rightValue;
@Override
public Association getAssociation() {
return Association.LEFT;
}
@Override
public boolean isBinary() {
return false;
}
public LogicOperatorExprToken(TokenMeta meta, TokenType type) {
super(meta, type);
}
public ExprStmtToken getRightValue() {
return rightValue;
}
public void setRightValue(ExprStmtToken rightValue) {
this.rightValue = rightValue;
}
@Override
public Token getLast() {
Token token = rightValue.getLast();
if (token instanceof ExprToken)
return ((ExprToken) token).getLast();
return token;
}
}
|
Fix waymo open dataset proto import.
PiperOrigin-RevId: 355350302 | # coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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.
"""Public API of the proto package."""
# pylint: disable=g-import-not-at-top,g-importing-member, import-outside-toplevel
try: # pylint: disable=g-statement-before-imports
from waymo_open_dataset import dataset_pb2 as waymo_dataset_pb2
except ImportError:
# If original waymo proto is not found, fallback to the pre-generated proto
from tensorflow_datasets.proto import waymo_dataset_generated_pb2 as waymo_dataset_pb2 # pylint: disable=line-too-long
| # coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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.
"""Public API of the proto package."""
# pylint: disable=g-import-not-at-top,g-importing-member, import-outside-toplevel
try: # pylint: disable=g-statement-before-imports
from waymo_open_dataset import waymo_dataset_pb2
except ImportError:
# If original waymo proto is not found, fallback to the pre-generated proto
from tensorflow_datasets.proto import waymo_dataset_generated_pb2 as waymo_dataset_pb2 # pylint: disable=line-too-long
|
Fix 4->7 days week in the Care Schedule | package org.motechproject.tama.api.model;
/**
* Created by IntelliJ IDEA.
* User: rob
* Date: 4/25/11
* Time: 8:48 PM
* To change this template use File | Settings | File Templates.
*/
public class AppointmentSchedule
{
public static enum Followup {
REGISTERED("Registered",7),
WEEK4("4 week follow-up",7*4),
WEEK12("12 week follow-up",7*12),
WEEK24("24 week follow-up",7*24),
WEEK36("36 week follow-up",7*36),
WEEK48("48 week follow-up",7*48);
final String value;
final int days;
Followup(String value, int days) {
this.value=value;
this.days=days;
}
@Override
public String toString(){
return value;
}
public String getKey(){
return name();
}
public int getDays() {
return this.days;
}
}
}
| package org.motechproject.tama.api.model;
/**
* Created by IntelliJ IDEA.
* User: rob
* Date: 4/25/11
* Time: 8:48 PM
* To change this template use File | Settings | File Templates.
*/
public class AppointmentSchedule
{
public static enum Followup {
REGISTERED("Registered",7),
WEEK4("4 week follow-up",4*7),
WEEK12("12 week follow-up",4*12),
WEEK24("24 week follow-up",4*24),
WEEK36("36 week follow-up",4*36),
WEEK48("48 week follow-up",4*48);
final String value;
final int days;
Followup(String value, int days) {
this.value=value;
this.days=days;
}
@Override
public String toString(){
return value;
}
public String getKey(){
return name();
}
public int getDays() {
return this.days;
}
}
}
|
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work. | #!/usr/bin/env python
import glob
import re
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
deps = set()
d = re.findall(r'\n\s*use\s+(\w+)',
open(src,'r').read())
for name in d:
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
deps.add(name)
if deps:
dependencies[module] = sorted(list(deps))
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
| #!/usr/bin/env python
import glob
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
d = set()
for line in open(src, 'r'):
words = line.split()
if words and words[0].lower() == 'use':
name = words[1].strip(',')
if name in ['mpi','hdf5','h5lt']:
continue
if name.startswith('xml_data_'):
name = name.replace('xml_data_', 'templates/')
d.add(name)
if d:
d = list(d)
d.sort()
dependencies[module] = d
keys = dependencies.keys()
keys.sort()
for module in keys:
for dep in dependencies[module]:
print("{0}.o: {1}.o".format(module, dep))
print('')
|
Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised. | import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English)
set_lang_class(de.German.lang, de.German)
set_lang_class(zh.Chinese.lang, zh.Chinese)
def load(name, **overrides):
target_name, target_version = util.split_data_name(name)
path = overrides.get('path', util.get_data_path())
path = util.match_best_version(target_name, target_version, path)
if isinstance(overrides.get('vectors'), basestring):
vectors_path = util.match_best_version(overrides.get('vectors'), None, path)
overrides['vectors'] = lambda nlp: nlp.vocab.load_vectors_from_bin_loc(
vectors_path / 'vocab' / 'vec.bin')
cls = get_lang_class(target_name)
return cls(path=path, **overrides)
| import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English)
set_lang_class(de.German.lang, de.German)
set_lang_class(zh.Chinese.lang, zh.Chinese)
def load(name, **overrides):
target_name, target_version = util.split_data_name(name)
path = overrides.get('path', util.get_data_path())
path = util.match_best_version(target_name, target_version, path)
if isinstance(overrides.get('vectors'), basestring):
vectors = util.match_best_version(overrides.get('vectors'), None, path)
cls = get_lang_class(target_name)
return cls(path=path, **overrides)
|
Put back in handling for animation being a function for transition definitions | var getInterpolation = require('interpolation-builder');
var createTransitions = require('./createTransitions');
module.exports = function(driver, states, transitions) {
// go through each transition and setup kimi with a function that works
// with values between 0 and 1
transitions.forEach( function(transition, i) {
var from = transition.from || throwError('from', i, transition);
var to = transition.to || throwError('to', i, transition);
var animation = transition.animation;
var duration;
var animationDefinition;
// if animation is an object then it's a Tween like definition
// otherwise we'll assume that animation is a function and we can simply
// pass that to the driver
if(typeof animation == 'object') {
animationDefinition = createTransitions(animation, states[ from ], states[ to ]);
// this
animation = getInterpolation(
animationDefinition.transitions
);
duration = animationDefinition.duration;
} else {
duration = animation.duration;
}
// animation will either be a function passed in or generated from an object definition
driver.fromTo(from, to, duration, animation);
});
};
function throwError(type, idx, transition) {
throw new Error(
'For the transition at ' + idx + ':\n' +
JSON.stringify(transition, unanimationined, ' ') + '\n' +
'you did not animationine ' + type + '\n\n'
);
} | var getInterpolation = require('interpolation-builder');
var createTransitions = require('./createTransitions');
module.exports = function(driver, states, transitions) {
// go through each transition and setup kimi with a function that works
// with values between 0 and 1
transitions.forEach( function(transition, i) {
var from = transition.from || throwError('from', i, transition);
var to = transition.to || throwError('to', i, transition);
var animation = transition.animation || {};
var animationDefinition = createTransitions(animation, states[ from ], states[ to ]);
// else build the the transition
if(typeof animation == 'object') {
// this
animation = getInterpolation(
animationDefinition.transitions
);
}
// animation will either be a function passed in or generated from an object definition
driver.fromTo(from, to, animationDefinition.duration, animation);
});
};
function throwError(type, idx, transition) {
throw new Error(
'For the transition at ' + idx + ':\n' +
JSON.stringify(transition, unanimationined, ' ') + '\n' +
'you did not animationine ' + type + '\n\n'
);
} |
Add Channel and the convenience exchange classes | """
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.exchange import DirectExchange
from rabbitpy.exchange import FanoutExchange
from rabbitpy.exchange import HeadersExchange
from rabbitpy.exchange import TopicExchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
| """
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
|
Clarify client code a bit | package com.darwinsys.clientware;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A JAX-RS client NOT using the JAX-RS Client API
* In fact, not using anything except Core Java APIs.
*/
public class UrlJaxRsClient {
static final String BASE_URL =
"http://androidcookbook.com/seam/resource/rest/recipe";
public static void main(String[] args) throws Exception {
final int recipeId = 4;
URL url = new URL(BASE_URL + "/" + recipeId);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Accept", "application/json");
InputStream is = connection.getInputStream();
// Read "is" to get the response from a GET
BufferedReader bi = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = bi.readLine()) != null) {
System.out.println(line);
}
}
}
| package com.darwinsys.clientware;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A JAX-RS client NOT using the JAX-RS Client API
* In fact, not using anything except Core Java APIs.
*/
public class UrlJaxRsClient {
static final String BASE_URL =
"http://androidcookbook.com/seam/resource/rest/recipe";
public static void main(String[] args) throws Exception {
URL url = new URL(BASE_URL + "/4");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Accept", "application/json");
InputStream is = connection.getInputStream();
// Read "is" to get the response from a GET
BufferedReader bi = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = bi.readLine()) != null) {
System.out.println(line);
}
}
}
|
Sort addresses on home-screen by name and value. | import './AddressList.less';
import AddrLine from './AddrLine.react';
import React, { PropTypes } from 'react';
import Component from 'react-pure-render/component';
import { connect } from 'react-redux';
class AddressList extends Component {
static propTypes = {
addresses: PropTypes.object.isRequired,
msg: PropTypes.object,
};
render() {
const { addresses, msg } = this.props;
return (
<section className="device-switch-list">
{addresses.sortBy(addr => addr.name)
.sortBy(addr => !addr.value)
.map(address =>
<AddrLine {...{ msg, address }} key={address.id} />
)
}
</section>
);
}
}
export default connect(state => ({
msg: state.intl.msg.home, /* PENDING: don't use this, create your own subtree in en.js */
}))(AddressList);
| import './AddressList.less';
import AddrLine from './AddrLine.react';
import React, { PropTypes } from 'react';
import Component from 'react-pure-render/component';
import { connect } from 'react-redux';
class AddressList extends Component {
static propTypes = {
addresses: PropTypes.object.isRequired,
msg: PropTypes.object,
};
render() {
const { addresses, msg } = this.props;
return (
<section className="device-switch-list">
{addresses.map(address =>
<AddrLine {...{ msg, address }} key={address.id} />
)
}
</section>
);
}
}
export default connect(state => ({
msg: state.intl.msg.home, /* PENDING: don't use this, create your own subtree in en.js */
}))(AddressList);
|
Fix legend gradient label text to use update set. | import {Perc, Label, GuideLabelStyle} from './constants';
import guideMark from './guide-mark';
import {TextMark} from '../marks/marktypes';
import {LegendLabelRole} from '../marks/roles';
import {addEncode} from '../encode/encode-util';
var alignExpr = 'datum.' + Perc + '<=0?"left"'
+ ':datum.' + Perc + '>=1?"right":"center"';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter, update;
encode.enter = enter = {
opacity: zero
};
addEncode(enter, 'fill', config.labelColor);
addEncode(enter, 'font', config.labelFont);
addEncode(enter, 'fontSize', config.labelFontSize);
addEncode(enter, 'baseline', config.gradientLabelBaseline);
addEncode(enter, 'limit', config.gradientLabelLimit);
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1},
text: {field: Label}
};
enter.x = update.x = {
field: Perc,
mult: config.gradientWidth
};
enter.y = update.y = {
value: config.gradientHeight,
offset: config.gradientLabelOffset
};
enter.align = update.align = {signal: alignExpr};
return guideMark(TextMark, LegendLabelRole, GuideLabelStyle, Perc, dataRef, encode, userEncode);
}
| import {Perc, Label, GuideLabelStyle} from './constants';
import guideMark from './guide-mark';
import {TextMark} from '../marks/marktypes';
import {LegendLabelRole} from '../marks/roles';
import {addEncode} from '../encode/encode-util';
var alignExpr = 'datum.' + Perc + '<=0?"left"'
+ ':datum.' + Perc + '>=1?"right":"center"';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter, update;
encode.enter = enter = {
opacity: zero,
text: {field: Label}
};
addEncode(enter, 'fill', config.labelColor);
addEncode(enter, 'font', config.labelFont);
addEncode(enter, 'fontSize', config.labelFontSize);
addEncode(enter, 'baseline', config.gradientLabelBaseline);
addEncode(enter, 'limit', config.gradientLabelLimit);
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1}
};
enter.x = update.x = {
field: Perc,
mult: config.gradientWidth
};
enter.y = update.y = {
value: config.gradientHeight,
offset: config.gradientLabelOffset
};
enter.align = update.align = {signal: alignExpr};
return guideMark(TextMark, LegendLabelRole, GuideLabelStyle, Perc, dataRef, encode, userEncode);
}
|
Revert temp fix for IP-based blacklist | <?php
namespace App\Http\Middleware;
use Closure;
use App\IpBlacklist;
use Log;
class IPBasedBlacklist
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$ip = $request->ip();
$blacklist = IpBlacklist
::where('ip_address', $ip)
->first();
if (empty($blacklist)) {
return $next($request);
}
Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), $blacklist->reason));
abort(503);
}
}
| <?php
namespace App\Http\Middleware;
use Closure;
use App\IpBlacklist;
use Log;
class IPBasedBlacklist
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$ip = $request->ip();
/*$blacklist = IpBlacklist
::where('ip_address', $ip)
->first();*/
$blacklistedIps = explode(',', env('BLACKLISTED_IPS', ''));
if (!in_array($ip, $blacklistedIps)) {
return $next($request);
}
Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), 'Not set.'));
abort(503);
}
}
|
Make sure state is different | 'use strict'
let Gpio = require('onoff').Gpio
let EventEmitter = require('events').EventEmitter
class Door extends EventEmitter {
constructor(options) {
super()
EventEmitter.call(this)
this.options = options
this.isOpen = false
let pins = options.pins
let sensor = new Gpio(pins.sensor, 'in', 'both')
let statusOpen = new Gpio(pins.statusOpen, 'out')
let statusClosed = new Gpio(pins.statusClosed, 'out')
let update = (err, value) => {
if (this.isOpen !== value) {
statusOpen.writeSync(value^1)
statusClosed.writeSync(value)
this.isOpen = value
this.emit(this.status())
}
}
sensor.read(update)
sensor.watch(update)
}
status() {
return this.isOpen ? 'open' : 'closed'
}
toggle() {
console.log('Door toggled')
var doorSwitch = new Gpio(this.options.pins.doorSwitch, 'out')
doorSwitch.writeSync(1)
setTimeout(function() {
doorSwitch.writeSync(0)
}, 100)
}
open() {
if (!this.isOpen) this.toggle()
}
close() {
if (this.isOpen) this.toggle()
}
}
module.exports = Door
| 'use strict'
let Gpio = require('onoff').Gpio
let EventEmitter = require('events').EventEmitter
class Door extends EventEmitter {
constructor(options) {
super()
EventEmitter.call(this)
this.options = options
this.isOpen = false
let pins = options.pins
let sensor = new Gpio(pins.sensor, 'in', 'both')
let statusOpen = new Gpio(pins.statusOpen, 'out')
let statusClosed = new Gpio(pins.statusClosed, 'out')
let update = (err, value) => {
statusOpen.writeSync(value^1)
statusClosed.writeSync(value)
this.isOpen = value
this.emit(this.status())
}
sensor.read(update)
sensor.watch(update)
}
status() {
return this.isOpen ? 'open' : 'closed'
}
toggle() {
console.log('Door toggled')
var doorSwitch = new Gpio(this.options.pins.doorSwitch, 'out')
doorSwitch.writeSync(1)
setTimeout(function() {
doorSwitch.writeSync(0)
}, 100)
}
open() {
if (!this.isOpen) this.toggle()
}
close() {
if (this.isOpen) this.toggle()
}
}
module.exports = Door
|
Remove extraneous and problematic import | import operator
from itertools import imap, repeat
from spicedham.baseplugin import BasePlugin
class NonsenseFilter(BasePlugin):
"""
Filter messages with no words in the database.
"""
def __init__(self, config, backend):
"""
Get values from the config.
"""
self.backend = backend
nonsensefilter_config = config.get('nonsensefilter', {})
self.filter_match = nonsensefilter_config.get('filter_match', 1)
self.filter_miss = nonsensefilter_config.get('filter_miss', None)
def train(self, response, value):
"""
Set each word to True.
"""
self.backend.set_key_list(self.__class__.__name__, {(word, True) for word in response})
# TODO: Will match responses consisting of only ''
def classify(self, response):
"""
If the message contains only words not found in the database return
filter_match. Else return filter_miss.
"""
classifier = self.__class__.__name__
list_in_dict = lambda x, y: not self.backend.get_key(x, y, False)
if all(imap(list_in_dict, repeat(classifier), response)):
return self.filter_match
else:
return self.filter_miss
| import operator
from itertools import imap, repeat
from spicedham.config import load_config
from spicedham.baseplugin import BasePlugin
class NonsenseFilter(BasePlugin):
"""
Filter messages with no words in the database.
"""
def __init__(self, config, backend):
"""
Get values from the config.
"""
self.backend = backend
nonsensefilter_config = config.get('nonsensefilter', {})
self.filter_match = nonsensefilter_config.get('filter_match', 1)
self.filter_miss = nonsensefilter_config.get('filter_miss', None)
def train(self, response, value):
"""
Set each word to True.
"""
self.backend.set_key_list(self.__class__.__name__, {(word, True) for word in response})
# TODO: Will match responses consisting of only ''
def classify(self, response):
"""
If the message contains only words not found in the database return
filter_match. Else return filter_miss.
"""
classifier = self.__class__.__name__
list_in_dict = lambda x, y: not self.backend.get_key(x, y, False)
if all(imap(list_in_dict, repeat(classifier), response)):
return self.filter_match
else:
return self.filter_miss
|
Add node column to assessments table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAssessmentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('assessments', function (Blueprint $table) {
$table->increments('id');
$table->integer('vn_id')->unsigned();
// $table->foreign('vn_id')->references('id')->on('vn')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->datetime('date_start')->nullable();
$table->datetime('date_end')->nullable();
$table->string('node')->nullable();
$table->char('score_story')->nullable()->default('');
$table->char('score_naki')->nullable()->default('');
$table->char('score_nuki')->nullable()->default('');
$table->char('score_graphic')->nullable()->default('');
$table->integer('score_all')->nullable();
$table->boolean('archive_savedata')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('assessments');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAssessmentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('assessments', function (Blueprint $table) {
$table->increments('id');
$table->integer('vn_id')->unsigned();
// $table->foreign('vn_id')->references('id')->on('vn')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->datetime('date_start')->nullable();
$table->datetime('date_end')->nullable();
$table->char('score_story')->nullable()->default('');
$table->char('score_naki')->nullable()->default('');
$table->char('score_nuki')->nullable()->default('');
$table->char('score_graphic')->nullable()->default('');
$table->integer('score_all')->nullable();
$table->boolean('archive_savedata')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('assessments');
}
}
|
Test change for closing an issue.
This is a place for a longer comment. Closes #1 | #!/usr/bin/env python
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt
def main():
koeffs = [0.3, 1.2, 0.1, 7]
p = np.poly1d(koeffs)
x = np.linspace(-5, 5, 100)
y = p(x) + 2 * np.random.randn(100) - 1
# fit
fit = np.polyfit(x, y, 3)
p_fit = np.poly1d(fit)
print "Real coefficients:", koeffs
print "Fitted coefficients:", fit
# plot
plt.scatter(x, y)
plt.plot(x, p_fit(x), 'orange', lw=2)
plt.show()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt
def main():
koeffs = [.3, 1.2, .1, 7]
p = np.poly1d(koeffs)
x = np.linspace(-5, 5, 100)
y = p(x) + 2 * np.random.randn(100) - 1
# fit
fit = np.polyfit(x, y, 3)
p_fit = np.poly1d(fit)
print "Real coefficients:", koeffs
print "Fitted coefficients:", fit
# plot
plt.scatter(x, y)
plt.plot(x, p_fit(x), 'orange', lw=2)
plt.show()
if __name__ == '__main__':
main()
|
Make the data not field mandatory | <?php
/**
* Function to create a form to
*/
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use SSI\DataBundle\Entity\SSIQueryMeta;
class CreateQueryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$meta = new SSIQueryMeta();
$tables = $meta->get_table_meta();
$builder
->add('Title')
->add('Description')
->add('Fields', 'choice',array(
'choices' => $tables,
'multiple' => true,
'expanded' => true,
))
->add('Visual', 'choice', array(
'choices' => self::allowed_tables(),
'expanded' => true,
))
->add('Data', 'text', array('required' => false))
->add('save', 'submit');
}
public function getName()
{
return 'task';
}
private function allowed_tables ()
{
return array('pie' => 'Pie Chart', 'hist' => 'Histogram');
}
}
?>
| <?php
/**
* Function to create a form to
*/
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use SSI\DataBundle\Entity\SSIQueryMeta;
class CreateQueryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$meta = new SSIQueryMeta();
$tables = $meta->get_table_meta();
$builder
->add('Title')
->add('Description')
->add('Fields', 'choice',array(
'choices' => $tables,
'multiple' => true,
'expanded' => true,
))
->add('Visual', 'choice', array(
'choices' => self::allowed_tables(),
'expanded' => true,
))
->add('Data')
->add('save', 'submit');
}
public function getName()
{
return 'task';
}
private function allowed_tables ()
{
return array('pie' => 'Pie Chart', 'hist' => 'Histogram');
}
}
?>
|
Use port 3000 instead of 5000. | var express = require('express');
var app = express();
// Serve assets in /public
var path = require('path');
app.use(express.static(path.join(__dirname, '../client')));
// Body parsing for JSON POST payloads
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// Middlewares
app.use(require('./middlewares/cross_origin_requests'));
app.use(require('./middlewares/http_verbs'));
app.use(require('./middlewares/add_user_to_request'));
// Mount controller files
app.use('/notes', require('./routes/notes'));
app.use('/users', require('./routes/users'));
app.use('/session', require('./routes/session'));
// Start server
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function() {
console.log('Listening on http://localhost:', app.get('port'));
});
| var express = require('express');
var app = express();
// Serve assets in /public
var path = require('path');
app.use(express.static(path.join(__dirname, '../client')));
// Body parsing for JSON POST payloads
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// Middlewares
app.use(require('./middlewares/cross_origin_requests'));
app.use(require('./middlewares/http_verbs'));
app.use(require('./middlewares/add_user_to_request'));
// Mount controller files
app.use('/notes', require('./routes/notes'));
app.use('/users', require('./routes/users'));
app.use('/session', require('./routes/session'));
// Start server
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('Listening on http://localhost:', app.get('port'));
});
|
BAP-108: Implement basic sorter interface
- removed getQueryBuilder() from interface
- added sorter to demo bundle
- added sorter service
- implemented sorters processing from request | <?php
namespace Acme\Bundle\DemoGridBundle\Datagrid;
use Oro\Bundle\GridBundle\Datagrid\DatagridManager;
use Oro\Bundle\GridBundle\Field\FieldDescription;
class UserDatagridManager extends DatagridManager
{
/**
* {@inheritdoc}
*/
protected function getListFields()
{
$email = new FieldDescription();
$email->setName('email');
$email->setOption('label', 'Email');
$firstName = new FieldDescription();
$firstName->setName('firstname');
$firstName->setOption('label', 'Firstname');
$lastName = new FieldDescription();
$lastName->setName('lastname');
$lastName->setOption('label', 'Lastname');
return array($email, $firstName, $lastName);
}
/**
* @return array
*/
protected function getSorters()
{
$email = new FieldDescription();
$email->setName('o.email');
$firstName = new FieldDescription();
$firstName->setName('o.firstname');
$lastName = new FieldDescription();
$lastName->setName('o.lastname');
return array($email, $firstName, $lastName);
}
}
| <?php
namespace Acme\Bundle\DemoGridBundle\Datagrid;
use Oro\Bundle\GridBundle\Datagrid\DatagridManager;
use Oro\Bundle\GridBundle\Field\FieldDescription;
class UserDatagridManager extends DatagridManager
{
/**
* {@inheritdoc}
*/
protected function getListFields()
{
$email = new FieldDescription();
$email->setName('email');
$email->setOption('label', 'Email');
$firstName = new FieldDescription();
$firstName->setName('firstname');
$firstName->setOption('label', 'Firstname');
$lastName = new FieldDescription();
$lastName->setName('lastname');
$lastName->setOption('label', 'Lastname');
return array($email, $firstName, $lastName);
}
/**
* @return array
*/
protected function getSorters()
{
return array();
}
}
|
Use more sensible name for post data | from Cookie import SimpleCookie
from urlparse import parse_qs
from utils import MultiDict, cached_property
class Request(object):
def __init__(self, event, context):
self.event = event
self.context = context
@property
def method(self):
return self.event['httpMethod']
@property
def query(self):
return self.event['queryStringParameters']
@cached_property
def form(self):
return MultiDict(parse_qs(self.event.get('body', '') or ''))
@cached_property
def cookies(self):
jar = SimpleCookie()
if self.event['headers'].get('Cookie'):
jar.load(self.event['headers']['Cookie'].encode('utf-8'))
return jar
@property
def stage(self):
return self.event['stage']
@property
def stageVar(self):
return self.event['stageVariables']
@property
def params(self):
return self.event['pathParameters']
| from Cookie import SimpleCookie
from urlparse import parse_qs
from utils import MultiDict, cached_property
class Request(object):
def __init__(self, event, context):
self.event = event
self.context = context
@property
def method(self):
return self.event['httpMethod']
@property
def query(self):
return self.event['queryStringParameters']
@cached_property
def post(self):
return MultiDict(parse_qs(self.event.get('body', '') or ''))
@cached_property
def cookies(self):
jar = SimpleCookie()
if self.event['headers'].get('Cookie'):
jar.load(self.event['headers']['Cookie'].encode('utf-8'))
return jar
@property
def stage(self):
return self.event['stage']
@property
def stageVar(self):
return self.event['stageVariables']
@property
def params(self):
return self.event['pathParameters']
|
Set an appropriate title in 404 view | import View from '../base/view';
export default class NotFound extends View {
createElement() {
const element = document.createElement('div');
element.setAttribute('class', 'not-found-view');
return element;
}
render() {
this.element.innerHTML = `
<div class="not-found-message">
<h2>
404 <span class="tagline">Здесь нет такой страницы</span>
</h2>
<p>
Но вообще есть замечательные <a href="/">спектакли</a>
</p>
</div>
`;
this.app.setTitle("404");
}
}
| import View from '../base/view';
export default class NotFound extends View {
createElement() {
const element = document.createElement('div');
element.setAttribute('class', 'not-found-view');
return element;
}
render() {
this.element.innerHTML = `
<div class="not-found-message">
<h2>
404 <span class="tagline">Здесь нет такой страницы</span>
</h2>
<p>
Но вообще есть замечательные <a href="/">спектакли</a>
</p>
</div>
`;
}
}
|
Call parent::__construct(); in the command. | <?php
namespace Staf\Generator;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'generator:build {definition=default}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Builds the static site';
/**
* The static site builder instance
*
* @var Builder
*/
protected $builder;
/**
* Set the instance of the builder upon instantiation.
*
* @param Builder $builder
*/
public function __construct(Builder $builder)
{
$this->builder = $builder;
parent::__construct();
}
/**
*
*/
public function handle()
{
$definitionName = $this->argument('definition');
$definition = array_get(config('generator.definitions'), $definitionName);
if ($definition === null) {
$this->error('Invalid site definition provided.');
return;
}
$this->builder->build($definition);
$this->info("Static site '$definitionName' built!");
}
}
| <?php
namespace Staf\Generator;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'generator:build {definition=default}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Builds the static site';
/**
* The static site builder instance
*
* @var Builder
*/
protected $builder;
/**
* Set the instance of the builder upon instantiation.
*
* @param Builder $builder
*/
public function __construct(Builder $builder)
{
$this->builder = $builder;
}
/**
*
*/
public function handle()
{
$definitionName = $this->argument('definition');
$definition = array_get(config('generator.definitions'), $definitionName);
if ($definition === null) {
$this->error('Invalid site definition provided.');
return;
}
$this->builder->build($definition);
$this->info("Static site '$definitionName' built!");
}
}
|
Remove InstrumentManagerView's unnecessary 'instrumentRemoved' model event listener. | define([
"use!underscore",
"use!backbone",
"baseView",
"settings",
"./instrumentView",
], function(_, Backbone, BaseView, settings, InstrumentView) {
var InstrumentManagerView = BaseView.extend({
modelEvents: {
"instrumentAdded": function (instrument) {
this.addInstrumentView(instrument);
}
},
render: function () {
this.removeAllChildViews();
_.each(this.model.instruments, function (instrument) {
this.addInstrumentView(instrument, true);
}, this);
this.trigger("resize");
return this;
},
addInstrumentView: function (instrument, preventResizeEvent) {
var instrumentView = this.addChildView(InstrumentView, {
model: instrument
});
instrumentView.on("removeInstrument", this.removeInstrument, this);
instrumentView.render();
this.$el.append(instrumentView.$el);
if (!preventResizeEvent)
this.trigger("resize");
},
removeInstrument: function (instrument) {
this.eventBus.trigger("removeInstrument", this.model, instrument);
},
});
return InstrumentManagerView;
});
| define([
"use!underscore",
"use!backbone",
"baseView",
"settings",
"./instrumentView",
], function(_, Backbone, BaseView, settings, InstrumentView) {
var InstrumentManagerView = BaseView.extend({
modelEvents: {
"instrumentAdded": function (instrument) {
this.addInstrumentView(instrument);
},
"instrumentRemoved": function (instrument) {
this.resizeNewInstrumentArea();
}
},
render: function () {
this.removeAllChildViews();
_.each(this.model.instruments, function (instrument) {
this.addInstrumentView(instrument, true);
}, this);
this.trigger("resize");
return this;
},
addInstrumentView: function (instrument, preventResizeEvent) {
var instrumentView = this.addChildView(InstrumentView, {
model: instrument
});
instrumentView.on("removeInstrument", this.removeInstrument, this);
instrumentView.render();
this.$el.append(instrumentView.$el);
if (!preventResizeEvent)
this.trigger("resize");
},
removeInstrument: function (instrument) {
this.eventBus.trigger("removeInstrument", this.model, instrument);
},
});
return InstrumentManagerView;
});
|
Add example of faking a filter | describe("ReverseController", function () {
var fakeReverseFilter;
// See: https://docs.angularjs.org/api/ng/provider/$filterProvider
beforeEach(module("app.controllers", function ($filterProvider) {
fakeReverseFilter = jasmine.createSpy("fakeReverseFilter");
$filterProvider.register("reverse", function () {
return fakeReverseFilter;
});
}));
beforeEach(inject(function ($controller) {
reverseController = $controller("ReverseController");
}));
describe("reverse() method", function () {
it("delegates to the reverse filter", function () {
var value = "reverse";
var expectedValue = "esrever";
fakeReverseFilter.and.returnValue(expectedValue);
var actualValue = reverseController.reverse(value);
expect(fakeReverseFilter).toHaveBeenCalledWith(value);
expect(actualValue).toBe(expectedValue);
});
});
}); | describe("ReverseController", function () {
var fakeReverseFilter;
// See: https://docs.angularjs.org/api/ng/provider/$filterProvider
beforeEach(module("app.controllers", function ($filterProvider) {
console.log($filterProvider);
fakeReverseFilter = jasmine.createSpy("fakeReverseFilter");
$filterProvider.register("reverse", function () {
return fakeReverseFilter;
});
}));
beforeEach(inject(function ($controller) {
reverseController = $controller("ReverseController");
}));
describe("reverse() method", function () {
it("delegates to the reverse filter", function () {
var value = "reverse";
var expectedValue = "esrever";
fakeReverseFilter.and.returnValue(expectedValue);
var actualValue = reverseController.reverse(value);
expect(fakeReverseFilter).toHaveBeenCalledWith(value);
expect(actualValue).toBe(expectedValue);
});
});
}); |
Add getInt, getFloat, getBoolean to variables | /*
* Copyright 2014-2015 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kotcrab.vis.runtime.component;
import com.artemis.Component;
import com.badlogic.gdx.utils.ObjectMap;
import com.kotcrab.vis.runtime.util.autotable.ATStringStringMap;
/**
* Stores user defined variables in key-value store
* @author Kotcrab
*/
public class VariablesComponent extends Component {
@ATStringStringMap
public ObjectMap<String, String> variables = new ObjectMap<String, String>();
public String get (String variableName) {
return variables.get(variableName);
}
public float getFloat (String variableName) {
return Float.valueOf(get(variableName));
}
public int getInt (String variableName) {
return Integer.valueOf(get(variableName));
}
public boolean getBoolean (String variableName) {
return Boolean.valueOf(get(variableName));
}
}
| /*
* Copyright 2014-2015 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kotcrab.vis.runtime.component;
import com.artemis.Component;
import com.badlogic.gdx.utils.ObjectMap;
import com.kotcrab.vis.runtime.util.autotable.ATStringStringMap;
/** @author Kotcrab */
public class VariablesComponent extends Component {
@ATStringStringMap
public ObjectMap<String, String> variables = new ObjectMap<String, String>();
public String get (String variableName) {
return variables.get(variableName);
}
}
|
Fix pledge while loging in in donation flow
BB-7015 #resolve | from bluebottle.payments.adapters import BasePaymentAdapter
from bluebottle.payments.exception import PaymentException
from .models import PledgeStandardPayment
class PledgePaymentAdapter(BasePaymentAdapter):
def create_payment(self):
try:
can_pledge = self.order_payment.user.can_pledge
except AttributeError as e:
can_pledge = False
if not can_pledge:
raise PaymentException('User does not have permission to pledge')
# A little hacky but we can set the status to pledged here
self.order_payment.pledged()
self.order_payment.save()
def get_authorization_action(self):
# Return type success to indicate no further authorization is required.
return {'type': 'success'}
def check_payment_status(self):
pass | from bluebottle.payments.adapters import BasePaymentAdapter
from bluebottle.payments.exception import PaymentException
from .models import PledgeStandardPayment
class PledgePaymentAdapter(BasePaymentAdapter):
def create_payment(self):
try:
can_pledge = self.order_payment.order.user.can_pledge
except AttributeError as e:
can_pledge = False
if not can_pledge:
raise PaymentException('User does not have permission to pledge')
# A little hacky but we can set the status to pledged here
self.order_payment.pledged()
self.order_payment.save()
def get_authorization_action(self):
# Return type success to indicate no further authorization is required.
return {'type': 'success'}
def check_payment_status(self):
pass |
Use Babel's `format_decimal` instead of deprecated `format_number` | """
byceps.util.templatefunctions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template global functions.
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import babel
from flask_babel import get_locale, get_timezone
def register(app):
"""Make functions available as global functions in templates."""
functions = [
(_format_date, 'format_date'),
(_format_datetime, 'format_datetime'),
(_format_time, 'format_time'),
(_format_number, 'format_number'),
]
for f, name in functions:
app.add_template_global(f, name)
def _format_date(*args) -> str:
return babel.dates.format_date(*args, locale=get_locale())
def _format_datetime(*args) -> str:
return babel.dates.format_datetime(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_time(*args) -> str:
return babel.dates.format_time(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_number(*args) -> str:
return babel.numbers.format_decimal(*args, locale=get_locale())
| """
byceps.util.templatefunctions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template global functions.
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import babel
from flask_babel import get_locale, get_timezone
def register(app):
"""Make functions available as global functions in templates."""
functions = [
(_format_date, 'format_date'),
(_format_datetime, 'format_datetime'),
(_format_time, 'format_time'),
(_format_number, 'format_number'),
]
for f, name in functions:
app.add_template_global(f, name)
def _format_date(*args) -> str:
return babel.dates.format_date(*args, locale=get_locale())
def _format_datetime(*args) -> str:
return babel.dates.format_datetime(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_time(*args) -> str:
return babel.dates.format_time(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_number(*args) -> str:
return babel.numbers.format_number(*args, locale=get_locale())
|
Fix bug where text nodes beginning with newline would be ignored | import NodeType from './node-type'
export default function isNodeSupported (node = {}) {
return !(
isTagNameIgnored(node.tagName) ||
isNodeTypeIgnored(node.nodeType) ||
isNodeValueIgnored(node.nodeValue)
)
}
/**
* Tag names that are not supported.
* @type {Array}
*/
const IGNORED_TAG_NAMES = ['script']
/**
* Checks if provided tag name is ignored (not supported).
* @param {String} tagName
* @return {Boolean}
*/
const isTagNameIgnored = (tagName = '') => (
IGNORED_TAG_NAMES.indexOf(tagName.toLowerCase()) > -1
)
/**
* Node types that are not supported.
* @type {Array}
*/
const IGNORED_NODE_TYPES = [NodeType.COMMENT]
/**
* Checks if provided node type is ignored (not supported).
* @param {Number} nodeType
* @return {Boolean}
*/
const isNodeTypeIgnored = (nodeType) => (
IGNORED_NODE_TYPES.indexOf(nodeType) > -1
)
/**
* Node values that are not supported.
* @type {RegExp}
*/
const IGNORED_NODE_VALUES = /^\n/
/**
* Checks if provided node value is ignored (not supported).
* @param {String} nodeValue
* @return {Boolean}
*/
const isNodeValueIgnored = (nodeValue) => (
IGNORED_NODE_VALUES.test((nodeValue || '').trim())
)
| import NodeType from './node-type'
export default function isNodeSupported (node = {}) {
return !(
isTagNameIgnored(node.tagName) ||
isNodeTypeIgnored(node.nodeType) ||
isNodeValueIgnored(node.nodeValue)
)
}
/**
* Tag names that are not supported.
* @type {Array}
*/
const IGNORED_TAG_NAMES = ['script']
/**
* Checks if provided tag name is ignored (not supported).
* @param {String} tagName
* @return {Boolean}
*/
const isTagNameIgnored = (tagName = '') => (
IGNORED_TAG_NAMES.indexOf(tagName.toLowerCase()) > -1
)
/**
* Node types that are not supported.
* @type {Array}
*/
const IGNORED_NODE_TYPES = [NodeType.COMMENT]
/**
* Checks if provided node type is ignored (not supported).
* @param {Number} nodeType
* @return {Boolean}
*/
const isNodeTypeIgnored = (nodeType) => (
IGNORED_NODE_TYPES.indexOf(nodeType) > -1
)
/**
* Node values that are not supported.
* @type {RegExp}
*/
const IGNORED_NODE_VALUES = /^\n/
/**
* Checks if provided node value is ignored (not supported).
* @param {String} nodeValue
* @return {Boolean}
*/
const isNodeValueIgnored = (nodeValue) => (
IGNORED_NODE_VALUES.test(nodeValue)
)
|
Test primary key in register fields | import pytest
from data import registers, fields, phases
@pytest.mark.parametrize('register', registers)
def test_register_key_matches_filename(register):
assert registers[register].register == register
@pytest.mark.parametrize('register', registers)
def test_register_primary_key_in_fields(register):
assert register in registers[register].fields
@pytest.mark.parametrize('register', registers)
def test_register_keys_are_known_fields(register):
for field in registers[register].keys:
assert field in fields
@pytest.mark.parametrize('register', registers)
def test_register_fields_are_register_fields(register):
for field in registers[register].keys:
assert field in registers['register'].fields
@pytest.mark.parametrize('register', registers)
def test_register_text_trailing_characters(register):
text = registers[register].text
assert text == text.rstrip(' \n\r.')
@pytest.mark.parametrize('register', registers)
def test_register_phase(register):
assert registers[register].phase in phases
@pytest.mark.parametrize('register', registers)
def test_register_fields_are_known(register):
item = registers[register]
for field in item.fields:
assert field in fields
@pytest.mark.parametrize('register', registers)
def test_register_fields_are_the_right_phase(register):
item = registers[register]
register_phase = phases.index(item.phase)
for field in item.fields:
field_phase = phases.index(fields[field].phase)
assert field_phase >= register_phase
| import pytest
from data import registers, fields, phases
@pytest.mark.parametrize('register', registers)
def test_register_key_matches_filename(register):
assert registers[register].register == register
@pytest.mark.parametrize('register', registers)
def test_register_keys_are_known_fields(register):
for field in registers[register].keys:
assert field in fields
@pytest.mark.parametrize('register', registers)
def test_register_fields_are_register_fields(register):
for field in registers[register].keys:
assert field in registers['register'].fields
@pytest.mark.parametrize('register', registers)
def test_register_text_trailing_characters(register):
text = registers[register].text
assert text == text.rstrip(' \n\r.')
@pytest.mark.parametrize('register', registers)
def test_register_phase(register):
assert registers[register].phase in phases
@pytest.mark.parametrize('register', registers)
def test_register_fields_are_known(register):
item = registers[register]
for field in item.fields:
assert field in fields
@pytest.mark.parametrize('register', registers)
def test_register_fields_are_the_right_phase(register):
item = registers[register]
register_phase = phases.index(item.phase)
for field in item.fields:
field_phase = phases.index(fields[field].phase)
assert field_phase >= register_phase
|
Add utf-8 BOM to CSV download | PT = PT || {};
PT.downloadCsv = function(serverResponse){
var survey = serverResponse.survey;
var responses = serverResponse.responses;
var a = document.createElement('a');
var csvString = "";
//Write title & prompts
csvString += survey.title + "\n";
csvString += 'Date of submission,"Location of submission (lat, lon)",';
survey.inputs.forEach(function(input){
csvString += '"' + input.label + '",';
})
//Write responses
responses.forEach(function(response){
csvString += "\n" + response.timestamp + ","
+ '"' + response.locationstamp.lat + ", " + response.locationstamp.lon + '",';
response.answers.forEach(function(answer){
if(answer.value){
if (typeof(answer.value) == "string"){
csvString += '"' + answer.value + '"';
} else if(answer.value.constructor == Array) {
csvString += '"' + answer.value.join(",") + '"';
} else {
csvString += '"' + answer.value.lat + ", " + answer.value.lon + '"';
}
}
csvString += ",";
})
})
a.href = "data:application/csv;charset=utf-8," + "\uFEFF" + encodeURIComponent(csvString);
a.target = "_blank";
a.download = "PT_Data_" + survey.code + ".csv";
document.body.appendChild(a);
a.click();
}; | PT = PT || {};
PT.downloadCsv = function(serverResponse){
var survey = serverResponse.survey;
var responses = serverResponse.responses;
var a = document.createElement('a');
var csvString = "";
//Write title & prompts
csvString += survey.title + "\n";
csvString += 'Date of submission,"Location of submission (lat, lon)",';
survey.inputs.forEach(function(input){
csvString += '"' + input.label + '",';
})
//Write responses
responses.forEach(function(response){
csvString += "\n" + response.timestamp + ","
+ '"' + response.locationstamp.lat + ", " + response.locationstamp.lon + '",';
response.answers.forEach(function(answer){
if(answer.value){
if (typeof(answer.value) == "string"){
csvString += '"' + answer.value + '"';
} else if(answer.value.constructor == Array) {
csvString += '"' + answer.value.join(",") + '"';
} else {
csvString += '"' + answer.value.lat + ", " + answer.value.lon + '"';
}
}
csvString += ",";
})
})
a.href = "data:application/csv;charset=utf-8," + encodeURIComponent(csvString);
a.target = "_blank";
a.download = "PT_Data_" + survey.code + ".csv";
document.body.appendChild(a);
a.click();
}; |
Fix Android tests affected by changes in stubs | package com.example.myapp;
import android.app.Activity;
import android.content.Context;
public class IntentSources extends Activity {
private static void sink(Object o) {}
public IntentSources(Context base) {
super(base);
}
public void test() throws java.io.IOException {
String trouble = this.getIntent().getStringExtra("key");
sink(trouble); // $hasRemoteTaintFlow
}
public void test2() throws java.io.IOException {
String trouble = getIntent().getStringExtra("key");
sink(trouble); // $hasRemoteTaintFlow
}
public void test3() throws java.io.IOException {
String trouble = getIntent().getExtras().getString("key");
sink(trouble); // $hasRemoteTaintFlow
}
}
class OtherClass {
private static void sink(Object o) {}
public void test(IntentSources is) throws java.io.IOException {
String trouble = is.getIntent().getStringExtra("key");
sink(trouble); // $hasRemoteTaintFlow
}
}
| package com.example.myapp;
import android.app.Activity;
public class IntentSources extends Activity {
private static void sink(Object o) {}
public void test() throws java.io.IOException {
String trouble = this.getIntent().getStringExtra("key");
sink(trouble); // $hasRemoteTaintFlow
}
public void test2() throws java.io.IOException {
String trouble = getIntent().getStringExtra("key");
sink(trouble); // $hasRemoteTaintFlow
}
public void test3() throws java.io.IOException {
String trouble = getIntent().getExtras().getString("key");
sink(trouble); // $hasRemoteTaintFlow
}
}
class OtherClass {
private static void sink(Object o) {}
public void test(IntentSources is) throws java.io.IOException {
String trouble = is.getIntent().getStringExtra("key");
sink(trouble); // $hasRemoteTaintFlow
}
}
|
Fix create empty item on remove | package main
import (
"errors"
"fmt"
)
var cmdRemove = &Command{
Run: runRemove,
UsageLine: "remove NAME",
Short: "Remove saved password",
Long: `Remove saved password by input name.`,
}
func runRemove(ctx context, args []string) error {
if len(args) == 0 {
return errors.New("item name required")
}
cfg, err := GetConfig()
if err != nil {
return err
}
Initialize(cfg)
is, err := LoadItems(cfg.DataFile)
if err != nil {
return err
}
name := args[0]
fit := is.Find(name)
if fit == nil {
return fmt.Errorf("item not found: %s", name)
}
nis := Items([]Item{})
for _, it := range is {
if it.Name != fit.Name {
nis = append(nis, it)
}
}
nis.Save(cfg.DataFile)
fmt.Fprintln(ctx.out, fmt.Sprintf("password of '%s' is removed successfully", name))
return nil
}
| package main
import (
"errors"
"fmt"
)
var cmdRemove = &Command{
Run: runRemove,
UsageLine: "remove NAME",
Short: "Remove saved password",
Long: `Remove saved password by input name.`,
}
func runRemove(ctx context, args []string) error {
if len(args) == 0 {
return errors.New("item name required")
}
cfg, err := GetConfig()
if err != nil {
return err
}
Initialize(cfg)
is, err := LoadItems(cfg.DataFile)
if err != nil {
return err
}
name := args[0]
fit := is.Find(name)
if fit == nil {
return fmt.Errorf("item not found: %s", name)
}
nis := Items(make([]Item, len(is)-1))
for _, it := range is {
if it.Name != fit.Name {
nis = append(nis, it)
}
}
nis.Save(cfg.DataFile)
fmt.Fprintln(ctx.out, fmt.Sprintf("password of '%s' is removed successfully", name))
return nil
}
|
Fix for count with one partition | def get_kv_shape(shape, key_axes):
func = lambda axis: shape[axis]
return _get_kv_func(func, shape, key_axes)
def get_kv_axes(shape, key_axes):
func = lambda axis: axis
return _get_kv_func(func, shape, key_axes)
def _get_kv_func(func, shape, key_axes):
key_res = [func(axis) for axis in key_axes]
value_res = [func(axis) for axis in range(len(shape)) if axis not in key_axes]
return key_res, value_res
def zip_with_index(rdd):
"""
Alternate version of Spark's zipWithIndex that eagerly returns count.
"""
starts = [0]
if rdd.getNumPartitions() > 1:
nums = rdd.mapPartitions(lambda it: [sum(1 for _ in it)]).collect()
count = sum(nums)
for i in range(len(nums) - 1):
starts.append(starts[-1] + nums[i])
else:
count = rdd.count()
def func(k, it):
for i, v in enumerate(it, starts[k]):
yield v, i
return count, rdd.mapPartitionsWithIndex(func)
| def get_kv_shape(shape, key_axes):
func = lambda axis: shape[axis]
return _get_kv_func(func, shape, key_axes)
def get_kv_axes(shape, key_axes):
func = lambda axis: axis
return _get_kv_func(func, shape, key_axes)
def _get_kv_func(func, shape, key_axes):
key_res = [func(axis) for axis in key_axes]
value_res = [func(axis) for axis in range(len(shape)) if axis not in key_axes]
return key_res, value_res
def zip_with_index(rdd):
"""
Alternate version of Spark's zipWithIndex that eagerly returns count.
"""
starts = [0]
count = None
if rdd.getNumPartitions() > 1:
nums = rdd.mapPartitions(lambda it: [sum(1 for _ in it)]).collect()
count = sum(nums)
for i in range(len(nums) - 1):
starts.append(starts[-1] + nums[i])
def func(k, it):
for i, v in enumerate(it, starts[k]):
yield v, i
return count, rdd.mapPartitionsWithIndex(func)
|
Use application/json as default content-type with Axios | var extend = require('../utils').extend;
require('native-promise-only');
var axios = require('axios');
var Axios = function(settings) {
return new Promise(function(resolve, reject) {
var options = {
method: settings.type.toLowerCase(),
url: settings.url,
responseType: "text",
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
};
if (settings.headers) {
options.headers = extend(options.headers, settings.headers);
}
if (settings.processData) {
options.params = settings.data;
} else {
options.data = settings.data;
}
return axios(options).then(function(response) {
settings.success(response.data);
return resolve(response);
}).catch(function(response) {
var error = response.data || response;
settings.error(error);
return reject(response);
});
});
};
module.exports = Axios;
| require('native-promise-only');
var axios = require('axios');
var Axios = function(settings) {
return new Promise(function(resolve, reject) {
var options = {
method: settings.type.toLowerCase(),
url: settings.url,
responseType: "text"
};
if (settings.headers) {
options.headers = settings.headers;
}
if (settings.processData) {
options.params = settings.data;
} else {
options.data = settings.data;
}
return axios(options).then(function(response) {
settings.success(response.data);
return resolve(response);
}).catch(function(response) {
var error = response.data || response;
settings.error(error);
return reject(response);
});
});
};
module.exports = Axios;
|
Fix invalid connection preface as is able to process as HTTP request | package h2spec
import (
"fmt"
"io"
"net"
"syscall"
"time"
)
func Http2ConnectionPrefaceTestGroup(ctx *Context) *TestGroup {
tg := NewTestGroup("3.5", "HTTP/2 Connection Preface")
tg.AddTestCase(NewTestCase(
"Sends invalid connection preface",
"The endpoint MUST terminate the TCP connection.",
func(ctx *Context) (expected []Result, actual Result) {
expected = []Result{
&ResultConnectionClose{},
}
tcpConn := CreateTcpConn(ctx)
defer tcpConn.conn.Close()
fmt.Fprintf(tcpConn.conn, "INVALID CONNECTION PREFACE\r\n\r\n")
timeCh := time.After(ctx.Timeout)
loop:
for {
select {
case <-tcpConn.dataCh:
break
case err := <-tcpConn.errCh:
opErr, ok := err.(*net.OpError)
if err == io.EOF || (ok && opErr.Err == syscall.ECONNRESET) {
actual = &ResultConnectionClose{}
} else {
actual = &ResultError{err}
}
break loop
case <-timeCh:
actual = &ResultTestTimeout{}
break loop
}
}
return expected, actual
},
))
return tg
}
| package h2spec
import (
"fmt"
"io"
"net"
"syscall"
"time"
)
func Http2ConnectionPrefaceTestGroup(ctx *Context) *TestGroup {
tg := NewTestGroup("3.5", "HTTP/2 Connection Preface")
tg.AddTestCase(NewTestCase(
"Sends invalid connection preface",
"The endpoint MUST terminate the TCP connection.",
func(ctx *Context) (expected []Result, actual Result) {
expected = []Result{
&ResultConnectionClose{},
}
tcpConn := CreateTcpConn(ctx)
defer tcpConn.conn.Close()
fmt.Fprintf(tcpConn.conn, "INVALID CONNECTION PREFACE")
timeCh := time.After(ctx.Timeout)
loop:
for {
select {
case <-tcpConn.dataCh:
break
case err := <-tcpConn.errCh:
opErr, ok := err.(*net.OpError)
if err == io.EOF || (ok && opErr.Err == syscall.ECONNRESET) {
actual = &ResultConnectionClose{}
} else {
actual = &ResultError{err}
}
break loop
case <-timeCh:
actual = &ResultTestTimeout{}
break loop
}
}
return expected, actual
},
))
return tg
}
|
Set author to 'Mozilla Automation and Testing Team' | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
version = '1.0'
setup(name='treeherder-client',
version=version,
description="Python library to submit data to treeherder-service",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Mozilla Automation and Testing Team',
author_email='tools@lists.mozilla.org',
url='https://github.com/mozilla/treeherder-client',
license='MPL',
packages=['thclient'],
zip_safe=False,
install_requires=['oauth2'],
test_suite='thclient.tests',
tests_require=["mock"],
)
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
version = '1.0'
setup(name='treeherder-client',
version=version,
description="Python library to submit data to treeherder-service",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Jonathan Eads',
author_email='jeads@mozilla.com',
url='https://github.com/mozilla/treeherder-client',
license='MPL',
packages=['thclient'],
zip_safe=False,
install_requires=['oauth2'],
test_suite='thclient.tests',
tests_require=["mock"],
)
|
Fix bug that led to togglegame at each error | package it.playfellas.superapp.logic.master;
import it.playfellas.superapp.events.EventFactory;
import it.playfellas.superapp.events.game.StartGameEvent;
import it.playfellas.superapp.logic.Config1;
import it.playfellas.superapp.network.TenBus;
/**
* Created by affo on 31/07/15.
*/
public class Master1Controller extends MasterController {
private Config1 conf;
public Master1Controller(Config1 conf){
super(conf);
this.conf = conf;
}
@Override
void onBeginStage() {
}
@Override
void onEndStage() {
}
@Override
void onAnswer(boolean rw) {
int score = getScore();
if (score != 0 && score % conf.getRuleChange() == 0) {
TenBus.get().post(EventFactory.gameChange());
}
}
@Override
StartGameEvent getNewGameEvent() {
return EventFactory.startGame1(conf);
}
}
| package it.playfellas.superapp.logic.master;
import it.playfellas.superapp.events.EventFactory;
import it.playfellas.superapp.events.game.StartGameEvent;
import it.playfellas.superapp.logic.Config1;
import it.playfellas.superapp.network.TenBus;
/**
* Created by affo on 31/07/15.
*/
public class Master1Controller extends MasterController {
private Config1 conf;
public Master1Controller(Config1 conf){
super(conf);
this.conf = conf;
}
@Override
void onBeginStage() {
}
@Override
void onEndStage() {
}
@Override
void onAnswer(boolean rw) {
if (getScore() % conf.getRuleChange() == 0) {
TenBus.get().post(EventFactory.gameChange());
}
}
@Override
StartGameEvent getNewGameEvent() {
return EventFactory.startGame1(conf);
}
}
|
Remove unnecessary method calls in undo command | package seedu.address.logic.commands;
public class UndoCommand extends Command {
public static final String COMMAND_WORD = "undo";
public static final String MESSAGE_USAGE = COMMAND_WORD;
public static final String MESSAGE_SUCCESS = "Successfully undo previous change";
public static final String MESSAGE_NO_CHANGE = "No change to be undone";
/**
* Default empty constructor.
*/
public UndoCommand() {
}
public CommandResult execute() {
if (!model.getFlag().equals("undo copy")) {
return new CommandResult(MESSAGE_NO_CHANGE);
} else {
model.resetData(model.getCopy());
model.updateFlag("empty copy");
return new CommandResult(MESSAGE_SUCCESS);
}
}
}
| package seedu.address.logic.commands;
public class UndoCommand extends Command {
public static final String COMMAND_WORD = "undo";
public static final String MESSAGE_USAGE = COMMAND_WORD;
public static final String MESSAGE_SUCCESS = "Successfully undo previous change";
public static final String MESSAGE_NO_CHANGE = "No change to be undone";
/**
* Default empty constructor.
*/
public UndoCommand() {
}
public CommandResult execute() {
if (!model.getFlag().equals("undo copy")) {
return new CommandResult(MESSAGE_NO_CHANGE);
} else {
model.resetData(model.getCopy());
model.clearCopy();
model.updateFlag("empty copy");
return new CommandResult(MESSAGE_SUCCESS);
}
}
}
|
Move the SERVER_NAME to the start of the default config
Minor nit but the SERVER_NAME is one of the more important settings
on a per app basis. | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
|
Remove south from app helper method for Django 1.7+ | from __future__ import absolute_import
import os
__version__ = VERSION = "0.3.0"
def get_fancypages_paths(path, use_with_oscar=False):
""" Get absolute paths for *path* relative to the project root """
paths = []
if use_with_oscar:
from fancypages.contrib import oscar_fancypages
base_dir = os.path.dirname(os.path.abspath(oscar_fancypages.__file__))
paths.append(os.path.join(base_dir, path))
return paths + [
os.path.join(os.path.dirname(os.path.abspath(__file__)), path)]
def get_required_apps():
apps = [
'django_extensions',
# used for image thumbnailing
'sorl.thumbnail',
# framework used for the internal API
'rest_framework',
# provides a convenience layer around model inheritance
# that makes lookup of nested models easier. This is used
# for the content block hierarchy.
'model_utils',
]
import django
if django.VERSION[1] < 7:
apps.append('south')
return apps
def get_fancypages_apps(use_with_oscar=False):
apps = ['fancypages.assets', 'fancypages']
if use_with_oscar:
apps += ['fancypages.contrib.oscar_fancypages']
return apps
| from __future__ import absolute_import
import os
__version__ = VERSION = "0.3.0"
def get_fancypages_paths(path, use_with_oscar=False):
""" Get absolute paths for *path* relative to the project root """
paths = []
if use_with_oscar:
from fancypages.contrib import oscar_fancypages
base_dir = os.path.dirname(os.path.abspath(oscar_fancypages.__file__))
paths.append(os.path.join(base_dir, path))
return paths + [
os.path.join(os.path.dirname(os.path.abspath(__file__)), path)]
def get_required_apps():
return [
'django_extensions',
# used for image thumbnailing
'sorl.thumbnail',
# framework used for the internal API
'rest_framework',
# provides a convenience layer around model inheritance
# that makes lookup of nested models easier. This is used
# for the content block hierarchy.
'model_utils',
# migration handling
'south',
]
def get_fancypages_apps(use_with_oscar=False):
apps = ['fancypages.assets', 'fancypages']
if use_with_oscar:
apps += ['fancypages.contrib.oscar_fancypages']
return apps
|
Make the test more comprehensive. | r"""
Tests for QtAwesome.
"""
# Standard library imports
import subprocess
import collections
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon()"', shell=True)
assert output_number == 0
def test_unique_font_family_name(qtbot):
"""
Test that each font used by qtawesome has a unique name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
Regression test for Issue #107
"""
resource = qta._instance()
assert isinstance(resource, IconicFont)
# Check that the fonts were loaded successfully.
fontnames = resource.fontname.values()
assert fontnames
# Check that qtawesome does not load fonts with duplicate family names.
duplicates = [fontname for fontname, count in
collections.Counter(fontnames).items() if count > 1]
assert not duplicates
if __name__ == "__main__":
pytest.main()
| r"""
Tests for QtAwesome.
"""
# Standard library imports
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon()"', shell=True)
assert output_number == 0
def test_unique_font_family_name(qtbot):
"""
Test that each font used by qtawesome has a unique name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
Regression test for Issue #107
"""
resource = qta._instance()
assert isinstance(resource, IconicFont)
prefixes = list(resource.fontname.keys())
assert prefixes
fontnames = set(resource.fontname.values())
assert fontnames
assert len(prefixes) == len(fontnames)
if __name__ == "__main__":
pytest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.