text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix syntax Error for compability with python 3.X | from neomodel import StructuredNode, StringProperty, DoesNotExist, CypherException
import pickle
class Person(StructuredNode):
name = StringProperty(unique_index=True)
def test_cypher_exception_can_be_displayed():
print(CypherException("SOME QUERY", (), "ERROR", None, None))
def test_object_does_not_exist():
try:
Person.nodes.get(name="johnny")
except Person.DoesNotExist as e:
pickle_instance = pickle.dumps(e)
assert pickle_instance
assert pickle.loads(pickle_instance)
assert isinstance(pickle.loads(pickle_instance), DoesNotExist)
def test_raise_does_not_exist():
try:
raise DoesNotExist("My Test Message")
except DoesNotExist as e:
pickle_instance = pickle.dumps(e)
assert pickle_instance
assert pickle.loads(pickle_instance)
assert isinstance(pickle.loads(pickle_instance), DoesNotExist)
| from neomodel import StructuredNode, StringProperty, DoesNotExist, CypherException
import pickle
class Person(StructuredNode):
name = StringProperty(unique_index=True)
def test_cypher_exception_can_be_displayed():
print CypherException("SOME QUERY", (), "ERROR", None, None)
def test_object_does_not_exist():
try:
Person.nodes.get(name="johnny")
except Person.DoesNotExist as e:
pickle_instance = pickle.dumps(e)
assert pickle_instance
assert pickle.loads(pickle_instance)
assert isinstance(pickle.loads(pickle_instance), DoesNotExist)
def test_raise_does_not_exist():
try:
raise DoesNotExist("My Test Message")
except DoesNotExist as e:
pickle_instance = pickle.dumps(e)
assert pickle_instance
assert pickle.loads(pickle_instance)
assert isinstance(pickle.loads(pickle_instance), DoesNotExist)
|
Remove no longer used constants | const router = require('express').Router();
const scraper = require('../service/scraper');
router.get('/', (req, res, next) => {
const packageName = req.query.package;
if (!packageName) {
const err = new Error('Undefined query');
err.satus = 404;
next(err);
}
scraper
.scan(packageName)
.then(result => {
const changes = result.changes;
res.json({ packageName, changes });
})
.catch(error => {
const err = new Error('Could not request info');
err.status = 404;
next(err);
});
});
module.exports = router;
| const router = require('express').Router();
const scraper = require('../service/scraper');
const baseUrl = 'https://play.google.com/store/apps/details?hl=en&id=';
const headers = { 'Accept-Language': 'en-US,en;q=0.8' };
router.get('/', (req, res, next) => {
const packageName = req.query.package;
if (!packageName) {
const err = new Error('Undefined query');
err.satus = 404;
next(err);
}
scraper
.scan(packageName)
.then(result => {
const changes = result.changes;
res.json({ packageName, changes });
})
.catch(error => {
const err = new Error('Could not request info');
err.status = 404;
next(err);
});
});
module.exports = router;
|
Rename toolId to id to fix json conversion | package fi.csc.chipster.toolbox;
import fi.csc.microarray.description.SADLDescription;
public class ToolboxTool {
private String id;
private SADLDescription sadlDescription;
private String sadlString;
private String source;
private String code;
private String module;
private String runtime;
public ToolboxTool() {
}
public ToolboxTool(String id, SADLDescription sadlDescription, String sadlString, String code, String source, String module, String runtime) {
this.id = id;
this.sadlDescription = sadlDescription;
this.sadlString = sadlString;
this.source = source;
this.code = code;
this.runtime = runtime;
this.module = module;
}
public String getId() {
return id;
}
public SADLDescription getSadlDescription() {
return sadlDescription;
}
public String getRuntime() {
return runtime;
}
public String getSadlString() {
return sadlString;
}
public String getSource() {
return source;
}
public String getCode() {
return code;
}
public String getModule() {
return module;
}
}
| package fi.csc.chipster.toolbox;
import fi.csc.microarray.description.SADLDescription;
public class ToolboxTool {
private String toolId;
private SADLDescription sadlDescription;
private String sadlString;
private String source;
private String code;
private String module;
private String runtime;
public ToolboxTool() {
}
public ToolboxTool(String toolId, SADLDescription sadlDescription, String sadlString, String code, String source, String module, String runtime) {
this.toolId = toolId;
this.sadlDescription = sadlDescription;
this.sadlString = sadlString;
this.source = source;
this.code = code;
this.runtime = runtime;
this.module = module;
}
public String getId() {
return toolId;
}
public SADLDescription getSadlDescription() {
return sadlDescription;
}
public String getRuntime() {
return runtime;
}
public String getSadlString() {
return sadlString;
}
public String getSource() {
return source;
}
public String getCode() {
return code;
}
public String getModule() {
return module;
}
}
|
Remove remote access check for development needs | <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
//if (isset($_SERVER['HTTP_CLIENT_IP'])
// || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
// || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
//) {
// header('HTTP/1.0 403 Forbidden');
// exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
//}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Fix template name on entry home page (/) on list page | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwargs.get('channel__long_slug', 'home')
return 'channel/{0}.html'.format(long_slug)
@property
def queryset(self):
if not self.kwargs.get('channel__long_slug'):
return Post.objects.filter(channel__homepage=True).all()
return Post.objects.filter(
channel__long_slug=self.kwargs['channel__long_slug']).all()
class OppsDetail(DetailView):
context_object_name = "context"
@property
def template_name(self):
return 'article/{0}/{1}.html'.format(
self.kwargs['channel__long_slug'], self.kwargs['slug'])
@property
def queryset(self):
return Post.objects.filter(
channel__long_slug=self.kwargs['channel__long_slug'],
slug=self.kwargs['slug']).all()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
return 'channel/{0}.html'.format(self.kwargs['channel__long_slug'])
@property
def queryset(self):
if not self.kwargs.get('channel__long_slug'):
return Post.objects.filter(channel__homepage=True).all()
return Post.objects.filter(
channel__long_slug=self.kwargs['channel__long_slug']).all()
class OppsDetail(DetailView):
context_object_name = "context"
@property
def template_name(self):
return 'article/{0}/{1}.html'.format(
self.kwargs['channel__long_slug'], self.kwargs['slug'])
@property
def queryset(self):
return Post.objects.filter(
channel__long_slug=self.kwargs['channel__long_slug'],
slug=self.kwargs['slug']).all()
|
Fix the missing ... in LogPrint(). | // Copyright 2017 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import "log"
// EnableLog controls whether to print log to console.
var EnableLog = true
// LogPrint prints the log.
func LogPrint(v ...interface{}) {
if EnableLog {
log.Print(v...)
}
}
// LogPrintf prints the log with the format.
func LogPrintf(format string, v ...interface{}) {
if EnableLog {
log.Printf(format, v...)
}
}
| // Copyright 2017 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import "log"
// EnableLog controls whether to print log to console.
var EnableLog = true
// LogPrint prints the log.
func LogPrint(v ...interface{}) {
if EnableLog {
log.Print(v)
}
}
// LogPrintf prints the log with the format.
func LogPrintf(format string, v ...interface{}) {
if EnableLog {
log.Printf(format, v...)
}
}
|
Create constant to store path for results | #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'
# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90
# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00
K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
MAX_V = 0.075
MAX_W = 1.25
elif TRAJECTORY == 'circular':
SIMULATION_TIME_IN_SECONDS = 120.0
MAX_V = 0.11
MAX_W = 1.25
elif TRAJECTORY == 'squared':
SIMULATION_TIME_IN_SECONDS = 160.0
MAX_V = 0.055
MAX_W = 1.20
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
RESULTS_DIRECTORY = '../last_results/'
| #!/usr/bin/env python
TRAJECTORY = 'squared'
CONTROLLER = 'pid'
# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90
# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00
K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
MAX_V = 0.075
MAX_W = 1.25
elif TRAJECTORY == 'circular':
SIMULATION_TIME_IN_SECONDS = 120.0
MAX_V = 0.11
MAX_W = 1.25
elif TRAJECTORY == 'squared':
SIMULATION_TIME_IN_SECONDS = 160.0
MAX_V = 0.055
MAX_W = 1.20
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
|
Add travis-ci to `powerd by` page. | from django.shortcuts import render
from django.contrib import admin, auth
# We don't need a user management
admin.site.unregister(auth.models.User)
admin.site.unregister(auth.models.Group)
def index(request):
return render(request, 'index.html')
def about_me(request):
return render(request, 'about-me.html')
def a_lot_tech(request):
techs = {
'Language': ['Python', 'HTML', 'JavaScript', 'Sass'],
'Framework': ['Django', 'Semantic UI'],
'Package Manager': ['PyPI', 'NPM', 'Bower'],
'Platform': ['GitHub', 'Heroku', 'Travis-CI'],
'Database': ['PostgreSQL', 'SQLite']
}
return render(request, 'a-lot.html', locals())
| from django.shortcuts import render
from django.contrib import admin, auth
# We don't need a user management
admin.site.unregister(auth.models.User)
admin.site.unregister(auth.models.Group)
def index(request):
return render(request, 'index.html')
def about_me(request):
return render(request, 'about-me.html')
def a_lot_tech(request):
techs = {
'Language': ['Python', 'HTML', 'JavaScript', 'Sass'],
'Framework': ['Django', 'Semantic UI'],
'Package Manager': ['PyPI', 'NPM', 'Bower'],
'Platform': ['GitHub', 'Heroku'],
'Database': ['PostgreSQL', 'SQLite']
}
return render(request, 'a-lot.html', locals())
|
Raise an error on dummy class init | import sys
if sys.version_info[0] < 3:
_available = False
else:
try:
from chainerx import _core
_available = True
except Exception:
_available = False
if _available:
from numpy import dtype, bool_, int8, int16, int32, int64, uint8, float32, float64 # NOQA
from chainerx._core import * # NOQA
from builtins import bool, int, float # NOQA
from chainerx.creation.from_data import asanyarray # NOQA
from chainerx.creation.from_data import fromfile # NOQA
from chainerx.creation.from_data import fromfunction # NOQA
from chainerx.creation.from_data import fromiter # NOQA
from chainerx.creation.from_data import fromstring # NOQA
from chainerx.creation.from_data import loadtxt # NOQA
_global_context = _core.Context()
_core.set_global_default_context(_global_context)
# Add workaround implementation for NumPy-compatible functions
from chainerx import _numpy_compat_workarounds
_numpy_compat_workarounds.populate()
else:
class ndarray(object):
"""Dummy class for type testing."""
def __init__(self, *args, **kwargs):
raise RuntimeError('chainerx is not available.')
def is_available():
return _available
| import sys
if sys.version_info[0] < 3:
_available = False
else:
try:
from chainerx import _core
_available = True
except Exception:
_available = False
if _available:
from numpy import dtype, bool_, int8, int16, int32, int64, uint8, float32, float64 # NOQA
from chainerx._core import * # NOQA
from builtins import bool, int, float # NOQA
from chainerx.creation.from_data import asanyarray # NOQA
from chainerx.creation.from_data import fromfile # NOQA
from chainerx.creation.from_data import fromfunction # NOQA
from chainerx.creation.from_data import fromiter # NOQA
from chainerx.creation.from_data import fromstring # NOQA
from chainerx.creation.from_data import loadtxt # NOQA
_global_context = _core.Context()
_core.set_global_default_context(_global_context)
# Add workaround implementation for NumPy-compatible functions
from chainerx import _numpy_compat_workarounds
_numpy_compat_workarounds.populate()
else:
class ndarray(object):
pass # for type testing
def is_available():
return _available
|
Fix problem after stopping process | import time
import threading
from . import app, mongo, controller
from bson.objectid import ObjectId
class Monitor(object):
def __init__(self, timeout=10):
self.thread = None
self.exit_event = None
self.timeout = timeout
def temperature(self, brew_id):
if self.thread:
raise RuntimeError("Brew still ongoing")
def run_in_background():
while True:
if self.exit_event.wait(self.timeout):
break
with app.app_context():
temperature = controller.get_temperature()
now = time.time()
query = {'_id': ObjectId(brew_id)}
op = {'$push': {'temperatures': (now, temperature)}}
mongo.db.brews.update(query, op)
self.exit_event = threading.Event()
self.thread = threading.Thread(target=run_in_background)
self.thread.start()
def stop(self):
self.exit_event.set()
self.thread.join()
self.thread = None
| import time
import threading
from . import app, mongo, controller
from bson.objectid import ObjectId
class Monitor(object):
def __init__(self, timeout=10):
self.thread = None
self.exit_event = None
self.timeout = timeout
def temperature(self, brew_id):
if self.thread:
raise RuntimeError("Brew still ongoing")
def run_in_background():
while True:
if self.exit_event.wait(self.timeout):
break
with app.app_context():
temperature = controller.get_temperature()
now = time.time()
query = {'_id': ObjectId(brew_id)}
op = {'$push': {'temperatures': (now, temperature)}}
mongo.db.brews.update(query, op)
self.exit_event = threading.Event()
self.thread = threading.Thread(target=run_in_background)
self.thread.start()
def stop(self):
self.exit_event.set()
self.thread.join()
|
Replace let with var to fix travis build | const spawn = require('cross-spawn');
/* eslint-disable no-var */
var args = process.argv.slice(2);
/* eslint-enable */
const server = args.indexOf('--dev') > -1
? null
: require('../../examples/server');
if (args.indexOf('--config') === -1) {
args = args.concat(['--config', 'test/e2e/nightwatch.config.js']);
}
if (args.indexOf('--env') === -1) {
args = args.concat(['--env', 'phantomjs']);
}
const i = args.indexOf('--test');
if (i > -1) {
args[i + 1] = `test/e2e/specs/${args[i + 1]}`;
}
if (args.indexOf('phantomjs') > -1) {
process.env.PHANTOMJS = true;
}
const runner = spawn('./node_modules/.bin/nightwatch', args, {
stdio: 'inherit'
});
runner.on('exit', (code) => {
if (server) server.close();
process.exit(code);
});
runner.on('error', (err) => {
if (server) server.close();
throw err;
});
| const spawn = require('cross-spawn');
let args = process.argv.slice(2);
const server = args.indexOf('--dev') > -1
? null
: require('../../examples/server');
if (args.indexOf('--config') === -1) {
args = args.concat(['--config', 'test/e2e/nightwatch.config.js']);
}
if (args.indexOf('--env') === -1) {
args = args.concat(['--env', 'phantomjs']);
}
const i = args.indexOf('--test');
if (i > -1) {
args[i + 1] = `test/e2e/specs/${args[i + 1]}`;
}
if (args.indexOf('phantomjs') > -1) {
process.env.PHANTOMJS = true;
}
const runner = spawn('./node_modules/.bin/nightwatch', args, {
stdio: 'inherit'
});
runner.on('exit', (code) => {
if (server) server.close();
process.exit(code);
});
runner.on('error', (err) => {
if (server) server.close();
throw err;
});
|
Add Python 3.5 to trove classifiers | import os
import re
from setuptools import setup
HERE = os.path.dirname(os.path.abspath(__file__))
def get_version():
filename = os.path.join(HERE, 'transfluent.py')
contents = open(filename).read()
pattern = r"^__version__ = '(.*?)'$"
return re.search(pattern, contents, re.MULTILINE).group(1)
setup(
name='transfluent',
version=get_version(),
description='A Python wrapper for Transfluent API',
long_description=(
open('README.rst').read() + '\n' +
open('CHANGES.rst').read()
),
author='Janne Vanhala',
author_email='janne.vanhala@gmail.com',
url='http://github.com/jpvanhal/python-transfluent',
py_modules=['transfluent'],
license=open('LICENSE').read(),
platforms='any',
install_requires=[
'requests>=1.0',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| import os
import re
from setuptools import setup
HERE = os.path.dirname(os.path.abspath(__file__))
def get_version():
filename = os.path.join(HERE, 'transfluent.py')
contents = open(filename).read()
pattern = r"^__version__ = '(.*?)'$"
return re.search(pattern, contents, re.MULTILINE).group(1)
setup(
name='transfluent',
version=get_version(),
description='A Python wrapper for Transfluent API',
long_description=(
open('README.rst').read() + '\n' +
open('CHANGES.rst').read()
),
author='Janne Vanhala',
author_email='janne.vanhala@gmail.com',
url='http://github.com/jpvanhal/python-transfluent',
py_modules=['transfluent'],
license=open('LICENSE').read(),
platforms='any',
install_requires=[
'requests>=1.0',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Add boto as requirement for funsize deployment. | from setuptools import setup
PACKAGE_NAME = 'funsize'
PACKAGE_VERSION = '0.1'
setup(name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description='partial mar webservice prototype',
long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura',
classifiers=[],
author='Anhad Jai Singh',
author_email='ffledgling@gmail.com',
url='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura',
license='MPL',
install_requires=[
'Flask==0.10.1',
'celery==3.1.11',
'nose==1.3.3',
'requests==2.2.1',
'boto==2.33.0',
],
packages=[
'funsize',
'funsize.backend',
'funsize.cache',
'funsize.frontend',
'funsize.utils',
],
tests_require=[
'nose',
'mock'
],
)
| from setuptools import setup
PACKAGE_NAME = 'funsize'
PACKAGE_VERSION = '0.1'
setup(name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description='partial mar webservice prototype',
long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura',
classifiers=[],
author='Anhad Jai Singh',
author_email='ffledgling@gmail.com',
url='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura',
license='MPL',
install_requires=[
'Flask==0.10.1',
'celery==3.1.11',
'nose==1.3.3',
'requests==2.2.1',
],
packages=[
'funsize',
'funsize.backend',
'funsize.cache',
'funsize.frontend',
'funsize.utils',
],
tests_require=[
'nose',
'mock'
],
)
|
Facebook: Fix toggle buttons not changing the focus highlight | $(document).ready(function() {
$('#toggle-livros').click(function(){
activate('livros');
deactivate('bio');
return false;
});
$('#toggle-bio').click(function(){
deactivate('livros');
activate('bio');
return false;
});
});
function activate(section) {
$('#' + section).show();
buttonOn('#toggle-' + section);
}
function deactivate(section) {
$('#' + section).hide();
buttonOff('#toggle-' + section);
}
function buttonOn(id) {
image = $(id + ' img:first-child');
image.attr("src", image.attr("src").replace("_off", "_on"));
}
function buttonOff(id) {
image = $(id + ' img:first-child');
image.attr("src", image.attr("src").replace("_on", "_off"));
}
| $(document).ready(function() {
$('#toggle-livros').click(function(){
activate('livros');
deactivate('bio');
return false;
});
$('#toggle-bio').click(function(){
deactivate('livros');
activate('bio');
return false;
});
});
function activate(section) {
$('#' + section).show();
buttonOn('#toggle-' + section);
}
function deactivate(section) {
$('#' + section).hide();
buttonOff('#toggle-' + section);
}
function buttonOn(id) {
$(id + ' img:first-child').attr("src").replace("_off", "_on");
}
function buttonOff(id) {
$(id + ' img:first-child').attr("src").replace("_on", "_off");
}
|
Add Python 3.6 to list trove classifiers | from setuptools import setup
from sky_area import __version__ as version
setup(
name='skyarea',
packages=['sky_area'],
scripts=['bin/run_sky_area'],
version=version,
description='Compute credible regions on the sky from RA-DEC MCMC samples',
author='Will M. Farr',
author_email='will.farr@ligo.org',
url='http://farr.github.io/skyarea/',
license='MIT',
keywords='MCMC credible regions skymap LIGO',
install_requires=['astropy', 'numpy', 'scipy', 'healpy', 'six'],
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Astronomy',
'Topic :: Scientific/Engineering :: Visualization']
)
| from setuptools import setup
from sky_area import __version__ as version
setup(
name='skyarea',
packages=['sky_area'],
scripts=['bin/run_sky_area'],
version=version,
description='Compute credible regions on the sky from RA-DEC MCMC samples',
author='Will M. Farr',
author_email='will.farr@ligo.org',
url='http://farr.github.io/skyarea/',
license='MIT',
keywords='MCMC credible regions skymap LIGO',
install_requires=['astropy', 'numpy', 'scipy', 'healpy', 'six'],
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Astronomy',
'Topic :: Scientific/Engineering :: Visualization']
)
|
Reduce the amount of console "spam", by ignoring `info`/`warn` calls, when running the unit-tests in Node.js/Travis
Compared to running the unit-tests in "regular" browsers, where any console output won't get mixed up with test output, in Node.js/Travis the test output looks quite noisy.
By ignoring `info`/`warn` calls, when running unit-tests in Node.js/Travis, the test output is a lot smaller not to mention that any *actual* failures are more easily spotted. | /* Copyright 2018 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { setVerbosityLevel, VerbosityLevel } from '../../src/shared/util';
import isNodeJS from '../../src/shared/is_node';
import { PDFNodeStream } from '../../src/display/node_stream';
import { setPDFNetworkStreamFactory } from '../../src/display/api';
// Ensure that this script only runs in Node.js environments.
if (!isNodeJS()) {
throw new Error('The `gulp unittestcli` command can only be used in ' +
'Node.js environments.');
}
// Reduce the amount of console "spam", by ignoring `info`/`warn` calls,
// when running the unit-tests in Node.js/Travis.
setVerbosityLevel(VerbosityLevel.ERRORS);
// Set the network stream factory for the unit-tests.
setPDFNetworkStreamFactory(function(params) {
return new PDFNodeStream(params);
});
| /* Copyright 2018 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import isNodeJS from '../../src/shared/is_node';
import { PDFNodeStream } from '../../src/display/node_stream';
import { setPDFNetworkStreamFactory } from '../../src/display/api';
// Ensure that this script only runs in Node.js environments.
if (!isNodeJS()) {
throw new Error('The `gulp unittestcli` command can only be used in ' +
'Node.js environments.');
}
// Set the network stream factory for the unit-tests.
setPDFNetworkStreamFactory(function(params) {
return new PDFNodeStream(params);
});
|
Drop Android 2.3 from autoprefixer option | // Parse CSS and add vendor prefixes
//
// grunt-postcss: <https://github.com/nDmitry/grunt-postcss>
// Autoprefixer: <https://github.com/postcss/autoprefixer>
'use strict';
var autoprefixer = require('autoprefixer');
module.exports = {
options: {<% if (cfg.cssSourceMap) { %>
map: {
inline: false
},<% } %>
processors: [
autoprefixer({
// Targeting notation: <https://github.com/ai/browserslist#queries>
browsers: [
'last 2 versions',
'Explorer >= 8',
'Firefox ESR',
'Android >= 4',
'iOS >= 7'
]
})
]
},
compile: {
files: [{
expand: true<% if (cfg.css) { %>,
cwd: '<%%= path.styles %>'<% } else { %>,
cwd: '<%%= path.css %>'<% } %>,
dest: '<%%= path.css %>',
src: '**/*.css'
}]
}
};
| // Parse CSS and add vendor prefixes
//
// grunt-postcss: <https://github.com/nDmitry/grunt-postcss>
// Autoprefixer: <https://github.com/postcss/autoprefixer>
'use strict';
var autoprefixer = require('autoprefixer');
module.exports = {
options: {<% if (cfg.cssSourceMap) { %>
map: {
inline: false
},<% } %>
processors: [
autoprefixer({
// Targeting notation: <https://github.com/ai/browserslist#queries>
browsers: [
'last 2 versions',
'Explorer >= 8',
'Firefox ESR',
'Android >= 2.3',
'iOS >= 7'
]
})
]
},
compile: {
files: [{
expand: true<% if (cfg.css) { %>,
cwd: '<%%= path.styles %>'<% } else { %>,
cwd: '<%%= path.css %>'<% } %>,
dest: '<%%= path.css %>',
src: '**/*.css'
}]
}
};
|
Add variable answer numbers to add answer option jquery | $(document).ready(function() {
var answer_number = 2;
// add a question to Make Survey form when user clicks on "add question"
$('#add-answer-option-field').on('click', function(event) {
var answerOptionNode = "<p><label>Answer Option " + answer_number + ": </label> <input type='text' name='answer-option-" + answer_number + "'></p>";
$('.answer-option-container').append(answerOptionNode);
answer_number++;
});
var menuToggle = $('#js-mobile-menu').unbind();
$('#js-navigation-menu').removeClass("show");
menuToggle.on('click', function(e) {
e.preventDefault();
$('#js-navigation-menu').slideToggle(function(){
if($('#js-navigation-menu').is(':hidden')) {
$('#js-navigation-menu').removeAttr('style');
}
});
});
});
| $(document).ready(function() {
var answer_number = 1;
// add a question to Make Survey form when user clicks on "add question"
$('#add-answer-option-field').on('click', function(event) {
var answerOptionNode = "<p><label>Answer Option: </label> <input type='text' name='answer-option-" + answer_number + "'></p>";
$('.answer-option-container').append(answerOptionNode);
answer_number++;
});
var menuToggle = $('#js-mobile-menu').unbind();
$('#js-navigation-menu').removeClass("show");
menuToggle.on('click', function(e) {
e.preventDefault();
$('#js-navigation-menu').slideToggle(function(){
if($('#js-navigation-menu').is(':hidden')) {
$('#js-navigation-menu').removeAttr('style');
}
});
});
});
|
Add source link to EIN validation regex | <?php
namespace Faker\Test\Provider\en_US;
use Faker\Provider\en_US\Company;
use Faker\Generator;
class CompanyTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Generator
*/
private $faker;
public function setUp()
{
$faker = new Generator();
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
/**
* @link https://stackoverflow.com/questions/4242433/regex-for-ein-number-and-ssn-number-format-in-jquery/35471665#35471665
*/
public function testEin()
{
$number = $this->faker->ein;
// should be in the format ##-#######, with a valid prefix
$this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number);
}
}
| <?php
namespace Faker\Test\Provider\en_US;
use Faker\Provider\en_US\Company;
use Faker\Generator;
class CompanyTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Generator
*/
private $faker;
public function setUp()
{
$faker = new Generator();
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testEin()
{
$number = $this->faker->ein;
// should be in the format ##-#######, with a valid prefix
$this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number);
}
}
|
Add Python 3.8 to supported versions | #!/usr/bin/env python3
import os.path
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="eventstreamd",
version="0.6.1",
description="Simple Event Stream Server",
long_description=read("README.md"),
long_description_content_type="text/markdown",
author="Sebastian Rittau",
author_email="srittau@rittau.biz",
url="https://github.com/srittau/eventstreamd",
packages=find_packages(),
scripts=[os.path.join("bin", "eventstreamd")],
tests_require=["asserts >= 0.6"],
license="MIT",
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Internet :: WWW/HTTP",
],
)
| #!/usr/bin/env python3
import os.path
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="eventstreamd",
version="0.6.1",
description="Simple Event Stream Server",
long_description=read("README.md"),
long_description_content_type="text/markdown",
author="Sebastian Rittau",
author_email="srittau@rittau.biz",
url="https://github.com/srittau/eventstreamd",
packages=find_packages(),
scripts=[os.path.join("bin", "eventstreamd")],
tests_require=["asserts >= 0.6"],
license="MIT",
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Topic :: Internet :: WWW/HTTP",
],
)
|
Enable some new React rules
The newer version of the React plugin gives us some nice new rules that
we want to enable. | module.exports = {
'extends': './index.js',
'plugins': [
'react'
],
'ecmaFeatures': {
'jsx': true
},
'rules': {
'react/display-name': 0,
'react/forbid-prop-types': 0,
'react/jsx-boolean-value': [2, 'never'],
'react/jsx-curly-spacing': [2, 'never'],
'react/jsx-indent-props': [2, 2],
'react/jsx-max-props-per-line': 0,
'react/jsx-no-duplicate-props': [2, { ignoreCase: true }],
'react/jsx-no-literals': 0,
'react/jsx-no-undef': 2,
'react/jsx-uses-react': 1,
'react/jsx-uses-vars': 1,
'react/no-did-mount-set-state': [1, 'allow-in-func'],
'react/no-did-update-set-state': 1,
'react/no-multi-comp': 1,
'react/no-unknown-property': 2,
'react/prop-types': 2,
'react/react-in-jsx-scope': 1,
'react/self-closing-comp': 2,
'react/sort-comp': 2,
'react/wrap-multilines': 2,
}
};
| module.exports = {
'extends': './index.js',
'plugins': [
'react'
],
'ecmaFeatures': {
'jsx': true
},
'rules': {
'react/display-name': 0,
'react/jsx-boolean-value': 2,
'react/jsx-no-undef': 2,
'react/jsx-uses-react': 1,
'react/jsx-uses-vars': 1,
'react/no-did-mount-set-state': [1, 'allow-in-func'],
'react/no-did-update-set-state': 1,
'react/no-multi-comp': 1,
'react/no-unknown-property': 2,
'react/prop-types': 2,
'react/react-in-jsx-scope': 1,
'react/self-closing-comp': 2,
'react/sort-comp': 2,
'react/wrap-multilines': 2,
}
};
|
Remove reference to images in Config file | var srcFolder = './src';
var distFolder = './dist';
var docsFolder = './docs';
var docsSrc = docsFolder + '/src';
var docsDist = docsFolder + '/dist';
var dirs = {
srcJS: srcFolder,
docs: {
src: docsSrc,
dist: docsDist,
srcJS: docsSrc,
distJS: docsDist,
srcCSS: docsFolder + '/**',
distCSS: docsDist + '/'
}
};
var files = {
docs: {
srcJS: [
dirs.docs.srcJS + '/List/index.js'
],
distJS: dirs.docs.distJS + '/index.js',
srcCSS: dirs.docs.srcCSS + '/*.less',
distCSS: dirs.docs.distCSS + '/index.css',
srcHTML: dirs.docs.src + '/index.html',
distHTML: dirs.docs.dist + '/index.html'
}
};
module.exports = {
dirs: dirs,
files: files
};
| var srcFolder = './src';
var distFolder = './dist';
var docsFolder = './docs';
var docsSrc = docsFolder + '/src';
var docsDist = docsFolder + '/dist';
var dirs = {
srcJS: srcFolder,
docs: {
src: docsSrc,
dist: docsDist,
srcJS: docsSrc,
distJS: docsDist,
srcCSS: docsFolder + '/**',
distCSS: docsDist + '/',
srcImg: srcFolder + '/img',
distImg: distFolder + '/img'
}
};
var files = {
docs: {
srcJS: [
dirs.docs.srcJS + '/List/index.js'
],
distJS: dirs.docs.distJS + '/index.js',
srcCSS: dirs.docs.srcCSS + '/*.less',
distCSS: dirs.docs.distCSS + '/index.css',
srcHTML: dirs.docs.src + '/index.html',
distHTML: dirs.docs.dist + '/index.html'
}
};
module.exports = {
dirs: dirs,
files: files
};
|
Add image crop on templatetags image_obj | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
new['flip'] = image.flip
new['flop'] = image.flop
if image.halign != "":
new['halign'] = image.halign
if image.valign != "":
new['valign'] = image.valign
new['fit_in'] = image.fit_in
new['smart'] = image.smart
if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \
image.crop_y2 > 0:
new['crop'] = ((image.crop_x1,image.crop_y1),
(image.crop_x2,image.crop_y2))
kwargs = dict(new, **kwargs)
return url(image_url=image.image.url, **kwargs)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
new['flip'] = image.flip
new['flop'] = image.flop
if image.halign != "":
new['halign'] = image.halign
if image.valign != "":
new['valign'] = image.valign
new['fit_in'] = image.fit_in
new['smart'] = image.smart
kwargs = dict(new, **kwargs)
return url(image_url=image.image.url, **kwargs)
|
Set the URL to include the modified query. Part of STRIPES-85.
At present we express URLs in the form:
http://localhost:3000/users/water
with the query in the path rather than in the URL query, as:
http://localhost:3000/users?q=water
That's just because at present Stripes Connect can't get at the URL
query, and we want to show searching working from top to bottom. Once
Stripes Connect is up to speed (probably towards the end of next week)
we will change the URLs used for searching.
Because that change is coming, I am not worrying too much in the
short term about this wrinkle: we currently set the whole of the path
to "/users/"+value, so it only works when the Users module is mounted
on /users. But since that's always, I am not losing sleep. | import React, { PropTypes } from 'react';
import css from './FilterPaneSearch.css';
import Icon from '@folio/stripes-components/lib/Icon';
import Button from '@folio/stripes-components/lib/Button';
class FilterPaneSearch extends React.Component{
static contextTypes = {
router: PropTypes.object.isRequired
};
constructor(props){
super(props);
this.searchInput = null;
}
clearSearchField(){
this.searchInput.value = '';
const evt = new Event('input', {bubbles: true});
this.searchInput.dispatchEvent(evt);
}
onChange() {
const value = this.searchInput.value;
this.context.router.transitionTo("/users/" + value);
}
render(){
return(
<div className={css.headerSearchContainer}>
<div style={{alignSelf:"center"}}><Icon icon="search"/></div>
<input className={css.headerSearchInput} ref={(ref) => this.searchInput = ref} type="text" value = {this.props.value} onChange={this.onChange.bind(this)} placeholder="Search"/>
<Button className={css.headerSearchClearButton} onClick={this.clearSearchField.bind(this)} ><Icon icon="clearX" iconClassName={css.clearIcon}/></Button>
</div>
);
}
}
export default FilterPaneSearch;
| import React from 'react';
import css from './FilterPaneSearch.css';
import Icon from '@folio/stripes-components/lib/Icon';
import Button from '@folio/stripes-components/lib/Button';
class FilterPaneSearch extends React.Component{
constructor(props){
super(props);
this.searchInput = null;
}
clearSearchField(){
this.searchInput.value = '';
const evt = new Event('input', {bubbles: true});
this.searchInput.dispatchEvent(evt);
}
onChange() {
console.log("changed: new value =", this.searchInput.value);
// XXX We need to somehow feed the changed value into stripes-connect for the parent component
}
render(){
return(
<div className={css.headerSearchContainer}>
<div style={{alignSelf:"center"}}><Icon icon="search"/></div>
<input className={css.headerSearchInput} ref={(ref) => this.searchInput = ref} type="text" value = {this.props.value} onChange={this.onChange.bind(this)} placeholder="Search"/>
<Button className={css.headerSearchClearButton} onClick={this.clearSearchField.bind(this)} ><Icon icon="clearX" iconClassName={css.clearIcon}/></Button>
</div>
);
}
}
export default FilterPaneSearch;
|
Set loginRequired to false. For users without login, this is required for "back" link on some pages to function.
SVN-Revision: 3990 | /*
The caLAB Software License, Version 0.5
Copyright 2006 SAIC. This software was developed in conjunction with the National
Cancer Institute, and so to the extent government employees are co-authors, any
rights in such works shall be subject to Title 17 of the United States Code,
section 105.
*/
package gov.nih.nci.calab.ui.core;
/**
* This class calls the Struts ForwardAction to forward to a page, aslo
* extends AbstractBaseAction to inherit the user authentication features.
*
* @author pansu
*/
/* CVS $Id: BaseForwardAction.java,v 1.4 2007-10-25 20:56:51 cais Exp $ */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.ForwardAction;
public class BaseForwardAction extends AbstractBaseAction {
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ForwardAction forwardAction = new ForwardAction();
return forwardAction.execute(mapping, form, request, response);
}
public boolean loginRequired() {
//return true;
return false;
}
public boolean canUserExecute(HttpSession session) {
return true;
}
}
| /*
The caLAB Software License, Version 0.5
Copyright 2006 SAIC. This software was developed in conjunction with the National
Cancer Institute, and so to the extent government employees are co-authors, any
rights in such works shall be subject to Title 17 of the United States Code,
section 105.
*/
package gov.nih.nci.calab.ui.core;
/**
* This class calls the Struts ForwardAction to forward to a page, aslo
* extends AbstractBaseAction to inherit the user authentication features.
*
* @author pansu
*/
/* CVS $Id: BaseForwardAction.java,v 1.3 2006-08-02 21:27:59 pansu Exp $ */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.ForwardAction;
public class BaseForwardAction extends AbstractBaseAction {
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ForwardAction forwardAction = new ForwardAction();
return forwardAction.execute(mapping, form, request, response);
}
public boolean loginRequired() {
return true;
}
public boolean canUserExecute(HttpSession session) {
return true;
}
}
|
Use platform EOL for newlines
- Fixes test for Windows | "use babel";
// const { dialog } = require("electron").remote;
const { existsSync } = require("fs");
const { EOL } = require("os");
import { _loadNotebook } from "../lib/import-notebook";
import { waitAsync } from "./helpers/test-utils";
describe("Import notebook", () => {
const sampleNotebook = require.resolve("./helpers/test-notebook.ipynb");
beforeEach(
waitAsync(async () => {
await atom.packages.activatePackage("language-python");
await _loadNotebook(sampleNotebook);
})
);
it("Should import a notebook and convert it to a script", () => {
const editor = atom.workspace.getActiveTextEditor();
const code = editor.getText();
expect(code.split(EOL)).toEqual([
"# %%",
"import pandas as pd",
"# %%",
"pd.util.testing.makeDataFrame()",
"# %%",
""
]);
});
});
| "use babel";
// const { dialog } = require("electron").remote;
const { existsSync } = require("fs");
import { _loadNotebook } from "../lib/import-notebook";
import { waitAsync } from "./helpers/test-utils";
describe("Import notebook", () => {
const sampleNotebook = require.resolve("./helpers/test-notebook.ipynb");
beforeEach(
waitAsync(async () => {
await atom.packages.activatePackage("language-python");
await _loadNotebook(sampleNotebook);
})
);
it("Should import a notebook and convert it to a script", () => {
const editor = atom.workspace.getActiveTextEditor();
const code = editor.getText();
expect(code.split("\n")).toEqual([
"# %%",
"import pandas as pd",
"# %%",
"pd.util.testing.makeDataFrame()",
"# %%",
""
]);
});
});
|
Add tag on image lib | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
| # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
|
Add ProjectExists to ProjectDBOpener interface. | package mc
type ProjectDB interface {
Project() *Project
UpdateProject(project *Project) error
InsertDirectory(dir *Directory) (*Directory, error)
UpdateDirectory(dir *Directory) error
Directories() []Directory
Ls(dir Directory) []File
InsertFile(f *File) (*File, error)
FindFile(fileName string, dirID int64) (*File, error)
UpdateFile(f *File) error
FindDirectory(path string) (*Directory, error)
Clone() ProjectDB
}
type ProjectDBSpec struct {
Name string
ProjectID string
Path string
}
type ProjectOpenFlags int
type ProjectDBOpener interface {
CreateProjectDB(dbSpec ProjectDBSpec) (ProjectDB, error)
OpenProjectDB(name string) (ProjectDB, error)
ProjectExists(name string) bool
PathToName(path string) string
}
type ProjectDBLister interface {
// All returns a list of the known ProjectDBs. The ProjectDBs
// are open.
All() ([]ProjectDB, error)
// Create will create a new local project and populate
// the default database entries. The returned ProjectDB
// has already been opened.
Create(dbSpec ProjectDBSpec) (ProjectDB, error)
}
type Configer interface {
APIKey() string
ConfigDir() string
ConfigFile() string
}
| package mc
type ProjectDB interface {
Project() *Project
UpdateProject(project *Project) error
InsertDirectory(dir *Directory) (*Directory, error)
UpdateDirectory(dir *Directory) error
Directories() []Directory
Ls(dir Directory) []File
InsertFile(f *File) (*File, error)
FindFile(fileName string, dirID int64) (*File, error)
UpdateFile(f *File) error
FindDirectory(path string) (*Directory, error)
Clone() ProjectDB
}
type ProjectDBSpec struct {
Name string
ProjectID string
Path string
}
type ProjectOpenFlags int
type ProjectDBOpener interface {
CreateProjectDB(dbSpec ProjectDBSpec) (ProjectDB, error)
OpenProjectDB(name string) (ProjectDB, error)
PathToName(path string) string
}
type ProjectDBLister interface {
// All returns a list of the known ProjectDBs. The ProjectDBs
// are open.
All() ([]ProjectDB, error)
// Create will create a new local project and populate
// the default database entries. The returned ProjectDB
// has already been opened.
Create(dbSpec ProjectDBSpec) (ProjectDB, error)
}
type Configer interface {
APIKey() string
ConfigDir() string
ConfigFile() string
}
|
Fix related box on tablet view
checkOverflow now checks for position:fixed rather than window width. | $(function(){
function checkOverflow(){
var $related = $(".related-positioning");
if($related.length !== 0 && $related.css('position') == 'fixed') {
var viewPort = $(window).height();
var relatedBox = $(".related").height();
var boxOffset = $related.position().top;
if(relatedBox > (viewPort - boxOffset)){
$related.css("position", "absolute");
return true;
} else {
$related.css("position", "fixed");
return false;
}
}
return false;
}
if(!checkOverflow()){
window.GOVUK.stopScrollingAtFooter.addEl($('.related-positioning'), $('#related .inner').height());
}
});
| $(function(){
function checkOverflow(){
if($(window).width() >= "768"){
if($(".related-positioning").length !== 0){
var viewPort = $(window).height();
var relatedBox = $(".related").height();
var boxOffset = $(".related-positioning").position().top;
if(relatedBox > (viewPort - boxOffset)){
$(".related-positioning").css("position", "absolute");
return true;
} else {
$(".related-positioning").css("position", "fixed");
return false;
}
}
}
return false;
}
if(!checkOverflow()){
window.GOVUK.stopScrollingAtFooter.addEl($('.related-positioning'), $('#related .inner').height());
}
});
|
Exclude AppCache js test on Firefox | ({
/**
* Verify the correct AppCache events are received and are in the right order, without an error event. This case
* covers when we have not seen the page before and must download resources.
*/
testAppCacheEvents: {
// AppCache not supported on IE < 10. Firefox displays a popup asking permission to use AppCache.
browsers:["-FIREFOX","-IE7","-IE8","-IE9"],
test: function(component){
var appCacheEvents = $A.test.getAppCacheEvents();
var lastEvent = appCacheEvents.length - 1;
// Error event is always the last event in the sequence
$A.test.assertNotEquals("error", appCacheEvents[lastEvent], "AppCache returned with an error.");
// Verify we received the events in the right order
$A.test.assertEquals("checking", appCacheEvents[0], "AppCache should begin with checking event.");
$A.test.assertEquals("downloading", appCacheEvents[1], "AppCache did not start downloading resources.");
// A progress event is fired for each file that is successfully downloaded. Only check that at least one
// file has been downloaded then check that AppCache completed.
$A.test.assertEquals("progress", appCacheEvents[2], "No files successfully downloaded.");
$A.test.assertEquals("cached", appCacheEvents[lastEvent], "Cached event to signal all files downloaded never fired");
}
}
})
| ({
/**
* Verify the correct AppCache events are received and are in the right order, without an error event. This case
* covers when we have not seen the page before and must download resources.
*/
testAppCacheEvents: {
// AppCache not supported on IE < 10
browsers:["-IE7","-IE8","-IE9"],
test: function(component){
var appCacheEvents = $A.test.getAppCacheEvents();
var lastEvent = appCacheEvents.length - 1;
// Error event is always the last event in the sequence
$A.test.assertNotEquals("error", appCacheEvents[lastEvent], "AppCache returned with an error.");
// Verify we received the events in the right order
$A.test.assertEquals("checking", appCacheEvents[0], "AppCache should begin with checking event.");
$A.test.assertEquals("downloading", appCacheEvents[1], "AppCache did not start downloading resources.");
// A progress event is fired for each file that is successfully downloaded. Only check that at least one
// file has been downloaded then check that AppCache completed.
$A.test.assertEquals("progress", appCacheEvents[2], "No files successfully downloaded.");
$A.test.assertEquals("cached", appCacheEvents[lastEvent], "Cached event to signal all files downloaded never fired");
}
}
})
|
Declare field as a List | /*
* 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 io.prestosql.parquet;
import com.google.common.collect.ImmutableList;
import io.prestosql.spi.type.Type;
import java.util.List;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
public class GroupField
extends Field
{
private final List<Optional<Field>> children;
public GroupField(Type type, int repetitionLevel, int definitionLevel, boolean required, List<Optional<Field>> children)
{
super(type, repetitionLevel, definitionLevel, required);
this.children = ImmutableList.copyOf(requireNonNull(children, "children is null"));
}
public List<Optional<Field>> getChildren()
{
return children;
}
}
| /*
* 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 io.prestosql.parquet;
import com.google.common.collect.ImmutableList;
import io.prestosql.spi.type.Type;
import java.util.List;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
public class GroupField
extends Field
{
private final ImmutableList<Optional<Field>> children;
public GroupField(Type type, int repetitionLevel, int definitionLevel, boolean required, ImmutableList<Optional<Field>> children)
{
super(type, repetitionLevel, definitionLevel, required);
this.children = requireNonNull(children, "children is required");
}
public List<Optional<Field>> getChildren()
{
return children;
}
}
|
Change hardcoded ip to localhost
This patch just changes the hardcoded ip to local host. We should really
make this configurable through congress.conf but this will probably be
fine for now.
Change-Id: If4980beb73e32e458d9b7dfafecb016f9c2f740c | #!/usr/bin/env python
# Copyright (c) 2014 VMware, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
OS_USERNAME = "demo"
OS_PASSWORD = "password"
# Change this to keystone URL specific to your installation
OS_AUTH_URL = "http://127.0.0.1:5000/v2.0"
# 35357
OS_TENANT_NAME = "demo"
| #!/usr/bin/env python
# Copyright (c) 2014 VMware, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
OS_USERNAME = "demo"
OS_PASSWORD = "password"
# Change this to keystone URL specific to your installation
OS_AUTH_URL = "http://10.37.2.84:5000/v2.0"
# 35357
OS_TENANT_NAME = "demo"
|
Allow pandas 1.1 as dependency | #! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7dev',
author='oemof developer group',
url='https://oemof.org/',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
long_description=read('README.rst'),
packages=find_packages(),
install_requires=['numpy >= 1.7.0, < 1.17',
'pandas >= 0.18.0, < 1.2'],
package_data={
'demandlib': [os.path.join('bdew_data', '*.csv')],
'demandlib.examples': ['*.csv']},
)
| #! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7dev',
author='oemof developer group',
url='https://oemof.org/',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
long_description=read('README.rst'),
packages=find_packages(),
install_requires=['numpy >= 1.7.0, < 1.17',
'pandas >= 0.18.0, < 0.25'],
package_data={
'demandlib': [os.path.join('bdew_data', '*.csv')],
'demandlib.examples': ['*.csv']},
)
|
Fix repo select on create | jQuery(function() {
var updateNameAndDescription = function() {
var urlField = $("#extension-url-short-field");
var repos = urlField.data("repos");
var current = urlField.val();
var repo = null;
for (var i = 0; i < repos.length; i++) {
if (repos[i].full_name == current) {
repo = repos[i];
break;
}
}
if (repo) {
$("#extension-url-field").val(repo.full_name);
$("#extension-name-field").val(repo.name);
$("#extension-desc-field").val(repo.description);
}
}
$("#extension-url-short-field").change(function(ev) {
updateNameAndDescription();
});
if ($("#extension-url-short-field").size > 0) {
updateNameAndDescription();
}
});
| jQuery(function() {
var updateNameAndDescription = function() {
var urlField = $("#extension-url-short-field");
var repos = urlField.data("repos");
var current = urlField.val();
var repo = null;
for (var i = 0; i < repos.length; i++) {
if (repos[i].full_name == current) {
repo = repos[i];
break;
}
}
if (repo) {
$("#extension-url-field").val(repo.full_name);
$("#extension-name-field").val(repo.name);
$("#extension-desc-field").val(repo.description);
}
}
$("#extension-url-short-field").change(function(ev) {
updateNameAndDescription();
});
updateNameAndDescription();
});
|
Add 'sure' to package reqs
Change-Id: Ie08d1a8b23e4fc8f4f18d53403fff8145022af32 | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
'sure',
]
test_requirements = [
]
setup(
name='adb_android',
version='1.0.0',
description="Enable android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='1.0.0',
description="Enable android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
|
Revert "turn off class caching"
This reverts commit 9bc61608d5739642bbea5afa9f66ea2f2c835b82. | <?php
// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// this check prevents access to debug front controllers that are deployed by accident to production servers.
// feel free to remove this, extend it, or make something more sophisticated.
if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
'127.0.0.1',
'::1',
))) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
use Symfony\Component\HttpFoundation\Request;
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$kernel->handle(Request::createFromGlobals())->send();
| <?php
// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// this check prevents access to debug front controllers that are deployed by accident to production servers.
// feel free to remove this, extend it, or make something more sophisticated.
if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
'127.0.0.1',
'::1',
))) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
const CLASS_CACHING = true;
if (false == CLASS_CACHING) {
require_once __DIR__.'/../app/bootstrap.php.cache';
$kernel->loadClassCache();
} else {
require_once __DIR__.'/../vendor/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
require_once __DIR__.'/../app/autoload.php';
}
use Symfony\Component\HttpFoundation\Request;
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->handle(Request::createFromGlobals())->send();
|
Add scroll to top on router update | import React, { Component } from 'react'
import { Router } from 'react-router-dom'
const LOCATION_CHANGE = '@@router/LOCATION_CHANGE'
class ConnectedRouter extends Component {
constructor (props) {
super(props)
this.handleLocationChange = this.handleLocationChange.bind(this)
}
componentWillMount () {
const { history } = this.props
this.unsubscribe = history.listen(this.handleLocationChange)
this.handleLocationChange(history.location)
}
componentWillUnmount () {
this.unsubscribe()
}
handleLocationChange (location) {
this.props.store.dispatch({
type: LOCATION_CHANGE,
payload: location
})
}
render () {
return <Router
onUpdate={() => window.scrollTo(0, 0)}
{...this.props}
/>
}
}
export default ConnectedRouter
| import React, { Component } from 'react'
import { Router } from 'react-router-dom'
const LOCATION_CHANGE = '@@router/LOCATION_CHANGE'
class ConnectedRouter extends Component {
constructor (props) {
super(props)
this.handleLocationChange = this.handleLocationChange.bind(this)
}
componentWillMount () {
const { history } = this.props
this.unsubscribe = history.listen(this.handleLocationChange)
this.handleLocationChange(history.location)
}
componentWillUnmount () {
this.unsubscribe()
}
handleLocationChange (location) {
this.props.store.dispatch({
type: LOCATION_CHANGE,
payload: location
})
}
render () {
return <Router {...this.props} />
}
}
export default ConnectedRouter
|
Fix tooltip in copy example | const LinkWithTooltip = React.createClass({
render() {
let tooltip = <Tooltip>{this.props.tooltip}</Tooltip>;
return (
<OverlayTrigger
overlay={tooltip} placement="top"
delayShow={300} delayHide={150}
>
<a href={this.props.href}>{this.props.children}</a>
</OverlayTrigger>
);
}
});
const copyInstance = (
<p className="muted" style={{ marginBottom: 0 }}>
Tight pants next level keffiyeh <LinkWithTooltip tooltip="Default tooltip" href="#">you probably</LinkWithTooltip> haven't
heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's
fixie sustainable quinoa 8-bit american apparel <LinkWithTooltip tooltip={<span>Another <strong>tooltip</strong></span>} href="#">have a</LinkWithTooltip>
terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four
loko mcsweeney's cleanse vegan chambray. A really ironic artisan <LinkWithTooltip tooltip="Another one here too" href="#">whatever keytar</LinkWithTooltip>,
scenester farm-to-table banksy Austin <LinkWithTooltip tooltip="The last tip!" href="#">twitter handle</LinkWithTooltip> freegan
cred raw denim single-origin coffee viral.
</p>
);
ReactDOM.render(copyInstance, mountNode);
| const LinkWithTooltip = React.createClass({
render() {
let tooltip = <Tooltip placement="top">{this.props.tooltip}</Tooltip>;
return (
<OverlayTrigger overlay={tooltip} delayShow={300} delayHide={150}>
<a href={this.props.href}>{this.props.children}</a>
</OverlayTrigger>
);
}
});
const copyInstance = (
<p className="muted" style={{ marginBottom: 0 }}>
Tight pants next level keffiyeh <LinkWithTooltip tooltip="Default tooltip" href="#">you probably</LinkWithTooltip> haven't
heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's
fixie sustainable quinoa 8-bit american apparel <LinkWithTooltip tooltip={<span>Another <strong>tooltip</strong></span>} href="#">have a</LinkWithTooltip>
terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four
loko mcsweeney's cleanse vegan chambray. A really ironic artisan <LinkWithTooltip tooltip="Another one here too" href="#">whatever keytar</LinkWithTooltip>,
scenester farm-to-table banksy Austin <LinkWithTooltip tooltip="The last tip!" href="#">twitter handle</LinkWithTooltip> freegan
cred raw denim single-origin coffee viral.
</p>
);
ReactDOM.render(copyInstance, mountNode);
|
Set a sane package discription | from setuptools import setup
def listify(filename):
return filter(None, open(filename, 'r').read().strip('\n').split('\n'))
setup(
name="distributex",
version="0.1",
url='http://github.com/calston/distributex',
license='MIT',
description="A network mutex service for distributed environments.",
long_description=open('README.md', 'r').read(),
author='Colin Alston',
author_email='colin.alston@gmail.com',
packages=[
"distributex",
"twisted.plugins",
],
package_data={
'twisted.plugins': ['twisted/plugins/distributex_plugin.py']
},
include_package_data=True,
install_requires=listify('requirements.txt'),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: System :: Clustering',
'Topic :: System :: Distributed Computing',
],
)
| from setuptools import setup
def listify(filename):
return filter(None, open(filename, 'r').read().strip('\n').split('\n'))
setup(
name="distributex",
version="0.1",
url='http://github.com/calston/distributex',
license='MIT',
description="Distributex. A network mutex service for distributed"
"environments.",
long_description=open('README.md', 'r').read(),
author='Colin Alston',
author_email='colin.alston@gmail.com',
packages=[
"distributex",
"twisted.plugins",
],
package_data={
'twisted.plugins': ['twisted/plugins/distributex_plugin.py']
},
include_package_data=True,
install_requires=listify('requirements.txt'),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: System :: Clustering',
'Topic :: System :: Distributed Computing',
],
)
|
Test should handle case where testrpc isn't running |
var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://0.0.0.0:8545'));
//TODO: when TestRPC can handle synchronous requests, use this
//var TestRPC = require("ethereumjs-testrpc");
//web3.setProvider(TestRPC.provider());
var LiveLibs = require('../index.js');
var liveLibs = new LiveLibs(web3, 'testrpc');
var deploy;
try {
deploy = liveLibs.deploy()
} catch(e) {
console.error('Error while setting up deploy: '+e);
console.error('Make sure you have testrpc running!')
process.exit(1);
}
deploy.then(function() {
describe('Retrieving lib info', function() {
it('foo', function() {
var libName = 'foo';
var libInfo = liveLibs.get(libName);
});
});
run(); // this is exposed because we're running mocha --delay
// we are runnning mocha --delay because we have to deploy before we run tests
// we have to deploy because TestRPC can't handle synchronous requests
}).catch(function(err) {
console.error('Problem while deploying to testrpc: ' + err);
});
|
var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://0.0.0.0:8545'));
//TODO: when TestRPC can handle synchronous requests, use this
//var TestRPC = require("ethereumjs-testrpc");
//web3.setProvider(TestRPC.provider());
var LiveLibs = require('../index.js');
var liveLibs = new LiveLibs(web3, 'testrpc');
liveLibs.deploy().then(function() {
describe('Retrieving lib info', function() {
it('foo', function() {
var libName = 'foo';
var libInfo = liveLibs.get(libName);
});
});
run(); // this is exposed because we're running mocha --delay
// we are runnning mocha --delay because we have to deploy before we run tests
// we have to deploy because TestRPC can't handle synchronous requests
}).catch(function(err) {
console.error('Problem while deploying to testrpc: ' + err);
});
|
Fix JDBC 4.0 source compatibility.
Closes #186. | package com.yammer.dropwizard.db;
import org.apache.tomcat.dbcp.dbcp.PoolingDataSource;
import org.apache.tomcat.dbcp.pool.ObjectPool;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
public class ManagedPooledDataSource extends PoolingDataSource implements ManagedDataSource {
private final ObjectPool pool;
public ManagedPooledDataSource(ObjectPool pool) {
super(pool);
this.pool = pool;
}
// JDK6 has JDBC 4.0 which doesn't have this -- don't add @Override
@SuppressWarnings("override")
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException("Doesn't use java.util.logging");
}
@Override
public void start() throws Exception {
// already started
}
@Override
public void stop() throws Exception {
pool.close();
}
}
| package com.yammer.dropwizard.db;
import org.apache.tomcat.dbcp.dbcp.PoolingDataSource;
import org.apache.tomcat.dbcp.pool.ObjectPool;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
public class ManagedPooledDataSource extends PoolingDataSource implements ManagedDataSource {
private final ObjectPool pool;
public ManagedPooledDataSource(ObjectPool pool) {
super(pool);
this.pool = pool;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException("Doesn't use java.util.logging");
}
@Override
public void start() throws Exception {
// already started
}
@Override
public void stop() throws Exception {
pool.close();
}
}
|
Update dimkarakostas population with alignmentalphabet | from string import ascii_lowercase
import django
import os
import string
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9
target_1 = Target(
endpoint=endpoint,
prefix=prefix,
alphabet=alphabet,
secretlength=secretlength,
alignmentalphabet=string.ascii_uppercase
)
target_1.save()
print 'Created Target:\n\tendpoint: {}\n\tprefix: {}\n\talphabet: {}\n\tsecretlength: {}'.format(endpoint, prefix, alphabet, secretlength)
snifferendpoint = 'http://127.0.0.1:9000'
sourceip = '192.168.1.70'
victim_1 = Victim(
target=target_1,
snifferendpoint=snifferendpoint,
sourceip=sourceip,
# method='serial'
)
victim_1.save()
print 'Created Victim:\n\tvictim_id: {}\n\tsnifferendpoint: {}\n\tsourceip: {}'.format(victim_1.id, snifferendpoint, sourceip)
| from string import ascii_lowercase
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9
target_1 = Target(
endpoint=endpoint,
prefix=prefix,
alphabet=alphabet,
secretlength=secretlength
)
target_1.save()
print 'Created Target:\n\tendpoint: {}\n\tprefix: {}\n\talphabet: {}\n\tsecretlength: {}'.format(endpoint, prefix, alphabet, secretlength)
snifferendpoint = 'http://127.0.0.1:9000'
sourceip = '192.168.1.70'
victim_1 = Victim(
target=target_1,
snifferendpoint=snifferendpoint,
sourceip=sourceip,
# method='serial'
)
victim_1.save()
print 'Created Victim:\n\tvictim_id: {}\n\tsnifferendpoint: {}\n\tsourceip: {}'.format(victim_1.id, snifferendpoint, sourceip)
|
Include study view screenshot references
Former-commit-id: e016cb052abecda7dc1c0cd1391edac077634e2a | var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./specUtils').waitForOncoprint;
var goToUrlAndSetLocalStorage = require('./specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./specUtils').waitForNetworkQuiet;
var assertScreenShotMatch = require('../lib/testUtils').assertScreenShotMatch;
const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");
describe('study view screenshot test', function(){
before(function(){
var url = `${CBIOPORTAL_URL}/study?id=laml_tcga`;
goToUrlAndSetLocalStorage(url);
});
it('study view laml_tcga', function() {
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
it('study view laml_tcga clinical data clicked', function() {
browser.click('.tabAnchor_clinicalData');
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
}); | var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./specUtils').waitForOncoprint;
var goToUrlAndSetLocalStorage = require('./specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./specUtils').waitForNetworkQuiet;
var assertScreenShotMatch = require('../lib/testUtils').assertScreenShotMatch;
const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");
describe('new study view screenshot test', function(){
before(function(){
var url = `${CBIOPORTAL_URL}/study?id=laml_tcga`;
goToUrlAndSetLocalStorage(url);
});
it('new study view laml_tcga', function() {
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
it('new study view laml_tcga clinical data clicked', function() {
browser.click('.tabAnchor_clinicalData');
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
}); |
Sort agencies page by name | const _ = require('lodash');
const gtfs = require('gtfs');
const router = require('express').Router();
const config = require('../config');
const utils = require('../lib/utils');
/*
* Show all agencies
*/
router.get('/', (req, res, next) => {
gtfs.agencies((err, agencies) => {
if (err) return next(err);
return res.render('agencies', { agencies: _.sortBy(agencies, 'agency_name') });
});
});
/*
* Show all timetable pages for an agency
*/
router.get('/timetablepages', (req, res, next) => {
const agencyKey = req.query.agency_key;
utils.getTimetablePages(agencyKey, (err, timetablePages) => {
if (err) return next(err);
return res.render('timetablepages', { agencyKey, timetablePages });
});
});
/*
* Show a specific timetable page
*/
router.get('/timetablepage', (req, res, next) => {
const agencyKey = req.query.agency_key;
const timetablePageId = req.query.timetable_page_id;
utils.getTimetablePage(agencyKey, timetablePageId, (err, timetablePage) => {
if (err) return next(err);
utils.generateHTML(agencyKey, timetablePage, config, (err, html) => {
if (err) return next(err);
res.send(html);
});
});
});
module.exports = router;
| const _ = require('lodash');
const gtfs = require('gtfs');
const router = require('express').Router();
const config = require('../config');
const utils = require('../lib/utils');
/*
* Show all agencies
*/
router.get('/', (req, res, next) => {
gtfs.agencies((err, agencies) => {
if (err) return next(err);
return res.render('agencies', { agencies });
});
});
/*
* Show all timetable pages for an agency
*/
router.get('/timetablepages', (req, res, next) => {
const agencyKey = req.query.agency_key;
utils.getTimetablePages(agencyKey, (err, timetablePages) => {
if (err) return next(err);
return res.render('timetablepages', { agencyKey, timetablePages });
});
});
/*
* Show a specific timetable page
*/
router.get('/timetablepage', (req, res, next) => {
const agencyKey = req.query.agency_key;
const timetablePageId = req.query.timetable_page_id;
utils.getTimetablePage(agencyKey, timetablePageId, (err, timetablePage) => {
if (err) return next(err);
utils.generateHTML(agencyKey, timetablePage, config, (err, html) => {
if (err) return next(err);
res.send(html);
});
});
});
module.exports = router;
|
Remove comments and use `JSON.parse` for `~/.jshintrc`. | var jshint = require('jshint').JSHINT
, puts = require('util').puts
, stdin = process.openStdin()
, fs = require('fs')
, jshintrc = process.argv[2] ? fs.readFileSync(process.argv[2], 'utf8') : ''
, body = [];
function allcomments(s) {
return /^\s*\/\/[^\n]\s*$|^\s*\/\*(?:[^\*]+|\*(?!\/))\*\/\s*$/.test(s);
}
function removecomments(s) {
return s.replace(/\/\/[^\n]|\/\*(?:[^\*]+|\*(?!\/))\*\//g, '');
}
stdin.on('data', function(chunk) {
body.push(chunk);
});
stdin.on('end', function() {
var error
, options;
if (allcomments(jshintrc)) {
body.push('\n' + jshintrc);
} else {
// Try standard `.jshintrc` JSON format.
try {
options = JSON.parse(removecomments(jshintrc));
} catch(e) {
puts('1:1:Invalid ~/.jshintrc file');
}
}
if( jshint( body.join(''), options ) ){
return;
}
var data = jshint.data();
for( var i = 0, len = data.errors.length; i < len; i += 1 ){
error = data.errors[i];
if( error && error.reason ){
puts( [error.line, error.character, error.reason].join(':') );
}
}
});
| var jshint = require('jshint').JSHINT
, puts = require('util').puts
, stdin = process.openStdin()
, fs = require('fs')
, jshintrc = process.argv[2] ? fs.readFileSync(process.argv[2]) : ''
, body = [];
function allcomments(s) {
return /^\s*\/\*(?:[^\*]+|\*(?!\/))\*\/\s*$|^\s*\/\/[^\n]\s*$/.test(s);
}
stdin.on('data', function(chunk) {
body.push(chunk);
});
stdin.on('end', function() {
var error
, options;
if (allcomments(jshintrc)) {
body.push('\n' + jshintrc);
} else {
// Try standard `.jshintrc` JSON format. Use `eval` because `.jshintrc`
// files might contain comments.
try {
options = eval('(' + jshintrc + '\n)');
} catch(e) {
puts('1:1:Invalid ~/.jshintrc file');
}
}
if( jshint( body.join(''), options ) ){
return;
}
var data = jshint.data();
for( var i = 0, len = data.errors.length; i < len; i += 1 ){
error = data.errors[i];
if( error && error.reason ){
puts( [error.line, error.character, error.reason].join(':') );
}
}
});
|
Correct comment in docs config | <?php
use allejo\Sami\ApiFilter;
use Sami\RemoteRepository\GitHubRemoteRepository;
use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;
$iterator = Finder::create()
->files()
->name('*.php')
->in($dir = __DIR__ . '/../src')
;
// generate documentation for all 0.* branches and the master branch
$versions = GitVersionCollection::create($dir)
->add('0.3', '0.3 branch')
->add('0.2', '0.2 branch')
->add('master', 'master branch')
;
$sami = new Sami($iterator, array(
'versions' => $versions,
'title' => 'PhpPulse API',
'build_dir' => __DIR__ . '/api/build/phppulse/%version%',
'cache_dir' => __DIR__ . '/api/cache/phppulse/%version%',
'remote_repository' => new GitHubRemoteRepository('allejo/PhpPulse', dirname($dir)),
'default_opened_level' => 2,
));
/*
* Include this section if you want sami to document
* private and protected functions/properties
*/
$sami['filter'] = function () {
return new ApiFilter();
};
return $sami;
| <?php
use allejo\Sami\ApiFilter;
use Sami\RemoteRepository\GitHubRemoteRepository;
use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;
$iterator = Finder::create()
->files()
->name('*.php')
->in($dir = __DIR__ . '/../src')
;
// generate documentation for all v2.0.* tags, the 2.0 branch, and the master one
$versions = GitVersionCollection::create($dir)
->add('0.3', '0.3 branch')
->add('0.2', '0.2 branch')
->add('master', 'master branch')
;
$sami = new Sami($iterator, array(
'versions' => $versions,
'title' => 'PhpPulse API',
'build_dir' => __DIR__ . '/api/build/phppulse/%version%',
'cache_dir' => __DIR__ . '/api/cache/phppulse/%version%',
'remote_repository' => new GitHubRemoteRepository('allejo/PhpPulse', dirname($dir)),
'default_opened_level' => 2,
));
/*
* Include this section if you want sami to document
* private and protected functions/properties
*/
$sami['filter'] = function () {
return new ApiFilter();
};
return $sami; |
Add benchmark test for FactorsList function | package numbers
import (
"errors"
"reflect"
"testing"
)
// TestFactorsList unit test FactorsList function.
func TestFactorsList(t *testing.T) {
testCases := []struct {
input int
expected []int
err error
}{
{2, []int{2}, nil},
{15, []int{3, 5}, nil},
{26, []int{2, 13}, nil},
{37, []int{37}, nil},
{42, []int{2, 3, 7}, nil},
{-1, []int(nil), errors.New("no prime factors for numbers below two. received '-1'")},
}
for _, test := range testCases {
observed, err := FactorsList(test.input)
if err != nil {
if test.err.Error() != err.Error() {
t.Error(err)
}
}
if !reflect.DeepEqual(observed, test.expected) {
t.Errorf("for input '%d', expected '%v', got '%v'",
test.input, test.expected, observed)
}
}
}
// BenchmarkFactorList benchmark FactorsList function.
func BenchmarkFactorList(b *testing.B) {
for i := 0; i <= b.N; i++ {
_, err := FactorsList(1000)
if err != nil {
b.Error(err)
}
}
}
| package numbers
import (
"errors"
"reflect"
"testing"
)
// TestFactorsList unit test FactorsList function.
func TestFactorsList(t *testing.T) {
testCases := []struct {
input int
expected []int
err error
}{
{2, []int{2}, nil},
{15, []int{3, 5}, nil},
{26, []int{2, 13}, nil},
{37, []int{37}, nil},
{42, []int{2, 3, 7}, nil},
{-1, []int(nil), errors.New("no prime factors for numbers below two. received '-1'")},
}
for _, test := range testCases {
observed, err := FactorsList(test.input)
if err != nil {
if test.err.Error() != err.Error() {
t.Error(err)
}
}
if !reflect.DeepEqual(observed, test.expected) {
t.Errorf("for input '%d', expected '%v', got '%v'",
test.input, test.expected, observed)
}
}
}
|
Add serialise and normalise for default field content | <?php
namespace verbb\feedme\fields;
use verbb\feedme\base\Field;
use verbb\feedme\base\FieldInterface;
use Craft;
use Cake\Utility\Hash;
class DefaultField extends Field implements FieldInterface
{
// Properties
// =========================================================================
public static $name = 'Default';
public static $class = 'craft\fields\Default';
// Templates
// =========================================================================
public function getMappingTemplate()
{
return 'feed-me/_includes/fields/default';
}
// Public Methods
// =========================================================================
public function parseField()
{
$value = $this->fetchValue();
// Default fields expect strings, if its an array for an odd reason, serialise it
if (is_array($value)) {
if (empty($value)) {
$value = '';
} else {
$value = json_encode($value);
}
}
// Lastly, get each field to prepare values how they should
$value = $this->field->serializeValue($this->field->normalizeValue($value));
return $value;
}
} | <?php
namespace verbb\feedme\fields;
use verbb\feedme\base\Field;
use verbb\feedme\base\FieldInterface;
use Craft;
use Cake\Utility\Hash;
class DefaultField extends Field implements FieldInterface
{
// Properties
// =========================================================================
public static $name = 'Default';
public static $class = 'craft\fields\Default';
// Templates
// =========================================================================
public function getMappingTemplate()
{
return 'feed-me/_includes/fields/default';
}
// Public Methods
// =========================================================================
public function parseField()
{
$value = $this->fetchValue();
// Default fields expect strings, if its an array for an odd reason, serialise it
if (is_array($value)) {
if (empty($value)) {
$value = '';
} else {
$value = json_encode($value);
}
}
return $value;
}
} |
Revert Profiler as optional dependency | <?php
namespace Lexik\Bundle\TranslationBundle\Util\Profiler;
use Symfony\Component\HttpKernel\Profiler\Profiler;
/**
* @author Cédric Girard <c.girard@lexik.fr>
*/
class TokenFinder
{
/**
* @var Profiler
*/
private $profiler;
/**
* @var int
*/
private $defaultLimit;
/**
* @param Profiler $profiler
* @param int $defaultLimit
*/
public function __construct(Profiler $profiler, $defaultLimit)
{
$this->profiler = $profiler;
$this->defaultLimit = $defaultLimit;
}
/**
* @param string $ip
* @param string $url
* @param int $limit
* @param string $method
* @param string $start
* @param string $end
* @return array
*/
public function find($ip = null, $url = null, $limit = null, $method = null, $start = null, $end = null)
{
$limit = $limit ?: $this->defaultLimit;
return $this->profiler->find($ip, $url, $limit, $method, $start, $end);
}
}
| <?php
namespace Lexik\Bundle\TranslationBundle\Util\Profiler;
use Symfony\Component\HttpKernel\Profiler\Profiler;
/**
* @author Cédric Girard <c.girard@lexik.fr>
*/
class TokenFinder
{
/**
* @var Profiler
*/
private $profiler;
/**
* @var int
*/
private $defaultLimit;
/**
* @param Profiler $profiler
* @param int $defaultLimit
*/
public function __construct(?Profiler $profiler, $defaultLimit)
{
$this->profiler = $profiler;
$this->defaultLimit = $defaultLimit;
}
/**
* @param string $ip
* @param string $url
* @param int $limit
* @param string $method
* @param string $start
* @param string $end
* @return array
*/
public function find($ip = null, $url = null, $limit = null, $method = null, $start = null, $end = null)
{
if ($this->profiler === null) {
return [];
}
$limit = $limit ?: $this->defaultLimit;
return $this->profiler->find($ip, $url, $limit, $method, $start, $end);
}
}
|
Append slash to API root if needed. | from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
| from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
return self._config_dict['API_ROOT']
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
Update password in unit test to comply with password rules | import pytest
from tenable_io.api.users import UserCreateRequest
from tests.base import BaseTest
from tests.config import TenableIOTestConfig
class TestImpersonation(BaseTest):
@pytest.fixture(scope='class')
def user(self, app, client):
user_id = client.users_api.create(UserCreateRequest(
username=app.session_name(u'test_impersonation%%s@%s' % TenableIOTestConfig.get('users_domain_name')),
name='test_impersonation',
password='Sdk!Test1',
permissions='16',
type='local',
email=app.session_name(u'test_user_email+%%s@%s' % TenableIOTestConfig.get('users_domain_name'))
))
user = client.users_api.get(user_id)
yield user
client.users_api.delete(user_id)
def test_impersonation(self, client, user):
impersonating_client = client.impersonate(user.username)
impersonating_user = impersonating_client.session_api.get()
assert impersonating_user.username == user.username, u'The current session user should be the impersonated user'
| import pytest
from tenable_io.api.users import UserCreateRequest
from tests.base import BaseTest
from tests.config import TenableIOTestConfig
class TestImpersonation(BaseTest):
@pytest.fixture(scope='class')
def user(self, app, client):
user_id = client.users_api.create(UserCreateRequest(
username=app.session_name(u'test_impersonation%%s@%s' % TenableIOTestConfig.get('users_domain_name')),
name='test_impersonation',
password='test_impersonation',
permissions='16',
type='local',
email=app.session_name(u'test_user_email+%%s@%s' % TenableIOTestConfig.get('users_domain_name'))
))
user = client.users_api.get(user_id)
yield user
client.users_api.delete(user_id)
def test_impersonation(self, client, user):
impersonating_client = client.impersonate(user.username)
impersonating_user = impersonating_client.session_api.get()
assert impersonating_user.username == user.username, u'The current session user should be the impersonated user'
|
Replace using tests.utils with openstack.common.test
It is the first step to replace using tests.utils with openstack.common.test.
All these tests don't use mock objects, stubs, config files and use only
BaseTestCase class.
Change-Id: I511816b5c9e6c5c34ebff199296ee4fc8b84c672
bp: common-unit-tests | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack.common import context
from openstack.common import test
class ContextTest(test.BaseTestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
def test_admin_context_show_deleted_flag_default(self):
ctx = context.get_admin_context()
self.assertFalse(ctx.show_deleted)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack.common import context
from tests import utils
class ContextTest(utils.BaseTestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
def test_admin_context_show_deleted_flag_default(self):
ctx = context.get_admin_context()
self.assertFalse(ctx.show_deleted)
|
Optimize StringBuffer if string is final. | package se.raddo.raddose3D;
/**
* WriterString writes all received data to a string.
*/
public class WriterString extends Writer {
/** All received data is kept in a Stringbuffer. */
private final StringBuffer data = new StringBuffer();
/** After close() is called further data results in RuntimeExceptions. */
private Boolean readonly = false;
@Override
public void write(final String s) {
if (readonly) {
throw new IllegalStateException("Writer has been closed");
}
data.append(s);
}
@Override
public void write(final StringBuffer b) {
if (readonly) {
throw new IllegalStateException("Writer has been closed");
}
data.append(b);
}
@Override
public void close() {
readonly = true;
data.trimToSize();
}
/**
* Retrieve all encountered data.
*
* @return
* one String containing all encountered data
*/
public String getDataString() {
return new String(data);
}
/**
* Retrieve all encountered data.
*
* @return
* StringBuffer object containing all encountered data
*/
public StringBuffer getDataStringBuffer() {
return data;
}
}
| package se.raddo.raddose3D;
/**
* WriterString writes all received data to a string.
*/
public class WriterString extends Writer {
/** All received data is kept in a Stringbuffer. */
private final StringBuffer data = new StringBuffer();
/** After close() is called further data results in RuntimeExceptions. */
private Boolean readonly = false;
@Override
public void write(final String s) {
if (readonly) {
throw new IllegalStateException("Writer has been closed");
}
data.append(s);
}
@Override
public void write(final StringBuffer b) {
if (readonly) {
throw new IllegalStateException("Writer has been closed");
}
data.append(b);
}
@Override
public void close() {
readonly = true;
}
/**
* Retrieve all encountered data.
*
* @return
* one String containing all encountered data
*/
public String getDataString() {
return new String(data);
}
/**
* Retrieve all encountered data.
*
* @return
* StringBuffer object containing all encountered data
*/
public StringBuffer getDataStringBuffer() {
return data;
}
}
|
[docs] Use captureMessage instead of exception | import React from 'react';
import * as Sentry from '@sentry/browser';
export default class Error extends React.Component {
static getInitialProps({ res, err }) {
const statusCode = res ? res.statusCode : err ? err.statusCode : null;
return { statusCode };
}
componentDidMount() {
let location;
if (typeof window !== 'undefined') {
Sentry.captureMessage(`404: ${window.location.href}`);
}
// Maybe redirect!?
console.log(window.location.pathname);
}
render() {
return (
<div
style={{
display: 'flex',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
flexDirection: 'column'
}}
>
<p style={{ textAlign: 'center' }}>
Uh oh, we couldn't find this page! Maybe it doesn't exist anymore! 😔
</p>
<p style={{ textAlign: 'center', marginTop: 10 }}>
<a href="/">Go back to the Expo documentation</a>
</p>
</div>
);
}
}
| import React from 'react';
import * as Sentry from '@sentry/browser';
export default class Error extends React.Component {
static getInitialProps({ res, err }) {
const statusCode = res ? res.statusCode : err ? err.statusCode : null;
return { statusCode };
}
componentDidMount() {
let location;
if (typeof window !== 'undefined') {
Sentry.captureException(new Error(`${window.location.href}`));
}
// Maybe redirect!?
console.log(window.location.pathname);
}
render() {
return (
<div
style={{
display: 'flex',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
flexDirection: 'column'
}}
>
<p style={{ textAlign: 'center' }}>
Uh oh, we couldn't find this page! Maybe it doesn't exist anymore! 😔
</p>
<p style={{ textAlign: 'center', marginTop: 10 }}>
<a href="/">Go back to the Expo documentation</a>
</p>
</div>
);
}
}
|
Make sure "fab publish" cleans the dist folder
This avoids accidentally uploading a package twice | import fabric.api as fab
def generate_type_hierarchy():
"""
Generate a document containing the available variable types.
"""
fab.local('./env/bin/python -m puresnmp.types > docs/typetree.rst')
@fab.task
def doc():
generate_type_hierarchy()
fab.local('sphinx-apidoc '
'-o docs/developer_guide/api '
'-f '
'-e '
'puresnmp '
'puresnmp/test')
with fab.lcd('docs'):
fab.local('make html')
@fab.task
def publish():
fab.local('rm -rf dist')
fab.local('python3 setup.py bdist_wheel --universal')
fab.local('python3 setup.py sdist')
fab.local('twine upload dist/*')
| import fabric.api as fab
def generate_type_hierarchy():
"""
Generate a document containing the available variable types.
"""
fab.local('./env/bin/python -m puresnmp.types > docs/typetree.rst')
@fab.task
def doc():
generate_type_hierarchy()
fab.local('sphinx-apidoc '
'-o docs/developer_guide/api '
'-f '
'-e '
'puresnmp '
'puresnmp/test')
with fab.lcd('docs'):
fab.local('make html')
@fab.task
def publish():
fab.local('python3 setup.py bdist_wheel --universal')
fab.local('python3 setup.py sdist')
fab.local('twine upload dist/*')
|
Fix crash when the launcher is started without internet access. | package de.craften.craftenlauncher.logic.download;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
public class VersionLoader {
private static final Logger LOGGER = LogManager.getLogger(VersionLoader.class);
public static List<String> getVersionStringList() {
String jsonString = DownloadHelper.downloadFileToString("https://s3.amazonaws.com/Minecraft.Download/versions/versions.json");
JsonObject versionsJson = new Gson().fromJson(jsonString, JsonObject.class);
if (versionsJson != null) {
List<String> versions = new ArrayList<>();
for (JsonElement version : versionsJson.getAsJsonArray("versions")) {
versions.add(version.getAsJsonObject().get("id").getAsString());
}
return versions;
} else {
LOGGER.warn("Downloading versions list failed, using local versions only");
return new ArrayList<>(); //TODO cache the versions or throw an exception
}
}
}
| package de.craften.craftenlauncher.logic.download;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
public class VersionLoader {
public static List<String> getVersionStringList() {
String jsonString = DownloadHelper.downloadFileToString("https://s3.amazonaws.com/Minecraft.Download/versions/versions.json");
JsonObject versionsJson = new Gson().fromJson(jsonString, JsonObject.class);
List<String> versions = new ArrayList<>();
for (JsonElement version : versionsJson.getAsJsonArray("versions")) {
versions.add(version.getAsJsonObject().get("id").getAsString());
}
return versions;
}
}
|
Use RuntimeException so we don't need leading \ on usage | <?php
namespace PiPHP\GPIO\FileSystem;
use RuntimeException;
final class FileSystem implements FileSystemInterface
{
/**
* {@inheritdoc}
*/
public function open($path, $mode)
{
$stream = @fopen($path, $mode);
$this->exceptionIfFalse($stream);
return $stream;
}
/**
* {@inheritdoc}
*/
public function getContents($path)
{
$stream = $this->open($path, 'r');
$contents = @stream_get_contents($stream);
fclose($stream);
$this->exceptionIfFalse($contents);
return $contents;
}
/**
* {@inheritdoc}
*/
public function putContents($path, $buffer)
{
$stream = $this->open($path, 'w');
$bytesWritten = @fwrite($stream, $buffer);
fclose($stream);
$this->exceptionIfFalse($bytesWritten);
return $bytesWritten;
}
private function exceptionIfFalse($result)
{
if (false === $result) {
$errorDetails = error_get_last();
throw new RuntimeException($errorDetails['message']);
}
}
}
| <?php
namespace PiPHP\GPIO\FileSystem;
final class FileSystem implements FileSystemInterface
{
/**
* {@inheritdoc}
*/
public function open($path, $mode)
{
$stream = @fopen($path, $mode);
$this->exceptionIfFalse($stream);
return $stream;
}
/**
* {@inheritdoc}
*/
public function getContents($path)
{
$stream = $this->open($path, 'r');
$contents = @stream_get_contents($stream);
fclose($stream);
$this->exceptionIfFalse($contents);
return $contents;
}
/**
* {@inheritdoc}
*/
public function putContents($path, $buffer)
{
$stream = $this->open($path, 'w');
$bytesWritten = @fwrite($stream, $buffer);
fclose($stream);
$this->exceptionIfFalse($bytesWritten);
return $bytesWritten;
}
private function exceptionIfFalse($result)
{
if (false === $result) {
$errorDetails = error_get_last();
throw new \RuntimeException($errorDetails['message']);
}
}
}
|
Add supposedly unused imports back again | """
This package implements a wxPython shell, based on PyShell,
which controls a seperate Python process, creating with the
`multiprocessing` package.
Here is the canonical way to use it:
1. Subclass multiprocessing.Process:
import multiprocessing
class CustomProcess(multiprocessing.Process):
def __init__(self,*args,**kwargs):
multiprocessing.Process.__init__(self,*args,**kwargs)
self.queue_pack=shelltoprocess.make_queue_pack()
# Put whatever code you want here
def run(self):
# Put whatever code you want here
self.console = shelltoprocess.Console(queue_pack=self.queue_pack)
self.console.interact()
custom_process = CustomProcess()
custom_process.start()
2. Set up the shell in the appropriate part of your code:
self.shell = shelltoprocess.Shell(parent_window,
queue_pack=custom_process.queue_pack)
"""
import multiprocessing
from shell import Shell
from console import Console
def make_queue_pack():
"""
Creates a "queue pack". This is the one object that connects between
the Shell and the Console. The same queue_pack must be fed into both.
See package documentation for more info.
"""
return [multiprocessing.Queue() for _ in range(4)]
__all__ = ["Shell", "Console", "make_queue_pack"]
| """
This package implements a wxPython shell, based on PyShell,
which controls a seperate Python process, creating with the
`multiprocessing` package.
Here is the canonical way to use it:
1. Subclass multiprocessing.Process:
import multiprocessing
class CustomProcess(multiprocessing.Process):
def __init__(self,*args,**kwargs):
multiprocessing.Process.__init__(self,*args,**kwargs)
self.queue_pack=shelltoprocess.make_queue_pack()
# Put whatever code you want here
def run(self):
# Put whatever code you want here
self.console = shelltoprocess.Console(queue_pack=self.queue_pack)
self.console.interact()
custom_process = CustomProcess()
custom_process.start()
2. Set up the shell in the appropriate part of your code:
self.shell = shelltoprocess.Shell(parent_window,
queue_pack=custom_process.queue_pack)
"""
import multiprocessing
def make_queue_pack():
"""
Creates a "queue pack". This is the one object that connects between
the Shell and the Console. The same queue_pack must be fed into both.
See package documentation for more info.
"""
return [multiprocessing.Queue() for _ in range(4)]
__all__ = ["Shell", "Console", "make_queue_pack"]
|
Remove rankBy parameter in request | let service;
let map;
const MTV = new google.maps.LatLng(37.4220, 122.0841);
function findNearbyPlaces() {
map = new google.maps.Map(document.getElementById('map'), {
center: MTV,
zoom: 15
});
let request = {
location: MTV,
radius: '5000',
type: ['restaurant']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if(status == google.maps.places.PlacesService.OK) {
for(let i = 0; i < 5; i++) {
console.log(results[i].name);
}
}
} | let service;
let map;
const MTV = new google.maps.LatLng(37.4220, 122.0841);
function findNearbyPlaces() {
map = new google.maps.Map(document.getElementById('map'), {
center: MTV,
zoom: 15
});
let request = {
location: MTV,
radius: '5000',
rankBy: google.maps.places.RankBy.PROMINENCE,
type: ['restaurant']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if(status == google.maps.places.PlacesService.OK) {
for(let i = 0; i < 5; i++) {
console.log(results[i].name);
}
}
} |
chore: Replace NotFound route component with Error404 component | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory, browserHistory } from 'react-router'
// Route-specific views:
import Home from './components/Home';
import About from './components/About';
import Focus from './components/Focus';
import Contact from './components/Contact';
import Error404 from './components/Error404';
// Route-invariant site layout views:
import NavBar from './components/NavBar';
import MainLayout from './components/MainLayout';
// Top-level React (pure functional) component:
const App = () => (
<Router history={ hashHistory }>
<Route path='/' component={ MainLayout }>
<IndexRoute component={ Home } />
<Route path='/about' component={ About } />
<Route path='/focus' component={ Focus } />
<Route path='/contact' component={ Contact } />
<Route path='*' component={ Error404 } />
</Route>
</Router>
);
export default App;
| 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory, browserHistory } from 'react-router'
// Route-specific views:
import Home from './components/Home';
import About from './components/About';
import Focus from './components/Focus';
import Contact from './components/Contact';
import Error404 from './components/Error404';
// Route-invariant site layout views:
import NavBar from './components/NavBar';
import MainLayout from './components/MainLayout';
// Top-level React (pure functional) component:
const App = () => (
<Router history={ hashHistory }>
<Route path='/' component={ MainLayout }>
<IndexRoute component={ Home } />
<Route path='/about' component={ About } />
<Route path='/focus' component={ Focus } />
<Route path='/contact' component={ Contact } />
<Route path='*' component={ NotFound } />
</Route>
</Router>
);
export default App;
|
Use factory to iterate over permutations
Signed-off-by: Jeffrey Elms <23ce84ca7a7de9dc17ad8e8b0bbd717d4f9f9884@freshred.net> | import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
from cocotb.regression import TestFactory
@cocotb.coroutine
def mux2_basic_test(dut, inputs=(1,0,0)):
"""Test for MUX2 options"""
yield Timer(2)
I0, I1, S0 = inputs
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
factory = TestFactory(mux2_basic_test)
input_permutations = [(x, y, z) for x in [0,1] for y in [0,1] for z in [0,1]]
factory.add_option("inputs", input_permutations)
factory.generate_tests()
| # Simple tests for an adder module
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
#from adder_model import adder_model
#import random
@cocotb.test()
def mux2_test(dut):
"""Test for MUX2 options"""
opts = [(x,y,z, x&~z | y&z) for x in [0,1] for y in [0,1] for z in [0,1]]
yield Timer(2)
for I0, I1, S0, _ in opts:
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
|
Add Params to constructor dockblock | <?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = [];
/**
* Constructor.
*
* @param RequestInterface
* @param ResponseInterface
* @param LoggerInterface
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
//--------------------------------------------------------------------
// Preload any models, libraries, etc, here.
//--------------------------------------------------------------------
// E.g.: $this->session = \Config\Services::session();
}
}
| <?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = [];
/**
* Constructor.
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
//--------------------------------------------------------------------
// Preload any models, libraries, etc, here.
//--------------------------------------------------------------------
// E.g.:
// $this->session = \Config\Services::session();
}
}
|
Use the correct userId when displaying who redacted a message | /*
Copyright 2015, 2016 OpenMarket Ltd
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.
*/
'use strict';
import React from 'react';
import { _t } from '../../../languageHandler';
module.exports = React.createClass({
displayName: 'UnknownBody',
render: function() {
let tooltip = _t("Removed or unknown message type");
if (this.props.mxEvent.isRedacted()) {
tooltip = _t("Message removed by %(userId)s", {
userId: this.props.mxEvent.getUnsigned().redacted_because.sender,
});
}
const text = this.props.mxEvent.getContent().body;
return (
<span className="mx_UnknownBody" title={tooltip}>
{ text }
</span>
);
},
});
| /*
Copyright 2015, 2016 OpenMarket Ltd
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.
*/
'use strict';
import React from 'react';
import { _t } from '../../../languageHandler';
module.exports = React.createClass({
displayName: 'UnknownBody',
render: function() {
let tooltip = _t("Removed or unknown message type");
if (this.props.mxEvent.isRedacted()) {
tooltip = _t("Message removed by %(userId)s", {userId: this.props.mxEvent.getSender()});
}
const text = this.props.mxEvent.getContent().body;
return (
<span className="mx_UnknownBody" title={tooltip}>
{ text }
</span>
);
},
});
|
Create plain object in toJSON method
Standard deep equality doesn't seem to fail because it doesn't check for
types (i.e. constructor). However, the deep equality that chai uses
takes that into account and seems like a good idea to remove the
prototype in the object to be used for JSON output. | 'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
return output;
}
ModelRenderer.prototype.toJSON = function toJSON() {
return R.mapObj(R.identity, this);
};
ModelRenderer.prototype.toString = function toString() {
var output = this.modelName;
if (!isEmptyObj(this.attrs)) {
output += ':\n';
output += R.join('\n', R.map(R.apply(attrToString), R.toPairs(this.attrs)));
}
return output;
};
module.exports = ModelRenderer;
| 'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
return output;
}
ModelRenderer.prototype.toJSON = function toJSON() {
return this;
};
ModelRenderer.prototype.toString = function toString() {
var output = this.modelName;
if (!isEmptyObj(this.attrs)) {
output += ':\n';
output += R.join('\n', R.map(R.apply(attrToString), R.toPairs(this.attrs)));
}
return output;
};
module.exports = ModelRenderer;
|
Simplify mutate() & cure() methods | <?php
namespace App\Models;
class Player extends \Pragma\ORM\Model
{
const GENOME_HOST = 0;
const GENOME_NORMAL = 1;
const GENOME_RESISTANT = 2;
private $name;
private $keyId;
private $genome;
private $role;
private $paralysed;
private $mutated;
private $alive;
public function __construct($name)
{
return parent::__construct('player');
$this->name=$name;
}
public function setGenome($genome){
if($genome>0){
$genome=1;
}elseif($genome<0){
$genome=-1;
}else{
$genome=0;
}
$this->genome=$genome;
}
public function mutate() {
if ($this->genome != self::GENOME_RESISTANT) {
$this->mutated = 1;
}
return $this->mutated;
}
public function cure() {
if ($this->genome != self::GENOME_HOST) {
$this->mutated = 0;
}
return !$this->mutated;
}
}
| <?php
namespace App\Models;
class Player extends \Pragma\ORM\Model
{
const GENOME_HOST = 0;
const GENOME_NORMAL = 1;
const GENOME_RESISTANT = 2;
private $name;
private $keyId;
private $genome;
private $role;
private $paralysed;
private $mutated;
private $alive;
public function __construct($name)
{
return parent::__construct('player');
$this->name=$name;
}
public function setGenome($genome){
if($genome>0){
$genome=1;
}elseif($genome<0){
$genome=-1;
}else{
$genome=0;
}
$this->genome=$genome;
}
public function mutate() {
if ($this->genome != self::GENOME_RESISTANT) {
$this->mutated=1;
return true;
}
return false;
}
public function cure() {
if ($this->genome != self::GENOME_HOST || !$this->mutated) {
$this->mutated=0;
return true;
}
return false;
}
}
|
Add newline at end of file | /*
#
# img2musicXML.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = im2x || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divClassName = "i2mx-checkup";
this.activate = function() {
var divList = document.getElementsByClassName(this.divClassName);
// @TODO: Implement multiple divs support
divList[0].innerHTML = "No checlist for now, but img2musicXML loaded successfully!"; // @TODO: Multi-line
}
}
var jsCheckup = new JsCheckup();
// @TODO: Check window.onload vs document.onload
// @TODO: Use event listener instead of onload
document.onload = function() {
jsCheckup.activate();
}
| /*
#
# img2musicXML.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = im2x || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divClassName = "i2mx-checkup";
this.activate = function() {
var divList = document.getElementsByClassName(this.divClassName);
// @TODO: Implement multiple divs support
divList[0].innerHTML = "No checlist for now, but img2musicXML loaded successfully!"; // @TODO: Multi-line
}
}
var jsCheckup = new JsCheckup();
// @TODO: Check window.onload vs document.onload
// @TODO: Use event listener instead of onload
document.onload = function() {
jsCheckup.activate();
} |
Update comment about the New function | package ghostinspector
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// APIV1Path is the protocol and base path of the Ghost Inspector API version 1
const APIV1Path = "https://api.ghostinspector.com/v1"
// GhostInspector handles sending to the API
type GhostInspector struct {
apikey string
}
// New creates a new Ghost Inspector client that can be used to send requests.
func New(apikey string) *GhostInspector {
return &GhostInspector{
apikey: apikey,
}
}
// Get sends GET requests to the Ghost Inspector API, using APIV1Path as the
// base path. This is mainly to be used internally, but exported for users if
// new API calls exists without them being reflected in this package.
func (gi *GhostInspector) Get(path, args string) (*Response, error) {
response, err := http.Get(fmt.Sprintf("%s%s?apiKey=%s&%s", APIV1Path, path, gi.apikey, args))
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
resp := Response{}
json.Unmarshal(body, &resp)
return &resp, nil
}
| package ghostinspector
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// APIV1Path is the protocol and base path of the Ghost Inspector API version 1
const APIV1Path = "https://api.ghostinspector.com/v1"
// GhostInspector handles sending to the API
type GhostInspector struct {
apikey string
}
// New creates a new *GhostInspector
func New(apikey string) *GhostInspector {
return &GhostInspector{
apikey: apikey,
}
}
// Get sends GET requests to the Ghost Inspector API, using APIV1Path as the
// base path. This is mainly to be used internally, but exported for users if
// new API calls exists without them being reflected in this package.
func (gi *GhostInspector) Get(path, args string) (*Response, error) {
response, err := http.Get(fmt.Sprintf("%s%s?apiKey=%s&%s", APIV1Path, path, gi.apikey, args))
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
resp := Response{}
json.Unmarshal(body, &resp)
return &resp, nil
}
|
Put the release number to 0.2 | from setuptools import setup
requires = [
'redis',
'retask',
'fedmsg',
]
setup(
name='autocloud',
version='0.2',
description='',
author='',
author_email='',
url='https://github.com/kushaldas/autocloud',
install_requires=requires,
packages=['autocloud', 'autocloud.web', 'autocloud.utils'],
include_package_data=True,
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
'Programming Language :: Python',
],
entry_points={
'moksha.consumer': [
"autocloud_consumer = autocloud.consumer:AutoCloudConsumer",
],
},
)
| from setuptools import setup
requires = [
'redis',
'retask',
'fedmsg',
]
setup(
name='autocloud',
version='0.1',
description='',
author='',
author_email='',
url='https://github.com/kushaldas/autocloud',
install_requires=requires,
packages=['autocloud', 'autocloud.web', 'autocloud.utils'],
include_package_data=True,
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
'Programming Language :: Python',
],
entry_points={
'moksha.consumer': [
"autocloud_consumer = autocloud.consumer:AutoCloudConsumer",
],
},
)
|
Add javadoc to source dao.
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2436 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.Source;
import java.util.List;
public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> {
public Class<Source> domainClass() {
return Source.class;
}
/**
* Finds all the activity sources available
*
* @return a list of all the available activity sources
*/
public List<Source> getAll() {
return getHibernateTemplate().find("from Source order by name");
}
/**
* Finds all the actiivty sources for the given activity source name
*
* @param name the name of the activity source to search for
* @return the source that was found for the given activity source name
*/
public Source getByName(String name) {
List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name);
if (!sources.isEmpty()) {
return sources.get(0);
}
return null;
}
}
| package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.Source;
import java.util.List;
public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> {
public Class<Source> domainClass() {
return Source.class;
}
public List<Source> getAll() {
return getHibernateTemplate().find("from Source order by name");
}
public Source getByName(String name) {
List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name);
if (!sources.isEmpty()) {
return sources.get(0);
}
return null;
}
}
|
Fix: Update return type in docblock | <?php
namespace TomPHP\ContainerConfigurator;
use TomPHP\ContainerConfigurator\Exception\UnknownContainerException;
final class ContainerAdapterFactory
{
/**
* @var array
*/
private $config;
public function __construct(array $config)
{
$this->config = $config;
}
/**
* @param object $container
*
* @throws UnknownContainerException
*
* @return ContainerAdapter
*/
public function create($container)
{
$class = '';
foreach ($this->config as $containerClass => $configuratorClass) {
if (is_a($container, $containerClass)) {
$class = $configuratorClass;
break;
}
}
if (!$class) {
throw UnknownContainerException::fromContainerName(
get_class($container),
array_keys($this->config)
);
}
$instance = new $class();
$instance->setContainer($container);
return $instance;
}
}
| <?php
namespace TomPHP\ContainerConfigurator;
use TomPHP\ContainerConfigurator\Exception\UnknownContainerException;
final class ContainerAdapterFactory
{
/**
* @var array
*/
private $config;
public function __construct(array $config)
{
$this->config = $config;
}
/**
* @param object $container
*
* @throws UnknownContainerException
*
* @return void
*/
public function create($container)
{
$class = '';
foreach ($this->config as $containerClass => $configuratorClass) {
if (is_a($container, $containerClass)) {
$class = $configuratorClass;
break;
}
}
if (!$class) {
throw UnknownContainerException::fromContainerName(
get_class($container),
array_keys($this->config)
);
}
$instance = new $class();
$instance->setContainer($container);
return $instance;
}
}
|
Remove a test that is no longer relevant | import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc')
mock_req.assert_called_with(
'POST',
settings.GO_API_URL,
auth=('session_id', '123'),
data=json.dumps({
'jsonrpc': '2.0',
'id': 'abc',
'params': ['foo', 'bar'],
'method': 'do_something',
}))
| import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_request(self, mock_req):
client.request('123', 'lorem ipsum', 'GET')
mock_req.assert_called_with(
'GET',
settings.GO_API_URL,
auth=('session_id', '123'),
data='lorem ipsum')
@patch('requests.request')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc')
mock_req.assert_called_with(
'POST',
settings.GO_API_URL,
auth=('session_id', '123'),
data=json.dumps({
'jsonrpc': '2.0',
'id': 'abc',
'params': ['foo', 'bar'],
'method': 'do_something',
}))
|
Add a bigIncrements to avoid issues with mysql8 | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFeaturablesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('featurables', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('feature_id');
$table->integer('featurable_id');
$table->string('featurable_type');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('featurables');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFeaturablesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('featurables', function (Blueprint $table) {
$table->integer('feature_id');
$table->integer('featurable_id');
$table->string('featurable_type');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('featurables');
}
}
|
Tweak payment receipt upload rejection resolution | // PaymentRequirementUpload class
'use strict';
var memoize = require('memoizee/plain')
, defineRequirementUpload = require('./requirement-upload')
, defineCost = require('./cost');
module.exports = memoize(function (db) {
var RequirementUpload = defineRequirementUpload(db)
, Cost = defineCost(db);
return RequirementUpload.extend('PaymentReceiptUpload', {
// Costs which are covered by the payment receipt
costs: { type: Cost, multiple: true },
applicableCosts: { type: Cost, multiple: true, value: function (_observe) {
var result = [], payable = _observe(this.master.costs.payable);
this.costs.forEach(function (cost) {
if (!payable.has(cost)) return;
if (_observe(cost._isPaidOnline)) return;
result.push(cost);
});
return result;
} },
// In case of receipt upload we do not show all reject reasons just memp
isRejected: { type: db.Boolean, value: function () {
if (this.status == null) return false;
if (this.status !== 'invalid') return false;
return Boolean(this.rejectReasonMemo);
} }
});
}, { normalizer: require('memoizee/normalizers/get-1')() });
| // PaymentRequirementUpload class
'use strict';
var memoize = require('memoizee/plain')
, defineRequirementUpload = require('./requirement-upload')
, defineCost = require('./cost');
module.exports = memoize(function (db) {
var RequirementUpload = defineRequirementUpload(db)
, Cost = defineCost(db);
return RequirementUpload.extend('PaymentReceiptUpload', {
// Costs which are covered by the payment receipt
costs: { type: Cost, multiple: true },
applicableCosts: { type: Cost, multiple: true, value: function (_observe) {
var result = [], payable = _observe(this.master.costs.payable);
this.costs.forEach(function (cost) {
if (!payable.has(cost)) return;
if (_observe(cost._isPaidOnline)) return;
result.push(cost);
});
return result;
} }
});
}, { normalizer: require('memoizee/normalizers/get-1')() });
|
Reduce splash screen load time | package com.amitness.photon;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SplashScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Thread myThread = new Thread() {
@Override
public void run() {
try{
sleep(2000);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
| package com.amitness.photon;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SplashScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Thread myThread = new Thread() {
@Override
public void run() {
try{
sleep(4000);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
|
Integrate recover middleware with new log | package horizon
import (
"net/http"
"runtime/debug"
gctx "github.com/goji/context"
"github.com/stellar/go-horizon/log"
"github.com/stellar/go-horizon/render/problem"
"github.com/zenazn/goji/web"
)
func RecoverMiddleware(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := gctx.FromC(*c)
defer func() {
if err := recover(); err != nil {
log.Errorf(ctx, "panic: %+v", err)
log.Errorf(ctx, "backtrace: %s", debug.Stack())
//TODO: include stack trace if in debug mode
problem.Render(gctx.FromC(*c), w, problem.ServerError)
}
}()
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
| package horizon
import (
"bytes"
"fmt"
gctx "github.com/goji/context"
"github.com/stellar/go-horizon/render/problem"
"github.com/zenazn/goji/web"
. "github.com/zenazn/goji/web/middleware"
"log"
"net/http"
"runtime/debug"
)
func RecoverMiddleware(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
reqID := GetReqID(*c)
defer func() {
if err := recover(); err != nil {
printPanic(reqID, err)
debug.PrintStack()
//TODO: include stack trace if in debug mode
problem.Render(gctx.FromC(*c), w, problem.ServerError)
}
}()
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func printPanic(reqID string, err interface{}) {
var buf bytes.Buffer
if reqID != "" {
fmt.Fprintf(&buf, "[%s] ", reqID)
}
fmt.Fprintf(&buf, "panic: %+v", err)
log.Print(buf.String())
}
|
Update to new URL dispatcher syntax | # Django
# Third-Party
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
from django.conf import settings
from django.urls import (
include,
path,
)
from django.contrib import admin
from django.http import (
HttpResponse,
HttpResponseRedirect,
)
schema_view = get_schema_view(
title='Barberscore API',
)
urlpatterns = [
path('', lambda r: HttpResponseRedirect('admin/')),
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('rq/', include('django_rq.urls')),
path('api-auth/', include('rest_framework.urls')),
path('schema/', schema_view),
path('docs/', include_docs_urls(title='Documentation', description='API Documentation')),
path('robots.txt', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path('__debug__/', include(debug_toolbar.urls)),
]
| # Django
# Third-Party
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
from django.conf import settings
from django.conf.urls import (
include,
url,
)
from django.contrib import admin
from django.http import (
HttpResponse,
HttpResponseRedirect,
)
schema_view = get_schema_view(
title='Barberscore API',
)
urlpatterns = [
url(r'^$', lambda r: HttpResponseRedirect('admin/')),
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls')),
# url(r'^bhs/', include('bhs.urls')),
url(r'^rq/', include('django_rq.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^schema/', schema_view),
url(r'^docs/', include_docs_urls(title='Documentation', description='API Documentation')),
url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
|
Make bluebird as default promise overriding ES6 promise
Closes #48 | import mongoose from 'mongoose';
import util from 'util';
import config from './config/env';
import app from './config/express';
const debug = require('debug')('express-mongoose-es6-rest-api:index');
// make bluebird default Promise
Promise = require('bluebird'); // eslint-disable-line no-global-assign
// plugin bluebird promise in mongoose
mongoose.Promise = Promise;
// connect to mongo db
mongoose.connect(config.db, { server: { socketOptions: { keepAlive: 1 } } });
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${config.db}`);
});
// print mongoose logs in dev env
if (config.MONGOOSE_DEBUG) {
mongoose.set('debug', (collectionName, method, query, doc) => {
debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
});
}
// module.parent check is required to support mocha watch
// src: https://github.com/mochajs/mocha/issues/1912
if (!module.parent) {
// listen on port config.port
app.listen(config.port, () => {
debug(`server started on port ${config.port} (${config.env})`);
});
}
export default app;
| import Promise from 'bluebird';
import mongoose from 'mongoose';
import util from 'util';
import config from './config/env';
import app from './config/express';
const debug = require('debug')('express-mongoose-es6-rest-api:index');
// plugin bluebird promise in mongoose
mongoose.Promise = Promise;
// connect to mongo db
mongoose.connect(config.db, { server: { socketOptions: { keepAlive: 1 } } });
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${config.db}`);
});
// print mongoose logs in dev env
if (config.MONGOOSE_DEBUG) {
mongoose.set('debug', (collectionName, method, query, doc) => {
debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
});
}
// module.parent check is required to support mocha watch
// src: https://github.com/mochajs/mocha/issues/1912
if (!module.parent) {
// listen on port config.port
app.listen(config.port, () => {
debug(`server started on port ${config.port} (${config.env})`);
});
}
export default app;
|
Print XML valdation error cause for information purpose | /*
* Copyright 2006-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.samples.common.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageHandlingException;
/**
* @author Christoph Deppisch
*/
public class XmlSchemaValidationException extends MessageHandlingException {
private static final long serialVersionUID = 1L;
/**
* Logger
*/
private static final Logger log = LoggerFactory.getLogger(XmlSchemaValidationException.class);
/**
* @param failedMessage
*/
public XmlSchemaValidationException(Message<?> failedMessage, Throwable cause) {
super(failedMessage);
log.error("Schema validation error", cause);
}
}
| /*
* Copyright 2006-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.samples.common.exceptions;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageHandlingException;
/**
* @author Christoph Deppisch
*/
public class XmlSchemaValidationException extends MessageHandlingException {
private static final long serialVersionUID = 1L;
/**
* @param failedMessage
*/
public XmlSchemaValidationException(Message<?> failedMessage, Throwable cause) {
super(failedMessage, cause);
}
}
|
Revert "For tests: exit 0 on success, exit 1 on failure."
This reverts commit 29f90785ff83bfb9174023606af9fbd32b315ae5. | /**
* Run this file to execute tests
*/
var args = process.argv;
for (var i = 0; i < args.length; i++) {
if (args[i] === '--coverage') {
doCoverage = true;
break;
}
}
var Jasmine = require('jasmine');
var jasmine = new Jasmine();
var istanbulRunReports = require('./istanbul');
jasmine.onComplete(function() {
// Restore console functions so reports work
for (var name in global.console) {
console[name] = _console[name];
}
// if the tests were instrumented, run the reports
if (global.__coverage__) {
istanbulRunReports();
}
});
// Override console methods as spies
// Allows test to run without output getting into test output
global._console = {};
for (var name in global.console) {
_console[name] = console[name].bind(console);
console[name] = jasmine.jasmine.createSpy('console.' + name);
}
// Include event simulator to install global.triggerEvent
require('./event_simulator.js');
jasmine.loadConfig({
'spec_dir': 'test',
'spec_files': [
'./testbuild.prod.js',
'./testbuild.debug.js'
],
'helpers': [
'environment.js',
'../precompile/tungsten_template/inline.js'
]
});
jasmine.execute();
| /**
* Run this file to execute tests
*/
var args = process.argv;
for (var i = 0; i < args.length; i++) {
if (args[i] === '--coverage') {
doCoverage = true;
break;
}
}
var Jasmine = require('jasmine');
var jasmine = new Jasmine();
var istanbulRunReports = require('./istanbul');
jasmine.onComplete(function(passed) {
// Restore console functions so reports work
for (var name in global.console) {
console[name] = _console[name];
}
// if the tests were instrumented, run the reports
if (global.__coverage__) {
istanbulRunReports();
}
var failedTests = !passed;
process.exit(failedTests);
});
// Override console methods as spies
// Allows test to run without output getting into test output
global._console = {};
for (var name in global.console) {
_console[name] = console[name].bind(console);
console[name] = jasmine.jasmine.createSpy('console.' + name);
}
// Include event simulator to install global.triggerEvent
require('./event_simulator.js');
jasmine.loadConfig({
'spec_dir': 'test',
'spec_files': [
'./testbuild.prod.js',
'./testbuild.debug.js'
],
'helpers': [
'environment.js',
'../precompile/tungsten_template/inline.js'
]
});
jasmine.execute();
|
Add a semicolon to end of line | // video.js
//
// data object representing an video
//
// Copyright 2011, StatusNet Inc.
//
// 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.
var DatabankObject = require('databank').DatabankObject,
ActivityObject = require('./activityobject').ActivityObject;
var Video = DatabankObject.subClass('video', ActivityObject);
Video.schema = {
pkey: "id",
fields: ['author',
'displayName',
'embedCode',
'published',
'stream',
'summary',
'updated',
'url']
};
exports.Video = Video;
| // video.js
//
// data object representing an video
//
// Copyright 2011, StatusNet Inc.
//
// 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.
var DatabankObject = require('databank').DatabankObject,
ActivityObject = require('./activityobject').ActivityObject
var Video = DatabankObject.subClass('video', ActivityObject);
Video.schema = {
pkey: "id",
fields: ['author',
'displayName',
'embedCode',
'published',
'stream',
'summary',
'updated',
'url']
};
exports.Video = Video;
|
Update test to be more tolerant. | package com.jenjinstudios.server.net;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.LinkedList;
import java.util.Timer;
/**
* @author Caleb Brinkman
*/
public class ServerUpdateTaskTest
{
@Test
public void testGetAverageUPS() throws Exception {
AuthServer authServer = Mockito.mock(AuthServer.class);
Mockito.when(authServer.getUps()).thenReturn(10);
Mockito.when(authServer.getSyncedTasks()).thenReturn(new LinkedList());
Mockito.when(authServer.getRepeatedTasks()).thenReturn(new LinkedList());
ServerUpdateTask serverUpdateTask = new ServerUpdateTask(authServer);
Timer loopTimer = new Timer("Foo", false);
loopTimer.scheduleAtFixedRate(serverUpdateTask, 0, 100);
Thread.sleep(1500);
Assert.assertEquals(serverUpdateTask.getAverageUPS(), 10, 1);
}
}
| package com.jenjinstudios.server.net;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.LinkedList;
import java.util.Timer;
/**
* @author Caleb Brinkman
*/
public class ServerUpdateTaskTest
{
@Test
public void testGetAverageUPS() throws Exception {
AuthServer authServer = Mockito.mock(AuthServer.class);
Mockito.when(authServer.getUps()).thenReturn(10);
Mockito.when(authServer.getSyncedTasks()).thenReturn(new LinkedList());
Mockito.when(authServer.getRepeatedTasks()).thenReturn(new LinkedList());
ServerUpdateTask serverUpdateTask = new ServerUpdateTask(authServer);
Timer loopTimer = new Timer("Foo", false);
loopTimer.scheduleAtFixedRate(serverUpdateTask, 0, 100);
Thread.sleep(1500);
Assert.assertEquals(serverUpdateTask.getAverageUPS(), 10, 0.1);
}
}
|
Fix browser name (one does not simply lowercase :bomb:. | /* globals module */
module.exports = function(grunt) {
return {
options: {
configFile: 'test/karma.conf.js',
hostname: 'localhost',
singleRun: true
},
local: {
browsers: ['Chrome'],
reporters: ['mocha']
},
dev: {
browsers: ['Chrome'],
reporters: ['mocha'],
singleRun: false
},
bs_ci: {
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 1,
browserNoActivityTimeout: 240000,
captureTimeout: 240000,
browsers: ['bs_win81_ie_11', 'bs_win8_ie_10', 'bs_mavericks_chrome_44', 'bs_yosemite_firefox_40'],
reporters: ['mocha'],
singleRun: true
},
travis_ci: {
browsers: ['Firefox'],
reporters: ['mocha'],
singleRun: true
}
};
};
| /* globals module */
module.exports = function(grunt) {
return {
options: {
configFile: 'test/karma.conf.js',
hostname: 'localhost',
singleRun: true
},
local: {
browsers: ['Chrome'],
reporters: ['mocha']
},
dev: {
browsers: ['Chrome'],
reporters: ['mocha'],
singleRun: false
},
bs_ci: {
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 1,
browserNoActivityTimeout: 240000,
captureTimeout: 240000,
browsers: ['bs_win81_ie_11', 'bs_win8_ie_10', 'bs_mavericks_chrome_44', 'bs_yosemite_firefox_40'],
reporters: ['mocha'],
singleRun: true
},
travis_ci: {
browsers: ['firefox'],
reporters: ['mocha'],
singleRun: true
}
};
};
|
fix(flow): Fix flow errors in login saga. | // @flow
import { take, call, put, select } from 'redux-saga/effects'
import {
APP_FINISHED_LOADING,
PERFORM_USER_LOGIN,
PERFORM_USER_LOGOUT,
USER_LOGGED_IN,
USER_LOGGED_OUT
} from 'actions/types'
export default function* login(
loginFunction: Function,
logoutFunction: Function
): Generator<*, *, *> {
yield take(APP_FINISHED_LOADING)
let userIsLoggedIn: boolean = ((yield select(
state => state.ui.userIsLoggedIn
): any): boolean)
while (true) {
const action = yield take([
USER_LOGGED_IN,
PERFORM_USER_LOGIN,
PERFORM_USER_LOGOUT
])
if (action.type == PERFORM_USER_LOGIN) {
if (!userIsLoggedIn) {
yield call(loginFunction, action)
}
} else if (action.type == USER_LOGGED_IN) {
userIsLoggedIn = true
} else if (action.type == PERFORM_USER_LOGOUT) {
yield call(logoutFunction)
yield put({ type: USER_LOGGED_OUT })
userIsLoggedIn = false
}
}
}
| // @flow
import { take, call, put, select } from 'redux-saga/effects'
import {
APP_FINISHED_LOADING,
PERFORM_USER_LOGIN,
PERFORM_USER_LOGOUT,
USER_LOGGED_IN,
USER_LOGGED_OUT
} from 'actions/types'
export default function* login(
loginFunction: Function,
logoutFunction: Function
): Generator<*, *, *> {
yield take(APP_FINISHED_LOADING)
let userIsLoggedIn = yield select(state => state.ui.userIsLoggedIn)
while (true) {
const action = yield take([
USER_LOGGED_IN,
PERFORM_USER_LOGIN,
PERFORM_USER_LOGOUT
])
if (action.type == PERFORM_USER_LOGIN) {
if (!userIsLoggedIn) {
yield call(loginFunction, action)
}
} else if (action.type == USER_LOGGED_IN) {
userIsLoggedIn = true
} else if (action.type == PERFORM_USER_LOGOUT) {
yield call(logoutFunction)
yield put({ type: USER_LOGGED_OUT })
userIsLoggedIn = false
}
}
}
|
Replace a redundant reference to app.config | # -*- coding: utf-8 -*-
"""
url-shortener
==============
An application for generating and storing shorter aliases for
requested URLs. Uses `spam-lists`__ to prevent generating a short URL
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.
.. __: https://github.com/piotr-rusin/spam-lists
"""
from url_shortener import app, event_handlers, views
__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 Piotr Rusin'
log_file = app.config['LOG_FILE']
if not app.debug and log_file is not None:
import logging
from logging.handlers import TimedRotatingFileHandler
file_handler = TimedRotatingFileHandler(log_file, when='d')
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
app.run()
| # -*- coding: utf-8 -*-
"""
url-shortener
==============
An application for generating and storing shorter aliases for
requested URLs. Uses `spam-lists`__ to prevent generating a short URL
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.
.. __: https://github.com/piotr-rusin/spam-lists
"""
from url_shortener import app, event_handlers, views
__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 Piotr Rusin'
log_file = app.config['LOG_FILE']
if not app.debug and log_file is not None:
import logging
from logging.handlers import TimedRotatingFileHandler
file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'], when='d')
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
app.run()
|
Add jsonSerialize() and implement JsonSerializable | <?php /* vim: set colorcolumn= expandtab shiftwidth=2 softtabstop=2 tabstop=4 smarttab: */
namespace BNETDocs\Models\Packet;
class Form extends \BNETDocs\Models\ActiveUser implements \JsonSerializable
{
// possible values for $error:
const ERROR_ACL_DENIED = 'ACL_DENIED';
const ERROR_INTERNAL = 'INTERNAL';
const ERROR_NONE = 'NONE';
const ERROR_NOT_FOUND = 'NOT_FOUND';
const ERROR_OUTOFBOUNDS_DIRECTION = 'OUTOFBOUNDS_DIRECTION';
const ERROR_OUTOFBOUNDS_FORMAT = 'OUTOFBOUNDS_FORMAT';
const ERROR_OUTOFBOUNDS_ID = 'OUTOFBOUNDS_ID';
const ERROR_OUTOFBOUNDS_NAME = 'OUTOFBOUNDS_NAME';
const ERROR_OUTOFBOUNDS_PACKET_ID = 'OUTOFBOUNDS_PACKET_ID';
const ERROR_OUTOFBOUNDS_REMARKS = 'OUTOFBOUNDS_REMARKS';
const ERROR_OUTOFBOUNDS_USED_BY = 'OUTOFBOUNDS_USED_BY';
const ERROR_SUCCESS = 'SUCCESS';
public $comments;
public $error;
public $form_fields;
public $packet;
public $products;
/**
* Implements the JSON serialization function from the JsonSerializable interface.
*/
public function jsonSerialize()
{
return [
'comments' => $this->comments,
'error' => $this->error,
'form_fields' => $this->form_fields,
'packet' => $this->packet,
'products' => $this->products,
];
}
}
| <?php /* vim: set colorcolumn= expandtab shiftwidth=2 softtabstop=2 tabstop=4 smarttab: */
namespace BNETDocs\Models\Packet;
class Form extends \BNETDocs\Models\ActiveUser
{
// possible values for $error:
const ERROR_ACL_DENIED = 'ACL_DENIED';
const ERROR_INTERNAL = 'INTERNAL';
const ERROR_NONE = 'NONE';
const ERROR_NOT_FOUND = 'NOT_FOUND';
const ERROR_OUTOFBOUNDS_DIRECTION = 'OUTOFBOUNDS_DIRECTION';
const ERROR_OUTOFBOUNDS_FORMAT = 'OUTOFBOUNDS_FORMAT';
const ERROR_OUTOFBOUNDS_ID = 'OUTOFBOUNDS_ID';
const ERROR_OUTOFBOUNDS_NAME = 'OUTOFBOUNDS_NAME';
const ERROR_OUTOFBOUNDS_PACKET_ID = 'OUTOFBOUNDS_PACKET_ID';
const ERROR_OUTOFBOUNDS_REMARKS = 'OUTOFBOUNDS_REMARKS';
const ERROR_OUTOFBOUNDS_USED_BY = 'OUTOFBOUNDS_USED_BY';
const ERROR_SUCCESS = 'SUCCESS';
public $comments;
public $error;
public $form_fields;
public $packet;
public $products;
}
|
Make header link to index.html so it works on the filesystem |
document.addEventListener("DOMContentLoaded", function() {
var h1 = document.querySelector("h1");
if (h1 && !document.title) {
document.title = "DevTools Demos - " + h1.textContent;
}
var body = document.body;
if (body.classList.contains("header")) {
var header = document.createElement("header");
var link = document.createElement("a");
link.setAttribute("href", "../index.html");
link.textContent = "DevTools Demos";
header.appendChild(link);
var repoLink = document.createElement("a");
repoLink.className = "repo-link";
repoLink.setAttribute("href", "https://github.com/bgrins/devtools-demos");
repoLink.textContent = "repository";
header.appendChild(repoLink);
body.insertBefore(header, body.firstChild);
}
});
|
document.addEventListener("DOMContentLoaded", function() {
var h1 = document.querySelector("h1");
if (h1 && !document.title) {
document.title = "DevTools Demos - " + h1.textContent;
}
var body = document.body;
if (body.classList.contains("header")) {
var header = document.createElement("header");
var link = document.createElement("a");
link.setAttribute("href", "../");
link.textContent = "DevTools Demos";
header.appendChild(link);
var repoLink = document.createElement("a");
repoLink.className = "repo-link";
repoLink.setAttribute("href", "https://github.com/bgrins/devtools-demos");
repoLink.textContent = "repository";
header.appendChild(repoLink);
body.insertBefore(header, body.firstChild);
}
});
|
Add a mock page component | import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import { project, workflow } from '../dev-classifier/mock-data';
import ProjectPage from './project-page';
function Page() {
return(
<p>Hello world!</p>
)
}
describe('ProjectPage', () => {
const background = {
src: 'the project background image url'
};
it('should render without crashing', () => {
shallow(<ProjectPage><Page /></ProjectPage>);
});
it('should render the project nav bar', () => {
const wrapper = shallow(<ProjectPage><Page /></ProjectPage>);
const navElement = wrapper.find('ProjectNavbar').first();
expect(navElement).to.have.lengthOf(1);
});
it('should receive a background, project and workflow props', () => {
const wrapper = mount(<ProjectPage background={background} project={project} workflow={workflow} ><Page /></ProjectPage>);
expect(wrapper.props().background).to.equal(background);
expect(wrapper.props().project).to.equal(project);
expect(wrapper.props().workflow).to.equal(workflow);
});
describe('with a launch-approved project', () => {
it('should not render the Zooniverse disclaimer.');
});
describe('without approval', () => {
it('should render the Zooniverse disclaimer.');
it('should render the disclaimer immediately after its children.')
});
});
| import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import { project, workflow } from '../dev-classifier/mock-data';
import ProjectPage from './project-page';
describe('ProjectPage', () => {
const background = {
src: 'the project background image url'
};
it('should render without crashing', () => {
shallow(<ProjectPage />);
});
it('should render the project nav bar', () => {
const wrapper = shallow(<ProjectPage />);
const navElement = wrapper.find('ProjectNavbar').first();
expect(navElement).to.have.lengthOf(1);
});
it('should receive a background, project and workflow props', () => {
const wrapper = mount(<ProjectPage background={background} project={project} workflow={workflow} />);
expect(wrapper.props().background).to.equal(background);
expect(wrapper.props().project).to.equal(project);
expect(wrapper.props().workflow).to.equal(workflow);
});
describe('with a launch-approved project', () => {
it('should not render the Zooniverse disclaimer.');
});
describe('without approval', () => {
it('should render the Zooniverse disclaimer.');
it('should render the disclaimer immediately after its children.')
});
});
|
Add common ignore list per README | # pylint: disable=C0103,C0111,R0903,R0904,W0212,W0232
# Copyright (c) 2011-2013 Rackspace Hosting
# All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Tests for common config."""
import unittest
from waldo.contrib import config
class TestParsers(unittest.TestCase):
def test_comma_separated_strings(self):
expected = ['1', '2', '3']
result = config.comma_separated_strings("1,2,3")
self.assertItemsEqual(result, expected)
def test_format_comma_separated_pairs(self):
expected = dict(A='1', B='2', C='3')
result = config.comma_separated_pairs("A=1,B=2,C=3")
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| # pylint: disable=R0904,W0212
# Copyright (c) 2011-2013 Rackspace Hosting
# All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Tests for common config."""
import unittest
from waldo.contrib import config
class TestParsers(unittest.TestCase):
def test_comma_separated_strings(self):
expected = ['1', '2', '3']
result = config.comma_separated_strings("1,2,3")
self.assertItemsEqual(result, expected)
def test_format_comma_separated_pairs(self):
expected = dict(A='1', B='2', C='3')
result = config.comma_separated_pairs("A=1,B=2,C=3")
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
|
Fix the name of the logger | package org.fluentd.logger.sender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Deque;
import java.util.LinkedList;
/**
* Calculate exponential delay for reconnecting
*/
public class ConstantDelayReconnector implements Reconnector {
private static final Logger LOG = LoggerFactory.getLogger(ConstantDelayReconnector.class);
private double wait = 50; // Default wait to 50 ms
private int maxErrorHistorySize = 100;
private Deque<Long> errorHistory = new LinkedList<Long>();
public ConstantDelayReconnector() {
errorHistory = new LinkedList<Long>();
}
public ConstantDelayReconnector(int wait) {
this.wait = wait;
errorHistory = new LinkedList<Long>();
}
public void addErrorHistory(long timestamp) {
errorHistory.addLast(timestamp);
if (errorHistory.size() > maxErrorHistorySize) {
errorHistory.removeFirst();
}
}
public boolean isErrorHistoryEmpty() {
return errorHistory.isEmpty();
}
public void clearErrorHistory() {
errorHistory.clear();
}
public boolean enableReconnection(long timestamp) {
int size = errorHistory.size();
if (size == 0) {
return true;
}
return (!(timestamp - errorHistory.getLast() < wait));
}
} | package org.fluentd.logger.sender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Deque;
import java.util.LinkedList;
/**
* Calculate exponential delay for reconnecting
*/
public class ConstantDelayReconnector implements Reconnector {
private static final Logger LOG = LoggerFactory.getLogger(ExponentialDelayReconnector.class);
private double wait = 50; // Default wait to 50 ms
private int maxErrorHistorySize = 100;
private Deque<Long> errorHistory = new LinkedList<Long>();
public ConstantDelayReconnector() {
errorHistory = new LinkedList<Long>();
}
public ConstantDelayReconnector(int wait) {
this.wait = wait;
errorHistory = new LinkedList<Long>();
}
public void addErrorHistory(long timestamp) {
errorHistory.addLast(timestamp);
if (errorHistory.size() > maxErrorHistorySize) {
errorHistory.removeFirst();
}
}
public boolean isErrorHistoryEmpty() {
return errorHistory.isEmpty();
}
public void clearErrorHistory() {
errorHistory.clear();
}
public boolean enableReconnection(long timestamp) {
int size = errorHistory.size();
if (size == 0) {
return true;
}
return (!(timestamp - errorHistory.getLast() < wait));
}
} |
Make back button more visible | import React from 'react';
import { connect } from 'react-redux';
class BackButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.context.history.goBack();
}
render() {
const divStyle = {
backgroundColor: 'white',
opacity: '0.7',
width: '75px',
position: 'fixed',
zIndex: 99,
left: '90px',
bottom: '10px',
height: '75px',
textAlign: 'center',
borderRadius: '50%',
boxShadow: '5px 5px 5px rgba(204, 197, 185, 0.7)',
cursor: 'pointer',
};
const arrowStyle = {
marginTop: '10px',
fontSize: '2em',
color: '#7AC29A',
position: 'relative',
top: '20px',
};
return (
<div onClick={this.handleClick} style={divStyle}>
<i style={arrowStyle} className="ti-arrow-left"></i>
</div>
);
}
}
BackButton.contextTypes = {
history: React.PropTypes.object,
};
export default connect()(BackButton);
| import React from 'react';
import { connect } from 'react-redux';
class BackButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.context.history.goBack();
}
render() {
const divStyle = {
backgroundColor: 'white',
opacity: '0.7',
width: '75px',
position: 'fixed',
zIndex: 99,
left: '90px',
bottom: '10px',
height: '75px',
textAlign: 'center',
borderRadius: '50%',
boxShadow: '4px 4px 4px rgba(204, 197, 185, 0.4)',
cursor: 'pointer',
};
const arrowStyle = {
marginTop: '10px',
fontSize: '2em',
color: '#7AC29A',
position: 'relative',
top: '20px',
};
return (
<div onClick={this.handleClick} style={divStyle}>
<i style={arrowStyle} className="ti-arrow-left"></i>
</div>
);
}
}
BackButton.contextTypes = {
history: React.PropTypes.object,
};
export default connect()(BackButton);
|
Fix "Trying to get property of non-object" | <?php
namespace App\Events;
use App\Comment;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class CommentCreated implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $comment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Comment $comment)
{
$this->comment = $comment;
$this->dontBroadcastToCurrentUser();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return ['submission.'.optional($this->comment->submission)->slug];
}
}
| <?php
namespace App\Events;
use App\Comment;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class CommentCreated implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $comment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Comment $comment)
{
$this->comment = $comment;
$this->dontBroadcastToCurrentUser();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return ['submission.'.$this->comment->submission->slug];
}
}
|
Return self in Pipeline add_after and add_before | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is not None:
self.convert_token = convert_token
else:
self.convert_token = lambda x: x
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
| class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is not None:
self.convert_token = convert_token
else:
self.convert_token = lambda x: x
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
|
Fix post insertion path for organization, better status codes | const app = require('express')();
const Organization = require('../models/Organization');
app.get('/', (req, res) => {
Organization.find()
.then(orgs => {
res.json(orgs);
});
});
app.get('/:id', (req, res) => {
if(!req.params.id) return res.sendStatus(400);
Organization.findOne({ _id: req.params.id })
.then((org) => {
if(!org) return res.sendStatus(404);
res.json(org.toPlainObject())
})
.catch((err) => res.sendStatus(500));
});
app.post('/', (req, res) => {
if(!req.body.name) return res.sendStatus(400);
let organization = new Organization({
name: req.body.name,
president: req.body.president,
logo: req.body.logo
});
organization.save()
.then((org) => { res.json(org.toPlainObject()) });
});
module.exports = app;
| const app = require('express')();
const Organization = require('../models/Organization');
app.get('/', (req, res) => {
Organization.find()
.then(orgs => {
res.json(orgs);
});
});
app.get('/:id', (req, res) => {
if(!req.params.id) return res.sendStatus(400);
Organization.findOne({ _id: req.params.id })
.then((org) => {
if(!org) return res.sendStatus(200);
res.json(org.toPlainObject())
});
});
app.post('/organization', (req, res) => {
if(!req.body.name) return res.sendStatus(400);
let organization = new Organization({
name: req.body.name,
president: req.body.president,
logo: req.body.logo
});
organization.save()
.then((org) => { res.json(org.toPlainObject()) });
});
module.exports = app;
|
Remove unused code block which is not affect hash calculation | package com.iyzipay;
import com.iyzipay.exception.HttpClientException;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashGenerator {
private HashGenerator() {
}
public static String generateHash(String apiKey, String secretKey, String randomString, Object request) {
StringBuilder hash = new StringBuilder();
byte[] result = null;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA1");
String input = apiKey + randomString + secretKey + request;
result = crypt.digest(input.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new HttpClientException("Hash cannot be generated", e);
}
return DatatypeConverter.printBase64Binary(result);
}
}
| package com.iyzipay;
import com.iyzipay.exception.HttpClientException;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashGenerator {
private HashGenerator() {
}
public static String generateHash(String apiKey, String secretKey, String randomString, Object request) {
StringBuilder hash = new StringBuilder();
byte[] result = null;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA1");
String input = apiKey + randomString + secretKey + request;
result = crypt.digest(input.getBytes());
for (int i = 0; i < result.length; i++) {
hash.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
throw new HttpClientException("Hash cannot be generated", e);
}
return DatatypeConverter.printBase64Binary(result);
}
}
|
Fix style: not foo in [] => foo not in | """Provides helper functions for interactive prompts
Written by Peter Duerr
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyexperiment import state
from pyexperiment import conf
def embed_interactive(**kwargs):
"""Embed an interactive terminal into a running python process
"""
if 'state' not in kwargs:
kwargs['state'] = state
if 'conf' not in kwargs:
kwargs['conf'] = conf
try:
import IPython
ipython_config = IPython.Config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
if IPython.__version__ == '1.2.1':
IPython.embed(config=ipython_config,
banner1='',
user_ns=kwargs)
else:
IPython.embed(config=ipython_config,
banner1='',
local_ns=kwargs)
except ImportError:
import readline # pylint: disable=unused-variable
import code
code.InteractiveConsole(kwargs).interact()
| """Provides helper functions for interactive prompts
Written by Peter Duerr
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyexperiment import state
from pyexperiment import conf
def embed_interactive(**kwargs):
"""Embed an interactive terminal into a running python process
"""
if not 'state' in kwargs:
kwargs['state'] = state
if not 'conf' in kwargs:
kwargs['conf'] = conf
try:
import IPython
ipython_config = IPython.Config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
if IPython.__version__ == '1.2.1':
IPython.embed(config=ipython_config,
banner1='',
user_ns=kwargs)
else:
IPython.embed(config=ipython_config,
banner1='',
local_ns=kwargs)
except ImportError:
import readline # pylint: disable=unused-variable
import code
code.InteractiveConsole(kwargs).interact()
|
Fix indent for the comment of source code | import hljs from './assets/lib/highlightjs/highlight.pack';
import Parallax from './js/parallax';
import Share from './js/share';
require('./sass/main.scss');
/**
* Enable parallax for the post list
*/
Array.prototype.forEach.call(document.querySelectorAll('.post-item'), elm => new Parallax(elm, 50));
/**
* Enable share buttons for the post detail page
*/
if (document.querySelector('.post-detail-wrapper .post-share')) {
new Share(document.querySelector('.post-detail-wrapper .post-share')).render();
}
/**
* Set target to new window for all hyperlinks in the post content
*/
(() => {
const links = document.querySelectorAll('.post-content a');
Array.prototype.forEach.call(links, (link) => {
if (/^(https?|ftp|\/)/.test(link.href)) {
link.setAttribute('target', '_blank');
}
});
})();
/**
* Enable hightlighjs
*/
hljs.initHighlightingOnLoad();
| import hljs from './assets/lib/highlightjs/highlight.pack';
import Parallax from './js/parallax';
import Share from './js/share';
require('./sass/main.scss');
/**
* Enable parallax for the post list
*/
Array.prototype.forEach.call(document.querySelectorAll('.post-item'), elm => new Parallax(elm, 50));
/**
* Enable share buttons for the post detail page
*/
if (document.querySelector('.post-detail-wrapper .post-share')) {
new Share(document.querySelector('.post-detail-wrapper .post-share')).render();
}
/**
* Set target to new windows for all hyperlinks in the post content
*/
(() => {
const links = document.querySelectorAll('.post-content a');
Array.prototype.forEach.call(links, (link) => {
if (/^(https?|ftp|\/)/.test(link.href)) {
link.setAttribute('target', '_blank');
}
});
})();
/**
* Enable hightlighjs
*/
hljs.initHighlightingOnLoad();
|
Fix template name on entry home page (/) on detail page | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwargs.get('channel__long_slug', 'home')
return 'channel/{0}.html'.format(long_slug)
@property
def queryset(self):
if not self.kwargs.get('channel__long_slug'):
return Post.objects.filter(channel__homepage=True).all()
return Post.objects.filter(
channel__long_slug=self.kwargs['channel__long_slug']).all()
class OppsDetail(DetailView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwargs.get('channel__long_slug', 'home')
return 'article/{0}/{1}.html'.format(long_slug, self.kwargs['slug'])
@property
def queryset(self):
long_slug = self.kwargs.get('channel__long_slug', 'home')
return Post.objects.filter(channel__long_slug=long_slug,
slug=self.kwargs['slug']).all()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwargs.get('channel__long_slug', 'home')
return 'channel/{0}.html'.format(long_slug)
@property
def queryset(self):
if not self.kwargs.get('channel__long_slug'):
return Post.objects.filter(channel__homepage=True).all()
return Post.objects.filter(
channel__long_slug=self.kwargs['channel__long_slug']).all()
class OppsDetail(DetailView):
context_object_name = "context"
@property
def template_name(self):
return 'article/{0}/{1}.html'.format(
self.kwargs['channel__long_slug'], self.kwargs['slug'])
@property
def queryset(self):
long_slug = self.kwargs.get('channel__long_slug', 'home')
return Post.objects.filter(channel__long_slug=long_slug,
slug=self.kwargs['slug']).all()
|
Fix fatal error when visible section is a descendant of invisible one. | "use strict";
/**
* to_tree(source[, root = null]) -> array
* - source (array): array of sections
* - root (mongodb.BSONPure.ObjectID|String): id of common root for result first level.
*
* Build sections tree (nested) from flat sorted array.
**/
module.exports = function (source, root) {
var result = [];
var nodes = {};
source.forEach(function (node) {
node.child_list = [];
nodes[node._id.toString()] = node;
});
root = !!root ? root.toString() : null;
// set children links for all nodes
// and collect root children to result array
source.forEach(function (node) {
node.parent = !!node.parent ? node.parent.toString() : null;
if (node.parent === root) {
result.push(node);
} else if (node.parent !== null) {
// Add child node if parent node actually exists.
// It may not if we deal with nested forum sections where visible
// section is a descendant of invisible section.
if (nodes[node.parent]) {
nodes[node.parent].child_list.push(node);
}
}
});
return result;
};
| "use strict";
/**
* to_tree(source[, root = null]) -> array
* - source (array): array of sections
* - root (mongodb.BSONPure.ObjectID|String): id of common root for result first level.
*
* Build sections tree (nested) from flat sorted array.
**/
module.exports = function (source, root) {
var result = [];
var nodes = {};
source.forEach(function (node) {
node.child_list = [];
nodes[node._id.toString()] = node;
});
root = !!root ? root.toString() : null;
// set children links for all nodes
// and collect root children to result array
source.forEach(function (node) {
node.parent = !!node.parent ? node.parent.toString() : null;
if (node.parent === root) {
result.push(node);
}
else {
if (node.parent !== null) {
nodes[node.parent].child_list.push(node);
}
}
});
return result;
};
|
[SwiftmailerBundle] Fix expected default value in SwiftmailerExtension unit test | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SwiftmailerBundle\Tests\DependencyInjection;
use Symfony\Bundle\SwiftmailerBundle\Tests\TestCase;
use Symfony\Bundle\SwiftmailerBundle\DependencyInjection\SwiftmailerExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class SwiftmailerExtensionTest extends TestCase
{
public function testConfigLoad()
{
$container = new ContainerBuilder();
$loader = new SwiftmailerExtension();
$loader->load(array(array()), $container);
$this->assertEquals('Swift_Mailer', $container->getParameter('swiftmailer.class'), '->mailerLoad() loads the swiftmailer.xml file if not already loaded');
$loader->load(array(array('transport' => 'sendmail')), $container);
$this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options');
$loader->load(array(array()), $container);
$this->assertEquals('smtp', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() provides default values for configuration options');
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SwiftmailerBundle\Tests\DependencyInjection;
use Symfony\Bundle\SwiftmailerBundle\Tests\TestCase;
use Symfony\Bundle\SwiftmailerBundle\DependencyInjection\SwiftmailerExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class SwiftmailerExtensionTest extends TestCase
{
public function testConfigLoad()
{
$container = new ContainerBuilder();
$loader = new SwiftmailerExtension();
$loader->load(array(array()), $container);
$this->assertEquals('Swift_Mailer', $container->getParameter('swiftmailer.class'), '->mailerLoad() loads the swiftmailer.xml file if not already loaded');
$loader->load(array(array('transport' => 'sendmail')), $container);
$this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options');
$loader->load(array(array()), $container);
$this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options');
}
}
|
Make public - otherwise not visible to the UI (JSP) | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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 matt_richardson.teamCity.buildTriggers.octopusDeploy;
public final class OctopusBuildTriggerUtil {
public static String OCTOPUS_URL = "octopus.build.trigger.url";
public static String OCTOPUS_APIKEY = "octopus.build.trigger.apikey";
public static String OCTOPUS_PROJECT_ID = "octopus.build.trigger.project.url";
public static String OCTOPUS_TRIGGER_ONLY_ON_SUCCESSFUL_DEPLOYMENT = "octopus.build.trigger.only.on.successful.deployment";
public static String POLL_INTERVAL_PROP = "octops.build.trigger.poll.interval";
public static final Integer DEFAULT_POLL_INTERVAL = 30; // seconds
public static final String CONNECTION_TIMEOUT_PROP = "octopus.build.trigger.connection.timeout";
public static final Integer DEFAULT_CONNECTION_TIMEOUT = 60 * 1000; // milliseconds
}
| /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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 matt_richardson.teamCity.buildTriggers.octopusDeploy;
final class OctopusBuildTriggerUtil {
public static String OCTOPUS_URL = "octopus.build.trigger.url";
public static String OCTOPUS_APIKEY = "octopus.build.trigger.apikey";
public static String OCTOPUS_PROJECT_ID = "octopus.build.trigger.project.url";
public static String OCTOPUS_TRIGGER_ONLY_ON_SUCCESSFUL_DEPLOYMENT = "octopus.build.trigger.only.on.successful.deployment";
public static String POLL_INTERVAL_PROP = "octops.build.trigger.poll.interval";
public static final Integer DEFAULT_POLL_INTERVAL = 30; // seconds
public static final String CONNECTION_TIMEOUT_PROP = "octopus.build.trigger.connection.timeout";
public static final Integer DEFAULT_CONNECTION_TIMEOUT = 60 * 1000; // milliseconds
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.