text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Use real readthedocs API again | // Main Module for searchthedocs demo
define(function (require) {
var _ = require('underscore'),
$ = require('jquery'),
SearchTheDocsView = require('searchthedocs/src/searchthedocs');
var searchthedocs_main = function() {
var search_options = {
default_endpoint: 'sections',
endpoints: {
sections: {
data_type: 'jsonp',
default_params: {format: 'jsonp'},
api_url: 'http://readthedocs.org/api/v2/search/section/',
content_url_format:
'http://{{domain}}.readthedocs.org/en/'
+ '{{version}}/{{path}}.html#{{page_id}}',
param_map: {
search: 'q',
domain: 'project'
},
result_format: {
records_path: 'results.hits.hits',
record_format: {
// Fields used in sidebar display
domain: 'fields.project',
title: 'fields.title',
// Fields used to build record_url
version: 'fields.version',
path: 'fields.path',
page_id: 'fields.page_id'
}
},
}
}
};
window.searchtd = new SearchTheDocsView({
brand: 'searchthedocs',
brand_href: '#',
search_options: search_options
});
$('#searchthedocs-container').append(searchtd.render().el);
};
return searchthedocs_main;
});
| // Main Module for searchthedocs demo
define(function (require) {
var _ = require('underscore'),
$ = require('jquery'),
SearchTheDocsView = require('searchthedocs/src/searchthedocs');
var searchthedocs_main = function() {
var search_options = {
default_endpoint: 'sections',
endpoints: {
sections: {
data_type: 'json',
//default_params: {format: 'jsonp'},
api_url: 'http://searchtd.dev:8000/api/v2/search/section/',
record_url:
'http://{{domain}}.readthedocs.org/en/'
+ '{{version}}/{{path}}.html#{{page_id}}',
param_map: {
search: 'q',
domain: 'project'
},
result_format: {
records_path: 'results.hits.hits',
record_format: {
// Fields used in sidebar display
domain: 'fields.project',
title: 'fields.title',
// Fields used to build record_url
version: 'fields.version',
path: 'fields.path',
page_id: 'fields.page_id'
}
},
}
}
};
window.searchtd = new SearchTheDocsView({
brand: 'searchthedocs',
brand_href: '#',
search_options: search_options
});
$('#searchthedocs-container').append(searchtd.render().el);
};
return searchthedocs_main;
});
|
Update the path and the url | <?php
/*
* This file is part of the AlphaLemonThemeEngineBundle and it is distributed
* under the MIT License. To use this bundle you must leave
* intact this copyright notice.
*
* Copyright (c) AlphaLemon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* For extra documentation and help please visit http://alphalemon.com
*
* @license MIT License
*/
namespace AlphaLemon\ElFinderBundle\Core\Connector;
/**
* Configures the connector
*
* @author AlphaLemon
*/
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
protected function configure()
{
$request = $this->container->get('request');
$options = array(
'roots' => array(
array(
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => 'bundles/alphalemonelfinder/vendor/ElFinder/files/', // path to files (REQUIRED)
'URL' => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/vendor/ElFinder/files/', // URL to files (REQUIRED)
'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL)
)
)
);
return $options;
}
}
| <?php
/*
* This file is part of the AlphaLemonThemeEngineBundle and it is distributed
* under the MIT License. To use this bundle you must leave
* intact this copyright notice.
*
* Copyright (c) AlphaLemon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* For extra documentation and help please visit http://alphalemon.com
*
* @license MIT License
*/
namespace AlphaLemon\ElFinderBundle\Core\Connector;
/**
* Configures the connector
*
* @author AlphaLemon
*/
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
protected function configure()
{
$request = $this->container->get('request');
$options = array(
'roots' => array(
array(
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => 'bundles/alphalemonelfinder/files/', // path to files (REQUIRED)
'URL' => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/files/', // URL to files (REQUIRED)
'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL)
)
)
);
return $options;
}
}
|
Change docstrong to reflect actual endpoint | from django.http import (HttpResponse,
HttpResponseNotFound)
from django.contrib.gis.measure import D
from working_waterfronts.working_waterfronts_api.models import PointOfInterest
from working_waterfronts.working_waterfronts_api.functions import get_lat_long_prox
import json
from .serializer import ObjectSerializer
def poi_list(request):
"""
*/pois/*
List all pointsofinterest in the database. There is no order to this list,
only whatever is returned by the database.
"""
error = {
'status': False,
'name': None,
'text': None,
'level': None,
'debug': None
}
data = {}
point, proximity, limit, error = get_lat_long_prox(request, error)
if point:
poi_list = PointOfInterest.objects.filter(
location__distance_lte=(point, D(mi=proximity)))[:limit]
else:
poi_list = PointOfInterest.objects.all()[:limit]
if not poi_list:
error = {
"status": True,
"name": "No PointsOfInterest",
"text": "No PointsOfInterest found",
"level": "Information",
"debug": ""
}
serializer = ObjectSerializer()
data = {
"pointsofinterest": json.loads(
serializer.serialize(
poi_list,
use_natural_foreign_keys=True
)
),
"error": error
}
return HttpResponse(json.dumps(data), content_type="application/json")
| from django.http import (HttpResponse,
HttpResponseNotFound)
from django.contrib.gis.measure import D
from working_waterfronts.working_waterfronts_api.models import PointOfInterest
from working_waterfronts.working_waterfronts_api.functions import get_lat_long_prox
import json
from .serializer import ObjectSerializer
def poi_list(request):
"""
*/pointsofinterest/*
List all pointsofinterest in the database. There is no order to this list,
only whatever is returned by the database.
"""
error = {
'status': False,
'name': None,
'text': None,
'level': None,
'debug': None
}
data = {}
point, proximity, limit, error = get_lat_long_prox(request, error)
if point:
poi_list = PointOfInterest.objects.filter(
location__distance_lte=(point, D(mi=proximity)))[:limit]
else:
poi_list = PointOfInterest.objects.all()[:limit]
if not poi_list:
error = {
"status": True,
"name": "No PointsOfInterest",
"text": "No PointsOfInterest found",
"level": "Information",
"debug": ""
}
serializer = ObjectSerializer()
data = {
"pointsofinterest": json.loads(
serializer.serialize(
poi_list,
use_natural_foreign_keys=True
)
),
"error": error
}
return HttpResponse(json.dumps(data), content_type="application/json")
|
Handle 404 when user doesn't exist in SIS | <?php
namespace UBC\Exam\MainBundle\EventListener;
use GuzzleHttp\Exception\ClientException;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use UBC\LtCommons\Service\StudentService;
class CourseInjectionListener {
protected $session;
protected $service;
public function __construct(Session $session, StudentService $service)
{
$this->session = $session;
$this->service = $service;
}
public function onLoginSuccess(InteractiveLoginEvent $event)
{
$courses = array();
$user = $event->getAuthenticationToken()->getUser();
// ignore the in_memory user
if ($user instanceof \UBC\Exam\MainBundle\Entity\User) {
$id = $user->getPuid();
if (!empty($id)) {
try {
$sections = $this->service->getStudentCurrentSections($id);
} catch (ClientException $e) {
// the user may not exists in SIS
if (404 == $e->getResponse()->getStatusCode()) {
$sections = array();
} else {
throw $e;
}
}
foreach($sections as $s) {
$key = $s->getCourse()->getCode() . ' ' . $s->getCourse()->getNumber();
$courses[$key] = $s->getCourse();
}
}
}
$this->session->set('courses', $courses);
}
} | <?php
namespace UBC\Exam\MainBundle\EventListener;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use UBC\LtCommons\Service\StudentService;
class CourseInjectionListener {
protected $session;
protected $service;
public function __construct(Session $session, StudentService $service)
{
$this->session = $session;
$this->service = $service;
}
public function onLoginSuccess(InteractiveLoginEvent $event)
{
$courses = array();
$user = $event->getAuthenticationToken()->getUser();
// ignore the in_memory user
if ($user instanceof \UBC\Exam\MainBundle\Entity\User) {
$id = $user->getPuid();
if (!empty($id)) {
// TODO don't throw exceptions on 404
$sections = $this->service->getStudentCurrentSections($id);
foreach($sections as $s) {
$key = $s->getCourse()->getCode() . ' ' . $s->getCourse()->getNumber();
$courses[$key] = $s->getCourse();
}
}
}
$this->session->set('courses', $courses);
}
} |
Make it clear that we are using an email as username | <?php
namespace SumoCoders\FrameworkMultiUserBundle\Security;
use SumoCoders\FrameworkMultiUserBundle\User\Interfaces\User;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class ObjectUserEmailProvider implements UserProviderInterface
{
/** @var UserRepositoryCollection */
private $userRepositoryCollection;
/**
* @param UserRepositoryCollection $userRepositoryCollection
*/
public function __construct(UserRepositoryCollection $userRepositoryCollection)
{
$this->userRepositoryCollection = $userRepositoryCollection;
}
public function loadUserByUsername($emailAddress)
{
foreach ($this->userRepositoryCollection->all() as $repository) {
$user = $repository->findByEmailAddress($emailAddress);
if ($user instanceof User) {
return $user;
}
}
// Since we are using the email as username we keep this exception since it is a part of symfony
throw new UsernameNotFoundException(
sprintf('Email "%s" does not exist.', $emailAddress)
);
}
public function refreshUser(UserInterface $user)
{
if (!$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getEmail());
}
public function supportsClass($class)
{
return $this->userRepositoryCollection->supportsClass($class);
}
}
| <?php
namespace SumoCoders\FrameworkMultiUserBundle\Security;
use SumoCoders\FrameworkMultiUserBundle\User\Interfaces\User;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class ObjectUserEmailProvider implements UserProviderInterface
{
/** @var UserRepositoryCollection */
private $userRepositoryCollection;
/**
* @param UserRepositoryCollection $userRepositoryCollection
*/
public function __construct(UserRepositoryCollection $userRepositoryCollection)
{
$this->userRepositoryCollection = $userRepositoryCollection;
}
public function loadUserByUsername($username)
{
foreach ($this->userRepositoryCollection->all() as $repository) {
$user = $repository->findByEmailAddress($username);
if ($user instanceof User) {
return $user;
}
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
public function refreshUser(UserInterface $user)
{
if (!$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getEmail());
}
public function supportsClass($class)
{
return $this->userRepositoryCollection->supportsClass($class);
}
}
|
Reduce gemfire server logging to warning | module.exports = function(grunt) {
grunt.initConfig(
{
pkg: grunt.file.readJSON('package.json'),
shell: {
rebuild: {
command: 'npm install --build-from-source'
},
benchmarkNode: {
command: 'node benchmark/node/benchmark.js'
},
startServer: {
command: 'cd tmp/gemfire && gfsh start server --dir=server --log-level=warning --cache-xml-file=../../benchmark/xml/BenchmarkServer.xml --name=server'
},
stopServer: {
command: 'cd tmp/gemfire && gfsh stop server --dir=server',
},
benchmarkJava: {
command: [
'cd benchmark/java',
'./gradlew clean run -q'
].join(" && ")
}
},
jasmine_node: {
all: ['spec/']
}
}
);
grunt.loadNpmTasks('grunt-jasmine-node');
grunt.loadNpmTasks('grunt-shell');
grunt.registerTask('build', ['shell:rebuild']);
grunt.registerTask('test', ['jasmine_node:all']);
grunt.registerTask('server:start', ['shell:startServer']);
grunt.registerTask('server:stop', ['shell:stopServer']);
grunt.registerTask('server:restart', ['server:stop', 'server:start']);
grunt.registerTask('benchmark:node', ['build', 'shell:benchmarkNode']);
grunt.registerTask('benchmark:java', ['shell:benchmarkJava']);
grunt.registerTask('benchmark', ['benchmark:node', 'benchmark:java']);
grunt.registerTask('default', ['build', 'test']);
};
| module.exports = function(grunt) {
grunt.initConfig(
{
pkg: grunt.file.readJSON('package.json'),
shell: {
rebuild: {
command: 'npm install --build-from-source'
},
benchmarkNode: {
command: 'node benchmark/node/benchmark.js'
},
startServer: {
command: 'cd tmp/gemfire && gfsh start server --dir=server --cache-xml-file=../../benchmark/xml/BenchmarkServer.xml --name=server'
},
stopServer: {
command: 'cd tmp/gemfire && gfsh stop server --dir=server',
},
benchmarkJava: {
command: [
'cd benchmark/java',
'./gradlew clean run -q'
].join(" && ")
}
},
jasmine_node: {
all: ['spec/']
}
}
);
grunt.loadNpmTasks('grunt-jasmine-node');
grunt.loadNpmTasks('grunt-shell');
grunt.registerTask('build', ['shell:rebuild']);
grunt.registerTask('test', ['jasmine_node:all']);
grunt.registerTask('server:start', ['shell:startServer']);
grunt.registerTask('server:stop', ['shell:stopServer']);
grunt.registerTask('server:restart', ['server:stop', 'server:start']);
grunt.registerTask('benchmark:node', ['build', 'shell:benchmarkNode']);
grunt.registerTask('benchmark:java', ['shell:benchmarkJava']);
grunt.registerTask('benchmark', ['benchmark:node', 'benchmark:java']);
grunt.registerTask('default', ['build', 'test']);
};
|
Define subprocesses in the context of the root process. Maybe this is more readable? | from simpy import Simulation, InterruptedException
def test_simple_process():
def pem(ctx, result):
while True:
result.append(ctx.now)
yield ctx.wait(1)
result = []
Simulation(pem, result).simulate(until=4)
assert result == [0, 1, 2, 3]
def test_interrupt():
def root(ctx):
def pem(ctx):
try:
yield ctx.wait(10)
raise RuntimeError('Expected an interrupt')
except InterruptedException:
pass
process = ctx.fork(pem)
yield ctx.wait(5)
process.interrupt()
Simulation(root).simulate(until=20)
def test_wait_for_process():
def root(ctx):
def pem(ctx):
yield ctx.wait(10)
yield ctx.wait(ctx.fork(pem))
assert ctx.now == 10
Simulation(root).simulate(until=20)
def test_process_result():
def root(ctx):
def pem(ctx):
yield ctx.wait(10)
ctx.exit('oh noes, i am dead x_x')
result = yield ctx.wait(ctx.fork(pem))
assert result == 'oh noes, i am dead x_x'
Simulation(root).simulate(until=20)
| from simpy import Simulation, InterruptedException
def test_simple_process():
def pem(ctx, result):
while True:
result.append(ctx.now)
yield ctx.wait(1)
result = []
Simulation(pem, result).simulate(until=4)
assert result == [0, 1, 2, 3]
def test_interrupt():
def pem(ctx):
try:
yield ctx.wait(10)
raise RuntimeError('Expected an interrupt')
except InterruptedException:
pass
def root(ctx):
process = ctx.fork(pem)
yield ctx.wait(5)
process.interrupt()
Simulation(root).simulate(until=20)
def test_wait_for_process():
def pem(ctx):
yield ctx.wait(10)
def root(ctx):
yield ctx.wait(ctx.fork(pem))
assert ctx.now == 10
Simulation(root).simulate(until=20)
def test_process_result():
def pem(ctx):
yield ctx.wait(10)
ctx.exit('oh noes, i am dead x_x')
def root(ctx):
result = yield ctx.wait(ctx.fork(pem))
assert result == 'oh noes, i am dead x_x'
Simulation(root).simulate(until=20)
|
Update requirement to Python 3.6 | import sys
from setuptools import setup
if sys.version_info < (3, 6):
raise Exception("Python 3.6 or higher is required. Your version is %s." % sys.version)
long_description = open('README.rst').read()
__version__ = ""
exec(open('ehforwarderbot/__version__.py').read())
setup(
name='ehforwarderbot',
packages=['ehforwarderbot'],
version=__version__,
description='An extensible message tunneling chat bot framework.',
long_description=long_description,
author='Eana Hufwe',
author_email='[email protected]',
url='https://github.com/blueset/ehforwarderbot',
license='GPLv3',
python_requires='>=3.6',
keywords=['EFB', 'EH Forwarder Bot', 'Chat tunneling', 'IM', 'messaging'],
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Communications :: Chat",
"Topic :: Software Development :: Libraries :: Application Frameworks",
"Topic :: Utilities"
],
install_requires=[
"PyYaml"
],
entry_points={
"console_scripts": ['ehforwarderbot = ehforwarderbot.__main__:main']
}
)
| import sys
from setuptools import setup
if sys.version_info < (3, 5):
raise Exception("Python 3.5 or higher is required. Your version is %s." % sys.version)
long_description = open('README.rst').read()
__version__ = ""
exec(open('ehforwarderbot/__version__.py').read())
setup(
name='ehforwarderbot',
packages=['ehforwarderbot'],
version=__version__,
description='An extensible message tunneling chat bot framework.',
long_description=long_description,
author='Eana Hufwe',
author_email='[email protected]',
url='https://github.com/blueset/ehforwarderbot',
license='GPLv3',
python_requires='>=3.6',
keywords=['EFB', 'EH Forwarder Bot', 'Chat tunneling', 'IM', 'messaging'],
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Communications :: Chat",
"Topic :: Software Development :: Libraries :: Application Frameworks",
"Topic :: Utilities"
],
install_requires=[
"PyYaml"
],
entry_points={
"console_scripts": ['ehforwarderbot = ehforwarderbot.__main__:main']
}
)
|
Remove remote receipt validation as we do not have it | angular.module('focus.services')
.factory('Store', function(AudioLibrary) {
var functions = {
initStore: function (){
console.log("Initializing Store")
if (!window.store) {
console.log('Store not available');
return;
}
var platform = device.platform.toLowerCase();
document.getElementsByTagName('body')[0].className = platform;
// Enable maximum logging level
//store.verbosity = store.DEBUG;
// Enable remote receipt validation
//store.validator = "https://api.fovea.cc:1982/check-purchase";
console.log('Register Products');
var sounds = AudioLibrary.getAllSounds();
sounds.map(function(sound) {
// Register all the sound tracks in the store\
store.register({
id: sound.id,
alias: sound.title, //todo: dont use title as alias?
type: store.NON_CONSUMABLE
});
store.when(sound.id).approved(function(product) {
console.log("purchased!")
product.finish();
});
});
store.refresh();
},
/*
Checks if the track with ID: trackID is owned by the user
*/
trackOwned: function(trackID) {
var p = store.get(trackID);
return p.owned;
},
/*
Purchases the track with ID: trackID
*/
purchaseTrack: function(trackID) {
var p = store.get(trackID);
console.log("Purchasing track", trackID);
store.order(p).then(console.log(trackID, "ordered"));
}
}
return functions;
});
| angular.module('focus.services')
.factory('Store', function(AudioLibrary) {
var functions = {
initStore: function (){
console.log("Initializing Store")
if (!window.store) {
console.log('Store not available');
return;
}
var platform = device.platform.toLowerCase();
document.getElementsByTagName('body')[0].className = platform;
// Enable maximum logging level
//store.verbosity = store.DEBUG;
// Enable remote receipt validation
store.validator = "https://api.fovea.cc:1982/check-purchase";
console.log('Register Products');
var sounds = AudioLibrary.getAllSounds();
sounds.map(function(sound) {
// Register all the sound tracks in the store\
store.register({
id: sound.id,
alias: sound.title, //todo: dont use title as alias?
type: store.NON_CONSUMABLE
});
store.when(sound.id).approved(function(product) {
console.log("purchased!")
product.finish();
});
});
store.refresh();
},
/*
Checks if the track with ID: trackID is owned by the user
*/
trackOwned: function(trackID) {
var p = store.get(trackID);
return p.owned;
},
/*
Purchases the track with ID: trackID
*/
purchaseTrack: function(trackID) {
var p = store.get(trackID);
console.log("Purchasing track", trackID);
store.order(p).then(console.log(trackID, "ordered"));
}
}
return functions;
});
|
Fix power entering the relay via FE or TESLA not working right | package mcjty.rftools.blocks.relay;
import net.darkhax.tesla.api.ITeslaConsumer;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fml.common.Optional;
import javax.annotation.Nullable;
import mcjty.lib.varia.EnergyTools;
@Optional.Interface(iface = "net.darkhax.tesla.api.ITeslaConsumer", modid = "tesla")
class RelayEnergyStorage implements IEnergyStorage, ITeslaConsumer {
private final RelayTileEntity relayTileEntity;
private final EnumFacing side;
public RelayEnergyStorage(RelayTileEntity relayTileEntity, @Nullable EnumFacing side) {
this.relayTileEntity = relayTileEntity;
this.side = side;
}
@Override
public int receiveEnergy(int maxReceive, boolean simulate) {
return relayTileEntity.receiveEnergy(side, maxReceive, simulate);
}
@Override
public int extractEnergy(int maxExtract, boolean simulate) {
return 0;
}
@Override
public int getEnergyStored() {
return relayTileEntity.getEnergyStored();
}
@Override
public int getMaxEnergyStored() {
return relayTileEntity.getMaxEnergyStored();
}
@Override
public boolean canExtract() {
return false;
}
@Override
public boolean canReceive() {
return true;
}
@Optional.Method(modid = "tesla")
@Override
public long givePower(long power, boolean simulated) {
return relayTileEntity.receiveEnergy(side, EnergyTools.unsignedClampToInt(power), simulated);
}
}
| package mcjty.rftools.blocks.relay;
import net.darkhax.tesla.api.ITeslaConsumer;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fml.common.Optional;
import javax.annotation.Nullable;
import mcjty.lib.varia.EnergyTools;
@Optional.Interface(iface = "net.darkhax.tesla.api.ITeslaConsumer", modid = "tesla")
class RelayEnergyStorage implements IEnergyStorage, ITeslaConsumer {
private final RelayTileEntity relayTileEntity;
private final EnumFacing side;
public RelayEnergyStorage(RelayTileEntity relayTileEntity, @Nullable EnumFacing side) {
this.relayTileEntity = relayTileEntity;
this.side = side;
}
@Override
public int receiveEnergy(int maxReceive, boolean simulate) {
return relayTileEntity.receiveEnergy(maxReceive, simulate);
}
@Override
public int extractEnergy(int maxExtract, boolean simulate) {
return 0;
}
@Override
public int getEnergyStored() {
return relayTileEntity.getEnergyStored();
}
@Override
public int getMaxEnergyStored() {
return relayTileEntity.getMaxEnergyStored();
}
@Override
public boolean canExtract() {
return false;
}
@Override
public boolean canReceive() {
return true;
}
@Optional.Method(modid = "tesla")
@Override
public long givePower(long power, boolean simulated) {
return relayTileEntity.receiveEnergy(EnergyTools.unsignedClampToInt(power), simulated);
}
}
|
Disable foreign key checks when creating round_id column | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoundsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('rounds', function (Blueprint $table)
{
$table->increments('id');
$table->string('name', 64);
$table->string('description');
$table->decimal('budget', 8, 2);
$table->decimal('min_request_amount', 8, 2);
$table->decimal('max_request_amount', 8, 2);
$table->date('start_date');
$table->date('end_date');
$table->timestamps();
});
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::table('applications', function (Blueprint $table)
{
$table->integer('round_id')->unsigned();
$table->foreign('round_id')->references('id')->on('rounds');
});
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::table('applications', function (Blueprint $table)
{
$table->dropForeign('round_id');
$table->dropColumn('round_id');
});
Schema::drop('rounds');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoundsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('rounds', function (Blueprint $table)
{
$table->increments('id');
$table->string('name', 64);
$table->string('description');
$table->decimal('budget', 8, 2);
$table->decimal('min_request_amount', 8, 2);
$table->decimal('max_request_amount', 8, 2);
$table->date('start_date');
$table->date('end_date');
$table->timestamps();
});
Schema::table('applications', function (Blueprint $table)
{
$table->integer('round_id')->unsigned();
$table->foreign('round_id')->references('id')->on('rounds');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('applications', function (Blueprint $table)
{
$table->dropForeign('round_id');
$table->dropColumn('round_id');
});
Schema::drop('rounds');
}
}
|
Fix action type which has incorrectly named ActionType. | import {RequestUtil} from 'mesosphere-shared-reactjs';
import {
REQUEST_SIDEBAR_OPEN,
REQUEST_SIDEBAR_CLOSE,
REQUEST_CLI_INSTRUCTIONS,
REQUEST_VERSIONS_SUCCESS,
REQUEST_VERSIONS_ERROR,
REQUEST_SIDEBAR_WIDTH_CHANGE
} from '../constants/ActionTypes';
import Config from '../config/Config';
var AppDispatcher = require('./AppDispatcher');
module.exports = {
open: function () {
AppDispatcher.handleSidebarAction({
type: REQUEST_SIDEBAR_OPEN,
data: true
});
},
close: function () {
AppDispatcher.handleSidebarAction({
type: REQUEST_SIDEBAR_CLOSE,
data: false
});
},
openCliInstructions: function () {
AppDispatcher.handleSidebarAction({
type: REQUEST_CLI_INSTRUCTIONS,
data: false
});
},
showVersions: function () {
var host = Config.rootUrl.replace(/:[0-9]{0,4}$/, '');
var url = host + '/pkgpanda/active.buildinfo.full.json';
RequestUtil.json({
url: url,
success: function (response) {
AppDispatcher.handleSidebarAction({
type: REQUEST_VERSIONS_SUCCESS,
data: response
});
},
error: function (e) {
AppDispatcher.handleSidebarAction({
type: REQUEST_VERSIONS_ERROR,
data: e.message
});
}
});
},
sidebarWidthChange: function () {
AppDispatcher.handleSidebarAction({
type: REQUEST_SIDEBAR_WIDTH_CHANGE
});
}
};
| import {RequestUtil} from 'mesosphere-shared-reactjs';
import ActionTypes from '../constants/ActionTypes';
import Config from '../config/Config';
var AppDispatcher = require('./AppDispatcher');
module.exports = {
open: function () {
AppDispatcher.handleSidebarAction({
type: ActionTypes.REQUEST_SIDEBAR_OPEN,
data: true
});
},
close: function () {
AppDispatcher.handleSidebarAction({
type: ActionTypes.REQUEST_SIDEBAR_CLOSE,
data: false
});
},
openCliInstructions: function () {
AppDispatcher.handleSidebarAction({
type: ActionTypes.REQUEST_CLI_INSTRUCTIONS,
data: false
});
},
showVersions: function () {
var host = Config.rootUrl.replace(/:[0-9]{0,4}$/, '');
var url = host + '/pkgpanda/active.buildinfo.full.json';
RequestUtil.json({
url: url,
success: function (response) {
AppDispatcher.handleSidebarAction({
type: ActionTypes.REQUEST_VERSIONS_SUCCESS,
data: response
});
},
error: function (e) {
AppDispatcher.handleSidebarAction({
type: ActionTypes.REQUEST_VERSIONS_ERROR,
data: e.message
});
}
});
},
sidebarWidthChange: function () {
AppDispatcher.handleSidebarAction({
type: ActionTypes.SIDEBAR_WIDTH_CHANGE
});
}
};
|
PROC-592: Add nonnull for fields in the model | package com.indeed.proctor.store;
import javax.annotation.Nonnull;
import java.util.Objects;
import java.util.Set;
/**
* Details of a single revision
*/
public class RevisionDetails {
@Nonnull
private final Revision revision;
@Nonnull
private final Set<String> modifiedTests;
public RevisionDetails(
@Nonnull final Revision revision,
@Nonnull final Set<String> modifiedTests
) {
this.revision = revision;
this.modifiedTests = modifiedTests;
}
@Nonnull
public Revision getRevision() {
return revision;
}
@Nonnull
public Set<String> getModifiedTests() {
return modifiedTests;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final RevisionDetails that = (RevisionDetails) o;
return Objects.equals(revision, that.revision) &&
Objects.equals(modifiedTests, that.modifiedTests);
}
@Override
public int hashCode() {
return Objects.hash(revision, modifiedTests);
}
@Override
public String toString() {
return com.google.common.base.Objects.toStringHelper(this)
.add("revision", revision)
.add("modifiedTests", modifiedTests)
.toString();
}
}
| package com.indeed.proctor.store;
import java.util.Objects;
import java.util.Set;
/**
* Details of a single revision
*/
public class RevisionDetails {
private final Revision revision;
private final Set<String> modifiedTests;
public RevisionDetails(
final Revision revision,
final Set<String> modifiedTests
) {
this.revision = revision;
this.modifiedTests = modifiedTests;
}
public Revision getRevision() {
return revision;
}
public Set<String> getModifiedTests() {
return modifiedTests;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final RevisionDetails that = (RevisionDetails) o;
return Objects.equals(revision, that.revision) &&
Objects.equals(modifiedTests, that.modifiedTests);
}
@Override
public int hashCode() {
return Objects.hash(revision, modifiedTests);
}
@Override
public String toString() {
return com.google.common.base.Objects.toStringHelper(this)
.add("revision", revision)
.add("modifiedTests", modifiedTests)
.toString();
}
}
|
Generalize to allow editing other configuration | import owebunit
import urlparse
from wolis_test_case import WolisTestCase
class AcpLoginTestCase(WolisTestCase):
def test_disable_captcha(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morpheus')
self.change_acp_knob(
link_text='Spambot countermeasures',
check_page_text='Enable spambot countermeasures',
name='enable_confirm',
value='0',
)
def change_acp_knob(self, link_text, check_page_text, name, value):
start_url = '/adm/index.php'
self.get_with_sid(start_url)
self.assert_status(200)
assert 'Board statistics' in self.response.body
url = self.link_href_by_text(link_text)
# already has sid
self.get(urlparse.urljoin(start_url, url))
self.assert_status(200)
assert check_page_text in self.response.body
assert len(self.response.forms) == 1
form = self.response.forms[0]
params = {
name: value,
}
params = owebunit.extend_params(form.params.list, params)
self.post(form.computed_action, body=params)
self.assert_status(200)
assert 'Configuration updated successfully' in self.response.body
if __name__ == '__main__':
import unittest
unittest.main()
| import owebunit
import urlparse
from wolis_test_case import WolisTestCase
class AcpLoginTestCase(WolisTestCase):
def test_disable_captcha(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morpheus')
start_url = '/adm/index.php'
self.get_with_sid(start_url)
self.assert_status(200)
assert 'Board statistics' in self.response.body
url = self.link_href_by_text('Spambot countermeasures')
# already has sid
self.get(urlparse.urljoin(start_url, url))
self.assert_status(200)
assert 'Enable spambot countermeasures' in self.response.body
assert len(self.response.forms) == 1
form = self.response.forms[0]
params = {
'enable_confirm': '0',
}
params = owebunit.extend_params(form.params.list, params)
self.post(form.computed_action, body=params)
self.assert_status(200)
assert 'Configuration updated successfully' in self.response.body
if __name__ == '__main__':
import unittest
unittest.main()
|
Add form-horizontal class for the view section | @extends('layouts.app')
@section('page-title')
{!! $t[$type.'_title'] or trans('eliurkis::crud.'.$type.'_title') !!}
@stop
@section('content')
<div id="form-manage" class="row form-horizontal">
@foreach ($fields as $name => $field)
<div class="{{ $formColsClasses[0] }} fieldtype_{{ $field['type'] }} fieldname_{{ $name }}">
<div class="form-group">
<label class="{{ $formColsClasses[1] }} control-label">{{ $field['label'] or $name }}</label>
<div class="{{ $formColsClasses[2] }}">
<p class="form-control-static">{!! $field['value_text'] !!}</p>
</div>
</div>
</div>
@endforeach
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="text-center">
<a href="{{ route($route.'.index') }}" class="btn btn-default">
<i class="fas fa-arrow-left"></i> {{ $t['go_back'] or trans('eliurkis::crud.go_back') }}
</a>
</div>
</div>
</div>
</div>
@stop
| @extends('layouts.app')
@section('page-title')
{!! $t[$type.'_title'] or trans('eliurkis::crud.'.$type.'_title') !!}
@stop
@section('content')
<div id="form-manage" class="row">
@foreach ($fields as $name => $field)
<div class="{{ $formColsClasses[0] }} fieldtype_{{ $field['type'] }} fieldname_{{ $name }}">
<div class="form-group">
<label class="{{ $formColsClasses[1] }} control-label">{{ $field['label'] or $name }}</label>
<div class="{{ $formColsClasses[2] }}">
<p class="form-control-static">{!! $field['value_text'] !!}</p>
</div>
</div>
</div>
@endforeach
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="text-center">
<a href="{{ route($route.'.index') }}" class="btn btn-default">
<i class="fas fa-arrow-left"></i> {{ $t['go_back'] or trans('eliurkis::crud.go_back') }}
</a>
</div>
</div>
</div>
</div>
@stop
|
Add support for component initialization that returns lists | from importlib import import_module
from collections import Iterable
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
if isinstance(component, Iterable):
components.extend(component)
else:
components.append(component)
return components
| from importlib import import_module
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
components.append(component)
return components
|
Set the Authorization header if a token exists | var svcMod = angular.module( "linksWeb.service-api", [] );
svcMod.factory( 'API', [ "$http", "$window", function ( $http, $window ) {
var apiRequest = function ( method, path, requestData, callback ) {
var headers = {
"Content-Type": "application/json"
};
if ( $window.sessionStorage.token ) {
headers.Authorization = "Token " + $window.sessionStorage.token;
}
var options = {
method: method,
url: path,
headers: headers,
data: requestData
};
$http( options )
.success( function ( data, status, headers, config ) {
callback( null, data );
} )
.error( function ( data, status, headers, config ) {
var error = {
data: data,
status: status
};
callback( error, null );
} );
};
return {
$get: function ( path, callback ) {
return apiRequest( 'GET', path, {}, callback );
},
$post: function ( path, requestData, callback ) {
return apiRequest( 'POST', path, requestData, callback );
},
$put: function ( path, requestData, callback ) {
return apiRequest( 'PUT', path, requestData, callback );
},
$patch: function ( path, requestData, callback ) {
return apiRequest( 'PATCH', path, requestData, callback );
},
$delete: function ( path, callback ) {
return apiRequest( 'DELETE', path, {}, callback );
}
};
} ] );
| var svcMod = angular.module( "linksWeb.service-api", [] );
svcMod.factory( 'API', [ "$http", "$window", function ( $http, $window ) {
var apiRequest = function ( method, path, requestData, callback ) {
var headers = {
"Content-Type": "application/json",
"Authorization": "Token " + $window.sessionStorage.token
};
var options = {
method: method,
url: path,
headers: headers,
data: requestData
};
$http( options )
.success( function ( data, status, headers, config ) {
callback( null, data );
} )
.error( function ( data, status, headers, config ) {
var error = {
data: data,
status: status
};
callback( error, null );
} );
};
return {
$get: function ( path, callback ) {
return apiRequest( 'GET', path, {}, callback );
},
$post: function ( path, requestData, callback ) {
return apiRequest( 'POST', path, requestData, callback );
},
$put: function ( path, requestData, callback ) {
return apiRequest( 'PUT', path, requestData, callback );
},
$patch: function ( path, requestData, callback ) {
return apiRequest( 'PATCH', path, requestData, callback );
},
$delete: function ( path, callback ) {
return apiRequest( 'DELETE', path, {}, callback );
}
};
} ] );
|
Correct error for array list | <?php
/**
* Created by EBelair.
* User: manu
* Date: 07/03/14
* Time: 19:20
*/
namespace SuchTable\Element;
use SuchTable\Element;
use SuchTable\Exception\InvalidArgumentException;
abstract class AbstractList extends Element
{
public function prepare()
{
if ($this->isPrepared === true) {
return $this;
}
parent::prepare();
if (!$getter = $this->getOption('getter')) {
throw new InvalidArgumentException(
sprintf("'getter' option is missing on '%s' element", $this->getName())
);
}
$content = [];
if ($value = $this->getValue()) {
foreach ($value as $line) {
if (is_array($line)) {
$li = $line[$getter];
} elseif (is_object($line)) {
$getter = 'get' . ucfirst($getter);
try {
$li = $line->$getter();
} catch (\Exception $e) {
throw new InvalidArgumentException(
sprintf('object has to be accessible with "%s" method', $getter)
);
}
} else {
throw new InvalidArgumentException(
sprintf("Invalid type of data, expected array or object found %s", gettype($line))
);
}
$content[] = $li;
}
$this->setValue($content);
}
}
}
| <?php
/**
* Created by EBelair.
* User: manu
* Date: 07/03/14
* Time: 19:20
*/
namespace SuchTable\Element;
use SuchTable\Element;
use SuchTable\Exception\InvalidArgumentException;
abstract class AbstractList extends Element
{
public function prepare()
{
if ($this->isPrepared === true) {
return $this;
}
parent::prepare();
if (!$getter = $this->getOption('getter')) {
throw new InvalidArgumentException(
sprintf("'getter' option is missing on '%s' element", $this->getName())
);
}
$getter = 'get' . ucfirst($getter);
$content = [];
if ($value = $this->getValue()) {
foreach ($value as $line) {
if (is_array($line)) {
$li = $value[$getter];
} elseif (is_object($line)) {
try {
$li = $line->$getter();
} catch (\Exception $e) {
throw new InvalidArgumentException(
sprintf('object has to be accessible with "%s" method', $getter)
);
}
} else {
throw new InvalidArgumentException(
sprintf("Invalid type of data, expected array or object found %s", gettype($line))
);
}
$content[] = $li;
}
$this->setValue($content);
}
}
}
|
Revert "Don't separate the validating generator"
This reverts commit f6851039a91adb5a3f9c130862e652df5aabe674. | <?php
declare(strict_types=1);
namespace App\Generators;
use GuzzleHttp\Promise\Promise;
/**
* This is the validating generator class.
*
* @author Graham Campbell <[email protected]>
*/
class ValidatingGenerator implements GeneratorInterface
{
/**
* The generator to wrap.
*
* @var \App\Generators\GeneratorInterface
*/
protected $generator;
/**
* Create a new validating generator instance.
*
* @param \App\Generators\GeneratorInterface $generator
*
* @return void
*/
public function __construct(GeneratorInterface $generator)
{
$this->generator = $generator;
}
/**
* Generate a new image.
*
* @param string $text
*
* @throws \App\Generators\ExceptionInterface
*
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function generate(string $text)
{
return (new Promise(function () use ($text) {
if (!$text) {
throw new ValidationException('No meme text provided!');
}
if (preg_match('/^[a-z0-9 .\-]+$/i', $text) !== 1) {
throw new ValidationException('Invalid meme text provided!');
}
if (strlen($text) > 128) {
throw new ValidationException('Meme text too long!');
}
}))->then(function () use ($text) {
return $this->generator->generate($text);
});
}
}
| <?php
declare(strict_types=1);
namespace App\Generators;
use GuzzleHttp\Promise\Promise;
/**
* This is the validating generator class.
*
* @author Graham Campbell <[email protected]>
*/
class ValidatingGenerator implements GeneratorInterface
{
/**
* The generator to wrap.
*
* @var \App\Generators\GeneratorInterface
*/
protected $generator;
/**
* Create a new validating generator instance.
*
* @param \App\Generators\GeneratorInterface $generator
*
* @return void
*/
public function __construct(GeneratorInterface $generator)
{
$this->generator = $generator;
}
/**
* Generate a new image.
*
* @param string $text
*
* @throws \App\Generators\ExceptionInterface
*
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function generate(string $text)
{
return (new Promise(function () use ($text) {
if (!$text) {
throw new ValidationException('No meme text provided!');
}
if (preg_match('/^[a-z0-9 .\-]+$/i', $text) !== 1) {
throw new ValidationException('Invalid meme text provided!');
}
if (strlen($text) > 128) {
throw new ValidationException('Meme text too long!');
}
return $this->generator->generate($text);
}));
}
}
|
Remove the sudo killall from the CLI script, as it prompts for a password regardless of nopasswd settings. NOTE: if upgrading from a version prior to this version, a reboot may be required! | <?php
namespace App\Console\Command;
use Doctrine\ORM\EntityManager;
use Entity\Station;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class RestartRadio extends CommandAbstract
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName('radio:restart')
->setDescription('Restart all radio stations.');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
\App\Debug::setEchoMode(true);
\App\Debug::log('Restarting all radio stations...');
\App\Debug::divider();
/** @var \Supervisor\Supervisor */
$supervisor = $this->di['supervisor'];
/** @var EntityManager $em */
$em = $this->di['em'];
$stations = $em->getRepository(Station::class)->findAll();
$supervisor->stopAllProcesses();
foreach($stations as $station)
{
/** @var Station $station */
\App\Debug::log('Restarting station #'.$station->id.': '.$station->name);
$station->writeConfiguration($this->di);
\App\Debug::divider();
}
$supervisor->startAllProcesses();
}
} | <?php
namespace App\Console\Command;
use Doctrine\ORM\EntityManager;
use Entity\Station;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class RestartRadio extends CommandAbstract
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName('radio:restart')
->setDescription('Restart all radio stations.');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
\App\Debug::setEchoMode(true);
\App\Debug::log('Restarting all radio stations...');
\App\Debug::divider();
/** @var \Supervisor\Supervisor */
$supervisor = $this->di['supervisor'];
/** @var EntityManager $em */
$em = $this->di['em'];
$stations = $em->getRepository(Station::class)->findAll();
$supervisor->stopAllProcesses();
// Get rid of any processes running from legacy tooling.
exec('sudo killall -9 liquidsoap icecast2 sc_serv');
foreach($stations as $station)
{
/** @var Station $station */
\App\Debug::log('Restarting station #'.$station->id.': '.$station->name);
$station->writeConfiguration($this->di);
\App\Debug::divider();
}
$supervisor->startAllProcesses();
}
} |
Update PHPUnit tests for Yii models. | <?php
namespace Sil\SilAuth\tests\unit\models;
use Sil\SilAuth\models\User;
use PHPUnit\Framework\TestCase;
class UserTest extends TestCase
{
public function testChangingAnExistingUuid()
{
// Arrange:
$uniqId = uniqid();
$user = new User();
$user->attributes = [
'email' => $uniqId . '@example.com',
'employee_id' => $uniqId,
'first_name' => 'Test ' . $uniqId,
'last_name' => 'User',
'username' => 'user' . $uniqId,
];
// Pre-assert:
$this->assertTrue($user->save(), sprintf(
'Failed to create User for test: %s',
print_r($user->getErrors(), true)
));
$this->assertTrue($user->refresh());
// Act:
$user->uuid = User::generateUuid();
// Assert:
$this->assertFalse($user->validate(['uuid']));
}
public function testGenerateUuid()
{
// Arrange: (n/a)
// Act:
$uuid = User::generateUuid();
// Assert:
$this->assertNotEmpty($uuid);
}
}
| <?php
namespace Sil\SilAuth\tests\unit\models;
use Sil\SilAuth\models\User;
use PHPUnit\Framework\TestCase;
class UserTest extends TestCase
{
public function testChangingAnExistingUuid()
{
// Arrange:
$user = new User();
// Pre-assert:
$this->assertTrue($user->save());
$this->assertTrue($user->refresh());
// Act:
$user->uuid = User::generateUuid();
// Assert:
$this->assertFalse($user->validate(['uuid']));
}
public function testGenerateUuid()
{
// Arrange: (n/a)
// Act:
$uuid = User::generateUuid();
// Assert:
$this->assertNotEmpty($uuid);
}
public function testValidationRules()
{
// Arrange:
$testCases = [
];
foreach ($testCases as $testName => $testData) {
// Act:
$user = new User();
$user->attributes = $testData['attributes'];
// Assert:
$this->assertSame($testData['expected'], $user->validate(), sprintf(
'Incorrectly %s a User with %s.',
($testData['expected'] ? 'rejected' : 'allowed'),
$testName
));
}
}
}
|
Add support for pit.only(), parity with it.only() | function install(globalObject) {
if (!globalObject.jasmine) {
throw new Error(
'It looks like you\'re trying to install jasmine-pit before installing ' +
'jasmine! Make sure there is a `jasmine` property on the global object ' +
'(window/global/etc) before calling install().'
);
}
var jasmine = globalObject.jasmine;
globalObject.pit = function pit(specName, promiseBuilder) {
return jasmine.getEnv().it(specName, runPitTest.bind(null, promiseBuilder));
};
globalObject.pit.only = function pitOnly(specName, promiseBuilder) {
return jasmine.getEnv().it.only(specName, runPitTest.bind(null, promiseBuilder));
};
globalObject.xpit = function xpit(specName, promiseBuilder) {
return jasmine.getEnv().xit(specName, runPitTest.bind(null, promiseBuilder));
};
function runPitTest(promiseBuilder) {
var jasmineEnv = jasmine.getEnv();
var spec = this;
var isFinished = false;
var error = null;
jasmineEnv.currentSpec.runs(function() {
try {
var promise = promiseBuilder.call(spec);
if (promise && promise.then) {
promise.then(function() {
isFinished = true;
})['catch'](function(err) {
error = err; isFinished = true;
});
} else {
isFinished = true;
}
} catch (e) {
error = e;
isFinished = true;
}
});
jasmineEnv.currentSpec.waitsFor(function() { return isFinished; });
jasmineEnv.currentSpec.runs(function() { if (error) throw error; });
};
}
exports.install = install;
| function install(globalObject) {
if (!globalObject.jasmine) {
throw new Error(
'It looks like you\'re trying to install jasmine-pit before installing ' +
'jasmine! Make sure there is a `jasmine` property on the global object ' +
'(window/global/etc) before calling install().'
);
}
var jasmine = globalObject.jasmine;
globalObject.pit = function pit(specName, promiseBuilder) {
var jasmineEnv = jasmine.getEnv();
return jasmineEnv.it(specName, function() {
var spec = this;
var isFinished = false;
var error = null;
jasmineEnv.currentSpec.runs(function() {
try {
var promise = promiseBuilder.call(spec);
if (promise && promise.then) {
promise.then(function() {
isFinished = true;
})['catch'](function(err) {
error = err; isFinished = true;
});
} else {
isFinished = true;
}
} catch (e) {
error = e;
isFinished = true;
}
});
jasmineEnv.currentSpec.waitsFor(function() { return isFinished; });
jasmineEnv.currentSpec.runs(function() { if (error) throw error; });
});
};
globalObject.xpit = function xpit(specName, promiseBuilder) {
return jasmine.getEnv().xit(specName, promiseBuilder);
};
}
exports.install = install;
|
Add additional check if plugin has already been registered | /**
* Install plugin.
*/
import Url from './url/index';
import Http from './http/index';
import Promise from './promise';
import Resource from './resource';
import Util, {options} from './util';
function plugin(Vue) {
if (plugin.installed) {
return;
}
Util(Vue);
Vue.url = Url;
Vue.http = Http;
Vue.resource = Resource;
Vue.Promise = Promise;
Object.defineProperties(Vue.prototype, {
$url: {
get() {
return options(Vue.url, this, this.$options.url);
}
},
$http: {
get() {
return options(Vue.http, this, this.$options.http);
}
},
$resource: {
get() {
return Vue.resource.bind(this);
}
},
$promise: {
get() {
return (executor) => new Vue.Promise(executor, this);
}
}
});
}
if (typeof window !== 'undefined' && window.Vue && !window.Vue.resource) {
window.Vue.use(plugin);
}
export default plugin;
| /**
* Install plugin.
*/
import Url from './url/index';
import Http from './http/index';
import Promise from './promise';
import Resource from './resource';
import Util, {options} from './util';
function plugin(Vue) {
if (plugin.installed) {
return;
}
Util(Vue);
Vue.url = Url;
Vue.http = Http;
Vue.resource = Resource;
Vue.Promise = Promise;
Object.defineProperties(Vue.prototype, {
$url: {
get() {
return options(Vue.url, this, this.$options.url);
}
},
$http: {
get() {
return options(Vue.http, this, this.$options.http);
}
},
$resource: {
get() {
return Vue.resource.bind(this);
}
},
$promise: {
get() {
return (executor) => new Vue.Promise(executor, this);
}
}
});
}
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}
export default plugin;
|
Use common colors, Reset after message.
Switch to colors that don't mess up on using light color schemes. | import os
import logging
import types
import json
import six
class JsonFormatter(logging.Formatter):
def format(self, record):
data = {
"level": record.levelno,
"levelName": record.levelname,
"msg": logging.Formatter.format(self, record)
}
if type(record.args) is types.DictType:
for k, v in six.iteritems(record.args):
data[k] = v
return json.dumps(data)
def setup_logging(verbose, quiet):
logger = logging.getLogger()
handler = logging.StreamHandler()
if os.environ.get('DESKTOPAPP'):
log_level = logging.INFO
handler.setFormatter(JsonFormatter())
else:
from colorlog import ColoredFormatter
formatter = ColoredFormatter(
"%(log_color)s%(message)s%(reset)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
)
if quiet:
log_level = logging.WARNING
elif verbose:
log_level = logging.DEBUG
else:
log_level = logging.INFO
handler.setFormatter(formatter)
logger.setLevel(log_level)
for h in logger.handlers:
logger.removeHandler(h)
logger.addHandler(handler)
| import os
import logging
import types
import json
import six
class JsonFormatter(logging.Formatter):
def format(self, record):
data = {
"level": record.levelno,
"levelName": record.levelname,
"msg": logging.Formatter.format(self, record)
}
if type(record.args) is types.DictType:
for k, v in six.iteritems(record.args):
data[k] = v
return json.dumps(data)
def setup_logging(verbose, quiet):
logger = logging.getLogger()
handler = logging.StreamHandler()
if os.environ.get('DESKTOPAPP'):
log_level = logging.INFO
handler.setFormatter(JsonFormatter())
else:
from colorlog import ColoredFormatter
formatter = ColoredFormatter(
"%(log_color)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'white',
'INFO': 'white',
'WARNING': 'bold_yellow',
'ERROR': 'bold_red',
'CRITICAL': 'bold_red',
}
)
if quiet:
log_level = logging.WARNING
elif verbose:
log_level = logging.DEBUG
else:
log_level = logging.INFO
handler.setFormatter(formatter)
logger.setLevel(log_level)
for h in logger.handlers:
logger.removeHandler(h)
logger.addHandler(handler)
|
Split delay configuration into default_delay and specific_delays |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
Replace get_the_post_thumbnail custom image tag generation. | <article id="post-<?php echo $singlePost->ID; ?>" <?php post_class('row'); ?>>
<div class="small-12 medium-4 column">
<?php
if (has_post_thumbnail( $singlePost->ID ) ) {
$thumbnailId = get_post_thumbnail_id( $singlePost->ID );
$imageTitle = get_the_title( $thumbnailId );
$image = wp_get_attachment_image_src( $thumbnailId, 'large' );
$imageMedium = wp_get_attachment_image_src( $thumbnailId, 'medium' );
?>
<div class="img-shadow center-block">
<a href="<?php echo $image[0]; ?>" target="_blank">
<img src="<?php echo $imageMedium[0]; ?>"
alt="<?php echo $imageTitle; ?>" title="<?php echo $imageTitle; ?>" />
</a>
</div>
<?php
}
?>
</div>
<div class="small-12 medium-8 column">
<h2><?php echo $singlePost->post_title; ?></h2>
<?php
$postContent = apply_filters('the_content', $singlePost->post_content);
if( $singlePost->read_more === 1 ) {
$postContent = '<a href="'. $singlePost->guid .'">' . $postContent . '</a>';
}
echo $postContent;
?>
</div>
</article>
<!-- #post-<?php $singlePost->ID; ?> -->
| <article id="post-<?php echo $singlePost->ID; ?>" <?php post_class('row'); ?>>
<div class="small-12 medium-4 column">
<?php
if (has_post_thumbnail( $singlePost->ID ) ) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $singlePost->ID ), 'large' );
?>
<div class="img-shadow center-block">
<a href="<?php echo $image[0]; ?>" target="_blank">
<?php echo get_the_post_thumbnail( $singlePost->ID, 'medium' ); ?>
</a>
</div>
<?php
}
?>
</div>
<div class="small-12 medium-8 column">
<h2><?php echo $singlePost->post_title; ?></h2>
<?php
$postContent = apply_filters('the_content', $singlePost->post_content);
if( $singlePost->read_more === 1 ) {
$postContent = '<a href="'. $singlePost->guid .'">' . $postContent . '</a>';
}
echo $postContent;
?>
</div>
</article>
<!-- #post-<?php $singlePost->ID; ?> -->
|
Fix unit test to sign action creators | import * as signUpActions from './signUp';
import reducer from './signUp';
describe('signUp reducer', () => {
it('should return the initial state', () => {
expect(
reducer(undefined, {})
).toEqual({
isFetchingSuccessful: false,
isFetching: false,
errorMessage: {}
}
)
})
it('should handle SIGN_UP_REQUEST', () => {
expect(
reducer([], {
type: 'SIGN_UP_REQUEST'
})
).toEqual({
isFetching: true,
errorMessage: {}
}
)
})
it('should handle SIGN_UP_SUCCESS', () => {
expect(
reducer([], {
type: 'SIGN_UP_SUCCESS'
})
).toEqual({
isFetchingSuccessful: true,
isFetching: false
}
)
})
it('should handle SIGN_UP_FAIL', () => {
const payload = {
uiError: {
usernameErr: 'Please enter a name',
fullNameErr: 'Please enter a full name',
}
};
expect(
reducer([], {
type: 'SIGN_UP_FAIL',
payload
})
).toEqual({
isFetchingSuccessful: true,
isFetching: false,
errorMessage: payload
}
)
})
}) | import * as signUpActions from './signUp';
import reducer from './signUp';
describe('signUp reducer', () => {
it('should return the initial state', () => {
expect(
reducer(undefined, {})
).toEqual({
isFetchingSuccessful: false,
isFetching: false,
errorMessage: {}
}
)
})
it('should handle SIGN_UP_REQUEST', () => {
const payload = {
uiError: {
usernameErr: 'Please enter a name',
fullNameErr: 'Please enter a full name',
}
};
expect(
reducer([], {
type: 'SIGN_UP_REQUEST'
})
).toEqual({
isFetching: true,
errorMessage: payload.uiError
}
)
})
it('should handle SIGN_UP_SUCCESS', () => {
expect(
reducer([], {
type: 'SIGN_UP_SUCCESS'
})
).toEqual({
isFetchingSuccessful: true,
isFetching: false
}
)
})
it('should handle SIGN_UP_FAIL', () => {
const payload = {
uiError: {
usernameErr: 'Please enter a name',
fullNameErr: 'Please enter a full name',
}
};
expect(
reducer([], {
type: 'SIGN_UP_FAIL'
})
).toEqual({
isFetchingSuccessful: true,
isFetching: false,
errorMessage: payload
}
)
})
}) |
Refactor if statement for clarity. | import React from 'react';
import { Link } from 'react-router-dom';
import { Button } from 'react-bootstrap';
import ModifyTitle from '../containers/ModifyTitle';
import ModifyIngredients from '../containers/ModifyIngredients';
import PropTypes from 'prop-types';
const ReviewRecipe = (props) => {
return (
<div>
<h4>Review Recipe</h4>
<ModifyTitle
nextButton={false}
/>
<ModifyIngredients
nextButton={false}
plusButton={false}
/>
<Link to="/">
<Button
bsStyle="primary"
bsSize="large"
style={props.buttonStyle}
onClick={() => {
if (props.tempRecipe.editMode) {
props.editRecipe(props.tempRecipe.id, props.tempRecipe);
} else {
props.addRecipe(props.tempRecipe);
}
props.clearTempRecipe();
}}
block
>
Submit
</Button>
</Link>
<Link to="/modify-ingredients">
<Button bsSize="large" block>Back</Button>
</Link>
</div>
);
};
ReviewRecipe.propTypes = {
buttonStyle: PropTypes.object.isRequired,
addRecipe: PropTypes.func.isRequired,
tempRecipe: PropTypes.object.isRequired,
clearTempRecipe: PropTypes.func.isRequired
};
export default ReviewRecipe;
| import React from 'react';
import { Link } from 'react-router-dom';
import { Button } from 'react-bootstrap';
import ModifyTitle from '../containers/ModifyTitle';
import ModifyIngredients from '../containers/ModifyIngredients';
import PropTypes from 'prop-types';
const ReviewRecipe = (props) => {
return (
<div>
<h4>Review Recipe</h4>
<ModifyTitle
nextButton={false}
/>
<ModifyIngredients
nextButton={false}
plusButton={false}
/>
<Link to="/">
<Button
bsStyle="primary"
bsSize="large"
style={props.buttonStyle}
onClick={() => {
props.tempRecipe.editMode ?
props.editRecipe(props.tempRecipe.id, props.tempRecipe)
: props.addRecipe(props.tempRecipe);
props.clearTempRecipe();
}}
block
>
Submit
</Button>
</Link>
<Link to="/modify-ingredients">
<Button bsSize="large" block>Back</Button>
</Link>
</div>
);
};
ReviewRecipe.propTypes = {
buttonStyle: PropTypes.object.isRequired,
addRecipe: PropTypes.func.isRequired,
tempRecipe: PropTypes.object.isRequired,
clearTempRecipe: PropTypes.func.isRequired
};
export default ReviewRecipe;
|
Split out the different headers into their own methods for greater flexibility. | function parseQString(qString) {
var d = /^\s*q=([01](?:\.\d+))\s*$/.exec(qString);
if (!!d) {
return 1;
}
return Number(d[1]);
}
function sortQArrayString(content) {
var entries = content.split(','),
sortData = [];
entries.forEach(function(rec) {
var s = rec.split(';');
sortData.append({
key: s[0],
quality: parseQString(s[1])
});
});
sortData.sort(function(a, b) {
if (a.quality > b.quality) { return -1; }
if (a.quality < b.quality) { return 1; }
return 0;
});
return sortData.map(function(rec) {
return rec.key;
});
}
function buildScanner(header, property) {
return function(req, res next) {
var data = req.headers[header];
if (data) {
req[property] = sortQArrayString(data);
}
if (next) next();
};
}
module.exports = {
language: function() {
return buildScanner('Accept-Languages', 'languages');
},
acceptedTypes: function() {
return buildScanner('Accept', 'acceptableTypes');
},
charsets: function() {
return buildScanner('Accept-Charset', 'charsets');
},
custom: buildScanner
}
| function parseQString(qString) {
var d = /^\s*q=([01](?:\.\d+))\s*$/.exec(qString);
if (!!d) {
return 1;
}
return Number(d[1]);
}
function sortQArrayString(content) {
var entries = content.split(','),
sortData = [];
entries.forEach(function(rec) {
var s = rec.split(';');
sortData.append({
key: s[0],
quality: parseQString(s[1])
});
});
sortData.sort(function(a, b) {
if (a.quality > b.quality) { return -1; }
if (a.quality < b.quality) { return 1; }
return 0;
});
return sortData.map(function(rec) {
return rec.key;
});
}
module.exports = function negotiate(config) {
config || config = {};
// Connect-conneg will only handle Languages, Accept, and Charset
// The gzip module handles the Accept-Encoding header
// Accept-Range is outside the scope of this module
return function(req, res, next) {
if (req.headers['Accept-Language']) {
req.languages = sortQArrayString(req.headers['Accept-Language']);
}
if (req.headers['Accept']) {
req.acceptableTypes = sortQArrayString(req.headers['Accept']);
}
if (req.headers['Accept-Charset']) {
req.charsets = sortQArrayString(req.headers['Accept-Charset']);
}
if (next) { next(); }
};
}
|
Change blocky renderer solution color | 'use strict';
// Paint a single cell in the maze a solid color padded with a single px of
// blank space.
module.exports = function (maze, canvas, opts, x, y) {
var cellSize = opts.cellSize;
var colors = {
'-2': 'dodgerblue', // Solution.
'-1': 'dodgerblue', // Solution.
'0': 'black', // Wall.
'1': 'white', // Path.
'2': 'chartreuse' // Path that is part of a character.
};
var color = colors[maze[y][x]];
switch (true) {
case opts.showSolution && opts.showText:
// Render the text on top of the solution.
if (maze[y][x] === -2) color = colors[ Math.abs(maze[y][x]) ];
break;
case opts.showSolution:
// Don't render the text.
if (maze[y][x] === 2) color = colors['1'];
break;
case opts.showText:
// Don't render the solution.
if (maze[y][x] < 0) color = colors[ Math.abs(maze[y][x]) ];
break;
default:
// Do not render the text or solution.
if (maze[y][x] !== 0) color = colors['1'];
}
canvas.paint(
color,
x * cellSize + 1,
y * cellSize + 1,
cellSize - 2,
cellSize - 2
);
};
| 'use strict';
// Paint a single cell in the maze a solid color padded with a single px of
// blank space.
module.exports = function (maze, canvas, opts, x, y) {
var cellSize = opts.cellSize;
var colors = {
'-2': 'red', // Solution.
'-1': 'red', // Solution.
'0': 'black', // Wall.
'1': 'white', // Path.
'2': 'chartreuse' // Path that is part of a character.
};
var color = colors[maze[y][x]];
switch (true) {
case opts.showSolution && opts.showText:
// Render the text on top of the solution.
if (maze[y][x] === -2) color = colors[ Math.abs(maze[y][x]) ];
break;
case opts.showSolution:
// Don't render the text.
if (maze[y][x] === 2) color = colors['1'];
break;
case opts.showText:
// Don't render the solution.
if (maze[y][x] < 0) color = colors[ Math.abs(maze[y][x]) ];
break;
default:
// Do not render the text or solution.
if (maze[y][x] !== 0) color = colors['1'];
}
canvas.paint(
color,
x * cellSize + 1,
y * cellSize + 1,
cellSize - 2,
cellSize - 2
);
};
|
Fix email address for pypi | #!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='rdspgbadger',
version='1.2.0',
description=("Fetch logs from RDS postgres instance and use them with "
"pgbadger to generate a report."),
url='http://github.com/fpietka/rds-pgbadger',
author='François Pietka',
author_email='[email protected]',
license='MIT',
packages=['package'],
install_requires=['boto3>=1.4.0'],
entry_points={
'console_scripts': [
'rds-pgbadger = package.rdspgbadger:main'
],
},
long_description=open('README.rst').read(),
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
zip_safe=True)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='rdspgbadger',
version='1.2.0',
description=("Fetch logs from RDS postgres instance and use them with "
"pgbadger to generate a report."),
url='http://github.com/fpietka/rds-pgbadger',
author='François Pietka',
author_email='francois[at]pietka[dot]fr',
license='MIT',
packages=['package'],
install_requires=['boto3>=1.4.0'],
entry_points={
'console_scripts': [
'rds-pgbadger = package.rdspgbadger:main'
],
},
long_description=open('README.rst').read(),
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
zip_safe=True)
|
Update context for one calendar | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
import datetime
from django.utils.translation import ugettext as _
from events.models import CalendarEventsPlugin as CalendarEventsPluginModel
from events.models import AllEventsPlugin as AllEventsPluginModel
from events.models import Event
class CalendarEventsPlugin(CMSPluginBase):
model = CalendarEventsPluginModel
name = _("Events (from one calendar)")
render_template = "events/plugin.html"
module = _("TheHerk")
def render(self, context, instance, placeholder):
events = Event.objects.filter(calendar__id=instance.calendar.id).filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show]
context.update({
'instance': instance,
'events': events,
'placeholder': placeholder,
})
return context
class AllEventsPlugin(CMSPluginBase):
model = AllEventsPluginModel
name = _("Events (all calendars)")
render_template = "events/plugin.html"
module = _("TheHerk")
def render(self, context, instance, placeholder):
events = Event.objects.filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show]
context.update({
'instance': instance,
'events': events,
'placeholder': placeholder,
})
return context
plugin_pool.register_plugin(CalendarEventsPlugin)
plugin_pool.register_plugin(AllEventsPlugin)
| from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
import datetime
from django.utils.translation import ugettext as _
from events.models import CalendarEventsPlugin as CalendarEventsPluginModel
from events.models import AllEventsPlugin as AllEventsPluginModel
from events.models import Event
class CalendarEventsPlugin(CMSPluginBase):
model = CalendarEventsPluginModel
name = _("Events (from one calendar)")
render_template = "events/plugin.html"
module = _("TheHerk")
def render(self, context, instance, placeholder):
events = Event.objects.filter(calendar__id=instance.calendar).filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show]
context.update({
'instance': instance,
'events': events,
'placeholder': placeholder,
})
return context
class AllEventsPlugin(CMSPluginBase):
model = AllEventsPluginModel
name = _("Events (all calendars)")
render_template = "events/plugin.html"
module = _("TheHerk")
def render(self, context, instance, placeholder):
events = Event.objects.filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show]
context.update({
'instance': instance,
'events': events,
'placeholder': placeholder,
})
return context
plugin_pool.register_plugin(CalendarEventsPlugin)
plugin_pool.register_plugin(AllEventsPlugin)
|
Fix the name for the installerDb field to match our conventions. | package org.opennms.netmgt.dao.db;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class PopulatedTemporaryDatabaseTestCase extends
TemporaryDatabaseTestCase {
private InstallerDb m_installerDb;
private ByteArrayOutputStream m_outputStream;
protected void setUp() throws Exception {
super.setUp();
initializeDatabase();
}
protected void initializeDatabase() throws Exception {
if (!isEnabled()) {
return;
}
m_installerDb = new InstallerDb();
// Create a ByteArrayOutputSteam to effectively throw away output.
resetOutputStream();
m_installerDb.setDatabaseName(getTestDatabase());
m_installerDb.setDataSource(getDataSource());
m_installerDb.setCreateSqlLocation(
"../opennms-daemon/src/main/filtered/etc/create.sql");
m_installerDb.setStoredProcedureDirectory(
"../opennms-daemon/src/main/filtered/etc");
//installerDb.setDebug(true);
m_installerDb.readTables();
m_installerDb.createSequences();
m_installerDb.updatePlPgsql();
m_installerDb.addStoredProcedures();
m_installerDb.createTables();
m_installerDb.closeConnection();
}
public ByteArrayOutputStream getOutputStream() {
return m_outputStream;
}
public void resetOutputStream() {
m_outputStream = new ByteArrayOutputStream();
m_installerDb.setOutputStream(new PrintStream(m_outputStream));
}
}
| package org.opennms.netmgt.dao.db;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class PopulatedTemporaryDatabaseTestCase extends
TemporaryDatabaseTestCase {
private InstallerDb installerDb;
private ByteArrayOutputStream m_outputStream;
protected void setUp() throws Exception {
super.setUp();
initializeDatabase();
}
protected void initializeDatabase() throws Exception {
if (!isEnabled()) {
return;
}
installerDb = new InstallerDb();
// Create a ByteArrayOutputSteam to effectively throw away output.
resetOutputStream();
installerDb.setDatabaseName(getTestDatabase());
installerDb.setDataSource(getDataSource());
installerDb.setCreateSqlLocation(
"../opennms-daemon/src/main/filtered/etc/create.sql");
installerDb.setStoredProcedureDirectory(
"../opennms-daemon/src/main/filtered/etc");
//installerDb.setDebug(true);
installerDb.readTables();
installerDb.createSequences();
installerDb.updatePlPgsql();
installerDb.addStoredProcedures();
installerDb.createTables();
installerDb.closeConnection();
}
public ByteArrayOutputStream getOutputStream() {
return m_outputStream;
}
public void resetOutputStream() {
m_outputStream = new ByteArrayOutputStream();
installerDb.setOutputStream(new PrintStream(m_outputStream));
}
}
|
Make modal close button more visible | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { actions } from '../../../store';
const ModalContent = connect(
null,
dispatch => {
return {
handleClose() {
actions.hideModal(dispatch);
}
};
}
)(props => {
return (
<React.Fragment>
<div className="modal-header">
<button
type="button"
className="modal-close"
aria-label="Close"
onClick={props.handleClose}>
<span aria-label="close modal" className="fa fa-times" />
</button>
<h4 className="modal-title">{props.title}</h4>
</div>
<div className="modal-body">{props.body}</div>
<div className="modal-footer">{props.footer}</div>
</React.Fragment>
);
});
ModalContent.propTypes = {
// The title of the modal.
title: PropTypes.string.isRequired,
// The body of the modal.
body: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
// The footer of the modal. Usually a set of control buttons.
footer: PropTypes.element
};
export default ModalContent;
| import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { actions } from '../../../store';
const ModalContent = connect(
null,
dispatch => {
return {
handleClose() {
actions.hideModal(dispatch);
}
};
}
)(props => {
return (
<React.Fragment>
<div className="modal-header">
<button
type="button"
className="modal-close"
aria-label="Close"
onClick={props.handleClose}>
<span aria-hidden="true">×</span>
</button>
<h4 className="modal-title">{props.title}</h4>
</div>
<div className="modal-body">{props.body}</div>
<div className="modal-footer">{props.footer}</div>
</React.Fragment>
);
});
ModalContent.propTypes = {
// The title of the modal.
title: PropTypes.string.isRequired,
// The body of the modal.
body: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
// The footer of the modal. Usually a set of control buttons.
footer: PropTypes.element
};
export default ModalContent;
|
Reset image when choosing new filter | package ui;
import rgb.InvertRGBStrategy;
import rgb.RGBStrategy;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by nick on 10/22/15.
*/
public class RGBPanel extends JPanel {
private BufferedImage originalImage;
private BufferedImage image;
private RGBStrategy converter;
public RGBPanel(){
this(new InvertRGBStrategy());
}
public RGBPanel(RGBStrategy converter){
super();
this.converter = converter;
setPreferredSize(new Dimension(600, 400));
image = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
originalImage = image;
}
public void setRGBStrategy(RGBStrategy strategy){
this.converter = strategy;
}
public void convert(){
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
for(int i = 0; i < originalImage.getWidth(); i++){
for(int j = 0; j < originalImage.getHeight(); j++){
Color color = new Color(originalImage.getRGB(i, j));
color = converter.convert(color);
newImage.setRGB(i, j, color.getRGB());
}
}
image = newImage;
invalidate();
repaint();
}
public void setImage(BufferedImage img){
this.originalImage = img;
this.image = img;
setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
invalidate();
repaint();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
| package ui;
import rgb.InvertRGBStrategy;
import rgb.RGBStrategy;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by nick on 10/22/15.
*/
public class RGBPanel extends JPanel {
private BufferedImage image;
private RGBStrategy converter;
public RGBPanel(){
this(new InvertRGBStrategy());
}
public RGBPanel(RGBStrategy converter){
super();
this.converter = converter;
setPreferredSize(new Dimension(600, 400));
image = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
}
public void setRGBStrategy(RGBStrategy strategy){
this.converter = strategy;
}
public void convert(){
for(int i = 0; i < image.getWidth(); i++){
for(int j = 0; j < image.getHeight(); j++){
Color color = new Color(image.getRGB(i, j));
color = converter.convert(color);
image.setRGB(i, j, color.getRGB());
}
}
invalidate();
repaint();
}
public void setImage(BufferedImage img){
this.image = img;
setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
invalidate();
repaint();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
|
Use the value accessor as the binding context for the template | // Expose plugin as an AMD module if AMD loader is present:
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['knockout', 'jquery'], factory);
} else {
window.ko.bindingHandlers.veil = factory(ko, jQuery);
}
}(function (ko, $) {
'use strict';
/**
* A Knockout binding handler for Veil
*
* @global
*/
var veil = {
/** @lends ko.bindingHandlers.veil */
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var $element = $(element),
veilTemplate = allBindingsAccessor().veilTemplate,
veilOptions = allBindingsAccessor().veilOptions || {},
contentCallback;
contentCallback = function(overlay) {
ko.renderTemplate(veilTemplate, valueAccessor(), {}, overlay.get(0));
};
$element.veil(veilOptions);
$element.veil().addCallback('afterCreate', contentCallback);
$element.on('click', function(ev) {
if ($element.veil().isActive()) {
$element.veil().hide();
} else {
$element.veil().show();
}
ev.stopPropagation();
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
try {
$(element).veil().destroy();
} catch (e) {
}
});
}
};
return veil;
})); | // Expose plugin as an AMD module if AMD loader is present:
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['knockout', 'jquery'], factory);
} else {
window.ko.bindingHandlers.veil = factory(ko, jQuery);
}
}(function (ko, $) {
'use strict';
/**
* A Knockout binding handler for Veil
*
* @global
*/
var veil = {
/** @lends ko.bindingHandlers.veil */
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var $element = $(element),
user = ko.unwrap(valueAccessor()),
veilTemplate = allBindingsAccessor().veilTemplate,
veilOptions = allBindingsAccessor().veilOptions || {},
contentCallback;
contentCallback = function(overlay) {
ko.renderTemplate(veilTemplate, bindingContext, {}, overlay.get(0));
};
$element.veil(veilOptions);
$element.veil().addCallback('afterCreate', contentCallback);
$element.on('click', function(ev) {
if ($element.veil().isActive()) {
$element.veil().hide();
} else {
$element.veil().show();
}
ev.stopPropagation();
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
try {
$(element).veil().destroy();
} catch (e) {
}
});
}
};
return veil;
})); |
Fix renderer problems in case of non-transit layer ids | /*
* Copyright (C) 2017 con terra GmbH ([email protected])
*
* 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.
*/
define([
"dojo/_base/declare",
"ct/array"
],
function (declare, ct_array) {
return declare([], {
_serviceMetadata: null,
constructor: function (serviceMetadata) {
this._serviceMetadata = serviceMetadata;
},
getRendererForLayer: function (layerId) {
var metadata = this._serviceMetadata;
var url = ct_array.arraySearchFirst(metadata.urls, function (url) {
return layerId === url.id;
}).url;
var details = ct_array.arraySearchFirst(metadata.details, function (detail) {
return url === detail.url;
});
var id = layerId.split("/")[layerId.split("/").length - 1];
return ct_array.arraySearchFirst(details.layers, function (metadata) {
return metadata.id.toString() === id;
}).drawingInfo.renderer;
}
});
}); | /*
* Copyright (C) 2017 con terra GmbH ([email protected])
*
* 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.
*/
define([
"dojo/_base/declare",
"ct/array"
],
function (declare, ct_array) {
return declare([], {
_serviceMetadata: null,
constructor: function (serviceMetadata) {
this._serviceMetadata = serviceMetadata;
},
getRendererForLayer: function (layerId) {
var metadata = this._serviceMetadata;
var url = ct_array.arraySearchFirst(metadata.urls, function (url) {
return layerId === url.id;
}).url;
var details = ct_array.arraySearchFirst(metadata.details, function (detail) {
return url === detail.url;
});
var id = layerId.split("/")[layerId.split("/").length - 1];
return details.layers[id] && details.layers[id].drawingInfo.renderer;
}
});
}); |
Load all settings instead of explicit list for first login | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { get } from '@ember/object';
import C from 'ui/utils/constants';
import { isDevBuild } from 'shared/utils/parse-version';
export default Route.extend({
access: service(),
settings: service(),
globalStore: service(),
model() {
let promises = [];
if ( get(this, 'access.firstLogin') ) {
promises.push(get(this, 'globalStore').find('preference'));
promises.push(get(this, 'settings').loadAll());
}
return Promise.all(promises).then(() => {
const cur = get(this, `settings.${ C.SETTING.TELEMETRY }`);
const version = get(this, `settings.${ C.SETTING.VERSION_RANCHER }`);
let optIn;
if ( !version || isDevBuild(version) ) {
// For dev builds, default to opt out
optIn = (cur === 'in');
} else {
// For releases, default to opt in
optIn = (cur !== 'out');
}
return {
user: get(this, 'access.me'),
code: get(this, 'access.userCode') || '',
optIn,
};
});
},
activate() {
$('BODY').addClass('container-farm'); // eslint-disable-line
},
deactivate() {
$('BODY').removeClass('container-farm'); // eslint-disable-line
},
});
| import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { get } from '@ember/object';
import C from 'ui/utils/constants';
import { isDevBuild } from 'shared/utils/parse-version';
export default Route.extend({
access: service(),
settings: service(),
globalStore: service(),
model() {
let promises = [];
if ( get(this, 'access.firstLogin') ) {
promises.push(get(this, 'globalStore').find('preference'));
promises.push(get(this, 'settings').load([
C.SETTING.VERSION_RANCHER,
C.SETTING.TELEMETRY,
C.SETTING.EULA_AGREED,
C.SETTING.UI_DEFAULT_LANDING
]));
}
return Promise.all(promises).then(() => {
const cur = get(this, `settings.${ C.SETTING.TELEMETRY }`);
const version = get(this, `settings.${ C.SETTING.VERSION_RANCHER }`);
let optIn;
if ( !version || isDevBuild(version) ) {
// For dev builds, default to opt out
optIn = (cur === 'in');
} else {
// For releases, default to opt in
optIn = (cur !== 'out');
}
return {
user: get(this, 'access.me'),
code: get(this, 'access.userCode') || '',
optIn,
};
});
},
activate() {
$('BODY').addClass('container-farm'); // eslint-disable-line
},
deactivate() {
$('BODY').removeClass('container-farm'); // eslint-disable-line
},
});
|
Add instance methods to single player imports
Fixes https://github.com/CookPete/react-player/issues/376 | import React, { Component } from 'react'
import { propTypes, defaultProps, DEPRECATED_CONFIG_PROPS } from './props'
import { getConfig, omit, isEqual } from './utils'
import Player from './Player'
const SUPPORTED_PROPS = Object.keys(propTypes)
export default function createSinglePlayer (activePlayer) {
return class SinglePlayer extends Component {
static displayName = `${activePlayer.displayName}Player`
static propTypes = propTypes
static defaultProps = defaultProps
static canPlay = activePlayer.canPlay
shouldComponentUpdate (nextProps) {
return !isEqual(this.props, nextProps)
}
componentWillUpdate (nextProps) {
this.config = getConfig(nextProps, defaultProps)
}
getDuration = () => {
if (!this.player) return null
return this.player.getDuration()
}
getCurrentTime = () => {
if (!this.player) return null
return this.player.getCurrentTime()
}
getInternalPlayer = (key = 'player') => {
if (!this.player) return null
return this.player.getInternalPlayer(key)
}
seekTo = fraction => {
if (!this.player) return null
this.player.seekTo(fraction)
}
ref = player => {
this.player = player
}
render () {
if (!activePlayer.canPlay(this.props.url)) {
return null
}
const { style, width, height, wrapper: Wrapper } = this.props
const otherProps = omit(this.props, SUPPORTED_PROPS, DEPRECATED_CONFIG_PROPS)
return (
<Wrapper style={{ ...style, width, height }} {...otherProps}>
<Player
{...this.props}
ref={this.ref}
activePlayer={activePlayer}
config={getConfig(this.props, defaultProps)}
/>
</Wrapper>
)
}
}
}
| import React, { Component } from 'react'
import { propTypes, defaultProps, DEPRECATED_CONFIG_PROPS } from './props'
import { getConfig, omit, isEqual } from './utils'
import Player from './Player'
const SUPPORTED_PROPS = Object.keys(propTypes)
export default function createSinglePlayer (activePlayer) {
return class SinglePlayer extends Component {
static displayName = `${activePlayer.displayName}Player`
static propTypes = propTypes
static defaultProps = defaultProps
static canPlay = activePlayer.canPlay
shouldComponentUpdate (nextProps) {
return !isEqual(this.props, nextProps)
}
componentWillUpdate (nextProps) {
this.config = getConfig(nextProps, defaultProps)
}
ref = player => {
this.player = player
}
render () {
if (!activePlayer.canPlay(this.props.url)) {
return null
}
const { style, width, height, wrapper: Wrapper } = this.props
const otherProps = omit(this.props, SUPPORTED_PROPS, DEPRECATED_CONFIG_PROPS)
return (
<Wrapper style={{ ...style, width, height }} {...otherProps}>
<Player
{...this.props}
ref={this.ref}
activePlayer={activePlayer}
config={getConfig(this.props, defaultProps)}
/>
</Wrapper>
)
}
}
}
|
Improve the responses. In the case of the success the json was invalid. It required quotes | """
@author: Ferdinand E. Silva
@email: [email protected]
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
| """
@author: Ferdinand E. Silva
@email: [email protected]
@website: http://ferdinandsilva.com
"""
import os
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return "{success: true}"
else:
return '{"error": "File is too large."}'
else:
return '{"error": "File has an invalid extension."}'
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
Exit quickly to avoid side effects | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.camera.AxisCamera;
/**
*
* @author profplump
*/
public class ReadSetCamera extends CommandBase {
public ReadSetCamera() {
requires(mainCamera);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
AxisCamera camera = mainCamera.getCamera();
System.err.println("Brightness: " + camera.getBrightness());
System.err.println("ColorLevel: " + camera.getColorLevel());
System.err.println("Compression: " + camera.getCompression());
System.err.println("ExposureControl: " + camera.getExposureControl());
System.err.println("ExposurePriority: " + camera.getExposurePriority());
System.err.println("MaxFPS: " + camera.getMaxFPS());
System.err.println("Resolution: " + camera.getResolution());
System.err.println("Rotation: " + camera.getRotation());
System.err.println("WhiteBalance: " + camera.getWhiteBalance());
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
this.execute();
return true;
}
// Called once after isFinished returns true
protected void end() {
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.camera.AxisCamera;
/**
*
* @author profplump
*/
public class ReadSetCamera extends CommandBase {
public ReadSetCamera() {
requires(mainCamera);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
AxisCamera camera = mainCamera.getCamera();
System.err.println("Brightness: " + camera.getBrightness());
System.err.println("ColorLevel: " + camera.getColorLevel());
System.err.println("Compression: " + camera.getCompression());
System.err.println("ExposureControl: " + camera.getExposureControl());
System.err.println("ExposurePriority: " + camera.getExposurePriority());
System.err.println("MaxFPS: " + camera.getMaxFPS());
System.err.println("Resolution: " + camera.getResolution());
System.err.println("Rotation: " + camera.getRotation());
System.err.println("WhiteBalance: " + camera.getWhiteBalance());
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
}
|
Tweak argument unpacking for rendering decorator.
Signed-off-by: crynobone <[email protected]> | <?php
namespace Orchestra\View;
use BadMethodCallException;
class Decorator
{
/**
* The registered custom macros.
*
* @var array
*/
protected $macros = [];
/**
* Registers a custom macro.
*
* @param string $name
* @param \Closure $macro
*
* @return void
*/
public function macro($name, $macro)
{
$this->macros[$name] = $macro;
}
/**
* Render the macro.
*
* @param string $name
* @param mixed $parameters
*
* @return string
*
* @throws \BadMethodCallException
*/
public function render($name, ...$parameters)
{
if (! isset($this->macros[$name])) {
throw new BadMethodCallException("Method [$name] does not exist.");
}
return $this->macros[$name](...$parameters);
}
/**
* Dynamically handle calls to custom macros.
*
* @param string $method
* @param array $parameters
*
* @return mixed
*/
public function __call($method, $parameters)
{
array_unshift($parameters, $method);
return $this->render($method, ...$parameters);
}
}
| <?php
namespace Orchestra\View;
use BadMethodCallException;
class Decorator
{
/**
* The registered custom macros.
*
* @var array
*/
protected $macros = [];
/**
* Registers a custom macro.
*
* @param string $name
* @param \Closure $macro
*
* @return void
*/
public function macro($name, $macro)
{
$this->macros[$name] = $macro;
}
/**
* Render the macro.
*
* @param string $name
* @param mixed $parameters
*
* @return string
*
* @throws \BadMethodCallException
*/
public function render($name, ...$parameters)
{
if (! isset($this->macros[$name])) {
throw new BadMethodCallException("Method [$name] does not exist.");
}
return $this->macros[$name](...$parameters);
}
/**
* Dynamically handle calls to custom macros.
*
* @param string $method
* @param array $parameters
*
* @return mixed
*/
public function __call($method, $parameters)
{
array_unshift($parameters, $method);
return $this->render(...$parameters);
}
}
|
Fix controller call for static methods | <?php
namespace MicroFW\Routing;
use MicroFW\Http\Response;
use MicroFW\Http\IResponse;
use MicroFW\Core\Exceptions\NotValidResponseException;
class Router
{
/** @var array */
private $routes;
public function __construct($routes)
{
$this->routes = $routes;
}
/**
* Return response for request based on URL.
*
* @param $request MicroFW\Http\Request
* @return MicroFW\Http\Response
*/
public function getResponse($request)
{
$path = $request->getPath();
$response = new Response('<h1>404</h1>', 404);
foreach ($this->routes as $url => $controller) {
$matches = [];
if (preg_match('/^[\/]{0,1}' . $url . '/', $path, $matches)) {
$matches = $this->cleanRoutesParameters($matches);
$response = call_user_func($controller, $request, $matches);
break;
}
}
if ($response instanceof IResponse) {
return $response;
} else {
throw new NotValidResponseException(
gettype($response) ." is not a response object."
);
}
}
private function cleanRoutesParameters($parameters)
{
$cleanedParameters = [];
foreach ($parameters as $name => $value) {
if (is_string($name)) {
$cleanedParameters[$name] = $value;
}
}
return $cleanedParameters;
}
}
| <?php
namespace MicroFW\Routing;
use MicroFW\Http\Response;
use MicroFW\Http\IResponse;
use MicroFW\Core\Exceptions\NotValidResponseException;
class Router
{
/** @var array */
private $routes;
public function __construct($routes)
{
$this->routes = $routes;
}
/**
* Return response for request based on URL.
*
* @param $request MicroFW\Http\Request
* @return MicroFW\Http\Response
*/
public function getResponse($request)
{
$path = $request->getPath();
$response = new Response('<h1>404</h1>', 404);
foreach ($this->routes as $url => $controller) {
$matches = [];
if (preg_match('/^[\/]{0,1}' . $url . '/', $path, $matches)) {
$matches = $this->cleanRoutesParameters($matches);
$response = $controller($request, $matches);
break;
}
}
if ($response instanceof IResponse) {
return $response;
} else {
throw new NotValidResponseException(
gettype($response) ." is not a response object."
);
}
}
private function cleanRoutesParameters($parameters)
{
$cleanedParameters = [];
foreach ($parameters as $name => $value) {
if (is_string($name)) {
$cleanedParameters[$name] = $value;
}
}
return $cleanedParameters;
}
}
|
Make function name match the module name. | /*global define*/
define(function() {
"use strict";
var context2DsByWidthAndHeight = {};
/**
* Extract a pixel array from a loaded image. Draws the image
* into a canvas so it can read the pixels back.
*
* @exports getImagePixels
*
* @param {Image} image The image to extract pixels from.
*
* @returns {CanvasPixelArray} The pixels of the image.
*/
var getImagePixels = function(image, width, height) {
if (typeof width === 'undefined') {
width = image.width;
}
if (typeof height === 'undefined') {
height = image.height;
}
var context2DsByHeight = context2DsByWidthAndHeight[width];
if (typeof context2DsByHeight === 'undefined') {
context2DsByHeight = {};
context2DsByWidthAndHeight[width] = context2DsByHeight;
}
var context2d = context2DsByHeight[height];
if (typeof context2d === 'undefined') {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
context2d = canvas.getContext('2d');
context2d.globalCompositeOperation = 'copy';
context2DsByHeight[height] = context2d;
}
context2d.drawImage(image, 0, 0, width, height);
return context2d.getImageData(0, 0, width, height).data;
};
return getImagePixels;
}); | /*global define*/
define(function() {
"use strict";
var context2DsByWidthAndHeight = {};
/**
* Extract a pixel array from a loaded image. Draws the image
* into a canvas so it can read the pixels back.
*
* @param {Image} image The image to extract pixels from.
*
* @returns {CanvasPixelArray} The pixels of the image.
*/
var imageToPixels = function(image, width, height) {
if (typeof width === 'undefined') {
width = image.width;
}
if (typeof height === 'undefined') {
height = image.height;
}
var context2DsByHeight = context2DsByWidthAndHeight[width];
if (typeof context2DsByHeight === 'undefined') {
context2DsByHeight = {};
context2DsByWidthAndHeight[width] = context2DsByHeight;
}
var context2d = context2DsByHeight[height];
if (typeof context2d === 'undefined') {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
context2d = canvas.getContext('2d');
context2d.globalCompositeOperation = 'copy';
context2DsByHeight[height] = context2d;
}
context2d.drawImage(image, 0, 0, width, height);
return context2d.getImageData(0, 0, width, height).data;
};
return imageToPixels;
}); |
Add DataFile class to split words of a line and count it | #!/usr/bin/python
# coding: latin-1
#------------------------------------------------------------------------------#
# Artificial Intelligence - Bayes Classification Algorithms #
# ============================================================================ #
# Organization: HE-Arc Engineering #
# Developer(s): Etienne Frank #
# Johan Chavaillaz #
# #
# Filename: BayesClassification.py #
# Version: 1.0 #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
# #
# LIBRARIES IMPORT #
# #
#------------------------------------------------------------------------------#
import sys
#------------------------------------------------------------------------------#
# #
# CLASSES #
# #
#------------------------------------------------------------------------------#
class DataFile:
def __init__(self, fileLine, isGood):
"""
:rtype : object
"""
self.isGood = isGood
self.fileLine = fileLine
self.wordsCount = {}
self.words = fileLine.split()
for word in self.words:
try:
self.wordsCount[word] += 1
except KeyError:
self.wordsCount[word] = 1
self.sumWords = sum(self.wordsCount.values())
def __repr__(self):
print("input : "+self.fileLine)
for key, val in self.wordsCount.items():
print(str(key)+" "+str(val))
print(str(self.sumWords))
return ""
#------------------------------------------------------------------------------#
# #
# UTILITIES FUNCTIONS #
# #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
# #
# "MAIN" FUNCTION #
# #
#------------------------------------------------------------------------------#
# If this is the main module, run this
if __name__ == '__main__':
argsCount = len(sys.argv)
argsIndex = 1
toto = DataFile("coucou je suis une grosse bite et je vous emmerde Monsieur le PD n'ha n'ha n'aire", True)
print(toto) | #!/usr/bin/python
# coding: latin-1
#------------------------------------------------------------------------------#
# Artificial Intelligence - Bayes Classification Algorithms #
# ============================================================================ #
# Organization: HE-Arc Engineering #
# Developer(s): Etienne Frank #
# Johan Chavaillaz #
# #
# Filename: BayesClassification.py #
# Version: 1.0 #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
# #
# LIBRARIES IMPORT #
# #
#------------------------------------------------------------------------------#
import sys
#------------------------------------------------------------------------------#
# #
# CLASSES #
# #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
# #
# UTILITIES FUNCTIONS #
# #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
# #
# "MAIN" FUNCTION #
# #
#------------------------------------------------------------------------------#
# If this is the main module, run this
if __name__ == '__main__':
argsCount = len(sys.argv)
argsIndex = 1 |
Use glyphicons in the header so they download earlier. | /*
* @flow
*/
import * as React from 'react';
import {getClassName} from './Bootstrap/GlyphiconNames';
export default function Navbar() {
return (
<nav className="navbar navbar-default navbar-fixed-top navbar-inverse">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="/" onClick={(e: SyntheticEvent<>) => {
e.preventDefault();
window.location.hash = '';
window.location.reload();
}}>
Bonsai
</a>
<p className="navbar-text">
<span
className={getClassName('tree-conifer')}
aria-hidden="true"></span>
Trim your dependency trees
</p>
</div>
<ul className="nav navbar-nav navbar-right">
<li>
<a className="navbar-link" href="https://pinterest.github.io/bonsai/">
<span
className={getClassName('book')}
aria-hidden="true"></span>
Docs
</a>
</li>
<li>
<a className="navbar-link" href="https://github.com/pinterest/bonsai">
Github
</a>
</li>
</ul>
</div>
</nav>
);
}
| /*
* @flow
*/
import * as React from 'react';
export default function Navbar() {
return (
<nav className="navbar navbar-default navbar-fixed-top navbar-inverse">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="/" onClick={(e: SyntheticEvent<>) => {
e.preventDefault();
window.location.hash = '';
window.location.reload();
}}>
Bonsai
</a>
<p className="navbar-text">
Trim your dependency trees
</p>
</div>
<ul className="nav navbar-nav navbar-right">
<li>
<a className="navbar-link" href="https://pinterest.github.io/bonsai/">
Docs
</a>
</li>
<li>
<a className="navbar-link" href="https://github.com/pinterest/bonsai">
Github
</a>
</li>
</ul>
</div>
</nav>
);
}
|
Throw more applicable exception, and spell it right this time. | <?php
namespace ComplexPie;
class Data extends Extension
{
protected static $static_ext = array();
public static function add_static_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_static_extension($extpoint, $ext, $priority);
}
public function add_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_extension($extpoint, $ext, $priority);
}
/**
* @todo This should cope with things that return an array and merge them
*/
public function __get($name)
{
foreach ($this->get_extensions('get') as $extension => $priority)
{
if (($return = $extension($this->dom, $name)) !== null)
{
return $return;
}
}
if (method_exists($this, "get_$name"))
{
return call_user_func(array($this, "get_$name"));
}
}
}
Data::add_static_extension_point('get');
| <?php
namespace ComplexPie;
class Data extends Extension
{
protected static $static_ext = array();
public static function add_static_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new Excetpion("$ext is not callable");
}
parent::add_static_extension($extpoint, $ext, $priority);
}
public function add_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new Excetpion("$ext is not callable");
}
parent::add_extension($extpoint, $ext, $priority);
}
/**
* @todo This should cope with things that return an array and merge them
*/
public function __get($name)
{
foreach ($this->get_extensions('get') as $extension => $priority)
{
if (($return = $extension($this->dom, $name)) !== null)
{
return $return;
}
}
if (method_exists($this, "get_$name"))
{
return call_user_func(array($this, "get_$name"));
}
}
}
Data::add_static_extension_point('get');
|
refactor(smButton): Use to manage css classes | (function() {
'use strict';
angular
.module('semantic.ui.elements.button', [])
.directive('smButton', smButton);
smButton['$inject'] = ['$animate'];
function smButton($animate) {
return {
restrict:'E',
replace: true,
transclude: true,
template: setTemplate,
link: function(scope, element, attrs, ctrl, transclude) {
var node = element[0];
transclude(scope, function(nodes) {
element.append(nodes);
});
if (isAnchorBtn(attrs)) {
scope.$watch(attrs.ngDisabled, function(isDisabled) {
element.attr('tabindex', isDisabled ? -1 : 0);
if (isDisabled) {
$animate.addClass(element, 'disabled');
}
});
}
if (attrs.ariaLabel === void 0) {
element.attr('aria-label', node.textContent.trim());
}
scope.$watch(attrs.ngDisabled, function(isDisabled) {
if (isDisabled) {
$animate.addClass(element, 'disabled');
}
});
}
};
function isAnchorBtn(attrs) {
return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0;
}
function setTemplate(element, attrs) {
if (isAnchorBtn(attrs)) {
return '<a class="ui button"></a>';
} else {
return '<button class="ui button"></button>';
}
}
}
})();
| (function() {
'use strict';
angular
.module('semantic.ui.elements.button', [])
.directive('smButton', smButton);
function smButton() {
return {
restrict:'E',
replace: true,
transclude: true,
template: setTemplate,
link: function(scope, element, attrs, ctrl, transclude) {
var node = element[0];
transclude(function(nodes) {
element.append(nodes);
});
if (isAnchorBtn(attrs)) {
scope.$watch(attrs.ngDisabled, function(isDisabled) {
element.attr('tabindex', isDisabled ? -1 : 0);
if (isDisabled) {
element.addClass('disabled');
}
});
}
if (attrs.ariaLabel === void 0) {
element.attr('aria-label', node.textContent.trim());
}
scope.$watch(attrs.ngDisabled, function(isDisabled) {
if (isDisabled) {
element.addClass('disabled');
}
});
}
};
function isAnchorBtn(attrs) {
return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0;
}
function setTemplate(element, attrs) {
if (isAnchorBtn(attrs)) {
return '<a class="ui button"></a>';
} else {
return '<button class="ui button"></button>';
}
}
}
})();
|
Add iterable to list of not allowed doubles types in specification | <?php
namespace spec\PhpSpec\CodeAnalysis;
use PhpSpec\CodeAnalysis\DisallowedScalarTypehintException;
use PhpSpec\CodeAnalysis\NamespaceResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class StaticRejectingNamespaceResolverSpec extends ObjectBehavior
{
function let(NamespaceResolver $namespaceResolver)
{
$this->beConstructedWith($namespaceResolver);
}
function it_is_initializable()
{
$this->shouldHaveType('PhpSpec\CodeAnalysis\NamespaceResolver');
}
function it_delegates_analysis_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
{
$this->analyse('foo');
$namespaceResolver->analyse('foo')->shouldhaveBeenCalled();
}
function it_delegates_resolution_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
{
$namespaceResolver->resolve('Bar')->willReturn('Foo\Bar');
$this->resolve('Bar')->shouldReturn('Foo\Bar');
}
function it_does_not_allow_resolution_of_scalar_types()
{
$this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('int');
$this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('float');
$this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('string');
$this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('bool');
$this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('iterable');
}
}
| <?php
namespace spec\PhpSpec\CodeAnalysis;
use PhpSpec\CodeAnalysis\NamespaceResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class StaticRejectingNamespaceResolverSpec extends ObjectBehavior
{
function let(NamespaceResolver $namespaceResolver)
{
$this->beConstructedWith($namespaceResolver);
}
function it_is_initializable()
{
$this->shouldHaveType('PhpSpec\CodeAnalysis\NamespaceResolver');
}
function it_delegates_analysis_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
{
$this->analyse('foo');
$namespaceResolver->analyse('foo')->shouldhaveBeenCalled();
}
function it_delegates_resolution_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
{
$namespaceResolver->resolve('Bar')->willReturn('Foo\Bar');
$this->resolve('Bar')->shouldReturn('Foo\Bar');
}
function it_does_not_allow_resolution_of_scalar_types()
{
$this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('int');
$this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('float');
$this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('string');
$this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('bool');
}
}
|
Fix FBTest: again the inline editor can be async on Mac | function runTest()
{
FBTest.sysout("issue5755.START");
FBTest.openNewTab(basePath + "html/5755/issue5755.html", function (win)
{
FBTest.openFirebug();
var panel = FBTest.selectPanel("html");
if (FBTest.ok(panel, "Firebug must be opened and switched to HTML panel now."))
{
// to make sure displayedAttributeValueLimit hasn't a value of 0
FBTest.setPref("displayedAttributeValueLimit", 10);
var longOnclickValue = win.document.getElementById("long-onclick").
getAttribute("onclick");
FBTest.selectElementInHtmlPanel("long-onclick", function (nodes)
{
// getting onclick attribute's value
var onclickValue = nodes.getElementsByClassName("nodeValue").item(1);
FBTest.synthesizeMouse(onclickValue);
// Wait till the inline editor is available.
var config = {tagName: "input", classes: "textEditorInner"};
FBTest.waitForDisplayedElement("html", config, function(texteditor)
{
if (FBTest.ok(texteditor, "Editor must be loaded now."))
{
FBTest.compare(longOnclickValue, texteditor.value,
"Inline editor must contain whole string of onclick value.");
}
FBTest.testDone("issue5755.DONE");
});
});
}
else
{
FBTest.testDone("issue5755.FAILED");
}
});
} | function runTest()
{
FBTest.sysout("issue5755.START");
FBTest.openNewTab(basePath + "html/5755/issue5755.html", function (win)
{
FBTest.openFirebug();
var panel = FBTest.selectPanel("html");
if (FBTest.ok(panel, "Firebug must be opened and switched to HTML panel now."))
{
// to make sure displayedAttributeValueLimit hasn't a value of 0
FBTest.setPref("displayedAttributeValueLimit", 10);
var longOnclickValue = win.document.getElementById("long-onclick").
getAttribute("onclick");
FBTest.selectElementInHtmlPanel("long-onclick", function (nodes)
{
// getting onclick attribute's value
var onclickValue = nodes.getElementsByClassName("nodeValue").item(1);
FBTest.synthesizeMouse(onclickValue);
var texteditor = panel.panelNode.getElementsByClassName("textEditorInner").item(0);
if (FBTest.ok(texteditor, "Editor must be loaded now."))
{
FBTest.compare(longOnclickValue, texteditor.value,
"Inline editor must contain whole string of onclick value.");
}
FBTest.testDone("issue5755.DONE");
});
}
else
{
FBTest.testDone("issue5755.FAILED");
}
});
} |
Set the git author name and e-mail | import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
"""Save exam or question content to a git repository and to a database."""
# object = None
# request = None
# template_name = None
def write_content(self, directory, form, inlines=None):
try:
repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH'])
os.environ['GIT_AUTHOR_NAME'] = 'Numbas'
os.environ['GIT_AUTHOR_EMAIL'] = '[email protected]'
path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'],
directory, self.object.filename)
fh = open(path_to_file, 'w')
fh.write(self.object.content)
fh.close()
repo.index.add([os.path.join(directory, self.object.filename)])
repo.index.commit('Made some changes to %s' % self.object.name)
except IOError:
error = "Could not save file."
return render(self.request, self.template_name,
{'form': form, 'inlines': inlines, 'error': error,
'object': self.object})
self.object = form.save()
if inlines is not None:
for formset in inlines:
formset.save()
return HttpResponseRedirect(self.get_success_url()) | import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
"""Save exam or question content to a git repository and to a database."""
# object = None
# request = None
# template_name = None
def write_content(self, directory, form, inlines=None):
try:
repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH'])
path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'],
directory, self.object.filename)
fh = open(path_to_file, 'w')
fh.write(self.object.content)
fh.close()
repo.index.add([os.path.join(directory, self.object.filename)])
repo.index.commit('Made some changes to %s' % self.object.name)
except IOError:
error = "Could not save file."
return render(self.request, self.template_name,
{'form': form, 'inlines': inlines, 'error': error,
'object': self.object})
self.object = form.save()
if inlines is not None:
for formset in inlines:
formset.save()
return HttpResponseRedirect(self.get_success_url()) |
Use string literals when declaring event listeners | <?php
namespace NUSWhispers\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'NUSWhispers\Events\ConfessionWasCreated' => [
'NUSWhispers\Listeners\SyncConfessionTags',
],
'NUSWhispers\Events\ConfessionWasUpdated' => [
'NUSWhispers\Listeners\SyncConfessionTags',
],
'NUSWhispers\Events\ConfessionWasDeleted' => [
'NUSWhispers\Listeners\DeleteConfessionFromFacebook',
],
'NUSWhispers\Events\ConfessionStatusWasChanged' => [
'NUSWhispers\Listeners\FlushConfessionQueue',
'NUSWhispers\Listeners\LogConfessionStatusChange',
],
'NUSWhispers\Events\ConfessionWasApproved' => [
'NUSWhispers\Listeners\PostConfessionToFacebook',
],
'NUSWhispers\Events\ConfessionWasFeatured' => [
'NUSWhispers\Listeners\PostConfessionToFacebook',
],
'NUSWhispers\Events\ConfessionWasRejected' => [
'NUSWhispers\Listeners\DeleteConfessionFromFacebook',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
}
}
| <?php
namespace NUSWhispers\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
\NUSWhispers\Events\ConfessionWasCreated::class => [
\NUSWhispers\Listeners\SyncConfessionTags::class,
],
\NUSWhispers\Events\ConfessionWasUpdated::class => [
\NUSWhispers\Listeners\SyncConfessionTags::class,
],
\NUSWhispers\Events\ConfessionWasDeleted::class => [
\NUSWhispers\Listeners\DeleteConfessionFromFacebook::class,
],
\NUSWhispers\Events\ConfessionStatusWasChanged::class => [
\NUSWhispers\Listeners\FlushConfessionQueue::class,
\NUSWhispers\Listeners\LogConfessionStatusChange::class,
],
\NUSWhispers\Events\ConfessionWasApproved::class => [
\NUSWhispers\Listeners\PostConfessionToFacebook::class,
],
\NUSWhispers\Events\ConfessionWasFeatured::class => [
\NUSWhispers\Listeners\PostConfessionToFacebook::class,
],
\NUSWhispers\Events\ConfessionWasRejected::class => [
\NUSWhispers\Listeners\DeleteConfessionFromFacebook::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
}
}
|
Allow the event sink host to be configured | 'use strict'
const ndjson = require('ndjson'),
request = require('request'),
zlib = require('zlib')
module.exports = (readableObjectStream, eventWriteKey, eventSinkHost) => {
const options = {
url: `https://${eventSinkHost || 'event-sink.appuri.net'}/e?jsonConnectorApiKey=${eventWriteKey}`,
headers: {
'Content-Type': 'application/x-ldjson',
'Content-Encoding': 'gzip'
}
},
serialize = ndjson.serialize(),
compress = zlib.createGzip(),
post = request.post(options)
readableObjectStream
.pipe(serialize)
.pipe(compress)
.pipe(post)
return new Promise((resolve, reject) => {
let resp
readableObjectStream.on('error', reject)
serialize.on('error', reject)
compress.on('error', reject)
post.on('error', reject)
post.on('response', response => {
resp = response
if (response.statusCode >= 400) {
var body = ''
response.setEncoding('utf8')
response.on('data', d => body += d)
response.on('error', () => reject({ statusCode: response.statusCode }))
response.on('end', () => {
try { body = JSON.parse(body) } catch(e){}
reject({
statusCode: response.statusCode,
responseBody: body
})
})
}
})
post.on('end', () => resolve(resp))
})
}
| 'use strict'
const ndjson = require('ndjson'),
request = require('request'),
zlib = require('zlib')
module.exports = (readableObjectStream, eventWriteKey) => {
const options = {
url: `https://event-sink.appuri.net/e?jsonConnectorApiKey=${eventWriteKey}`,
headers: {
'Content-Type': 'application/x-ldjson',
'Content-Encoding': 'gzip'
}
},
serialize = ndjson.serialize(),
compress = zlib.createGzip(),
post = request.post(options)
readableObjectStream
.pipe(serialize)
.pipe(compress)
.pipe(post)
return new Promise((resolve, reject) => {
let resp
readableObjectStream.on('error', reject)
serialize.on('error', reject)
compress.on('error', reject)
post.on('error', reject)
post.on('response', response => {
resp = response
if (response.statusCode >= 400) {
var body = ''
response.setEncoding('utf8')
response.on('data', d => body += d)
response.on('error', () => reject({ statusCode: response.statusCode }))
response.on('end', () => {
try { body = JSON.parse(body) } catch(e){}
reject({
statusCode: response.statusCode,
responseBody: body
})
})
}
})
post.on('end', () => resolve(resp))
})
}
|
Update Laravel .htaccess to fix redirect loop on DirectoryIndex pages such as /tests/ | (function(exports) {
"use strict";
var request = require('request');
var Sink = require('pipette').Sink;
var unzipper = require('../process-zip');
var fs = require('fs');
exports.downloadLaravel = function(grunt, init, done) {
unzipper.processZip(request('https://github.com/laravel/laravel/archive/master.zip'), {
fromdir: 'laravel-master/',
todir: 'build/',
verbose: function(msg) {
grunt.verbose.writeln(msg);
},
complete: done,
rename: function(file) {
var matches = /^(.*)\.md$/.exec(file);
if (matches) {
return matches[1] + '-Laravel.md';
}
if (/build\/public\/.htaccess$/.test(file)) {
// need to append this file because it already exists (comes with h5bp)
new Sink(this).on('data', function(buffer) {
// need to add an exception for pages served via DirectoryIndex
// before the line containing
// RewriteRule ^(.*)/$
// insert
// RewriteCond %{REQUEST_FILENAME}/index.html !-f
var htaccess = buffer.toString().replace(/(RewriteRule \^\(\.\*\)\/\$[^\r\n]*)/g, 'RewriteCond %{REQUEST_FILENAME}/index.html !-f\n $1');
htaccess = '\n' +
'# ----------------------------------------------------------------------\n' +
'# Laravel framework\n' +
'# ----------------------------------------------------------------------\n' +
htaccess;
fs.appendFileSync(file, htaccess);
});
}
return file;
}
});
};
})(typeof exports === 'object' && exports || this);
| (function(exports) {
"use strict";
var request = require('request');
var Sink = require('pipette').Sink;
var unzipper = require('../process-zip');
var fs = require('fs');
exports.downloadLaravel = function(grunt, init, done) {
unzipper.processZip(request('https://github.com/laravel/laravel/archive/master.zip'), {
fromdir: 'laravel-master/',
todir: 'build/',
verbose: function(msg) {
grunt.verbose.writeln(msg);
},
complete: done,
rename: function(file) {
var matches = /^(.*)\.md$/.exec(file);
if (matches) {
return matches[1] + '-Laravel.md';
}
if (/build\/public\/.htaccess$/.test(file)) {
// need to append this file because it already exists (comes with h5bp)
new Sink(this).on('data', function(buffer) {
var htaccess = '\n' +
'# ----------------------------------------------------------------------\n' +
'# Laravel framework\n' +
'# ----------------------------------------------------------------------\n' +
buffer.toString();
fs.appendFileSync(file, htaccess);
});
}
return file;
}
});
};
})(typeof exports === 'object' && exports || this);
|
Update name property, rename id in failed function call. | (function (env) {
"use strict";
env.ddg_spice_rfc = function(api_result) {
if (!api_result || api_result.error || api_result.message == "no results.") {
return Spice.failed('request_for_comments');
}
Spice.add({
id: "rfc",
name: "Answer",
data: api_result,
meta: {
sourceName: "RFC Search"
},
normalize: function(item) {
return {
title: item.title,
altSubtitle: item.authors,
description: item.moreinfo,
url: item.link,
number: item.number,
date: item.date
};
},
templates: {
group: 'text',
detail: false,
item_detail: false,
options: {
moreAt: false,
footer: Spice.rfc.footer
},
variants: {
tile: 'wide',
tileTitle: '3line-small',
tileSnippet: 'small',
tileFooter: '2line'
}
}
});
};
}(this));
| (function (env) {
"use strict";
env.ddg_spice_rfc = function(api_result) {
if (!api_result || api_result.error || api_result.message == "no results.") {
return Spice.failed('rfc');
}
Spice.add({
id: "rfc",
name: "Reference",
data: api_result,
meta: {
sourceName: "RFC Search"
},
normalize: function(item) {
return {
title: item.title,
altSubtitle: item.authors,
description: item.moreinfo,
url: item.link,
number: item.number,
date: item.date
};
},
templates: {
group: 'text',
detail: false,
item_detail: false,
options: {
moreAt: false,
footer: Spice.rfc.footer
},
variants: {
tile: 'wide',
tileTitle: '3line-small',
tileSnippet: 'small',
tileFooter: '2line'
}
}
});
};
}(this));
|
Make sure django is 1.8 or higher | #!/usr/bin/env python
"""
Install wagtailvideos using setuptools
"""
with open('README.rst', 'r') as f:
readme = f.read()
from setuptools import find_packages, setup
setup(
name='wagtailvideos',
version='0.1.11',
description="A wagtail module for uploading and displaying videos in various codecs.",
long_description=readme,
author='Takeflight',
author_email='[email protected]',
url='https://github.com/takeflight/wagtailvideos',
install_requires=[
'wagtail>=1.4',
'Django>=1.8',
'django-enumchoicefield==0.6.0',
],
extras_require={
'testing': [
'mock==2.0.0'
]
},
zip_safe=False,
license='BSD License',
packages=find_packages(),
include_package_data=True,
package_data={},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
],
)
| #!/usr/bin/env python
"""
Install wagtailvideos using setuptools
"""
with open('README.rst', 'r') as f:
readme = f.read()
from setuptools import find_packages, setup
setup(
name='wagtailvideos',
version='0.1.11',
description="A wagtail module for uploading and displaying videos in various codecs.",
long_description=readme,
author='Takeflight',
author_email='[email protected]',
url='https://github.com/takeflight/wagtailvideos',
install_requires=[
'wagtail>=1.4',
'django-enumchoicefield==0.6.0',
],
extras_require={
'testing': [
'mock==2.0.0'
]
},
zip_safe=False,
license='BSD License',
packages=find_packages(),
include_package_data=True,
package_data={},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
],
)
|
Add assert to num knots validation unit test | import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
assert False, "Number of knots validation should have failed"
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
| import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
|
Move progressbar stuff to dedicated function | var QuestionView = function (data) {
//View for the overview screen
this.createProgressBar = function() {
var answered = app.model.getCategoryAnswered(data);
if (answered){
var progress = Math.round(answered.sizeFinished / answered.sizeQuestions);
log('Current category progress: ' + progress);
$.getScript('js/progressbar.js').done(function(){
//create the progressbar
jQMProgressBar('pb_question')
.setOuterTheme('b')
.setInnerTheme('e')
.isMini(true)
.setMax(progress)
.setStartFrom(0)
.setInterval(10)
.showCounter(true)
.build()
.run();
});
}
}
this.initialize = function () {
// View constructor
if (app.loggedin == true){
//Show all categories
log('Loading question..');
result = app.model.getQuestion(data);
if (result){
log(result);
result.catid = data;
render('question', {
question: result,
});
this.createProgressBar();
} else {
setErrorMessage('Error retrieving question.');
goToScreen();
}
} else {
//Re-render and show login page with login filled in
setErrorMessage('You are not logged in!');
log('Not logged in for question!');
redirect('login');
}
}
this.initialize();
} | var QuestionView = function (data) {
//View for the overview screen
this.initialize = function () {
// View constructor
if (app.loggedin == true){
//Show all categories
log('Loading question..');
result = app.model.getQuestion(data);
if (result){
log(result);
var selected;
result.catid = data;
render('question', {
question: result,
});
var answered = app.model.getCategoryAnswered(data);
if (answered){
var progress = Math.round(answered.sizeFinished / answered.sizeQuestions);
log('Current category progress: ' + progress);
$.getScript('js/progressbar.js').done(function(){
//create the progressbar
jQMProgressBar('pb_question')
.setOuterTheme('b')
.setInnerTheme('e')
.isMini(true)
.setMax(progress)
.setStartFrom(0)
.setInterval(10)
.showCounter(true)
.build()
.run();
});
}
} else {
setErrorMessage('Error retrieving question.');
goToScreen();
}
} else {
//Re-render and show login page with login filled in
setErrorMessage('You are not logged in!');
log('Not logged in for question!');
redirect('login');
}
}
this.initialize();
} |
Handle toJSON call with missing this.data | "use strict";
var util = require("util");
var AbstractError = require("./AbstractError.js"),
defaultRenderer = require("./defaultRenderer.js");
/**
* generate Error-classes based on AbstractError
*
* @param error
* @returns {Function}
*/
function erroz(error) {
var errorFn = function (data) {
//add per instance properties
this.data = data;
this.message = this.message || erroz.options.renderMessage(error.template, data);
errorFn.super_.call(this, this.constructor);
};
util.inherits(errorFn, AbstractError);
//add static error properties (name, status, etc.)
for (var errKey in error) {
if (error.hasOwnProperty(errKey)) {
errorFn.prototype[errKey] = error[errKey];
}
}
errorFn.prototype.toJSON = function() {
var data = this.data || {};
if(erroz.options.includeStack) {
data.stack = this.stack;
}
return {
status: this.status,
code: this.code,
message: this.message,
data: data
};
};
return errorFn;
}
erroz.options = {
/**
* overwrite this function for custom rendered messages
*
* @param {Object} data
* @param {String=} template
* @returns {String}
*/
renderMessage: defaultRenderer,
includeStack: true
};
module.exports = erroz; | "use strict";
var util = require("util");
var AbstractError = require("./AbstractError.js"),
defaultRenderer = require("./defaultRenderer.js");
/**
* generate Error-classes based on AbstractError
*
* @param error
* @returns {Function}
*/
function erroz(error) {
var errorFn = function (data) {
//add per instance properties
this.data = data;
this.message = this.message || erroz.options.renderMessage(error.template, data);
errorFn.super_.call(this, this.constructor);
};
util.inherits(errorFn, AbstractError);
//add static error properties (name, status, etc.)
for (var errKey in error) {
if (error.hasOwnProperty(errKey)) {
errorFn.prototype[errKey] = error[errKey];
}
}
errorFn.prototype.toJSON = function() {
var data = this.data;
if(erroz.options.includeStack) {
data.stack = this.stack;
}
return {
status: this.status,
code: this.code,
message: this.message,
data: data
};
};
return errorFn;
}
erroz.options = {
/**
* overwrite this function for custom rendered messages
*
* @param {Object} data
* @param {String=} template
* @returns {String}
*/
renderMessage: defaultRenderer,
includeStack: true
};
module.exports = erroz; |
Fix form submission bug in comment dialog | ;(function($, ns) {
ns.Comment = chorus.dialogs.Base.extend({
className : "comment",
title : t("comments.new_dialog.title"),
persistent : true,
events: {
"submit form": "save"
},
makeModel : function(options){
this._super("makeModel", options);
this.model = new chorus.models.Comment({
entityType : this.options.launchElement.data("entity-type"),
entityId : this.options.launchElement.data("entity-id")
});
this.model.bind("saved", this.saved, this);
this.entityTitle = this.options.launchElement.data("entity-title")
},
postRender: function() {
var self = this;
_.defer(function() {
self.$("textarea").elastic();
// Workaround elastic's blur making the form not submit (sometimes!!!)
//
self.$("textarea").unbind("blur");
});
},
additionalContext : function() {
return { entityTitle : this.entityTitle }
},
save: function(e) {
console.log("save!")
e.preventDefault();
this.model.save({body : this.$("textarea[name=body]").val().trim()})
},
saved : function() {
this.pageModel.trigger("invalidated");
this.closeModal();
}
});
})(jQuery, chorus.dialogs);
| ;(function($, ns) {
ns.Comment = chorus.dialogs.Base.extend({
className : "comment",
title : t("comments.new_dialog.title"),
persistent : true,
events: {
"submit form": "save"
},
makeModel : function(options){
this._super("makeModel", options);
this.model = new chorus.models.Comment({
entityType : this.options.launchElement.data("entity-type"),
entityId : this.options.launchElement.data("entity-id")
});
this.model.bind("saved", this.saved, this);
this.entityTitle = this.options.launchElement.data("entity-title")
},
postRender: function() {
var self = this;
_.defer(function() { self.$("textarea").elastic() });
},
additionalContext : function() {
return { entityTitle : this.entityTitle }
},
save: function(e) {
e.preventDefault();
this.model.save({body : this.$("textarea[name=body]").val().trim()})
},
saved : function() {
this.pageModel.trigger("invalidated");
this.closeModal();
}
});
})(jQuery, chorus.dialogs);
|
Delete whitespace at line 7
Delete a white space for travis | from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class ControlerLogoutTest(TestCase):
"""Unit test suite for testing the controler of
Logout in the app: tosp_auth.
Test that if the functionality of logout is correct.
"""
def setUp(self):
"""Initialize the browser and create a user, before running the tests.
"""
User.objects.create_user(
username='thelma', email='[email protected]', password='junipero')
def test_logout_does_not_do_that(self):
"""Verify if the Logout works.
"""
self.client.login(username='thelma', password='junipero')
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Log Out")
self.client.logout()
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "login")
def test_expected_url(self):
"""Verify if redirect to the right url.
"""
self.client.login(username='thelma', password='junipero')
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.client.logout()
| from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class ControlerLogoutTest(TestCase):
"""Unit test suite for testing the controler of
Logout in the app: tosp_auth.
Test that if the functionality of logout is correct.
"""
def setUp(self):
"""Initialize the browser and create a user, before running the tests.
"""
User.objects.create_user(
username='thelma', email='[email protected]', password='junipero')
def test_logout_does_not_do_that(self):
"""Verify if the Logout works.
"""
self.client.login(username='thelma', password='junipero')
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Log Out")
self.client.logout()
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "login")
def test_expected_url(self):
"""Verify if redirect to the right url.
"""
self.client.login(username='thelma', password='junipero')
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.client.logout()
|
Fix for fixtures populator entity array | <?php
namespace Kunstmaan\FixturesBundle\Populator;
use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\FixturesBundle\Populator\Methods\MethodInterface;
class Populator
{
/**
* @var MethodInterface[]
*/
private $populators;
public function __construct()
{
$this->populators = new ArrayCollection();
}
public function populate($entity, $data)
{
foreach ($data as $property => $value) {
foreach ($this->populators as $populator) {
if ($populator->canSet($entity, $property, $value)) {
if ($value instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
$populator->set($entity, $property, $value->getEntity());
} elseif(is_array($value)) {
foreach($value as &$item) {
if($item instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
$item = $item->getEntity();
}
}
$populator->set($entity, $property, $value);
} else {
$populator->set($entity, $property, $value);
}
break;
}
}
}
}
public function addPopulator(MethodInterface $populator, $alias)
{
$this->populators->set($alias, $populator);
return $this;
}
}
| <?php
namespace Kunstmaan\FixturesBundle\Populator;
use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\FixturesBundle\Populator\Methods\MethodInterface;
class Populator
{
/**
* @var MethodInterface[]
*/
private $populators;
public function __construct()
{
$this->populators = new ArrayCollection();
}
public function populate($entity, $data)
{
foreach ($data as $property => $value) {
foreach ($this->populators as $populator) {
if ($populator->canSet($entity, $property, $value)) {
if ($value instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
$populator->set($entity, $property, $value->getEntity());
} else {
$populator->set($entity, $property, $value);
}
break;
}
}
}
}
public function addPopulator(MethodInterface $populator, $alias)
{
$this->populators->set($alias, $populator);
return $this;
}
}
|
Make owner visible to superusers | from django.contrib import admin
from .models import FileUpload
class FileUploadAdmin(admin.ModelAdmin):
def get_changeform_initial_data(self, request):
return {'owner': request.user}
def get_fields(self, request, obj=None):
if request.user.is_superuser:
return ['file', 'url_name', 'owner']
else:
return ['file', 'url_name']
def get_readonly_fields(self, request, obj=None):
if obj:
return self.readonly_fields + ('file', 'url_name')
return self.readonly_fields
def has_change_permission(self, request, obj=None):
has_class_permission = super().has_change_permission(request, obj)
if not has_class_permission:
return False
if obj is None:
return True
owns_object = request.user.id == obj.owner.id
if request.user.is_superuser or owns_object:
return True
return False
def has_delete_permission(self, request, obj=None):
return self.has_change_permission(request, obj)
def get_queryset(self, request):
if request.user.is_superuser:
return FileUpload.objects.all()
return FileUpload.objects.filter(owner=request.user)
def save_model(self, request, obj, form, change):
if not change:
obj.owner = request.user
obj.save()
admin.site.register(FileUpload, FileUploadAdmin)
| from django.contrib import admin
from .models import FileUpload
class FileUploadAdmin(admin.ModelAdmin):
readonly_fields = ['owner']
def get_fields(self, request, obj=None):
if request.user.is_superuser:
return ['file', 'url_name', 'owner']
else:
return ['file', 'url_name']
def get_readonly_fields(self, request, obj=None):
if obj:
return self.readonly_fields + ['file', 'url_name']
return self.readonly_fields
def has_change_permission(self, request, obj=None):
has_class_permission = super().has_change_permission(request, obj)
if not has_class_permission:
return False
if obj is None:
return True
owns_object = request.user.id == obj.owner.id
if request.user.is_superuser or owns_object:
return True
return False
def has_delete_permission(self, request, obj=None):
return self.has_change_permission(request, obj)
def get_queryset(self, request):
if request.user.is_superuser:
return FileUpload.objects.all()
return FileUpload.objects.filter(owner=request.user)
def save_model(self, request, obj, form, change):
if not change:
obj.owner = request.user
obj.save()
admin.site.register(FileUpload, FileUploadAdmin)
|
Allow `@tailwind screens` directive inside an at-rule | import _ from 'lodash'
import postcss from 'postcss'
import cloneNodes from '../util/cloneNodes'
import buildMediaQuery from '../util/buildMediaQuery'
export default function(config) {
return function(css) {
const screens = config().screens
const responsiveRules = []
let finalRules = []
css.walkAtRules('responsive', atRule => {
const nodes = atRule.nodes
responsiveRules.push(...cloneNodes(nodes))
atRule.before(nodes)
atRule.remove()
})
_.keys(screens).forEach(screen => {
const mediaQuery = postcss.atRule({
name: 'media',
params: buildMediaQuery(screens[screen]),
})
mediaQuery.append(
responsiveRules.map(rule => {
const cloned = rule.clone()
cloned.selectors = _.map(rule.selectors, selector => `.${screen}\\:${selector.slice(1)}`)
return cloned
})
)
finalRules.push(mediaQuery)
})
const hasScreenRules = finalRules.some(i => i.nodes.length !== 0)
if (!hasScreenRules) {
return
}
let includesScreensExplicitly = false
css.walkAtRules('tailwind', atRule => {
if (atRule.params === 'screens') {
atRule.replaceWith(finalRules)
includesScreensExplicitly = true
}
})
if (!includesScreensExplicitly) {
css.append(finalRules)
return
}
}
}
| import _ from 'lodash'
import postcss from 'postcss'
import cloneNodes from '../util/cloneNodes'
import buildMediaQuery from '../util/buildMediaQuery'
export default function(config) {
return function(css) {
const screens = config().screens
const responsiveRules = []
let finalRules = []
css.walkAtRules('responsive', atRule => {
const nodes = atRule.nodes
responsiveRules.push(...cloneNodes(nodes))
atRule.before(nodes)
atRule.remove()
})
_.keys(screens).forEach(screen => {
const mediaQuery = postcss.atRule({
name: 'media',
params: buildMediaQuery(screens[screen]),
})
mediaQuery.append(
responsiveRules.map(rule => {
const cloned = rule.clone()
cloned.selectors = _.map(rule.selectors, selector => `.${screen}\\:${selector.slice(1)}`)
return cloned
})
)
finalRules.push(mediaQuery)
})
const hasScreenRules = finalRules.some(i => i.nodes.length !== 0)
if (!hasScreenRules) {
return
}
const includesScreensExplicitly = css.some(
rule => rule.type === 'atrule' && rule.params === 'screens'
)
if (!includesScreensExplicitly) {
css.append(finalRules)
return
}
css.walkAtRules('tailwind', atRule => {
if (atRule.params === 'screens') {
atRule.replaceWith(finalRules)
}
})
}
}
|
Use an IRC username that's not already registered. | from buildbot.status import html, words
from buildbot.status.web.authz import Authz
from .djangoauth import DjangoAuth
authz = Authz(
auth = DjangoAuth(),
gracefulShutdown = 'auth',
forceBuild = 'auth',
forceAllBuilds = 'auth',
pingBuilder = 'auth',
stopBuild = 'auth',
stopAllBuilds = 'auth',
cancelPendingBuild = 'auth',
stopChange = 'auth',
cleanShutdown = 'auth',
)
def get_status(secrets):
return [
html.WebStatus(
http_port = '8010',
authz = authz,
order_console_by_time = True,
revlink = 'http://code.djangoproject.com/changeset/%s',
changecommentlink = (
r'\b#(\d+)\b',
r'http://code.djangoproject.com/ticket/\1',
r'Ticket \g<0>'
)
),
words.IRC(
host = 'irc.freenode.net',
channels = ['#django-dev'],
nick = 'djbuilds',
password = str(secrets['irc']['password']),
notify_events = {
'successToFailure': True,
'failureToSuccess': True,
}
),
] | from buildbot.status import html, words
from buildbot.status.web.authz import Authz
from .djangoauth import DjangoAuth
authz = Authz(
auth = DjangoAuth(),
gracefulShutdown = 'auth',
forceBuild = 'auth',
forceAllBuilds = 'auth',
pingBuilder = 'auth',
stopBuild = 'auth',
stopAllBuilds = 'auth',
cancelPendingBuild = 'auth',
stopChange = 'auth',
cleanShutdown = 'auth',
)
def get_status(secrets):
return [
html.WebStatus(
http_port = '8010',
authz = authz,
order_console_by_time = True,
revlink = 'http://code.djangoproject.com/changeset/%s',
changecommentlink = (
r'\b#(\d+)\b',
r'http://code.djangoproject.com/ticket/\1',
r'Ticket \g<0>'
)
),
words.IRC(
host = 'irc.freenode.net',
channels = ['#django-dev'],
nick = 'djbuildbot',
password = str(secrets['irc']['password']),
notify_events = {
'successToFailure': True,
'failureToSuccess': True,
}
),
] |
Fix plotband label unmount crashing | import React, { useRef, useEffect, useState } from 'react';
import uuid from 'uuid/v4';
import { attempt } from 'lodash-es';
import useModifiedProps from '../UseModifiedProps';
import useAxis from '../UseAxis';
export default function usePlotBandLineLifecycle(props, plotType) {
const { id = uuid, axisId, children, ...rest } = props;
const axis = useAxis(axisId);
const idRef = useRef();
const [plotbandline, setPlotbandline] = useState(null);
const modifiedProps = useModifiedProps(rest);
useEffect(() => {
if (!axis) return;
if (!plotbandline || modifiedProps !== false) {
if (!plotbandline) {
idRef.current = typeof id === 'function' ? id() : id;
}
const myId = idRef.current;
const opts = {
id: myId,
...rest
};
if (plotbandline) axis.removePlotBandOrLine(idRef.current);
axis.addPlotBandOrLine(opts, plotType);
setPlotbandline({
id: myId,
getPlotBandLine: () => {
if (axis && axis.object && axis.object.plotLinesAndBands) {
const plotbandlineObject = axis.object.plotLinesAndBands.find(
plb => plb.id === myId
);
return plotbandlineObject;
}
}
});
}
});
useEffect(() => {
return () => {
attempt(axis.removePlotBandOrLine, idRef.current);
};
}, []);
return plotbandline;
}
| import React, { useRef, useEffect, useState } from 'react';
import uuid from 'uuid/v4';
import { attempt } from 'lodash-es';
import useModifiedProps from '../UseModifiedProps';
import useAxis from '../UseAxis';
export default function usePlotBandLineLifecycle(props, plotType) {
const { id = uuid, axisId, children, ...rest } = props;
const axis = useAxis(axisId);
const idRef = useRef();
const [plotbandline, setPlotbandline] = useState(null);
const modifiedProps = useModifiedProps(rest);
useEffect(() => {
if (!axis) return;
if (!plotbandline || modifiedProps !== false) {
if (!plotbandline) {
idRef.current = typeof id === 'function' ? id() : id;
}
const myId = idRef.current;
const opts = {
id: myId,
...rest
};
if (plotbandline) axis.removePlotBandOrLine(idRef.current);
axis.addPlotBandOrLine(opts, plotType);
setPlotbandline({
id: myId,
getPlotBandLine: () => {
const plotbandlineObject = axis.object.plotLinesAndBands.find(
plb => plb.id === myId
);
return plotbandlineObject;
}
});
}
});
useEffect(() => {
return () => {
attempt(axis.removePlotBandOrLine, idRef.current);
};
}, []);
return plotbandline;
}
|
Make check against None instead of falsey things. | import logging
import lintreview.tools as tools
from lintreview.diff import DiffCollection
from lintreview.review import Problems
from lintreview.review import Review
log = logging.getLogger(__name__)
class Processor(object):
def __init__(self, client, number, head, target_path):
self._client = client
self._number = number
self._head = head
self._target_path = target_path
self._changes = None
self._problems = Problems(target_path)
self._review = Review(client, number)
def load_changes(self):
log.info('Loading pull request patches from github.')
files = self._client.pull_requests.list_files(self._number)
pull_request_patches = files.all()
self._changes = DiffCollection(pull_request_patches)
self._problems.set_changes(self._changes)
def run_tools(self, repo_config):
if self._changes is None:
raise RuntimeError('No loaded changes, cannot run tools. '
'Try calling load_changes first.')
files_to_check = self._changes.get_files(append_base=self._target_path)
tools.run(
repo_config,
self._problems,
files_to_check,
self._target_path)
def publish(self, wait_time=0):
self._problems.limit_to_changes()
self._review.publish(self._problems, self._head, wait_time)
| import logging
import lintreview.tools as tools
from lintreview.diff import DiffCollection
from lintreview.review import Problems
from lintreview.review import Review
log = logging.getLogger(__name__)
class Processor(object):
def __init__(self, client, number, head, target_path):
self._client = client
self._number = number
self._head = head
self._target_path = target_path
self._changes = None
self._problems = Problems(target_path)
self._review = Review(client, number)
def load_changes(self):
log.info('Loading pull request patches from github.')
files = self._client.pull_requests.list_files(self._number)
pull_request_patches = files.all()
self._changes = DiffCollection(pull_request_patches)
self._problems.set_changes(self._changes)
def run_tools(self, repo_config):
if not self._changes:
raise RuntimeError('No loaded changes, cannot run tools. '
'Try calling load_changes first.')
files_to_check = self._changes.get_files(append_base=self._target_path)
tools.run(
repo_config,
self._problems,
files_to_check,
self._target_path)
def publish(self, wait_time=0):
self._problems.limit_to_changes()
self._review.publish(self._problems, self._head, wait_time)
|
Add Waldo joke and simplify HAL joke | import re
from pal.services.service import Service
from pal.services.service import wrap_response
class JokeService(Service):
_JOKES = {
'pod bay doors':
"I'm sorry Jeff, I'm afraid I can't do that.",
'laws of robotics':
"1. A robot may not injure a human being or, through inaction, "
"allow a human being to come to harm.\n2. A robot must obey the "
"orders given it by human beings, except where such orders would "
"conflict with the First Law.\n3. A robot must protect its own "
"existence as long as such protection does not conflict with the "
"First or Second Law.",
'knock knock': "Who's there?",
'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.",
"where's waldo": "He's right there, can't you see him?",
}
def applies_to_me(self, client, feature_request_type):
return True
def get_confidence(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return 9001
return 0
@wrap_response
def go(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return self._JOKES[joke]
return ('ERROR', 'Tom Hanks was in 1 movies.')
| import re
from pal.services.service import Service
from pal.services.service import wrap_response
class JokeService(Service):
_JOKES = {
'open the pod bay doors pal':
"I'm sorry, Jeff, I'm afraid I can't do that.",
'laws of robotics':
"1. A robot may not injure a human being or, through inaction, "
"allow a human being to come to harm.\n2. A robot must obey the "
"orders given it by human beings, except where such orders would "
"conflict with the First Law.\n3. A robot must protect its own "
"existence as long as such protection does not conflict with the "
"First or Second Law.",
'knock knock': "Who's there?",
'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.",
}
def applies_to_me(self, client, feature_request_type):
return True
def get_confidence(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return 9001
return 0
@wrap_response
def go(self, params):
for joke in self._JOKES:
query = re.sub(r'[^a-z ]', '', params['query'].lower())
if joke in query:
return self._JOKES[joke]
return ('ERROR', 'Tom Hanks was in 1 movies.')
|
Sort fundraiser on newest on hp | from django.utils.timezone import now
from apps.banners.models import Slide
from apps.campaigns.models import Campaign
from apps.fundraisers.models import FundRaiser
from apps.projects.models import Project
from apps.quotes.models import Quote
from apps.statistics.models import Statistic
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePage(object):
def get(self, language):
self.id = 1
self.quotes= Quote.objects.published().filter(language=language)
self.slides = Slide.objects.published().filter(language=language)
stats = Statistic.objects.order_by('-creation_date').all()
if len(stats) > 0:
self.stats = stats[0]
else:
self.stats = None
projects = Project.objects.filter(phase='campaign').order_by('?')
if len(projects) > 4:
self.projects = projects[0:4]
elif len(projects) > 0:
self.projects = projects[0:len(projects)]
else:
self.projects = None
try:
self.campaign = Campaign.objects.get(start__lte=now(), end__gte=now())
# NOTE: MultipleObjectsReturned is not caught yet!
self.fundraisers = FundRaiser.objects.filter(project__is_campaign=True).order_by('-created')
except Campaign.DoesNotExist:
self.campaign, self.fundraisers = None, None
return self | from django.utils.timezone import now
from apps.banners.models import Slide
from apps.campaigns.models import Campaign
from apps.fundraisers.models import FundRaiser
from apps.projects.models import Project
from apps.quotes.models import Quote
from apps.statistics.models import Statistic
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePage(object):
def get(self, language):
self.id = 1
self.quotes= Quote.objects.published().filter(language=language)
self.slides = Slide.objects.published().filter(language=language)
stats = Statistic.objects.order_by('-creation_date').all()
if len(stats) > 0:
self.stats = stats[0]
else:
self.stats = None
projects = Project.objects.filter(phase='campaign').order_by('?')
if len(projects) > 4:
self.projects = projects[0:4]
elif len(projects) > 0:
self.projects = projects[0:len(projects)]
else:
self.projects = None
try:
self.campaign = Campaign.objects.get(start__lte=now(), end__gte=now())
# NOTE: MultipleObjectsReturned is not caught yet!
self.fundraisers = FundRaiser.objects.filter(project__is_campaign=True).order_by('?')
except Campaign.DoesNotExist:
self.campaign, self.fundraisers = None, None
return self |
Use API Deep Merge in all w4t | /**
* Copyright (c) 2014 by Center Open Middleware. All Rights Reserved.
* Titanium Appcelerator 3.3.0GA
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
* App Base Development Framework Team
*
* Alejandro F.Carrera
* Carlos Blanco Vallejo
* Santiago Blanco Ventas
*
*/
"use strict";
// Yaast Framework Init (Global Scope)
var Yaast = {
"Log": function(msg, type, error, extra) {
var self = {
'name': 'W4TLog',
'message': msg
};
if(error) {
self.details = (extra) ? {
'message': error.message,
'info': extra
} : error.message;
self.source = error.sourceURL;
}
Ti.API[type](self);
return self;
},
"FontAwesome": require('fonts/FontAwesome4'),
"API": require('lib/API'),
"Sandbox": {
'currentView': null
}
};
// Merge shortcut
Yaast["MergeObject"] = Yaast.API.SW.Utils.mergeObject;
(function() {
if (Yaast.API.HW.System.isTablet()) {
var Window = require('ui/window/appWindow');
Window.window.open();
}
else alert("Wirecloud4Tablet has not compatibility with Smartphone's'");
}()); | /**
* Copyright (c) 2014 by Center Open Middleware. All Rights Reserved.
* Titanium Appcelerator 3.3.0GA
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
* App Base Development Framework Team
*
* Alejandro F.Carrera
* Carlos Blanco Vallejo
* Santiago Blanco Ventas
*
*/
"use strict";
// Yaast Framework Init (Global Scope)
var Yaast = {
"Log": function(msg, type, error, extra){
var self = {
'name': 'W4TLog',
'message': msg
};
if(error){
self.details = (extra) ? {
'message': error.message,
'info': extra
} : error.message;
self.source = error.sourceURL;
}
Ti.API[type](self);
return self;
},
"MergeObject": function (obj1, obj2){
var result = null, key;
if (obj1 !== null && obj2 !== null){
for (key in obj2){
obj1[key] = obj2[key];
}
result = obj1;
}
return result;
},
"FontAwesome": require('fonts/FontAwesome4'),
"API": require('lib/API'),
"Sandbox": {
'currentView': null
}
};
(function() {
if (Yaast.API.HW.System.isTablet()) {
var Window = require('ui/window/appWindow');
Window.window.open();
}
else alert("Wirecloud4Tablet has not compatibility with Smartphone's'");
}()); |
system: Fix typo for requiring L10nProvider files | <?php
/**
* Factory class for providing Localization implementations
* @author M2Mobi, Heinz Wiesinger
*/
class L10nFactory
{
/**
* Instance of the L10nProvider
* @var array
*/
private static $lprovider;
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* This method returns an object with the appropriate localization
* implementation provider
* @param String $provider The localization implementation requested
* @param String $language POSIX locale definition
* @return L10nProvider $return Instance of the localization provider requested
*/
public static function get_localization($provider, $language)
{
switch($provider)
{
case "php":
if (!isset(self::$lprovider[$provider]))
{
require_once("class.l10nproviderphp.inc.php");
self::$lprovider[$provider] = new L10nProviderPHP($language);
}
return self::$lprovider[$provider];
break;
case "gettext":
default:
if (!isset(self::$lprovider[$provider]))
{
require_once("class.l10nprovidergettext.inc.php");
self::$lprovider[$provider] = new L10nProviderGettext($language);
}
return self::$lprovider[$provider];
break;
}
}
}
?>
| <?php
/**
* Factory class for providing Localization implementations
* @author M2Mobi, Heinz Wiesinger
*/
class L10nFactory
{
/**
* Instance of the L10nProvider
* @var array
*/
private static $lprovider;
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* This method returns an object with the appropriate localization
* implementation provider
* @param String $provider The localization implementation requested
* @param String $language POSIX locale definition
* @return L10nProvider $return Instance of the localization provider requested
*/
public static function get_localization($provider, $language)
{
switch($provider)
{
case "php":
if (!isset(self::$lprovider[$provider]))
{
require_once("class.class.l10nproviderphp.inc.php");
self::$lprovider[$provider] = new L10nProviderPHP($language);
}
return self::$lprovider[$provider];
break;
case "gettext":
default:
if (!isset(self::$lprovider[$provider]))
{
require_once("class.class.l10nprovidergettext.inc.php");
self::$lprovider[$provider] = new L10nProviderGettext($language);
}
return self::$lprovider[$provider];
break;
}
}
}
?>
|
Fix margins on index titles | @if (!$hideTitle && !empty($post_title))
@typography([
'id' => 'mod-posts-' . $ID . '-label',
'element' => 'h4',
'variant' => 'h2',
'classList' => ['module-title']
])
{!! apply_filters('the_title', $post_title) !!}
@endtypography
@endif
<div class="o-grid">
@foreach ($items as $item)
<div class="{{ apply_filters('Municipio/Controller/Archive/GridColumnClass', $columnClass) }}">
@card([
'link' => $item['permalink'],
'classList' => ['u-height--100', 'u-height-100'],
'context' => 'index',
'hasAction' => true,
])
@if($item['thumbnail'][0])
<div class="c-card__image c-card__image--secondary">
<div class="c-card__image-background u-ratio-16-9" alt="{{ $item['title'] }}" style="height:initial; background-image:url('{{ $item['thumbnail'][0] }}');"></div>
</div>
@endif
<div class="c-card__body">
@if (!empty($item['title']))
@typography([
'element' => "h2",
'classList' => ['c-card__heading'],
])
{{ $item['title'] }}
@endtypography
@endif
{!! $item['lead'] !!}
</div>
@endcard
</div>
@endforeach
</div> | @if (!$hideTitle && !empty($post_title))
@typography(['element' => 'h2'])
{!! apply_filters('the_title', $post_title) !!}
@endtypography
@endif
<div class="o-grid">
@foreach ($items as $item)
<div class="{{ apply_filters('Municipio/Controller/Archive/GridColumnClass', $columnClass) }}">
@card([
'link' => $item['permalink'],
'classList' => ['u-height--100', 'u-height-100'],
'context' => 'index',
'hasAction' => true,
])
@if($item['thumbnail'][0])
<div class="c-card__image c-card__image--secondary">
<div class="c-card__image-background u-ratio-16-9" alt="{{ $item['title'] }}" style="height:initial; background-image:url('{{ $item['thumbnail'][0] }}');"></div>
</div>
@endif
<div class="c-card__body">
@if (!empty($item['title']))
@typography([
'element' => "h2",
'classList' => ['c-card__heading'],
])
{{ $item['title'] }}
@endtypography
@endif
{!! $item['lead'] !!}
</div>
@endcard
</div>
@endforeach
</div> |
[FIX] Fix issue on root directory | package com.freak.asteroid.randomiser;
import android.app.Activity;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
File root = new File(Environment.getExternalStorageDirectory() + "/Musique");
RandomiseThread randomiser = new RandomiseThread(root);
randomiser.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| package com.freak.asteroid.randomiser;
import android.app.Activity;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
File root = new File(Environment.getExternalStorageDirectory() + "/Music");
RandomiseThread randomiser = new RandomiseThread(root);
randomiser.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
Comment out our global stuff for now | """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
#def __getattribute__(self, *args, **kw):
# # @@ TODO: Namespace moksha app's Global objects
# # load them in the middlware...
# # ensure that this object is always in pylons.g, even if we are
# # running a full moksha stack, or as middleware
# # proxy to them on incoming request
# print "Globals.__getattr__(%s)" % locals()
# frame = inspect.currentframe()
# caller = frame.f_back.f_back.f_globals['__name__']
# print "caller = ", caller
# return object.__getattribute__(self, *args, **kw)
| """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
def __getattribute__(self, *args, **kw):
# @@ TODO: Namespace moksha app's Global objects
# load them in the middlware...
# ensure that this object is always in pylons.g, even if we are
# running a full moksha stack, or as middleware
# proxy to them on incoming request
print "Globals.__getattr__(%s)" % locals()
frame = inspect.currentframe()
caller = frame.f_back.f_back.f_globals['__name__']
print "caller = ", caller
return object.__getattribute__(self, *args, **kw)
|
Set a user agent for the webhook if not provided | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import logging
import requests
import json
from django.utils.encoding import smart_text
from awx.main.notifications.base import TowerBaseEmailBackend
from awx.main.utils import get_awx_version
logger = logging.getLogger('awx.main.notifications.webhook_backend')
class WebhookBackend(TowerBaseEmailBackend):
init_parameters = {"url": {"label": "Target URL", "type": "string"},
"headers": {"label": "HTTP Headers", "type": "object"}}
recipient_parameter = "url"
sender_parameter = None
def __init__(self, headers, fail_silently=False, **kwargs):
self.headers = headers
super(WebhookBackend, self).__init__(fail_silently=fail_silently)
def format_body(self, body):
return body
def send_messages(self, messages):
sent_messages = 0
if 'User-Agent' not in self.headers:
self.headers['User-Agent'] = "Tower {}".format(get_awx_version())
for m in messages:
r = requests.post("{}".format(m.recipients()[0]),
data=json.dumps(m.body),
headers=self.headers)
if r.status_code >= 400:
logger.error(smart_text("Error sending notification webhook: {}".format(r.text)))
if not self.fail_silently:
raise Exception(smart_text("Error sending notification webhook: {}".format(r.text)))
sent_messages += 1
return sent_messages
| # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import logging
import requests
import json
from django.utils.encoding import smart_text
from awx.main.notifications.base import TowerBaseEmailBackend
logger = logging.getLogger('awx.main.notifications.webhook_backend')
class WebhookBackend(TowerBaseEmailBackend):
init_parameters = {"url": {"label": "Target URL", "type": "string"},
"headers": {"label": "HTTP Headers", "type": "object"}}
recipient_parameter = "url"
sender_parameter = None
def __init__(self, headers, fail_silently=False, **kwargs):
self.headers = headers
super(WebhookBackend, self).__init__(fail_silently=fail_silently)
def format_body(self, body):
return body
def send_messages(self, messages):
sent_messages = 0
for m in messages:
r = requests.post("{}".format(m.recipients()[0]),
data=json.dumps(m.body),
headers=self.headers)
if r.status_code >= 400:
logger.error(smart_text("Error sending notification webhook: {}".format(r.text)))
if not self.fail_silently:
raise Exception(smart_text("Error sending notification webhook: {}".format(r.text)))
sent_messages += 1
return sent_messages
|
Remove the tabindex that flickity adds so it does not tab to it, rather it will tab to natural tabbable elements inside the hero area. | var Flickity = require('flickity');
(function(Flickity) {
"use strict";
if(document.querySelector('.rotate') !== null) {
new Flickity('.rotate', {
on: {
ready: function() {
// Get the height of the first image that loaded and dynamically set the height
if(document.querySelector('.flickity-enabled .is-selected img') != null) {
document.querySelector('.flickity-viewport').style.height = document.querySelector('.flickity-enabled .is-selected img').offsetHeight + 'px';
}
// Visually hide the dots for accessibility
if(document.querySelector('.flickity-page-dots') != null) {
document.querySelector('.flickity-page-dots').classList.add('visually-hidden');
}
}
},
accessibility: true,
prevNextButtons: true,
pageDots: true,
resize: true,
setGallerySize: true,
wrapAround: true,
});
document.querySelector('.rotate').removeAttribute('tabindex');
}
})(Flickity);
| var Flickity = require('flickity');
(function(Flickity) {
"use strict";
if(document.querySelector('.rotate') !== null) {
new Flickity('.rotate', {
on: {
ready: function() {
// Get the height of the first image that loaded and dynamically set the height
if(document.querySelector('.flickity-enabled .is-selected img') != null) {
document.querySelector('.flickity-viewport').style.height = document.querySelector('.flickity-enabled .is-selected img').offsetHeight + 'px';
}
// Visually hide the dots for accessibility
if(document.querySelector('.flickity-page-dots') != null) {
document.querySelector('.flickity-page-dots').classList.add('visually-hidden');
}
}
},
accessibility: true,
prevNextButtons: true,
pageDots: true,
resize: true,
setGallerySize: true,
wrapAround: true,
});
}
})(Flickity);
|
Move disconnect decision into Connection.handle | import asyncio
from .message import Message
class Connection:
"""
Communicates with an IRC network.
Incoming data is transformed into Message objects, and sent to `listeners`.
"""
def __init__(self, listeners, host, port, ssl=True):
self.listeners = listeners
self.host = host
self.port = port
self.ssl = ssl
@asyncio.coroutine
def connect(self):
"""Connect to the server, and dispatch incoming messages."""
connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl)
self.reader, self.writer = yield from connection
self.on_connect()
self._connected = True
while self._connected:
message = yield from self.reader.readline()
self.handle(message)
def disconnect(self):
"""Close the connection to the server."""
self._connected = False
self.writer.close()
self.on_disconnect()
def handle(self, raw_message):
"""Dispatch the message to all listeners."""
if not raw_message:
self.disconnect()
return
message = Message(raw_message)
for listener in self.listeners:
listener.handle(self, message)
def on_connect(self):
"""Upon connection to the network, send user's credentials."""
self.send(b'USER meshybot 0 * :MeshyBot7')
self.send(b'NICK meshybot')
def on_disconnect(self):
print('Connection closed')
def send(self, message):
message = message + b'\r\n'
print('write', message)
self.writer.write(message)
| import asyncio
from .message import Message
class Connection:
"""
Communicates with an IRC network.
Incoming data is transformed into Message objects, and sent to `listeners`.
"""
def __init__(self, listeners, host, port, ssl=True):
self.listeners = listeners
self.host = host
self.port = port
self.ssl = ssl
@asyncio.coroutine
def connect(self):
"""Connect to the server, and dispatch incoming messages."""
connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl)
self.reader, self.writer = yield from connection
self.on_connect()
self._connected = True
while self._connected:
message = yield from self.reader.readline()
if not message:
self.disconnect()
return
self.handle(message)
def disconnect(self):
"""Close the connection to the server."""
self._connected = False
self.writer.close()
self.on_disconnect()
def handle(self, raw_message):
"""Dispatch the message to all listeners."""
message = Message(raw_message)
for listener in self.listeners:
listener.handle(self, message)
def on_connect(self):
"""Upon connection to the network, send user's credentials."""
self.send(b'USER meshybot 0 * :MeshyBot7')
self.send(b'NICK meshybot')
def on_disconnect(self):
print('Connection closed')
def send(self, message):
message = message + b'\r\n'
print('write', message)
self.writer.write(message)
|
Remove magic numbers and print statements | package seedu.ezdo.model;
import java.util.EmptyStackException;
/*
* Array-based implementation for a stack with fixed size. Used for undo & redo stacks.
* If stack goes past max capacity, the oldest item to be pushed is replaced.
*/
public class FixedStack<T> {
private int index;
private T[] array;
public FixedStack(int capacity) {
array = (T[]) new Object[capacity];
index = -1;
}
public void push(T item) {
index = (index + 1) % ModelManager.STACK_CAPACITY; // wraps around
array[index] = item;
}
public T pop() throws EmptyStackException {
if (index == -1 || array[index] == null) {
throw new EmptyStackException();
}
T item = array[index];
array[index] = null;
if (index == 0) {
index = array.length - 1;
} else {
index = index - 1;
}
return item;
}
public boolean isEmpty() {
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
return false;
}
}
return true;
}
public void clear() {
for (int i = 0; i < array.length; i++) {
array[i] = null;
}
index = -1;
}
}
| package seedu.ezdo.model;
import java.util.EmptyStackException;
/*
* Array-based implementation for a stack with fixed size. Used for undo & redo stacks.
* If stack goes past max capacity, the oldest item to be pushed is replaced.
*/
public class FixedStack<T> {
private int index;
private T[] array;
public FixedStack(int capacity) {
array = (T[]) new Object[capacity];
index = -1;
}
public void push(T item) {
index = (index + 1) % 5; // wraps around
array[index] = item;
System.out.println("item added at index: " + index);
}
public T pop() throws EmptyStackException {
if (index == -1 || array[index] == null) {
throw new EmptyStackException();
}
T item = array[index];
array[index] = null;
System.out.println(item + " at index " + index + " removed");
if (index == 0) {
index = array.length - 1;
System.out.println("index now: " + index);
} else {
index = index - 1;
System.out.println("index now: " + index);
}
return item;
}
public boolean isEmpty() {
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
return false;
}
}
return true;
}
public void clear() {
for (int i = 0; i < array.length; i++) {
array[i] = null;
}
index = -1;
}
}
|
Create a temp folder when project is being created | <?php
namespace ActiveCollab\Shade\Command;
use ActiveCollab\Shade\Project, ActiveCollab\Shade\Element\Video;
use Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface;
/**
* Create a new project
*
* @package ActiveCollab\Shade\Command
*/
class ProjectCommand extends Command
{
/**
* Configure the command
*/
function configure()
{
$this->setName('project')->addArgument('name')->setDescription('Create a new project');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$project = new Project(getcwd());
if($project->isValid()) {
$output->writeln('Project already initialized');
} else {
$configuration = [
'name' => $input->getArgument('name'),
'video_groups' => [
Video::GETTING_STARTED => 'Getting Started',
]
];
if (empty($configuration['name'])) {
$configuration['name'] = basename($project->getPath());
}
if (file_put_contents($project->getPath() . '/project.json', json_encode($configuration, JSON_PRETTY_PRINT))) {
$output->writeln('Project initialized');
} else {
$output->writeln('<error>Failed to create a project configuration file</error>');
}
if (!mkdir($project->getPath() . '/temp')) {
$output->writeln('<error>Failed to create temp folder</error>');
}
}
}
} | <?php
namespace ActiveCollab\Shade\Command;
use ActiveCollab\Shade\Project, ActiveCollab\Shade\Element\Video;
use Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface;
/**
* Create a new project
*
* @package ActiveCollab\Shade\Command
*/
class ProjectCommand extends Command
{
/**
* Configure the command
*/
function configure()
{
$this->setName('project')->addArgument('name')->setDescription('Create a new project');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$project = new Project(getcwd());
if($project->isValid()) {
$output->writeln('Project already initialized');
} else {
$configuration = [
'name' => $input->getArgument('name'),
'video_groups' => [
Video::GETTING_STARTED => 'Getting Started',
]
];
if (empty($configuration['name'])) {
$configuration['name'] = basename($project->getPath());
}
if (file_put_contents($project->getPath() . '/project.json', json_encode($configuration, JSON_PRETTY_PRINT))) {
$output->writeln('Project initialized');
} else {
$output->writeln('<error>Failed to create a project configuration file</error>');
}
}
}
} |
Fix hasNext method to only stop when play not have winned | package wumpus;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import wumpus.Environment.*;
/**
* The iteration of plays that the player can take until reaches its end.
*/
public class Runner implements Iterable<Player>, Iterator<Player> {
private static final int DEFAULT_MAX_ITERATIONS = 200;
private final World world;
private int iterations = 0;
/**
* The runner constructor.
* @param world The world instance.
*/
public Runner(World world) {
this.world = world;
}
/**
* Returns the iterator that can be user in a loop.
* @return Itself
*/
public Iterator<Player> iterator() {
return this;
}
/**
* Check if the game has ended.
* @return
*/
public boolean hasNext() {
Player player = world.getPlayer();
return iterations < DEFAULT_MAX_ITERATIONS &&
player.isAlive() && player.getResult() != Result.WIN;
}
/**
* Get player instance to calculate the next iteration.
* @return The current player instance
*/
public Player next() {
if (!hasNext()) throw new NoSuchElementException();
iterations++;
return world.getPlayer();
}
/**
* Operation not supported, throws an error.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Get how many iterations have been made so far.
* @return The amount of iterations
*/
public int getDepth() {
return iterations;
}
}
| package wumpus;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import wumpus.Environment.*;
/**
* The iteration of plays that the player can take until reaches its end.
*/
public class Runner implements Iterable<Player>, Iterator<Player> {
private static final int DEFAULT_MAX_ITERATIONS = 200;
private final World world;
private int iterations = 0;
/**
* The runner constructor.
* @param world The world instance.
*/
public Runner(World world) {
this.world = world;
}
/**
* Returns the iterator that can be user in a loop.
* @return Itself
*/
public Iterator<Player> iterator() {
return this;
}
/**
* Check if the game has ended.
* @return
*/
public boolean hasNext() {
Player player = world.getPlayer();
return iterations < DEFAULT_MAX_ITERATIONS &&
player.isAlive() && player.getResult() == Result.WIN;
}
/**
* Get player instance to calculate the next iteration.
* @return The current player instance
*/
public Player next() {
if (!hasNext()) throw new NoSuchElementException();
iterations++;
return world.getPlayer();
}
/**
* Operation not supported, throws an error.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Get how many iterations have been made so far.
* @return The amount of iterations
*/
public int getDepth() {
return iterations;
}
}
|
Fix attempt to unset static property | <?php
namespace Aedart\Scaffold\Cache;
use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Builders\IndexBuilder;
use Illuminate\Contracts\Cache\Repository;
/**
* Cache Helper
*
* @author Alin Eugen Deac <[email protected]>
* @package Aedart\Scaffold\Cache
*/
class CacheHelper
{
/**
* Default cache directory
*/
const DEFAULT_CACHE_DIRECTORY = IndexBuilder::DEFAULT_SCAFFOLD_INDEX_DIRECTORY . 'cache/';
/**
* @var Repository
*/
static protected $cache;
/**
* Register the cache directory
*
* @param string $directory
*/
static public function setCacheDirectory($directory)
{
$ioc = IoC::getInstance();
$config = $ioc->make('config');
$config->set('cacheDir', $directory);
$ioc->container()['config'] = $config;
}
/**
* Returns a cache repository instance
*
* @return Repository
*/
static public function make()
{
if(!isset(self::$cache)){
$ioc = IoC::getInstance();
$repository = $ioc->make(Repository::class);
self::$cache = $repository;
}
return self::$cache;
}
/**
* Destroy the cache instance inside this helper
*/
static public function destroy()
{
self::$cache = null;
}
} | <?php
namespace Aedart\Scaffold\Cache;
use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Builders\IndexBuilder;
use Illuminate\Contracts\Cache\Repository;
/**
* Cache Helper
*
* @author Alin Eugen Deac <[email protected]>
* @package Aedart\Scaffold\Cache
*/
class CacheHelper
{
/**
* Default cache directory
*/
const DEFAULT_CACHE_DIRECTORY = IndexBuilder::DEFAULT_SCAFFOLD_INDEX_DIRECTORY . 'cache/';
/**
* @var Repository
*/
static protected $cache;
/**
* Register the cache directory
*
* @param string $directory
*/
static public function setCacheDirectory($directory)
{
$ioc = IoC::getInstance();
$config = $ioc->make('config');
$config->set('cacheDir', $directory);
$ioc->container()['config'] = $config;
}
/**
* Returns a cache repository instance
*
* @return Repository
*/
static public function make()
{
if(!isset(self::$cache)){
$ioc = IoC::getInstance();
$repository = $ioc->make(Repository::class);
self::$cache = $repository;
}
return self::$cache;
}
/**
* Destroy the cache instance inside this helper
*/
static public function destroy()
{
unset(self::$cache);
}
} |
Add repr to Deployment class | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.users import User
class Deployment(GitHubCore):
CUSTOM_HEADERS = {
'Accept': 'application/vnd.github.cannonball-preview+json'
}
def __init__(self, deployment, session=None):
super(Deployment, self).__init__(deployment, session)
self._api = deployment.get('url')
#: GitHub's id of this deployment
self.id = deployment.get('id')
#: SHA of the branch on GitHub
self.sha = deployment.get('sha')
#: User object representing the creator of the deployment
self.creator = deployment.get('creator')
if self.creator:
self.creator = User(self.creator, self)
#: JSON string payload of the Deployment
self.payload = deployment.get('payload')
#: Date the Deployment was created
self.created_at = deployment.get('created_at')
if self.created_at:
self.created_at = self._strptime(self.created_at)
#: Date the Deployment was updated
self.updated_at = deployment.get('updated_at')
if self.updated_at:
self.updated_at = self._strptime(self.updated_at)
#: Description of the deployment
self.description = deployment.get('description')
#: URL to get the statuses of this deployment
self.statuses_url = deployment.get('statuses_url')
def __repr__(self):
return '<Deployment [{0} @ {1}]>'.format(self.id, self.sha)
| # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.users import User
class Deployment(GitHubCore):
CUSTOM_HEADERS = {
'Accept': 'application/vnd.github.cannonball-preview+json'
}
def __init__(self, deployment, session=None):
super(Deployment, self).__init__(deployment, session)
self._api = deployment.get('url')
#: GitHub's id of this deployment
self.id = deployment.get('id')
#: SHA of the branch on GitHub
self.sha = deployment.get('sha')
#: User object representing the creator of the deployment
self.creator = deployment.get('creator')
if self.creator:
self.creator = User(self.creator, self)
#: JSON string payload of the Deployment
self.payload = deployment.get('payload')
#: Date the Deployment was created
self.created_at = deployment.get('created_at')
if self.created_at:
self.created_at = self._strptime(self.created_at)
#: Date the Deployment was updated
self.updated_at = deployment.get('updated_at')
if self.updated_at:
self.updated_at = self._strptime(self.updated_at)
#: Description of the deployment
self.description = deployment.get('description')
#: URL to get the statuses of this deployment
self.statuses_url = deployment.get('statuses_url')
|
Use aggregation to namespace the connection id
re #506 | define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'] + ':' + opts['aggregation'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
| define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
|
Add Model::newInstance() and create() methods example. | <?php
/**
* PunyApp:
* The puny developer framework for rapid compiling.
*/
class SampleModel extends PunyApp_Model {
public function addUser($userid, $email, $pass) {
if ($this->isUserId($userid)) {
return false;
}
$sample = $this->newInstance();
$sample->userid = $userid;
$sample->email = $email;
$sample->pass = sha1($pass);
$sample->save();
}
public function deleteUser($userid) {
return $this->delete(
array('userid' => '?'),
array($userid)
);
}
public function getUser($userid) {
return $this->findOne(
array(
'fields' => array('id', 'userid', 'email'),
'where' => array('userid' => '?')
),
array($userid)
);
}
public function isUserId($userid) {
return $this->has(
array(
'where' => array('userid' => '?')
),
array($userid)
);
}
public function hasUser($userid, $pass) {
return $this->has(
array(
'where' => array(
'userid' => ':userid',
'pass' => ':pass'
)
),
array(
':userid' => $userid,
':pass' => sha1($pass)
)
);
}
}
| <?php
/**
* PunyApp:
* The puny developer framework for rapid compiling.
*/
class SampleModel extends PunyApp_Model {
public function addUser($user_id, $email, $pass) {
if ($this->isUserId($user_id)) {
return false;
}
return $this->insert(array(
'userId' => ':userId',
'email' => ':email',
'pass' => ':pass',
'updateAt' => ':updateAt'
), array(
':userId' => $user_id,
':email' => $email,
':pass' => sha1($pass),
':updateAt' => PunyApp::now()
));
}
public function deleteUser($user_id) {
return $this->delete(array('userId' => '?'), array($user_id));
}
public function getUser($user_id) {
return $this->findOne(
array('id', 'userId', 'email'),
array('userId' => '?'),
array($user_id)
);
}
public function isUserId($user_id) {
return $this->count(array('userId' => '?'), array($user_id)) > 0;
}
public function isUser($user_id, $pass) {
return $this->count(array(
'userId' => ':userId',
'pass' => ':pass'
), array(
':userId' => $user_id,
':pass' => sha1($pass)
)) > 0;
}
}
|
Add addType method to page | var registerMiddleware = require('./middleware'),
registerModel = require('./model'),
registerApi = require('./api');
module.exports = function setup(options, imports, register) {
var frontend = imports.frontend.app,
backend = imports.backend,
content = imports.content,
security = imports.security,
mongoose = imports.mongoose.mongoose,
api = imports.api.app;
security.permissions.page = ['use', 'content'];
var plugin = {
models: {},
middleware: {},
types: {},
client: {
js: [__dirname + '/client/javascript/**/*.js'],
html: [__dirname + '/client/javascript/**/*.html']
},
api: null,
addType: function (name, config) {
this.type[name] = config;
}
};
var page = registerModel(mongoose);
plugin.api = registerApi(mongoose, plugin);
plugin.models[ page.config.name.toLowerCase() ] = page;
plugin.middleware = registerMiddleware(mongoose);
// register REST api at backend
api.use(plugin.api);
var renderStack = [
plugin.middleware.loadPage,
plugin.middleware.loadPageType(plugin.types),
plugin.middleware.loadNavigation,
content.middleware.loadContent,
content.middleware.renderContent(content.types),
plugin.middleware.renderSlots,
plugin.middleware.renderPage,
plugin.middleware.errorHandler
];
// REGISTER client assets
backend.build.addSrc('js', plugin.client.js);
backend.build.addSrc('html', plugin.client.html);
// register render stack
frontend.get('*', renderStack);
register(null, {
page: plugin
});
}; | var registerMiddleware = require('./middleware'),
registerModel = require('./model'),
registerApi = require('./api');
module.exports = function setup(options, imports, register) {
var frontend = imports.frontend.app,
backend = imports.backend,
content = imports.content,
security = imports.security,
mongoose = imports.mongoose.mongoose,
api = imports.api.app;
security.permissions.page = ['use', 'content'];
var plugin = {
models: {},
middleware: {},
types: {},
client: {
js: [__dirname + '/client/javascript/**/*.js'],
html: [__dirname + '/client/javascript/**/*.html']
},
api: null
};
var page = registerModel(mongoose);
plugin.api = registerApi(mongoose, plugin);
plugin.models[ page.config.name.toLowerCase() ] = page;
plugin.middleware = registerMiddleware(mongoose);
// register REST api at backend
api.use(plugin.api);
var renderStack = [
plugin.middleware.loadPage,
plugin.middleware.loadPageType(plugin.types),
plugin.middleware.loadNavigation,
content.middleware.loadContent,
content.middleware.renderContent(content.types),
plugin.middleware.renderSlots,
plugin.middleware.renderPage,
plugin.middleware.errorHandler
];
// REGISTER client assets
backend.build.addSrc('js', plugin.client.js);
backend.build.addSrc('html', plugin.client.html);
// register render stack
frontend.get('*', renderStack);
register(null, {
page: plugin
});
}; |
Use single quotes to reflect the existing conversion | var kickass = require('../index');
var params = {
q: 'test',
field:'seeders',
order:'desc'
}
describe('kickass', function(){
it('should contain an array of torrents', function(done) {
kickass(params, function(err, result) {
expect(err).toBeNull();
expect(result.list.length).not.toBe(0);
result.list.forEach(function(element) {
expect(element.title).not.toBeNull();
expect(element.link).not.toBeNull();
expect(element.guid).not.toBeNull();
expect(element.pubDate).not.toBeNull();
expect(element.torrentLink).not.toBeNull();
expect(element.files).not.toBeNull();
expect(element.comments).not.toBeNull();
expect(element.hash).not.toBeNull();
expect(element.peers).not.toBeNull();
expect(element.seeds).not.toBeNull();
expect(element.leechs).not.toBeNull();
expect(element.size).toBeGreaterThan(0);
expect(element.votes).not.toBeNull();
expect(element.verified).not.toBeNull();
})
done();
})
});
it('should return an empty list', function(done) {
params.q = '3d8f7c6e91bbaa6766948ec13320533f';
kickass(params, function(err, result) {
expect(err).toBeNull();
expect(result.list.length).toBe(0);
done();
});
})
}); | var kickass = require('../index');
var params = {
q: 'test',
field:'seeders',
order:'desc'
}
describe('kickass', function(){
it('should contain an array of torrents', function(done) {
kickass(params, function(err, result) {
expect(err).toBeNull();
expect(result.list.length).not.toBe(0);
result.list.forEach(function(element) {
expect(element.title).not.toBeNull();
expect(element.link).not.toBeNull();
expect(element.guid).not.toBeNull();
expect(element.pubDate).not.toBeNull();
expect(element.torrentLink).not.toBeNull();
expect(element.files).not.toBeNull();
expect(element.comments).not.toBeNull();
expect(element.hash).not.toBeNull();
expect(element.peers).not.toBeNull();
expect(element.seeds).not.toBeNull();
expect(element.leechs).not.toBeNull();
expect(element.size).toBeGreaterThan(0);
expect(element.votes).not.toBeNull();
expect(element.verified).not.toBeNull();
})
done();
})
});
it("should return an empty list", function(done) {
params.q = "3d8f7c6e91bbaa6766948ec13320533f"
kickass(params, function(err, result) {
expect(err).toBeNull();
expect(result.list.length).toBe(0);
done();
});
})
}); |
Switch from arrays to Sets | import normalizeEvents from './tools/normalizeEvents';
import normalizeListener from './tools/normalizeListener';
export default function stereo () {
let listeners = {};
let emitter = {
on(events, listener) {
// Normalize arguments.
events = normalizeEvents(events);
listener = normalizeListener(listener);
// Register the listener.
for (let event of events) {
let register = listeners[event];
if (!register) listeners[event] = new Set([listener]);
else if (!register.has(listener)) register.add(listener);
}
},
once(events, listener) {
events = normalizeEvents(events);
listener = normalizeListener(listener);
function listenerWrapper (...args) {
emitter.off(events, listenerWrapper);
listener(...args);
}
emitter.on(events, listenerWrapper);
},
off(events, listener) {
// Normalize arguments.
events = normalizeEvents(events);
// If no listener is specified, unregister all listeners.
if (listener == null) for (let event of events) {
delete listeners[event];
}
// Otherwise unregister the given listener.
else {
listener = normalizeListener(listener);
for (let event of events) {
listeners[event].delete(listener);
}
}
},
emit(events, ...args) {
// Normalize arguments.
events = normalizeEvents(events);
// Dispatch listeners.
for (let event of events) {
let register = listeners[event];
if (register) for (let listener of register) {
listener(...args);
}
}
}
};
return emitter;
}
| import normalizeEvents from './tools/normalizeEvents';
import normalizeListener from './tools/normalizeListener';
export default function stereo () {
let listeners = {};
let emitter = {
on(events, listener) {
// Normalize arguments.
events = normalizeEvents(events);
listener = normalizeListener(listener);
// Register the listener.
for (let event of events) {
let register = listeners[event];
if (!register) listeners[event] = [listener];
else if (!register.includes(listener)) {
register.push(listener);
}
}
},
once(events, listener) {
events = normalizeEvents(events);
listener = normalizeListener(listener);
function listenerWrapper (...args) {
emitter.off(events, listenerWrapper);
listener(...args);
}
emitter.on(events, listenerWrapper);
},
off(events, listener) {
// Normalize arguments.
events = normalizeEvents(events);
// If no listener is specified, unregister all listeners.
if (listener == null) for (let event of events) {
delete listeners[event];
}
// Otherwise unregister the given listener.
else {
listener = normalizeListener(listener);
for (let event of events) {
let register = listeners[event];
let index = register.indexOf(listener);
if (index !== -1) register.splice(index, 1);
}
}
},
emit(events, ...args) {
// Normalize arguments.
events = normalizeEvents(events);
// Dispatch listeners.
for (let event of events) {
let register = listeners[event];
if (register) for (let listener of register) {
listener(...args);
}
}
}
};
return emitter;
}
|
Fix compilation issue on not latest JDKs | /*
* (c) 2015 CenturyLink. 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 com.centurylink.cloud.sdk.tests.mocks;
import com.centurylink.cloud.sdk.tests.TestModule;
import org.mockito.Spy;
import java.lang.reflect.Field;
import java.util.stream.Stream;
/**
* @author Ilya Drabenia
*/
public class BindSpiesModule extends TestModule {
private final Object target;
public BindSpiesModule(Object target) {
this.target = target;
}
@Override
protected void configure() {
overrideSpyBinding();
}
@SuppressWarnings("unchecked")
private void overrideSpyBinding() {
Stream
.of(declaredFields())
.filter(f -> f.isAnnotationPresent(Spy.class))
.forEach(f ->
bind(f.getType()).toProvider(new SpyProvider(f.getType())
)
);
}
private Field[] declaredFields() {
return target
.getClass()
.getDeclaredFields();
}
}
| /*
* (c) 2015 CenturyLink. 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 com.centurylink.cloud.sdk.tests.mocks;
import com.centurylink.cloud.sdk.tests.TestModule;
import org.mockito.Spy;
import java.lang.reflect.Field;
import java.util.stream.Stream;
/**
* @author Ilya Drabenia
*/
public class BindSpiesModule extends TestModule {
private final Object target;
public BindSpiesModule(Object target) {
this.target = target;
}
@Override
protected void configure() {
overrideSpyBinding();
}
private void overrideSpyBinding() {
Stream
.of(declaredFields())
.filter(f -> f.isAnnotationPresent(Spy.class))
.forEach(f ->
bind(f.getType()).toProvider(new SpyProvider(f.getType())
)
);
}
private Field[] declaredFields() {
return target
.getClass()
.getDeclaredFields();
}
}
|
Use more robust quickfix parser.
The yamllint implementation had some issues that the common code does
not. | import os
import logging
from lintreview.tools import Tool
from lintreview.tools import run_command, process_quickfix
from lintreview.utils import in_path
log = logging.getLogger(__name__)
class Yamllint(Tool):
name = 'yamllint'
def check_dependencies(self):
"""
See if yamllint is on the PATH
"""
return in_path('yamllint')
def match_file(self, filename):
base = os.path.basename(filename)
name, ext = os.path.splitext(base)
return ext in ['.yml', '.yaml']
def process_files(self, files):
"""
Run code checks with yamllint.
Only a single process is made for all files
to save resources.
Configuration is not supported at this time
"""
log.debug('Processing %s files with %s', files, self.name)
command = ['yamllint', '--format=parsable']
# Add config file if its present
if self.options.get('config'):
command += ['-c', self.apply_base(self.options['config'])]
command += files
output = run_command(command, split=True, ignore_error=True)
if not output:
log.debug('No yamllint errors found.')
return False
process_quickfix(self.problems, output, lambda x: x)
| import os
import logging
from lintreview.tools import Tool
from lintreview.tools import run_command
from lintreview.utils import in_path
log = logging.getLogger(__name__)
class Yamllint(Tool):
name = 'yamllint'
def check_dependencies(self):
"""
See if yamllint is on the PATH
"""
return in_path('yamllint')
def match_file(self, filename):
base = os.path.basename(filename)
name, ext = os.path.splitext(base)
return ext in ['.yml', '.yaml']
def process_files(self, files):
"""
Run code checks with yamllint.
Only a single process is made for all files
to save resources.
Configuration is not supported at this time
"""
log.debug('Processing %s files with %s', files, self.name)
command = ['yamllint', '--format=parsable']
# Add config file if its present
if self.options.get('config'):
command += ['-c', self.apply_base(self.options['config'])]
command += files
output = run_command(command, split=True, ignore_error=True)
if not output:
log.debug('No yamllint errors found.')
return False
for line in output:
filename, line, error = self._parse_line(line)
self.problems.add(filename, line, error)
def _parse_line(self, line):
"""
yamllint only generates results as stdout.
Parse the output for real data.
"""
parts = line.split(':', 3)
if len(parts) == 3:
message = parts[2].strip()
else:
message = parts[3].strip()
return (parts[0], int(parts[1]), message)
|
Change the exception with a more sensible one | <?php
namespace Ojs\JournalBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
/**
* ArticleFileRepository
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ArticleFileRepository extends EntityRepository
{
/**
* Get Article full text file.
* @param integer $articleId
* @return ArticleFile[]
* @throws NoResultException
*/
public function getArticleFullTextFiles($articleId)
{
try {
$article = $this
->getEntityManager()
->getRepository('OjsJournalBundle:Article')
->find($articleId);
if (!$article) {
throw new NoResultException();
}
$q = $this
->createQueryBuilder('a')
->select('a')
->where('a.article = :article AND a.type= 0')
->setParameter('article', $article)
->getQuery();
// The Query::getResult() method throws an exception
// if there is no record matching the criteria.
return $q->getResult();
} catch (NoResultException $e) {
$message = sprintf('There is no full text file for this article.');
throw new NoResultException($message, 0, $e);
}
}
}
| <?php
namespace Ojs\JournalBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
/**
* ArticleFileRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ArticleFileRepository extends EntityRepository
{
/**
* Get Article full text file.
* @param integer $articleId
* @return ArticleFile[]
* @throws UsernameNotFoundException
*/
public function getArticleFullTextFiles($articleId)
{
try {
$article = $this
->getEntityManager()
->getRepository('OjsJournalBundle:Article')
->find($articleId);
if (!$article) {
throw new NoResultException();
}
$q = $this
->createQueryBuilder('a')
->select('a')
->where('a.article = :article AND a.type= 0')
->setParameter('article', $article)
->getQuery();
// The Query::getResult() method throws an exception
// if there is no record matching the criteria.
return $q->getResult();
} catch (NoResultException $e) {
$message = sprintf('There is no full text file for this article.');
throw new UsernameNotFoundException($message, 0, $e); // TODO: UsernameNotFoundException?!
}
}
}
|
[IMP] Add debug assets to HTTP cases | # -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self.do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(SomethingCase, self).tearDown(*args, **kwargs)
def test_something(self):
"""First line of docstring appears in test logs.
Other lines do not.
Any method starting with ``test_`` will be tested.
"""
pass
class UICase(HttpCase):
def test_ui_web(self):
"""Test backend tests."""
self.phantom_js("/web/tests?debug=assets&module=module_name", "", login="admin")
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/?debug=assets",
code="odoo.__DEBUG__.services['web.Tour']"
".run('test_module_name', 'test')",
ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
login="admin")
| # -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self.do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(SomethingCase, self).tearDown(*args, **kwargs)
def test_something(self):
"""First line of docstring appears in test logs.
Other lines do not.
Any method starting with ``test_`` will be tested.
"""
pass
class UICase(HttpCase):
def test_ui_web(self):
"""Test backend tests."""
self.phantom_js("/web/tests?module=module_name", "", login="admin")
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/",
code="odoo.__DEBUG__.services['web.Tour']"
".run('test_module_name', 'test')",
ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
login="admin")
|
Allow for error handler to be passed as parameter
So that errors can be properly handled in cases like Promises etc. | (function(){
module.exports = concat
var fs = require('fs')
function concat(files, target, done, errFunction){
validateInputs(files, target, done, errFunction)
var writeStream = fs.createWriteStream(target, {flags: 'a'})
writeFiles(files.reverse(), writeStream, done, errFunction)
}
function writeFiles(files, writeStream, callback, errFunction){
if(files.length){
var currentFile = files.pop()
var readStream = fs.createReadStream(currentFile)
readStream.pipe(writeStream, { end: false })
readStream.on('error', errFunction)
readStream.on('end', function onReadEnd(){
writeFiles(files, writeStream, callback, errFunction)
})
} else {
writeStream.end();
callback()
}
}
function validateInputs(files, target, done, errFunction){
if(!(files instanceof Array)){
throw new Error('Expected array but got:', files)
}
files.forEach(function(f){
if(f && f.constructor !== String){
throw new Error('Unexpected input file path:', f)
}
})
if(target.constructor !== String || target.length === 0){
throw new Error('Expected string destination but got:', target)
}
if(typeof done !== 'function' && typeof errFunction !== 'function'){
throw new Error('Expected callback and errFunction to be functions!')
}
}
})()
| (function(){
module.exports = concat
var fs = require('fs')
function concat(files, target, done){
validateInputs(files, target, done)
var writeStream = fs.createWriteStream(target, {flags: 'a'})
writeFiles(files.reverse(), writeStream, done)
}
function writeFiles(files, writeStream, callback){
if(files.length){
var currentFile = files.pop()
var readStream = fs.createReadStream(currentFile)
readStream.pipe(writeStream, { end: false })
readStream.on('error', onError)
readStream.on('end', function onReadEnd(){
writeFiles(files, writeStream, callback)
})
} else {
writeStream.end();
callback()
}
}
function validateInputs(files, target, done){
if(!(files instanceof Array)){
throw new Error('Expected array but got:', files)
}
files.forEach(function(f){
if(f && f.constructor !== String){
throw new Error('Unexpected input file path:', f)
}
})
if(target.constructor !== String || target.length === 0){
throw new Error('Expected string destination but got:', target)
}
if(typeof done !== 'function'){
throw new Error('Expected callback to bea function but got:', done)
}
}
function onError(err) {
throw err
}
})()
|
Add retry for socket error | import socket
from celery.result import ResultBase, AsyncResult, GroupResult
import deployer
from deployer.tasks.exceptions import TaskExecutionException
from deployer.util import retry
__author__ = 'sukrit'
def check_or_raise_task_exception(result):
if isinstance(result, AsyncResult) and result.failed():
if isinstance(result.result, TaskExecutionException):
raise result.result
else:
raise TaskExecutionException(result.result, result.traceback)
def _check_error(result):
if not result or not isinstance(result, AsyncResult):
return
check_or_raise_task_exception(result)
_check_error(result.parent)
@retry(10, delay=5, backoff=1, except_on=(IOError, socket.error))
def simple_result(result):
# DO not remove line below
# Explanation: https://github.com/celery/celery/issues/2315
deployer.celery.app.set_current()
if isinstance(result, GroupResult):
return simple_result(result.results)
elif hasattr(result, '__iter__') and not isinstance(result, dict):
return [simple_result(each_result)
for each_result in result]
elif isinstance(result, ResultBase):
_check_error(result)
if result.ready():
check_or_raise_task_exception(result)
return simple_result(result.result)
else:
raise TaskNotReadyException()
return result
class TaskNotReadyException(Exception):
pass
| from celery.result import ResultBase, AsyncResult, GroupResult
import deployer
from deployer.tasks.exceptions import TaskExecutionException
__author__ = 'sukrit'
def check_or_raise_task_exception(result):
if isinstance(result, AsyncResult) and result.failed():
if isinstance(result.result, TaskExecutionException):
raise result.result
else:
raise TaskExecutionException(result.result, result.traceback)
def _check_error(result):
if not result or not isinstance(result, AsyncResult):
return
check_or_raise_task_exception(result)
_check_error(result.parent)
def simple_result(result):
# DO not remove line below
# Explanation: https://github.com/celery/celery/issues/2315
deployer.celery.app.set_current()
if isinstance(result, GroupResult):
return simple_result(result.results)
elif hasattr(result, '__iter__') and not isinstance(result, dict):
return [simple_result(each_result)
for each_result in result]
elif isinstance(result, ResultBase):
_check_error(result)
if result.ready():
check_or_raise_task_exception(result)
return simple_result(result.result)
else:
raise TaskNotReadyException()
return result
class TaskNotReadyException(Exception):
pass
|
Add missing EDUPUB property "seriespage" | package com.adobe.epubcheck.vocab;
public class StagingEdupubVocab
{
public static final String URI = "http://www.idpf.org/epub/vocab/structure/#";
public static final Vocab VOCAB = new EnumVocab(EPUB_TYPES.class, URI);
public static enum EPUB_TYPES
{
ABSTRACT,
ANSWER,
ANSWERS,
ASSESSMENTS,
BIBLIOREF,
CREDIT,
CREDITS,
FEEDBACK,
FILL_IN_THE_BLANK_PROBLEM,
GENERAL_PROBLEM,
GLOSSREF,
INDEX_EDITOR_NOTE,
INDEX_ENTRY,
INDEX_ENTRY_LIST,
INDEX_GROUP,
INDEX_HEADNOTES,
INDEX_LEGEND,
INDEX_LOCATOR,
INDEX_LOCATOR_LIST,
INDEX_LOCATOR_RANGE,
INDEX_TERM,
INDEX_TERM_CATEGORIES,
INDEX_TERM_CATEGORY,
INDEX_XREF_PREFERRED,
INDEX_XREF_RELATED,
KEYWORD,
LABEL,
LEARNING_OBJECTIVES,
LEARNING_OUTCOME,
LEARNING_OUTCOMES,
LEARNING_RESOURCES,
LEARNING_STANDARD,
LEARNING_STANDARDS,
MATCH_PROBLEM,
MULTIPLE_CHOICE_PROBLEM,
ORDINAL,
PRACTICE,
PRACTICES,
PULLQUOTE,
QUESTION,
REFERRER,
SERIESPAGE,
TOC_BRIEF,
TRUE_FALSE_PROBLEM;
}
}
| package com.adobe.epubcheck.vocab;
public class StagingEdupubVocab
{
public static final String URI = "http://www.idpf.org/epub/vocab/structure/#";
public static final Vocab VOCAB = new EnumVocab(EPUB_TYPES.class, URI);
public static enum EPUB_TYPES
{
ABSTRACT,
ANSWER,
ANSWERS,
ASSESSMENTS,
BIBLIOREF,
CREDIT,
CREDITS,
FEEDBACK,
FILL_IN_THE_BLANK_PROBLEM,
GENERAL_PROBLEM,
GLOSSREF,
INDEX_EDITOR_NOTE,
INDEX_ENTRY,
INDEX_ENTRY_LIST,
INDEX_GROUP,
INDEX_HEADNOTES,
INDEX_LEGEND,
INDEX_LOCATOR,
INDEX_LOCATOR_LIST,
INDEX_LOCATOR_RANGE,
INDEX_TERM,
INDEX_TERM_CATEGORIES,
INDEX_TERM_CATEGORY,
INDEX_XREF_PREFERRED,
INDEX_XREF_RELATED,
KEYWORD,
LABEL,
LEARNING_OBJECTIVES,
LEARNING_OUTCOME,
LEARNING_OUTCOMES,
LEARNING_RESOURCES,
LEARNING_STANDARD,
LEARNING_STANDARDS,
MATCH_PROBLEM,
MULTIPLE_CHOICE_PROBLEM,
ORDINAL,
PRACTICE,
PRACTICES,
PULLQUOTE,
QUESTION,
REFERRER,
TOC_BRIEF,
TRUE_FALSE_PROBLEM;
}
}
|
Set status to 5 - Production/Stable
Signed-off-by: Chris Warrick <[email protected]> | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
from setuptools import setup
with open('requirements.txt', 'r') as fh:
dependencies = [l.strip() for l in fh]
setup(name='coil',
version='1.3.1',
description='A user-friendly CMS frontend for Nikola.',
keywords='coil,nikola,cms',
author='Chris Warrick, Roberto Alsina, Henry Hirsch et al.',
author_email='[email protected]',
url='https://github.com/getnikola/coil',
license='MIT',
long_description=io.open('./README.rst', 'r', encoding='utf-8').read(),
platforms='any',
zip_safe=False,
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=['Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'],
packages=['coil'],
install_requires=dependencies,
include_package_data=True,
entry_points={
'console_scripts': [
'coil = coil.__main__:main',
]
},
)
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
from setuptools import setup
with open('requirements.txt', 'r') as fh:
dependencies = [l.strip() for l in fh]
setup(name='coil',
version='1.3.1',
description='A user-friendly CMS frontend for Nikola.',
keywords='coil,nikola,cms',
author='Chris Warrick, Roberto Alsina, Henry Hirsch et al.',
author_email='[email protected]',
url='https://github.com/getnikola/coil',
license='MIT',
long_description=io.open('./README.rst', 'r', encoding='utf-8').read(),
platforms='any',
zip_safe=False,
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=['Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'],
packages=['coil'],
install_requires=dependencies,
include_package_data=True,
entry_points={
'console_scripts': [
'coil = coil.__main__:main',
]
},
)
|
Set searchableEntity Id in constructor
In order to break earlier if there is no primary key | <?php
namespace Algolia\SearchBundle\Searchable;
use Algolia\SearchBundle\Normalizer\SearchableArrayNormalizer;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Serializer\Serializer;
class SearchableEntity implements SearchableEntityInterface
{
private $id;
protected $indexName;
protected $entity;
protected $entityMetadata;
protected $normalizers;
public function __construct($indexName, $entity, $entityMetadata, array $normalizers = [])
{
$this->indexName = $indexName;
$this->entity = $entity;
$this->entityMetadata = $entityMetadata;
$this->normalizers = $normalizer ?? [new SearchableArrayNormalizer()];
$this->setId();
}
public function getIndexName()
{
return $this->indexName;
}
public function getSearchableArray()
{
$serializer = new Serializer($this->normalizers);
return $serializer->normalize($this->entity, 'searchableArray', [
'fieldsMapping' => $this->entityMetadata->fieldMappings,
]);
}
private function setId()
{
$ids = $this->entityMetadata->getIdentifierValues($this->entity);
if (empty($ids)) {
throw new Exception('Entity has no primary key');
}
if (1 == count($ids)) {
$this->id = reset($ids);
}
$objectID = '';
foreach ($ids as $key => $value) {
$objectID .= $key . '-' . $value . '__';
}
$this->id = rtrim($objectID, '_');
}
public function getId()
{
return $this->id;
}
}
| <?php
namespace Algolia\SearchBundle\Searchable;
use Algolia\SearchBundle\Normalizer\SearchableArrayNormalizer;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Serializer\Serializer;
class SearchableEntity implements SearchableEntityInterface
{
protected $indexName;
protected $entity;
protected $entityMetadata;
protected $normalizers;
public function __construct($indexName, $entity, $entityMetadata, array $normalizers = [])
{
$this->indexName = $indexName;
$this->entity = $entity;
$this->entityMetadata = $entityMetadata;
$this->normalizers = $normalizer ?? [new SearchableArrayNormalizer()];
}
public function getIndexName()
{
return $this->indexName;
}
public function getSearchableArray()
{
$serializer = new Serializer($this->normalizers);
return $serializer->normalize($this->entity, 'searchableArray', [
'fieldsMapping' => $this->entityMetadata->fieldMappings,
]);
}
public function getId()
{
$ids = $this->entityMetadata->getIdentifierValues($this->entity);
if (empty($ids)) {
throw new Exception('Entity has no primary key');
}
if (1 == count($ids)) {
return reset($ids);
}
$objectID = '';
foreach ($ids as $key => $value) {
$objectID .= $key . '-' . $value . '__';
}
return rtrim($objectID, '_');
}
}
|
Add pypi links to issues and docs [ci skip] | """colorise module setup script for distribution."""
from setuptools import setup
import os
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
setup(
name='colorise',
version=get_version(os.path.join('colorise', '__init__.py')),
author='Alexander Asp Bock',
author_email='[email protected]',
platforms='Platform independent',
description=('Easily print colored text to the console'),
license='BSD 3-Clause License',
keywords='text, color, colorise, colorize, console, terminal',
packages=['colorise', 'colorise.win', 'colorise.nix'],
package_data={'colorise': ['tests', 'examples']},
url='https://github.com/MisanthropicBit/colorise',
project_urls={
'Issue Tracker': 'https://github.com/MisanthropicBit/colorise/issues',
'Documentation': 'https://colorise.readthedocs.io/en/latest/'
},
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Utilities',
'Topic :: Terminals',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: PyPy'
]
)
| """colorise module setup script for distribution."""
from setuptools import setup
import os
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
setup(
name='colorise',
version=get_version(os.path.join('colorise', '__init__.py')),
author='Alexander Asp Bock',
author_email='[email protected]',
platforms='Platform independent',
description=('Easily print colored text to the console'),
license='BSD 3-Clause License',
keywords='text, color, colorise, colorize, console, terminal',
packages=['colorise', 'colorise.win', 'colorise.nix'],
package_data={'colorise': ['tests', 'examples']},
url='https://github.com/MisanthropicBit/colorise',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Utilities',
'Topic :: Terminals',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: PyPy'
]
)
|
Fix regression where unable to open file on remote. | from sublime_plugin import TextCommand
from ...core.base_command import BaseCommand
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):
"""
Open a new browser window to the web-version of the currently opened
(or specified) file. If `preselect` is `True`, include the selected
lines in the request.
At present, this only supports github.com and GitHub enterprise.
"""
def run(self, edit, preselect=False, fpath=None):
fpath = fpath or self.get_rel_path()
start_line = None
end_line = None
if preselect:
selections = self.view.sel()
if len(selections) >= 1:
first_selection = selections[0]
last_selection = selections[-1]
# Git lines are 1-indexed; Sublime rows are 0-indexed.
start_line = self.view.rowcol(first_selection.begin())[0] + 1
end_line = self.view.rowcol(last_selection.end())[0] + 1
default_name, default_remote_url = self.get_remotes().popitem(last=False)
open_file_in_browser(
fpath,
default_remote_url,
self.get_commit_hash_for_head(),
start_line=start_line,
end_line=end_line
)
| from sublime_plugin import TextCommand
from ...common.file_and_repo import FileAndRepo
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo):
"""
Open a new browser window to the web-version of the currently opened
(or specified) file. If `preselect` is `True`, include the selected
lines in the request.
At present, this only supports github.com and GitHub enterprise.
"""
def run(self, preselect=False, fpath=None):
fpath = fpath or self.get_rel_path()
start_line = None
end_line = None
if preselect:
selections = self.view.sel()
if len(selections) >= 1:
first_selection = selections[0]
last_selection = selections[-1]
# Git lines are 1-indexed; Sublime rows are 0-indexed.
start_line = self.view.rowcol(first_selection.begin())[0] + 1
end_line = self.view.rowcol(last_selection.end())[0] + 1
default_name, default_remote_url = self.get_remotes().popitem(last=False)
open_file_in_browser(
fpath,
default_remote_url,
self.get_commit_hash_for_head(),
start_line=start_line,
end_line=end_line
)
|
Change positioning of rows in spendings' index view | @extends('layout')
@section('body')
<div class="wrapper my-3">
<h2>{{ __('general.spendings') }}</h2>
<div class="box mt-3">
@if (count($spendings))
@foreach ($spendings as $spending)
<div class="box__section row">
<div class="row__column">
<div class="color-dark">{{ $spending->description }}</div>
<div class="mt-1" style="font-size: 14px; font-weight: 600;">{{ $spending->formatted_happened_on }}</div>
</div>
<div class="row__column row__column--middle">
@if ($spending->tag)
<div style="
display: inline-block;
padding: 5px 10px;
text-transform: uppercase;
font-size: 12px;
font-weight: bolder;
bolder; color: #FFF;
background: #333;
border-radius: 5px;
">{{ $spending->tag->name }}</div>
@endif
</div>
<div class="row__column row__column--middle text-right" style="color: red;">€ {{ $spending->formatted_amount }}</div>
</div>
@endforeach
@else
<div class="box__section text-center">You don't have any spendings</div>
@endif
</div>
</div>
@endsection
| @extends('layout')
@section('body')
<div class="wrapper my-3">
<h2>{{ __('general.spendings') }}</h2>
<div class="box mt-3">
@if (count($spendings))
@foreach ($spendings as $spending)
<div class="box__section row">
<div class="row__column">
@if ($spending->tag)
<div style="
margin-bottom: 10px;
display: inline-block;
padding: 5px 10px;
text-transform: uppercase;
font-size: 12px;
font-weight: bolder;
bolder; color: #FFF;
background: #333;
border-radius: 5px;
">{{ $spending->tag->name }}</div>
@endif
<div>{{ $spending->description }}</div>
<div style="margin-top: 10px; font-size: 14px;">{{ $spending->formatted_happened_on }}</div>
</div>
<div class="row__column text-right" style="color: red;">€ {{ $spending->formatted_amount }}</div>
</div>
@endforeach
@else
<div class="box__section text-center">You don't have any spendings</div>
@endif
</div>
</div>
@endsection
|
Remove redundant stacktrace from the test console | package io.quarkus.reactive.mssql.client;
import java.net.ConnectException;
import java.sql.SQLException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.vertx.mssqlclient.MSSQLPool;
@Path("/dev")
public class DevModeResource {
@Inject
MSSQLPool client;
@GET
@Path("/error")
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage<Response> getErrorMessage() throws SQLException {
CompletableFuture<Response> future = new CompletableFuture<>();
client.query("SELECT 1").execute(ar -> {
Class<?> expectedExceptionClass = ConnectException.class;
if (ar.succeeded()) {
future.complete(Response.serverError().entity("Expected SQL query to fail").build());
} else if (!expectedExceptionClass.isAssignableFrom(ar.cause().getClass())) {
future.complete(Response.serverError()
.entity("Expected " + expectedExceptionClass + ", got " + ar.cause().getClass()).build());
} else {
future.complete(Response.ok(ar.cause().getMessage()).build());
}
});
return future;
}
}
| package io.quarkus.reactive.mssql.client;
import java.net.ConnectException;
import java.sql.SQLException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.vertx.mssqlclient.MSSQLPool;
@Path("/dev")
public class DevModeResource {
@Inject
MSSQLPool client;
@GET
@Path("/error")
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage<Response> getErrorMessage() throws SQLException {
CompletableFuture<Response> future = new CompletableFuture<>();
client.query("SELECT 1").execute(ar -> {
Class<?> expectedExceptionClass = ConnectException.class;
if (ar.succeeded()) {
future.complete(Response.serverError().entity("Expected SQL query to fail").build());
} else if (!expectedExceptionClass.isAssignableFrom(ar.cause().getClass())) {
ar.cause().printStackTrace();
future.complete(Response.serverError()
.entity("Expected " + expectedExceptionClass + ", got " + ar.cause().getClass()).build());
} else {
future.complete(Response.ok(ar.cause().getMessage()).build());
}
});
return future;
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.