text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix mari pointing to dead dir
|
/*
* itsjoke.js - It's Joke!.
*
* Contributed by Capuccino and Ovyerus.
*/
/* eslint-env node */
const fs = require('fs');
const files = fs.readdirSync(`${__baseDir}/assets/itsjoke`);
exports.commands = [
'mari'
];
exports.mari = {
desc: "It's joke!",
longDesc: "Send a random picture of the it's joke meme.",
main(bot, ctx) {
return new Promise((resolve, reject) => {
ctx.channel.sendTyping();
let fileName = files[Math.floor(Math.random() * files.length)];
let file = fs.readFileSync(`${__baseDir}/assets/itsjoke/${fileName}`);
ctx.createMessage('', {file, name: fileName}).then(resolve).catch(reject);
});
}
};
|
/*
* itsjoke.js - It's Joke!.
*
* Contributed by Capuccino and Ovyerus.
*/
/* eslint-env node */
const fs = require('fs');
const files = fs.readdirSync(`${__baseDir}/res/itsjoke`);
exports.commands = [
'mari'
];
exports.mari = {
desc: "It's joke!",
longDesc: "Send a random picture of the it's joke meme.",
main(bot, ctx) {
return new Promise((resolve, reject) => {
ctx.channel.sendTyping();
let fileName = files[Math.floor(Math.random() * files.length)];
let file = fs.readFileSync(`${__baseDir}/assets/itsjoke/${fileName}`);
ctx.createMessage('', {file, name: fileName}).then(resolve).catch(reject);
});
}
};
|
Fix filtering for deleted users
|
<?php
namespace ForkCMS\Modules\Backend\Backend\Actions;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ForkCMS\Modules\Backend\Domain\Action\AbstractActionController;
use ForkCMS\Modules\Backend\Domain\UserGroup\UserGroup;
use Symfony\Component\HttpFoundation\Request;
/**
*Overview of the available groups in the backend
*/
final class UserGroupIndex extends AbstractActionController
{
protected function execute(Request $request): void
{
$this->assign(
'groupDataGrid',
$this->dataGridFactory->forEntity(UserGroup::class, static function (QueryBuilder $queryBuilder): void {
$queryBuilder
->leftJoin('UserGroup.users', 'Users', Join::WITH, 'Users.deletedAt IS NULL')
->addSelect('Users');
})
);
}
}
|
<?php
namespace ForkCMS\Modules\Backend\Backend\Actions;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ForkCMS\Modules\Backend\Domain\Action\AbstractActionController;
use ForkCMS\Modules\Backend\Domain\UserGroup\UserGroup;
use Symfony\Component\HttpFoundation\Request;
/**
*Overview of the available groups in the backend
*/
final class UserGroupIndex extends AbstractActionController
{
protected function execute(Request $request): void
{
$this->assign(
'groupDataGrid',
$this->dataGridFactory->forEntity(UserGroup::class, static function (QueryBuilder $queryBuilder): void {
$queryBuilder
->leftJoin('UserGroup.users', 'Users', Join::WITH, 'Users.deleted = 0')
->addSelect('Users');
})
);
}
}
|
Fix and ungodly number of linter errors
|
navigator.geolocation.getCurrentPosition(function (position) {
var mapToMake = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
makeMap(mapToMake);
}, function (err) {
console.error(err);
});
var map;
var marker;
var destinationMarker;
var makeMap = function (currentLatLngObj) {
map = new google.maps.Map(document.getElementById('map'), {
center: currentLatLngObj,
zoom: 13
});
marker = new google.maps.Marker({
position: currentLatLngObj,
map: map,
animation: google.maps.Animation.DROP,
icon: '/assets/bolt.png'
});
destinationMarker = new google.maps.Marker({
position: randomCoordsAlongCircumference(currentLatLngObj, 1),
map: map,
animation: google.maps.Animation.DROP,
icon: '/assets/finish-line.png' // change to finish line image
});
};
var randomCoordsAlongCircumference = function (originObj, radius) {
var randomTheta = Math.random() * 2 * Math.PI;
return {
lat: originObj.lat + (radius / 69 * Math.cos(randomTheta)),
lng: originObj.lng + (radius / 69 * Math.sin(randomTheta))
};
};
|
navigator.geolocation.getCurrentPosition(function(position) {
makeMap({lat: position.coords.latitude, lng: position.coords.longitude});
}, function(err) {
console.error(err);
});
var map;
var marker;
var destinationMarker;
var makeMap = function(currentLatLngObj) {
map = new google.maps.Map(document.getElementById('map'), {
center: currentLatLngObj,
zoom: 13
});
marker = new google.maps.Marker({
position: currentLatLngObj,
map: map,
animation: google.maps.Animation.DROP,
icon: '/assets/bolt.png'
});
destinationMarker = new google.maps.Marker({
position: randomCoordsAlongCircumference(currentLatLngObj, 1),
map: map,
animation: google.maps.Animation.DROP,
icon: '/assets/finish-line.png' // change to finish line image
});
};
var randomCoordsAlongCircumference = function(originObj, radius) {
var randomTheta = Math.random() * 2 * Math.PI;
return {
lat: originObj.lat + (radius / 69 * Math.cos(randomTheta)),
lng: originObj.lng + (radius / 69 * Math.sin(randomTheta))
};
};
|
Include dotfiles when copying the site
Part one of fixing issue #141.
|
'use strict';
const gulp = require('gulp');
const shell = require('shelljs');
const size = require('gulp-size');
const argv = require('yargs').argv;
// 'gulp jekyll:tmp' -- copies your Jekyll site to a temporary directory
// to be processed
gulp.task('site:tmp', () =>
gulp.src(['src/**/*', '!src/assets/**/*', '!src/assets'], {dot: true})
.pipe(gulp.dest('.tmp/src'))
.pipe(size({title: 'Jekyll'}))
);
// 'gulp jekyll' -- builds your site with development settings
// 'gulp jekyll --prod' -- builds your site with production settings
gulp.task('site', done => {
if (!argv.prod) {
shell.exec('jekyll build');
done();
} else if (argv.prod) {
shell.exec('jekyll build --config _config.yml,_config.build.yml');
done();
}
});
// 'gulp doctor' -- literally just runs jekyll doctor
gulp.task('site:check', done => {
shell.exec('jekyll doctor');
done();
});
|
'use strict';
const gulp = require('gulp');
const shell = require('shelljs');
const size = require('gulp-size');
const argv = require('yargs').argv;
// 'gulp jekyll:tmp' -- copies your Jekyll site to a temporary directory
// to be processed
gulp.task('site:tmp', () =>
gulp.src(['src/**/*', '!src/assets/**/*', '!src/assets'])
.pipe(gulp.dest('.tmp/src'))
.pipe(size({title: 'Jekyll'}))
);
// 'gulp jekyll' -- builds your site with development settings
// 'gulp jekyll --prod' -- builds your site with production settings
gulp.task('site', done => {
if (!argv.prod) {
shell.exec('jekyll build');
done();
} else if (argv.prod) {
shell.exec('jekyll build --config _config.yml,_config.build.yml');
done();
}
});
// 'gulp doctor' -- literally just runs jekyll doctor
gulp.task('site:check', done => {
shell.exec('jekyll doctor');
done();
});
|
Fix bug with messages not showing up for the user that sends the message
|
// require('./Pad.js')
function DrawingAppCtrl($scope, socket, drawingPad) {
console.log("starting");
$socket = socket;
$scope.message;
$scope.messages = [];
$scope.joined = false;
$scope.username;
drawingPad.initialize(socket);
$scope.sendMsg = function (message) {
$scope.messages.push({msg: message, name: $scope.username});
$scope.message = "";
socket.emit('msg', {msg: message, name: $scope.username});
}
$scope.join = function (groupName) {
$scope.joined = true;
socket.emit('joinGroup', {name: groupName});
}
$scope.chooseUsername = function (name) {
console.log("stuff");
$scope.username = name;
socket.emit('setUsername', {username: name});
}
// socket.on('joinRoom', function(newRoom) {
// })
socket.on('draw', function (data) {
drawingPad.drawLineFrom( data.begin, data.end );
});
socket.on('addMsg', function (data) {
console.log(data);
$scope.messages.push(data);
});
}
|
// require('./Pad.js')
function DrawingAppCtrl($scope, socket, drawingPad) {
console.log("starting");
$socket = socket;
$scope.message;
$scope.messages = [];
$scope.joined = false;
$scope.username;
drawingPad.initialize(socket);
$scope.sendMsg = function (message) {
$scope.messages.push(message);
$scope.message = "";
socket.emit('msg', {msg: message, name: $scope.username});
}
$scope.join = function (groupName) {
$scope.joined = true;
socket.emit('joinGroup', {name: groupName});
}
$scope.chooseUsername = function (name) {
console.log("stuff");
$scope.username = name;
socket.emit('setUsername', {username: name});
}
// socket.on('joinRoom', function(newRoom) {
// })
socket.on('draw', function (data) {
drawingPad.drawLineFrom( data.begin, data.end );
});
socket.on('addMsg', function (data) {
console.log(data);
$scope.messages.push(data);
});
}
|
Change Database with a more fitting name
|
//Dear source-code readers, pay no attention to these global variables
var APP_ID = 'YtKfTS2Zo8ELUk63LzB0';
var APP_CODE = 'SB1wcsUEGzLA3SRHJJ7CPw';
// Reference to the root of the Firebase database
var database = new Firebase("https://battleshiphere.firebaseio.com/");
$("#upload").click(function() {
var name = $("#nameInput").val();
var text = $("#messageInput").val();
if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
console.log(name.length);
console.log(text.length);
database.push({name: name, text: text});
database.on('child_added', function(update) {
console.log("Callback function: New data has been added to the database");
});
}else {
console.log("Please input values into the textbox");
}
});
console.log('LOADED BACKEND');
|
//Dear source-code readers, pay no attention to these global variables
var APP_ID = 'YtKfTS2Zo8ELUk63LzB0';
var APP_CODE = 'SB1wcsUEGzLA3SRHJJ7CPw';
// Reference to the root of the Firebase database
var database = new Firebase("https://brilliant-torch-6592.firebaseio.com/");
$("#upload").click(function() {
var name = $("#nameInput").val();
var text = $("#messageInput").val();
if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
console.log(name.length);
console.log(text.length);
database.push({name: name, text: text});
database.on('child_added', function(update) {
console.log("Callback function: New data has been added to the database");
});
}else {
console.log("Please input values into the textbox");
}
});
console.log('LOADED BACKEND');
|
Add flag option `start-hot` and apply env
* Add flag option `start-hot` to server.js
* Apply env to `start-hot` mode of server.js
|
/* eslint-disable no-console */
/**
* Setup and run the development server for Hot-Module-Replacement
* https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
* @flow
*/
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { spawn } from 'child_process';
import config from './webpack.config.development';
const argv = require('minimist')(process.argv.slice(2));
const app = express();
const compiler = webpack(config);
const PORT = process.env.PORT || 3000;
const wdm = webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
stats: {
colors: true
}
});
app.use(wdm);
app.use(webpackHotMiddleware(compiler));
const server = app.listen(PORT, 'localhost', serverError => {
if (serverError) {
return console.error(serverError);
}
if (argv['start-hot']) {
spawn('npm', ['run', 'start-hot'], { env: process.env, stdio: 'inherit' })
.on('close', code => process.exit(code))
.on('error', spawnError => console.error(spawnError));
}
console.log(`Listening at http://localhost:${PORT}`);
});
process.on('SIGTERM', () => {
console.log('Stopping dev server');
wdm.close();
server.close(() => {
process.exit(0);
});
});
|
/* eslint-disable no-console */
/**
* Setup and run the development server for Hot-Module-Replacement
* https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
* @flow
*/
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { spawn } from 'child_process';
import config from './webpack.config.development';
const app = express();
const compiler = webpack(config);
const PORT = process.env.PORT || 3000;
const wdm = webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
stats: {
colors: true
}
});
app.use(wdm);
app.use(webpackHotMiddleware(compiler));
const server = app.listen(PORT, 'localhost', serverError => {
if (serverError) {
return console.error(serverError);
}
spawn('npm', ['run', 'start-hot'], { stdio: 'inherit' })
.on('close', code => process.exit(code))
.on('error', spawnError => console.error(spawnError));
console.log(`Listening at http://localhost:${PORT}`);
});
process.on('SIGTERM', () => {
console.log('Stopping dev server');
wdm.close();
server.close(() => {
process.exit(0);
});
});
|
Make it parse (using PHP 5.5).
|
<?php
$path = $_SERVER['PATH_INFO'];
if ($path = '/address')
{
$controller = new \Controller();
$return = $controller->ex();
echo $return;
}
class Controller
{
private $addresses = [];
function ex()
{
$this->rcd();
$id = $_GET['id'];
$address = $this->addresses[$id];
return json_encode($address);
}
function rcd()
{
$file = fopen('example.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
$this->addresses[] = [
name => $line[0],
phone => $line[1],
street => $line[2]
];
}
fclose($file);
}
}
?>
|
<?php
$path = $_SERVER['PATH_INFO'];
if ($path = '/address')
{
$controller = new \Controller();
$return = $controller->ex();
echo $return;
}
class Controller
{
$addresses = [];
function ex()
{
$this->rcd();
$id = $_GET['id']
$address = $this->addresses[$id];
return json_encode($address);
}
function rcd()
{
$file = fopen('example.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
$this->addresses[] = [
name = $line[0],
phone = $line[1],
street = $line[2]
]
}
fclose($file);
}
}
?>
|
BAP-4107: Change UX
- remove mock
|
<?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\ParameterBag;
class ProviderManager
{
protected $providers;
public function __construct()
{
$this->providers = new ArrayCollection();
}
/**
* @param AbstractProvider $provider
*/
public function addProvider(AbstractProvider $provider)
{
$this->providers->add($provider);
}
/**
* @param string $entityName
* @param ParameterBag $parameters
*
* @return AbstractProvider
*/
public function selectByParams($entityName, ParameterBag $parameters)
{
$parameters->set('entityName', $entityName);
/** @var AbstractProvider $provider */
foreach ($this->providers as $provider) {
if ($provider->isApplied($parameters)) {
return $provider;
}
}
return $this->providers->first();
}
}
|
<?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\ParameterBag;
class ProviderManager
{
protected $providers;
public function __construct()
{
$this->providers = new ArrayCollection();
}
/**
* @param AbstractProvider $provider
*/
public function addProvider(AbstractProvider $provider)
{
$this->providers->add($provider);
}
/**
* @param string $entityName
* @param ParameterBag $parameters
*
* @return AbstractProvider
*/
public function selectByParams($entityName, ParameterBag $parameters)
{
$parameters->set('entityName', $entityName);
// @TODO: remove this before merge
$parameters->set('plain-list', '1');
/** @var AbstractProvider $provider */
foreach ($this->providers as $provider) {
if ($provider->isApplied($parameters)) {
return $provider;
}
}
return $this->providers->first();
}
}
|
Make OidcTokenRequest a local struct
|
package api
import (
"errors"
"fmt"
)
var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience")
type OidcToken struct {
Token string `json:"token"`
}
func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) {
type oidcTokenRequest struct {
Audience string `json:"audience"`
}
var m *oidcTokenRequest
switch len(audience) {
case 0:
m = nil
case 1:
m = &oidcTokenRequest{Audience: audience[0]}
default:
return nil, nil, ErrAudienceTooLong
}
u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId)
req, err := c.newRequest("POST", u, m)
if err != nil {
return nil, nil, err
}
t := &OidcToken{}
resp, err := c.doRequest(req, t)
if err != nil {
return nil, nil, err
}
return t, resp, err
}
|
package api
import (
"errors"
"fmt"
)
var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience")
type OidcTokenRequest struct {
Audience string `json:"audience"`
}
type OidcToken struct {
Token string `json:"token"`
}
func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) {
var m *OidcTokenRequest
switch len(audience) {
case 0:
m = nil
case 1:
m = &OidcTokenRequest{Audience: audience[0]}
default:
return nil, nil, ErrAudienceTooLong
}
u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId)
req, err := c.newRequest("POST", u, m)
if err != nil {
return nil, nil, err
}
t := &OidcToken{}
resp, err := c.doRequest(req, t)
if err != nil {
return nil, nil, err
}
return t, resp, err
}
|
Insert new files, AngularJS para Zumbis, Aula 14
|
angular.module('app').directive('ngCepValidator', function($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModel) {
$scope.$watch($attrs.ngModel, function(value) {
if(value) {
if(value.match(/^[0-9]{5}-[0-9]{3}$/)) {
$http.get('http://api.postmon.com.br/v1/cep/' + value)
.then(function(response) {
console.log(response);
});
ngModel.$setValidity($attrs.ngModel, true);
} else {
ngModel.$setValidity($attrs.ngModel, false);
}
} else {
ngModel.$setValidity($attrs.ngModel, false);
}
});
}
}
})
|
angular.module('app').directive('ngCepValidator', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModel) {
$scope.$watch($attrs.ngModel, function(value) {
if(value) {
if(value.match(/^[0-9]{5}-[0-9]{3}$/)) {
ngModel.$setValidity($attrs.ngModel, true);
} else {
ngModel.$setValidity($attrs.ngModel, false);
}
} else {
ngModel.$setValidity($attrs.ngModel, false);
}
});
}
}
})
|
Revert the mess WordPress makes
|
<?php
$m = new Mustache_Engine([
'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
'extension' => '.html',
]),
]);
$template = $m->loadTemplate('govuk_template');
echo $template->render([
'pageTitle' => html_entity_decode(\Missing\String::get_output(function () { wp_title('|', true, 'right'); })),
'assetPath' => get_template_directory_uri().'/build/govuk_template/assets/',
'head' => \Missing\String::get_output('wp_head'),
'bodyClasses' => implode(' ', array_map('esc_attr', get_body_class())),
'cookieMessage' => \Missing\String::get_output(function () { get_template_part('templates/cookies'); }),
'content' => \Missing\String::get_output(function () { get_template_part('templates/base'); }),
'footerSupportLinks' => \Missing\String::get_output(function () { get_template_part('templates/footer'); }),
'bodyEnd' => \Missing\String::get_output('wp_footer'),
]);
|
<?php
$m = new Mustache_Engine([
'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
'extension' => '.html',
]),
]);
$template = $m->loadTemplate('govuk_template');
echo $template->render([
'pageTitle' => \Missing\String::get_output(function () { wp_title('|', true, 'right'); }),
'assetPath' => get_template_directory_uri().'/build/govuk_template/assets/',
'head' => \Missing\String::get_output('wp_head'),
'bodyClasses' => implode(' ', array_map('esc_attr', get_body_class())),
'cookieMessage' => \Missing\String::get_output(function () { get_template_part('templates/cookies'); }),
'content' => \Missing\String::get_output(function () { get_template_part('templates/base'); }),
'footerSupportLinks' => \Missing\String::get_output(function () { get_template_part('templates/footer'); }),
'bodyEnd' => \Missing\String::get_output('wp_footer'),
]);
|
Handle label if plural or singular
|
import inflect from 'i';
import numeral from 'numeral';
import FormattedNumber from '../types/formatted_number';
import { GraphQLString } from 'graphql';
const { pluralize, singularize } = inflect();
export default fn => ({
type: FormattedNumber,
args: {
format: {
type: GraphQLString,
description: 'Returns a `String` when format is specified. e.g.`"0,0.0000"`',
},
label: {
type: GraphQLString,
},
},
resolve: (obj, { format, label }, { fieldName }) => {
let value = fn ? fn(obj) : obj[fieldName];
if (!value) return null;
const count = value;
if (!!format) {
value = numeral(value).format(format);
}
if (!!label) {
value = `${value} ${count === 1 ? singularize(label) : pluralize(label)}`;
}
return value;
},
});
|
import inflect from 'i';
import numeral from 'numeral';
import FormattedNumber from '../types/formatted_number';
import { GraphQLString } from 'graphql';
const { pluralize } = inflect();
export default fn => ({
type: FormattedNumber,
args: {
format: {
type: GraphQLString,
description: 'Returns a `String` when format is specified. e.g.`"0,0.0000"`',
},
label: {
type: GraphQLString,
},
},
resolve: (obj, { format, label }, { fieldName }) => {
let value = fn ? fn(obj) : obj[fieldName];
if (!value) return null;
if (!!format) {
value = numeral(value).format(format);
}
if (!!label) {
value = `${value} ${pluralize(label)}`;
}
return value;
},
});
|
Add a correct url to the qr-code to allow scanning with other apps
|
import View from './View'
export default class RoomView extends View {
constructor() {
super();
this.title = 'Room';
this.templateUrl = 'templates/room';
}
afterInit() {
const roomId = 'test';
const joinUrl = location.href.split('#')[0] + '#/join/';
[1, 2].forEach(playerId => {
const joinArea = this.find(`.join-area:nth-child(${playerId})`);
const qrCodeHolder = joinArea.querySelector('.code-holder');
const clearCode = joinArea.querySelector('.clear-code');
new QRCode(qrCodeHolder, `${joinUrl}${roomId}-${playerId}`);
clearCode.value = `${roomId}-${playerId}`;
});
}
joinLeft() {
CastleCrush.ViewManager.load('game');
}
joinRight() {
CastleCrush.ViewManager.load('game');
}
}
|
import View from './View'
export default class RoomView extends View {
constructor() {
super();
this.title = 'Room';
this.templateUrl = 'templates/room';
}
afterInit() {
const roomId = 'test';
[1, 2].forEach(playerId => {
const joinArea = this.find(`.join-area:nth-child(${playerId})`);
const qrCodeHolder = joinArea.querySelector('.code-holder');
const clearCode = joinArea.querySelector('.clear-code');
new QRCode(qrCodeHolder, `${roomId}-${playerId}`);
clearCode.value = `${roomId}-${playerId}`;
});
}
joinLeft() {
CastleCrush.ViewManager.load('game');
}
joinRight() {
CastleCrush.ViewManager.load('game');
}
}
|
Add copy image in gulp
|
var gulp = require('gulp'),
gulpCopy = require('gulp-file-copy');
gulp.task('copy', function() {
gulp.src('./bower_components/jquery/jquery.min.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./bower_components/moment/min/moment-with-locales.min.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./bower_components/local-storage/src/LocalStorage.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./jquery-mobile/jquery.mobile-1.4.5.css')
.pipe(gulp.dest('./css/lib/'));
gulp.src('./jquery-mobile/images/ajax-loader.gif')
.pipe(gulp.dest('./js/lib/images/'));
});
|
var gulp = require('gulp'),
gulpCopy = require('gulp-file-copy');
gulp.task('copy', function() {
gulp.src('./bower_components/jquery/jquery.min.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./bower_components/moment/min/moment-with-locales.min.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./bower_components/local-storage/src/LocalStorage.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./jquery-mobile/jquery.mobile-1.4.5.css')
.pipe(gulp.dest('./css/lib/'));
});
|
Define Node properties and methods
|
<?php
namespace Gt\Dom;
use DOMNode;
/**
* Represents any web page loaded in the browser and serves as an entry point
* into the web page's content, the DOM tree (including elements such as
* <body> or <table>).
*
* @method Node importNode(DOMNode $importedNode, bool $deep = false)
*/
class Document extends \DOMDocument {
use LiveProperty, ParentNode;
public function __construct($document = null) {
parent::__construct("1.0", "utf-8");
$this->registerNodeClass("\\DOMNode", Node::class);
$this->registerNodeClass("\\DOMElement", Element::class);
$this->registerNodeClass("\\DOMAttr", Attr::class);
$this->registerNodeClass("\\DOMDocumentFragment", DocumentFragment::class);
$this->registerNodeClass("\\DOMDocumentType", DocumentType::class);
$this->registerNodeClass("\\DOMCharacterData", CharacterData::class);
$this->registerNodeClass("\\DOMText", Text::class);
$this->registerNodeClass("\\DOMComment", Comment::class);
if ($document instanceof \DOMDocument) {
$node = $this->importNode($document->documentElement, true);
$this->appendChild($node);
return;
}
}
protected function getRootDocument(): \DOMDocument {
return $this;
}
}#
|
<?php
namespace Gt\Dom;
/**
* Represents any web page loaded in the browser and serves as an entry point
* into the web page's content, the DOM tree (including elements such as
* <body> or <table>).
*/
class Document extends \DOMDocument {
use LiveProperty, ParentNode;
public function __construct($document = null) {
parent::__construct("1.0", "utf-8");
$this->registerNodeClass("\\DOMNode", Node::class);
$this->registerNodeClass("\\DOMElement", Element::class);
$this->registerNodeClass("\\DOMAttr", Attr::class);
$this->registerNodeClass("\\DOMDocumentFragment", DocumentFragment::class);
$this->registerNodeClass("\\DOMDocumentType", DocumentType::class);
$this->registerNodeClass("\\DOMCharacterData", CharacterData::class);
$this->registerNodeClass("\\DOMText", Text::class);
$this->registerNodeClass("\\DOMComment", Comment::class);
if ($document instanceof \DOMDocument) {
$node = $this->importNode($document->documentElement, true);
$this->appendChild($node);
return;
}
}
protected function getRootDocument(): \DOMDocument {
return $this;
}
}#
|
Move from python anywhere to webfaction
|
import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_command.sh') as f:
raw_command = f.read()
if lines:
subject = 'Tube delays for commute'
body = ', '.join(': '.join([line.capitalize(), s]) for line, s in status.items())
else:
subject = 'Good service for commute'
body = 'Good service on all lines'
os.system(raw_command.format(subject=subject, body=body))
def main():
commute_lines = ['metropolitan', 'jubilee', 'central']
status = update()
delays = {c: status[c] for c in commute_lines if status[c] != 'Good Service'}
email(delays)
if __name__ == '__main__':
main()
|
import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_command.sh') as f:
raw_command = f.read()
if lines:
subject = 'Tube delays for commute'
body = ', '.join(': '.join([line.capitalize(), s]) for line, s in status.items())
else:
subject = 'Good service for commute'
body = 'Good service on all lines'
# We must have this running on PythonAnywhere - Monday to Sunday.
# Ignore Saturday and Sunday
if datetime.date.today().isoweekday() in range(1, 6):
os.system(raw_command.format(subject=subject, body=body))
def main():
commute_lines = ['metropolitan', 'jubilee', 'central']
status = update()
delays = {c: status[c] for c in commute_lines if status[c] != 'Good Service'}
email(delays)
if __name__ == '__main__':
main()
|
Fix race in TestThrottle test.
Closes #355.
|
// Copyright (c) 2013-2014 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package legacyrpc
import (
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestThrottle(t *testing.T) {
const threshold = 1
busy := make(chan struct{})
srv := httptest.NewServer(throttledFn(threshold,
func(w http.ResponseWriter, r *http.Request) {
<-busy
}),
)
codes := make(chan int, 2)
for i := 0; i < cap(codes); i++ {
go func() {
res, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
codes <- res.StatusCode
}()
}
got := make(map[int]int, cap(codes))
for i := 0; i < cap(codes); i++ {
got[<-codes]++
if i == 0 {
close(busy)
}
}
want := map[int]int{200: 1, 429: 1}
if !reflect.DeepEqual(want, got) {
t.Fatalf("status codes: want: %v, got: %v", want, got)
}
}
|
// Copyright (c) 2013-2014 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package legacyrpc
import (
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
)
func TestThrottle(t *testing.T) {
const threshold = 1
srv := httptest.NewServer(throttledFn(threshold,
func(w http.ResponseWriter, r *http.Request) {
time.Sleep(20 * time.Millisecond)
}),
)
codes := make(chan int, 2)
for i := 0; i < cap(codes); i++ {
go func() {
res, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
codes <- res.StatusCode
}()
}
got := make(map[int]int, cap(codes))
for i := 0; i < cap(codes); i++ {
got[<-codes]++
}
want := map[int]int{200: 1, 429: 1}
if !reflect.DeepEqual(want, got) {
t.Fatalf("status codes: want: %v, got: %v", want, got)
}
}
|
Add importlib if not included
|
#!/usr/bin/env python
from setuptools import setup
from exoline import __version__ as version
with open('requirements.txt') as f:
required = f.read().splitlines()
try:
from collections import OrderedDict
except ImportError:
required.append('ordereddict>=1.1')
try:
import importlib
except ImportError:
required.append('importlib>=1.0.2')
setup(
name='exoline',
version=version,
url = 'http://github.com/dweaver/exoline',
author = 'Dan Weaver',
author_email = 'danweaver@exosite.com',
description = 'Command line interface for Exosite platform.',
long_description = open('README.md').read() + '\n\n' +
open('HISTORY.md').read(),
packages=['exoline'],
package_dir={'exoline': 'exoline'},
scripts=['bin/exo', 'bin/exoline'],
keywords=['exosite', 'onep', 'one platform', 'm2m'],
install_requires=required,
zip_safe=False,
)
|
#!/usr/bin/env python
from setuptools import setup
from exoline import __version__ as version
with open('requirements.txt') as f:
required = f.read().splitlines()
try:
from collections import OrderedDict
except ImportError:
required.append('ordereddict==1.1')
setup(
name='exoline',
version=version,
url = 'http://github.com/dweaver/exoline',
author = 'Dan Weaver',
author_email = 'danweaver@exosite.com',
description = 'Command line interface for Exosite platform.',
long_description = open('README.md').read() + '\n\n' +
open('HISTORY.md').read(),
packages=['exoline'],
package_dir={'exoline': 'exoline'},
scripts=['bin/exo', 'bin/exoline'],
keywords=['exosite', 'onep', 'one platform', 'm2m'],
install_requires=required,
zip_safe=False,
)
|
Make DQN backward compatible with pytorch 0.1.2.
|
from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Takes best action based on estimated state-action values."""
state = state.cuda() if self.cuda else state
q_val, argmax_a = self.policy(
Variable(state, volatile=True)).data.max(1)
"""
result = self.policy(Variable(state_batch, volatile=True))
print(result)
"""
return (q_val.squeeze()[0], argmax_a.squeeze()[0])
|
from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Takes best action based on estimated state-action values."""
state = state.cuda() if self.cuda else state
q_val, argmax_a = self.policy(
Variable(state, volatile=True)).data.max(1)
"""
result = self.policy(Variable(state_batch, volatile=True))
print(result)
"""
return (q_val[0], argmax_a[0])
|
Add mode config based on MIN env variable
|
import path from 'path';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
const sourcePath = path.join(__dirname, './src');
const distPath = path.join(__dirname, './dist');
export default {
mode: (process.env.MIN === 'true') ? 'production' : 'none',
entry: {
js: [path.join(sourcePath, '/component.js')],
},
output: {
path: distPath,
filename: (process.env.MIN === 'true') ? 'index.min.js' : 'index.js',
library: 'zbutton',
libraryTarget: 'umd',
umdNamedDefine: true,
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [MiniCssExtractPlugin.loader, 'css-loader?sourceMap', 'postcss-loader'],
},
{
test: /\.hbs$/,
exclude: /node_modules/,
use: ['handlebars-loader'],
},
],
},
resolve: {
extensions: ['.js', '.css'],
},
plugins: [
new MiniCssExtractPlugin({ filename: 'style.css' }),
],
};
|
import path from 'path';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
const sourcePath = path.join(__dirname, './src');
const distPath = path.join(__dirname, './dist');
export default {
mode: 'production',
entry: {
js: [path.join(sourcePath, '/component.js')],
},
output: {
path: distPath,
filename: (process.env.MIN === 'true') ? 'index.min.js' : 'index.js',
library: 'zbutton',
libraryTarget: 'umd',
umdNamedDefine: true,
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [MiniCssExtractPlugin.loader, 'css-loader?sourceMap', 'postcss-loader'],
},
{
test: /\.hbs$/,
exclude: /node_modules/,
use: ['handlebars-loader'],
},
],
},
resolve: {
extensions: ['.js', '.css'],
},
plugins: [
new MiniCssExtractPlugin({ filename: 'style.css' }),
],
};
|
Order tags: users first, guest after
|
<?php
class Denkmal_Paging_Tag_VenueUserLatest extends Denkmal_Paging_Tag_Abstract {
/**
* @param Denkmal_Model_Venue $venue
* @param DateTime|null $createdMin
*/
public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
if ($createdMin == null) {
$createdMin = (new DateTime())->sub(new DateInterval('PT1H'));
}
$join = 'JOIN `denkmal_model_message` m ON `m`.`id` = `denkmal_model_tag_model`.`modelId` ';
$join .= 'AND `denkmal_model_tag_model`.`modelType` = ' . Denkmal_Model_Message::getTypeStatic();
$group = '`denkmal_model_tag_model`.`tagId`';
$where = '`m`.`venue` = ' . $venue->getId();
$where .= ' AND `m`.`created` > ' . $createdMin->getTimestamp();
$order = 'ISNULL(`m`.user) ASC, `m`.`created` DESC, `denkmal_model_tag_model`.tagId ASC';
$source = new CM_PagingSource_Sql('`denkmal_model_tag_model`.tagId', 'denkmal_model_tag_model', $where, $order, $join, $group);
$source->enableCacheLocal(100);
parent::__construct($source);
}
}
|
<?php
class Denkmal_Paging_Tag_VenueUserLatest extends Denkmal_Paging_Tag_Abstract {
/**
* @param Denkmal_Model_Venue $venue
* @param DateTime|null $createdMin
*/
public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
if ($createdMin == null) {
$createdMin = (new DateTime())->sub(new DateInterval('PT1H'));
}
$join = 'JOIN `denkmal_model_message` m ON `m`.`id` = `denkmal_model_tag_model`.`modelId` ';
$join .= 'AND `denkmal_model_tag_model`.`modelType` = ' . Denkmal_Model_Message::getTypeStatic();
$group = '`denkmal_model_tag_model`.`tagId`';
$where = '`m`.`venue` = ' . $venue->getId();
$where .= ' AND `m`.`created` > ' . $createdMin->getTimestamp();
$where .= ' AND `m`.`user` IS NOT NULL';
$order = '`m`.`created` DESC, `denkmal_model_tag_model`.tagId ASC';
$source = new CM_PagingSource_Sql('`denkmal_model_tag_model`.tagId', 'denkmal_model_tag_model', $where, $order, $join, $group);
$source->enableCacheLocal(100);
parent::__construct($source);
}
}
|
Add missing semicolons in Travis.Controllers.Builds.List
|
Travis.Controllers.Builds.List = SC.ArrayProxy.extend({
parent: null,
repositoryBinding: 'parent.repository',
contentBinding: 'parent.repository.builds',
init: function() {
SC.run.later(this.updateTimes.bind(this), Travis.UPDATE_TIMES_INTERVAL);
this.view = Travis.View.create({
builds: this,
repositoryBinding: 'builds.repository',
templateName: 'app/templates/builds/list'
});
},
destroy: function() {
// console.log('destroying list in: ' + this.selector + ' .details')
if(this.view) {
this.view.$().remove();
this.view.destroy();
}
},
updateTimes: function() {
var builds = this.get('builds');
if(builds) {
$.each(builds, function(ix, build) { build.updateTimes(); }.bind(this));
}
SC.run.later(this.updateTimes.bind(this), Travis.UPDATE_TIMES_INTERVAL);
}
});
|
Travis.Controllers.Builds.List = SC.ArrayProxy.extend({
parent: null,
repositoryBinding: 'parent.repository',
contentBinding: 'parent.repository.builds',
init: function() {
SC.run.later(this.updateTimes.bind(this), Travis.UPDATE_TIMES_INTERVAL);
this.view = Travis.View.create({
builds: this,
repositoryBinding: 'builds.repository',
templateName: 'app/templates/builds/list'
})
},
destroy: function() {
// console.log('destroying list in: ' + this.selector + ' .details')
if(this.view) {
this.view.$().remove();
this.view.destroy();
}
},
updateTimes: function() {
var builds = this.get('builds');
if(builds) $.each(builds, function(ix, build) { build.updateTimes() }.bind(this));
SC.run.later(this.updateTimes.bind(this), Travis.UPDATE_TIMES_INTERVAL);
}
});
|
Change ArcadeDrive to TankDrive for speed control
|
package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* Rotates the Robot without PID values
*/
public class DrivetrainRotateNoPIDCommand extends Command {
private double degrees;
private double startAngle;
public DrivetrainRotateNoPIDCommand(double _degrees) {
requires(Robot.drivetrain);
degrees = _degrees;
startAngle = Robot.drivetrain.getGyroAngle();
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (degrees < 0) {
Robot.drivetrain.tankDrive(-0.5, 0.5);
} else if (degrees > 0) {
Robot.drivetrain.tankDrive(0.5, -0.5);
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return Math.abs(startAngle - Robot.drivetrain.getGyroAngle()) >= degrees;
}
// Called once after isFinished returns true
protected void end() {
Robot.drivetrain.stop();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* Rotates the Robot without PID values
*/
public class DrivetrainRotateNoPIDCommand extends Command {
private double degrees;
private double startAngle;
public DrivetrainRotateNoPIDCommand(double _degrees) {
requires(Robot.drivetrain);
degrees = _degrees;
startAngle = Robot.drivetrain.getGyroAngle();
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.drivetrain.arcadeDrive(0, degrees , false);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return Math.abs(startAngle - Robot.drivetrain.getGyroAngle()) >= degrees;
}
// Called once after isFinished returns true
protected void end() {
Robot.drivetrain.stop();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
Add test case for `count` method
|
var assert = require('assert')
var mongo = require('../')
var db = mongo('mongodb://read:read@ds031617.mongolab.com:31617/esdiscuss')
before(function (done) {
this.timeout(10000)
db._get(done)
})
describe('read only operation', function () {
it('db.getCollectionNames', function (done) {
db.getCollectionNames()
.then(function (names) {
assert(names.indexOf('contents') != -1)
assert(names.indexOf('headers') != -1)
assert(names.indexOf('history') != -1)
assert(names.indexOf('messages') != -1)
assert(names.indexOf('topics') != -1)
})
.nodeify(done)
})
it('db.collection("name").find().limit(10)', function (done) {
db.collection('headers').find().limit(10)
.then(function (headers) {
assert(Array.isArray(headers))
assert(headers.length === 10)
})
.nodeify(done)
})
it('db.collection("name").find().count()', function (done) {
db.collection('headers').count()
.then(function (count) {
assert(typeof count === 'number');
assert(count > 0);
})
.nodeify(done)
})
})
|
var assert = require('assert')
var mongo = require('../')
var db = mongo('mongodb://read:read@ds031617.mongolab.com:31617/esdiscuss')
before(function (done) {
this.timeout(10000)
db._get(done)
})
describe('read only operation', function () {
it('db.getCollectionNames', function (done) {
db.getCollectionNames()
.then(function (names) {
assert(names.indexOf('contents') != -1)
assert(names.indexOf('headers') != -1)
assert(names.indexOf('history') != -1)
assert(names.indexOf('messages') != -1)
assert(names.indexOf('topics') != -1)
})
.nodeify(done)
})
it('db.collection("name").find().limit(10)', function (done) {
db.collection('headers').find().limit(10)
.then(function (headers) {
assert(Array.isArray(headers))
assert(headers.length === 10)
})
.nodeify(done)
})
})
|
Remove unused import in TaskDefinitionViewer
|
// This file is part of BenchExec, a framework for reliable benchmarking:
// https://github.com/sosy-lab/benchexec
//
// SPDX-FileCopyrightText: 2019-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
import React from "react";
import TaskDefinitionViewer from "../components/TaskDefinitionViewer.js";
import fs from "fs";
import renderer from "react-test-renderer";
const testDir = "src/tests/task_definition_files/";
fs.readdirSync(testDir)
.filter((file) => file.endsWith(".yml"))
.forEach((file) => {
it("Render TaskDefinitionViewer for " + file, () => {
const content = fs.readFileSync(testDir + file, { encoding: "UTF-8" });
const component = renderer.create(
<TaskDefinitionViewer
yamlText={content}
createHref={(fileUrl) => fileUrl}
/>,
);
expect(component).toMatchSnapshot();
});
});
|
// This file is part of BenchExec, a framework for reliable benchmarking:
// https://github.com/sosy-lab/benchexec
//
// SPDX-FileCopyrightText: 2019-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
import React from "react";
import TaskDefinitionViewer from "../components/TaskDefinitionViewer.js";
import fs from "fs";
import renderer from "react-test-renderer";
import path from "path";
const testDir = "src/tests/task_definition_files/";
fs.readdirSync(testDir)
.filter((file) => file.endsWith(".yml"))
.forEach((file) => {
it("Render TaskDefinitionViewer for " + file, () => {
const content = fs.readFileSync(testDir + file, { encoding: "UTF-8" });
const component = renderer.create(
<TaskDefinitionViewer
yamlText={content}
createHref={(fileUrl) => fileUrl}
/>,
);
expect(component).toMatchSnapshot();
});
});
|
Change time frequency: one virtual day per second
|
import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import eventActions from '../actions/eventActionCreators'
const TIME_INIT = moment('2190-07-02').utc()
const DELAY = 1000
class Time extends Component {
componentWillMount () {
this.setState({ time: TIME_INIT })
}
componentDidMount () {
this.timer = setInterval(this._interval.bind(this), DELAY)
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return <div>{this.state.time.format('MMM Do YYYY').valueOf()}</div>
}
_interval () {
this._advanceTime()
if (Math.random() < 0.01) this._triggerEvent()
}
_advanceTime () {
const time = this.state.time.add(1, 'days')
this.setState({ time })
}
_triggerEvent () {
const n = Math.random()
const eventCategory = (n < 0.5) ? 'easy' : (n < 0.75 ? 'medium' : 'hard')
this.props.dispatch(eventActions.triggerEvent(eventCategory))
}
}
Time.propTypes = {
dispatch: PropTypes.func.isRequired,
}
export default Time
|
import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import eventActions from '../actions/eventActionCreators'
const TIME_INIT = moment('2190-07-02').utc()
const DELAY = 250
class Time extends Component {
componentWillMount () {
this.setState({ time: TIME_INIT })
}
componentDidMount () {
this.timer = setInterval(this._interval.bind(this), DELAY)
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return <div>{this.state.time.format('MMM Do YYYY').valueOf()}</div>
}
_interval () {
this._advanceTime()
if (Math.random() < 0.01) this._triggerEvent()
}
_advanceTime () {
const time = this.state.time.add(1, 'days')
this.setState({ time })
}
_triggerEvent () {
const n = Math.random()
const eventCategory = (n < 0.5) ? 'easy' : (n < 0.75 ? 'medium' : 'hard')
this.props.dispatch(eventActions.triggerEvent(eventCategory))
}
}
Time.propTypes = {
dispatch: PropTypes.func.isRequired,
}
export default Time
|
Fix the name of the COURSE_DISCOVERY_CFG variable to match what is configured in edx/configuration
|
from os import environ
import yaml
from edx_course_discovery.settings.base import *
from edx_course_discovery.settings.utils import get_env_setting
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['*']
LOGGING = environ.get('LOGGING', LOGGING)
CONFIG_FILE = get_env_setting('COURSE_DISCOVERY_CFG')
with open(CONFIG_FILE) as f:
config_from_yaml = yaml.load(f)
vars().update(config_from_yaml)
DB_OVERRIDES = dict(
PASSWORD=environ.get('DB_MIGRATION_PASS', DATABASES['default']['PASSWORD']),
ENGINE=environ.get('DB_MIGRATION_ENGINE', DATABASES['default']['ENGINE']),
USER=environ.get('DB_MIGRATION_USER', DATABASES['default']['USER']),
NAME=environ.get('DB_MIGRATION_NAME', DATABASES['default']['NAME']),
HOST=environ.get('DB_MIGRATION_HOST', DATABASES['default']['HOST']),
PORT=environ.get('DB_MIGRATION_PORT', DATABASES['default']['PORT']),
)
for override, value in DB_OVERRIDES.iteritems():
DATABASES['default'][override] = value
|
from os import environ
import yaml
from edx_course_discovery.settings.base import *
from edx_course_discovery.settings.utils import get_env_setting
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['*']
LOGGING = environ.get('LOGGING', LOGGING)
CONFIG_FILE = get_env_setting('EDX_COURSE_DISCOVERY_CFG')
with open(CONFIG_FILE) as f:
config_from_yaml = yaml.load(f)
vars().update(config_from_yaml)
DB_OVERRIDES = dict(
PASSWORD=environ.get('DB_MIGRATION_PASS', DATABASES['default']['PASSWORD']),
ENGINE=environ.get('DB_MIGRATION_ENGINE', DATABASES['default']['ENGINE']),
USER=environ.get('DB_MIGRATION_USER', DATABASES['default']['USER']),
NAME=environ.get('DB_MIGRATION_NAME', DATABASES['default']['NAME']),
HOST=environ.get('DB_MIGRATION_HOST', DATABASES['default']['HOST']),
PORT=environ.get('DB_MIGRATION_PORT', DATABASES['default']['PORT']),
)
for override, value in DB_OVERRIDES.iteritems():
DATABASES['default'][override] = value
|
Add 'All' option to lists
|
from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['categories'].insert(0, 'Tất cả')
doc['cuisines'] = diners_collection.distinct('cuisine')
doc['cuisines'].insert(0, 'Tất cả')
doc['districts'] = diners_collection.distinct('address.district')
doc['districts'].insert(0, 'Tất cả')
doc['price_max'] = list(diners_collection.aggregate([{
"$group":
{
"_id": None,
"value": {"$max": "$price_max"}
}
}]))[0]['value']
doc['price_min'] = list(diners_collection.aggregate([{
"$group":
{
"_id": None,
"value": {"$min": "$price_min"}
}
}]))[0]['value']
diner_options_collection.insert(doc)
if __name__ == '__main__':
main()
|
from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['cuisines'] = diners_collection.distinct('cuisine')
doc['districts'] = diners_collection.distinct('address.district')
doc['price_max'] = list(diners_collection.aggregate([{
"$group":
{
"_id": None,
"value": {"$max": "$price_max"}
}
}]))[0]['value']
doc['price_min'] = list(diners_collection.aggregate([{
"$group":
{
"_id": None,
"value": {"$min": "$price_min"}
}
}]))[0]['value']
diner_options_collection.insert(doc)
if __name__ == '__main__':
main()
|
Replace @represent w/ @config throughout
New name, same functionality.
|
from tangled.web import Resource, config
from tangled.site.resources.entry import Entry
class Docs(Entry):
@config('text/html', template_name='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for prefix, dir_app in static_dirs.items():
if prefix[0] == 'docs':
links.append({
'href': '/'.join(prefix),
'text': prefix[1],
})
self.urlvars['id'] = 'docs'
data = super().GET()
data['links'] = sorted(links, key=lambda i: i['text'])
return data
|
from tangled.web import Resource, represent
from tangled.site.resources.entry import Entry
class Docs(Entry):
@represent('text/html', template_name='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for prefix, dir_app in static_dirs.items():
if prefix[0] == 'docs':
links.append({
'href': '/'.join(prefix),
'text': prefix[1],
})
self.urlvars['id'] = 'docs'
data = super().GET()
data['links'] = sorted(links, key=lambda i: i['text'])
return data
|
Set the module as auto_install
So it installs when both sale_payment_method and sale_automatic_workflow are installed.
This module acts as the glue between them
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Sale Payment Method - Automatic Reconcile',
'version': '1.0',
'author': ['Camptocamp', 'Akretion'],
'license': 'AGPL-3',
'category': 'Generic Modules/Others',
'depends': ['sale_payment_method',
'sale_automatic_workflow'],
'website': 'http://www.camptocamp.com',
'data': [],
'test': [],
'installable': True,
'auto_install': True,
}
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Sale Payment Method - Automatic Reconcile',
'version': '1.0',
'author': ['Camptocamp', 'Akretion'],
'license': 'AGPL-3',
'category': 'Generic Modules/Others',
'depends': ['sale_payment_method',
'sale_automatic_workflow'],
'website': 'http://www.camptocamp.com',
'data': [],
'test': [],
'installable': True,
'auto_install': False,
}
|
Allow NULL values in transformers.
|
<?php
namespace CatLab\Charon\Transformers;
use CatLab\Charon\Exceptions\InvalidPropertyException;
use CatLab\Charon\Interfaces\Context;
use CatLab\Charon\Interfaces\Transformer;
/**
* Class DateTransformer
* @package CatLab\Charon\Transformers
*/
class DateTransformer implements Transformer
{
protected $format = DATE_RFC822;
/**
* @param $value
* @param Context $context
* @return mixed
* @throws InvalidPropertyException
*/
public function toResourceValue($value, Context $context)
{
if ($value === null) {
return null;
}
if (!$value instanceof \DateTime) {
throw new InvalidPropertyException("Date value must implement \\DateTime");
}
return $value->format($this->format);
}
/**
* @param $value
* @param Context $context
* @return mixed
*/
public function toEntityValue($value, Context $context)
{
if ($value === null) {
return null;
}
return \DateTime::createFromFormat($this->format, $value);
}
}
|
<?php
namespace CatLab\Charon\Transformers;
use CatLab\Charon\Exceptions\InvalidPropertyException;
use CatLab\Charon\Interfaces\Context;
use CatLab\Charon\Interfaces\Transformer;
/**
* Class DateTransformer
* @package CatLab\Charon\Transformers
*/
class DateTransformer implements Transformer
{
protected $format = DATE_RFC822;
/**
* @param $value
* @param Context $context
* @return mixed
* @throws InvalidPropertyException
*/
public function toResourceValue($value, Context $context)
{
if (!$value instanceof \DateTime) {
throw new InvalidPropertyException("Date value must implement \\DateTime");
}
return $value->format($this->format);
}
/**
* @param $value
* @param Context $context
* @return mixed
*/
public function toEntityValue($value, Context $context)
{
return \DateTime::createFromFormat($this->format, $value);
}
}
|
Fix Assigning Themes To Inputs
Fix the assigning the themes to inputs because Unbound Input is the only
input that uses Higher Order Components and is the only input that has
originialClass Props inside of them for the theme to attach to.
|
import Form from "./components/form.js"
import Input from "./components/input.js"
import UnboundInput from "./components/unbound_input.js"
import Submit from "./components/submit.js"
import FormErrorList from "./components/form_error_list.js"
import Fieldset from "./components/fieldset.js"
import FieldsetText from "./components/fieldset_text.js"
import ValueLinkedSelect from "./components/value_linked_select.js"
import util from "./util.js"
import typeMapping from "./type_mapping.js"
import * as factories from "./factories.js"
const HigherOrderComponents = {
Boolean: require("./higher_order_components/boolean.js"),
Focusable: require("./higher_order_components/focusable.js"),
}
// Setter and getter for the Frig default theme
function defaultTheme(theme) {
if (theme === null) return Form.defaultProps.theme
if (typeof theme !== "object") throw "Invalid theme. Expected an object"
Form.originalClass.defaultProps.theme = theme
UnboundInput.originalClass.defaultProps.theme = theme
}
export default {
defaultTheme,
Form,
Input,
UnboundInput,
Submit,
FormErrorList,
Fieldset,
FieldsetText,
ValueLinkedSelect,
HigherOrderComponents,
util,
typeMapping,
factories,
}
|
import Form from "./components/form.js"
import Input from "./components/input.js"
import UnboundInput from "./components/unbound_input.js"
import Submit from "./components/submit.js"
import FormErrorList from "./components/form_error_list.js"
import Fieldset from "./components/fieldset.js"
import FieldsetText from "./components/fieldset_text.js"
import ValueLinkedSelect from "./components/value_linked_select.js"
import util from "./util.js"
import typeMapping from "./type_mapping.js"
import * as factories from "./factories.js"
const HigherOrderComponents = {
Boolean: require("./higher_order_components/boolean.js"),
Focusable: require("./higher_order_components/focusable.js"),
}
// Setter and getter for the Frig default theme
function defaultTheme(theme) {
if (theme === null) return Form.defaultProps.theme
if (typeof theme !== "object") throw "Invalid theme. Expected an object"
Form.originalClass.defaultProps.theme = theme
Input.originalClass.defaultProps.theme = theme
}
export default {
defaultTheme,
Form,
Input,
UnboundInput,
Submit,
FormErrorList,
Fieldset,
FieldsetText,
ValueLinkedSelect,
HigherOrderComponents,
util,
typeMapping,
factories,
}
|
Add parameter to UML constants
|
/**
* Created by Leandro Luque on 24/07/17.
*/
/* JSHint configurations */
/* jshint esversion: 6 */
/* jshint -W097 */
'use strict';
// A.
const ATTRIBUTE = "A1";
// C.
const CLASS = "C1";
// D.
const DEFAULT = "~";
// I.
const INITIAL_VALUE = "I1";
const INTERFACE = "I2";
const IS_ABSTRACT = "I3";
const IS_LEAF = "I4";
const IS_READ_ONLY = "I5";
const IS_STATIC = "I6";
// M.
const MODEL = "M1";
// O.
const OPERATION = "O1";
// P.
const PRIVATE = "-";
const PROTECTED = "#";
const PUBLIC = "+";
const PARAMETER = "P1"
// R.
const RETURN_TYPE = "R1";
// S.
const STEREOTYPE = "S1";
// T.
const TYPE = "T1";
// V.
const VISIBILITY = "V1";
|
/**
* Created by Leandro Luque on 24/07/17.
*/
/* JSHint configurations */
/* jshint esversion: 6 */
/* jshint -W097 */
'use strict';
// A.
const ATTRIBUTE = "A1";
// C.
const CLASS = "C1";
// D.
const DEFAULT = "~";
// I.
const INITIAL_VALUE = "I1";
const INTERFACE = "I2";
const IS_ABSTRACT = "I3";
const IS_LEAF = "I4";
const IS_READ_ONLY = "I5";
const IS_STATIC = "I6";
// M.
const MODEL = "M1";
// O.
const OPERATION = "O1";
// P.
const PRIVATE = "-";
const PROTECTED = "#";
const PUBLIC = "+";
// R.
const RETURN_TYPE = "R1";
// S.
const STEREOTYPE = "S1";
// T.
const TYPE = "T1";
// V.
const VISIBILITY = "V1";
|
Allow public download from S3
|
'use stirct'
var opbeat = require('opbeat').start()
var uuid = require('node-uuid')
var AWS = require('aws-sdk')
var Printer = require('ipp-printer')
var port = process.env.PORT || 3000
var s3 = new AWS.S3()
var printer = new Printer({ name: 'printbin', port: port, zeroconf: false })
printer.on('job', function (job) {
var key = uuid.v4() + '.ps'
console.log('processing job %d (key: %s)', job.id, key)
job.on('end', function () {
console.log('done reading job %d (key: %s)', job.id, key)
})
var params = {
Bucket: 'watson-printbin',
ACL: 'public-read',
ContentType: 'application/postscript',
Key: key,
Body: job
}
s3.upload(params, function (err, data) {
if (err) return opbeat.captureError(err)
console.log('done uploading job %d (key: %s)', job.id, key)
})
})
|
'use stirct'
var opbeat = require('opbeat').start()
var uuid = require('node-uuid')
var AWS = require('aws-sdk')
var Printer = require('ipp-printer')
var port = process.env.PORT || 3000
var s3 = new AWS.S3()
var printer = new Printer({ name: 'printbin', port: port, zeroconf: false })
printer.on('job', function (job) {
var key = uuid.v4() + '.ps'
console.log('processing job %d (key: %s)', job.id, key)
job.on('end', function () {
console.log('done reading job %d (key: %s)', job.id, key)
})
var params = {
Bucket: 'watson-printbin',
Key: key,
Body: job
}
s3.upload(params, function (err, data) {
if (err) return opbeat.captureError(err)
console.log('done uploading job %d (key: %s)', job.id, key)
})
})
|
Add missing words to comment
+review REVIEW-6446
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.caching.internal.tasks;
import org.gradle.api.internal.TaskOutputsInternal;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginReader;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginWriter;
import java.io.InputStream;
import java.io.OutputStream;
public interface TaskOutputPacker {
// Initial format version
// NOTE: This should be changed whenever we change the way we pack a cache entry, such as
// - changing from gzip to bzip2.
// - adding/removing properties to the origin metadata
// - using a different format for the origin metadata
// - any major changes of the layout of a cache entry
int CACHE_ENTRY_FORMAT = 1;
void pack(TaskOutputsInternal taskOutputs, OutputStream output, TaskOutputOriginWriter writeOrigin);
void unpack(TaskOutputsInternal taskOutputs, InputStream input, TaskOutputOriginReader readOrigin);
}
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.caching.internal.tasks;
import org.gradle.api.internal.TaskOutputsInternal;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginReader;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginWriter;
import java.io.InputStream;
import java.io.OutputStream;
public interface TaskOutputPacker {
// Initial format version
// NOTE: This should be changed whenever we pack a cache entry, such as
// - changing from gzip to bzip2.
// - adding/removing properties to the origin metadata
// - using a different format for the origin metadata
// - any major changes of the layout of a cache entry
int CACHE_ENTRY_FORMAT = 1;
void pack(TaskOutputsInternal taskOutputs, OutputStream output, TaskOutputOriginWriter writeOrigin);
void unpack(TaskOutputsInternal taskOutputs, InputStream input, TaskOutputOriginReader readOrigin);
}
|
Add ability to add your own data in export (exporter.getJSON)
|
export default class Exporter {
constructor(editor) {
this.editor = editor;
}
getData() {
var tweenTime = this.editor.tweenTime;
var domain = this.editor.timeline.x.domain();
var domain_start = domain[0];
var domain_end = domain[1];
return {
settings: {
time: tweenTime.timer.getCurrentTime(),
duration: tweenTime.timer.getDuration(),
domain: [domain_start.getTime(), domain_end.getTime()]
},
data: tweenTime.data
};
}
getJSON() {
var options = this.editor.options;
var json_replacer = function(key, val) {
// Disable all private properies from TweenMax/TimelineMax
if (key.indexOf('_') === 0) {
return undefined;
}
if (options.json_replacer !== undefined) {
return options.json_replacer(key, val);
}
return val;
};
var data = this.getData();
// Give the possibility to add your own data in the export.
// ex: new Editor({getJSON: function(data) {data.test = 42; return data;} })
if (typeof this.editor.options.getJSON !== 'undefined') {
data = this.editor.options.getJSON(data);
}
return JSON.stringify(data, json_replacer, 2);
}
}
|
export default class Exporter {
constructor(editor) {
this.editor = editor;
}
getData() {
var tweenTime = this.editor.tweenTime;
var domain = this.editor.timeline.x.domain();
var domain_start = domain[0];
var domain_end = domain[1];
return {
settings: {
time: tweenTime.timer.getCurrentTime(),
duration: tweenTime.timer.getDuration(),
domain: [domain_start.getTime(), domain_end.getTime()]
},
data: tweenTime.data
};
}
getJSON() {
var options = this.editor.options;
var json_replacer = function(key, val) {
// Disable all private properies from TweenMax/TimelineMax
if (key.indexOf('_') === 0) {
return undefined;
}
if (options.json_replacer !== undefined) {
return options.json_replacer(key, val);
}
return val;
};
var data = this.getData();
return JSON.stringify(data, json_replacer, 2);
}
}
|
Add status and exam in test Biopsy
|
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
notes= "nota",
footer= "legenda",
status = "status",
exam = "exame"
)
biopsy.save()
self.assertEquals("clinica",biopsy.clinical_information)
self.assertEquals("macroscopia",biopsy.macroscopic)
self.assertEquals("microscopia",biopsy.microscopic)
self.assertEquals("conclusao",biopsy.conclusion)
self.assertEquals("nota",biopsy.notes)
self.assertEquals("legenda",biopsy.footer)
self.assertEquals("status",biopsy.status)
self.assertEquals("exame",biopsy.exam)
|
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
notes= "nota",
footer= "legenda"
)
biopsy.save()
self.assertEquals("clinica",biopsy.clinical_information)
self.assertEquals("macroscopia",biopsy.macroscopic)
self.assertEquals("microscopia",biopsy.microscopic)
self.assertEquals("conclusao",biopsy.conclusion)
self.assertEquals("nota",biopsy.notes)
self.assertEquals("legenda",biopsy.footer)
|
Fix extras_require for test deps
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from os import path
import sys
install_requires = [
'itsdangerous',
'msgpack-python',
'pysha3',
'six',
]
extras_require = {
'test': [
'coverage',
'nose',
],
}
if sys.version_info < (3, 4, 0):
install_requires.append('enum34')
if sys.version_info < (3, 3, 0):
extras_require['test'].append('mock')
setup(
name='nuts',
version='1.0.0',
author='Tarjei Husøy',
author_email='pypi@thusoy.com',
url='https://github.com/thusoy/nuts-auth',
description='An authenticated datagram protocol. That might fly in space.',
install_requires=install_requires,
extras_require=extras_require,
packages=find_packages(),
zip_safe=False,
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from os import path
import sys
install_requires = [
'itsdangerous',
'msgpack-python',
'pysha3',
'six',
]
extras_require = {
'test': [
'coverage',
'nose',
],
}
if sys.version_info < (3, 4, 0):
install_requires.append('enum34')
if sys.version_info < (3, 3, 0):
extras_require['test'].append('mock')
setup(
name='nuts',
version='1.0.0',
author='Tarjei Husøy',
author_email='pypi@thusoy.com',
url='https://github.com/thusoy/nuts-auth',
description='An authenticated datagram protocol. That might fly in space.',
install_requires=install_requires,
extras_require={
},
packages=find_packages(),
zip_safe=False,
)
|
Add all of the states
|
/*global exports */
(function () {
"use strict";
var popularNamesPerState = function(req, res) {
var body = JSON.stringify([
{name: 'Smith', geo: {lat: -36.64, lon: 144.11}},
{name: 'Smith', geo: {lat: -31.0, lon: 146.4}},
{name: 'Smith', geo: {lat: -24.9, lon: 145.0}},
{name: 'Smith', geo: {lat: -14.5, lon: 131.7}},
{name: 'Smith', geo: {lat: -27.9, lon: 134.3}},
{name: 'Smith', geo: {lat: -42.39, lon: 146.73}},
{name: 'Smith', geo: {lat: -28.1, lon: 119.3}}
]);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Length', body.length);
res.end(body);
};
exports.list = function(req, res) {
popularNamesPerState(req, res);
};
})();
|
/*global exports */
(function () {
"use strict";
var popularNamesPerState = function(req, res) {
var body = JSON.stringify([
{name: 'Smith', geo: {lat: -37.716, lon: 144.891}},
{name: 'Jones', geo: {lat: -41.218, lon: 1446.188}},
{name: 'Nyuan', geo: {lat: -25.173, lon: 144.891}},
{name: 'Potter', geo: {lat: -33.390, lon: 149.547}},
{name: 'Brown', geo: {lat: -28.101, lon: 115.192}}
]);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Length', body.length);
res.end(body);
};
exports.list = function(req, res) {
popularNamesPerState(req, res);
};
})();
|
Simplify code loading MNIST dataset.
|
import os
import gzip
import pickle
import sys
# Python 2/3 compatibility.
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
'''Adapted from theano tutorial'''
def load_mnist(data_file = os.path.join(os.path.dirname(__file__), 'mnist.pkl.gz')):
if not os.path.exists(data_file):
origin = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
print('Downloading data from {}'.format(origin))
urlretrieve(origin, data_file)
print('... loading data')
with gzip.open(data_file, 'rb') as f:
if sys.version_info[0] == 3:
return pickle.load(f, encoding='latin1')
else:
return pickle.load(f)
|
import os
import gzip
import pickle
import sys
# Python 2/3 compatibility.
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
'''Adapted from theano tutorial'''
def load_mnist(data_file = os.path.join(os.path.dirname(__file__), 'mnist.pkl.gz')):
if not os.path.exists(data_file):
origin = ('http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz')
print('Downloading data from %s' % origin)
urlretrieve(origin, data_file)
print('... loading data')
f = gzip.open(data_file, 'rb')
if sys.version_info[0] == 3:
train_set, valid_set, test_set = pickle.load(f, encoding='latin1')
else:
train_set, valid_set, test_set = pickle.load(f)
f.close()
train_set_x, train_set_y = train_set
valid_set_x, valid_set_y = valid_set
test_set_x, test_set_y = test_set
return (train_set_x, train_set_y), (valid_set_x, valid_set_y), (test_set_x, test_set_y)
|
Set audit job to Tuesday.
|
export default (app) => {
app.jobs.schedule('send audit email', '0 21 * * TUE', async () => {
app.info('CRON: sending audit email - starting')
const mailerConfig = app.get('mailer')
const recipients =
mailerConfig.auditRecipients && mailerConfig.auditRecipients.split(',')
app.info(`recipients: ${JSON.stringify(recipients)}`)
if (recipients) {
await Promise.all(
recipients.map(async (recipient) => {
await app.service('admin/audit').find({
query: { email: 'true', recipient },
})
})
)
} else {
app.info('CRON: no audit recipients specified, no audit email sent')
}
app.info('CRON: sending audit email - done')
})
}
|
export default (app) => {
app.jobs.schedule('send audit email', '0 16 * * 5', async () => {
app.info('CRON: sending audit email - starting')
const mailerConfig = app.get('mailer')
const recipients =
mailerConfig.auditRecipients && mailerConfig.auditRecipients.split(',')
app.info(`recipients: ${JSON.stringify(recipients)}`)
if (recipients) {
await Promise.all(
recipients.map(async (recipient) => {
await app.service('admin/audit').find({
query: { email: 'true', recipient },
})
})
)
} else {
app.info('CRON: no audit recipients specified, no audit email sent')
}
app.info('CRON: sending audit email - done')
})
}
|
Remove wpautop for full width template
|
<?php
/**
* Template Name: Full Width
*
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site may use a
* different template.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Bemmy
*/
// Full Width template removes wpautop!
remove_filter('the_content', 'wpautop');
get_header(); ?>
<div id="primary" class="page">
<main id="main" class="page__main page__main--full-width" role="main">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
|
<?php
/**
* Template Name: Full Width
*
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site may use a
* different template.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Bemmy
*/
get_header(); ?>
<div id="primary" class="page">
<main id="main" class="page__main page__main--full-width" role="main">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
|
Fix building Mono 32-bit with Mac 10.7 SDK
|
class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10.6',
sources = [
'http://download.mono-project.com/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with-mcs-docs=no',
'--with-moonlight=no',
'--enable-quiet-build',
]
)
if Package.profile.name == 'darwin':
self.configure_flags.extend ([
# fix build on lion, it uses 64-bit host even with -m32
'--build=i386-apple-darwin11.2.0',
])
# Mono (in libgc) likes to fail to build randomly
self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done'
# def prep (self):
# Package.prep (self)
# self.sh ('patch -p1 < "%{sources[1]}"')
def install (self):
Package.install (self)
if Package.profile.name == 'darwin':
self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"')
MonoPackage ()
|
class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10.6',
sources = [
'http://download.mono-project.com/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with-mcs-docs=no',
'--with-moonlight=no',
'--enable-quiet-build'
]
)
# Mono (in libgc) likes to fail to build randomly
self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done'
# def prep (self):
# Package.prep (self)
# self.sh ('patch -p1 < "%{sources[1]}"')
def install (self):
Package.install (self)
if Package.profile.name == 'darwin':
self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"')
MonoPackage ()
|
packer/rpc: Use the proper Server for tests
|
package rpc
import (
"cgl.tideland.biz/asserts"
"net/rpc"
"testing"
)
type testUi struct {
sayCalled bool
sayFormat string
sayVars []interface{}
}
func (u *testUi) Say(format string, a ...interface{}) {
u.sayCalled = true
u.sayFormat = format
u.sayVars = a
}
func TestUiRPC(t *testing.T) {
assert := asserts.NewTestingAsserts(t, true)
// Create the UI to test
ui := new(testUi)
// Start the RPC server
server := NewServer()
server.RegisterUi(ui)
server.Start()
defer server.Stop()
// Create the client over RPC and run some methods to verify it works
client, err := rpc.Dial("tcp", server.Address())
if err != nil {
panic(err)
}
uiClient := &Ui{client}
uiClient.Say("format", "arg0", 42)
assert.Equal(ui.sayFormat, "format", "format should be correct")
}
|
package rpc
import (
"cgl.tideland.biz/asserts"
"net/rpc"
"testing"
)
type testUi struct {
sayCalled bool
sayFormat string
sayVars []interface{}
}
func (u *testUi) Say(format string, a ...interface{}) {
u.sayCalled = true
u.sayFormat = format
u.sayVars = a
}
func TestUiRPC(t *testing.T) {
assert := asserts.NewTestingAsserts(t, true)
// Create the UI to test
ui := new(testUi)
uiServer := &UiServer{ui}
// Start the RPC server
readyChan := make(chan int)
stopChan := make(chan int)
defer func() { stopChan <- 1 }()
go testRPCServer(":1234", "Ui", uiServer, readyChan, stopChan)
<-readyChan
// Create the client over RPC and run some methods to verify it works
client, err := rpc.Dial("tcp", ":1234")
if err != nil {
panic(err)
}
uiClient := &Ui{client}
uiClient.Say("format", "arg0", 42)
assert.Equal(ui.sayFormat, "format", "format should be correct")
}
|
Use _.uniqueId() instead of Math.random() for dummy badges
|
import _ from 'underscore';
import { PROJECT_BADGE } from '~/badges/constants';
import { DUMMY_IMAGE_URL, TEST_HOST } from 'spec/test_constants';
export const createDummyBadge = () => {
const id = _.uniqueId();
return {
id,
imageUrl: `${TEST_HOST}/badges/${id}/image/url`,
isDeleting: false,
linkUrl: `${TEST_HOST}/badges/${id}/link/url`,
kind: PROJECT_BADGE,
renderedImageUrl: `${DUMMY_IMAGE_URL}?id=${id}`,
renderedLinkUrl: `${TEST_HOST}/badges/${id}/rendered/link/url`,
};
};
export const createDummyBadgeResponse = () => ({
image_url: `${TEST_HOST}/badge/image/url`,
link_url: `${TEST_HOST}/badge/link/url`,
kind: PROJECT_BADGE,
rendered_image_url: DUMMY_IMAGE_URL,
rendered_link_url: `${TEST_HOST}/rendered/badge/link/url`,
});
|
import { PROJECT_BADGE } from '~/badges/constants';
import { DUMMY_IMAGE_URL, TEST_HOST } from 'spec/test_constants';
export const createDummyBadge = () => {
const id = Math.floor(1000 * Math.random());
return {
id,
imageUrl: `${TEST_HOST}/badges/${id}/image/url`,
isDeleting: false,
linkUrl: `${TEST_HOST}/badges/${id}/link/url`,
kind: PROJECT_BADGE,
renderedImageUrl: `${DUMMY_IMAGE_URL}?id=${id}`,
renderedLinkUrl: `${TEST_HOST}/badges/${id}/rendered/link/url`,
};
};
export const createDummyBadgeResponse = () => ({
image_url: `${TEST_HOST}/badge/image/url`,
link_url: `${TEST_HOST}/badge/link/url`,
kind: PROJECT_BADGE,
rendered_image_url: DUMMY_IMAGE_URL,
rendered_link_url: `${TEST_HOST}/rendered/badge/link/url`,
});
|
Change to more generic variable names in _fill_queue
|
from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
contact_keys = yield model_proxy.index_keys_page(
'user_account', user_account_key, max_results=max_results,
continuation=cursor)
except VumiRiakError:
raise CollectionUsageError(
"Riak error, possible invalid cursor: %r" % (cursor,))
cursor = contact_keys.continuation
returnValue((cursor, contact_keys))
@inlineCallbacks
def _fill_queue(q, get_page, get_dict):
keys_deferred = get_page(None)
while True:
cursor, keys = yield keys_deferred
if cursor is not None:
# Get the next page of keys while we fetch the objects
keys_deferred = get_page(cursor)
for key in keys:
obj = yield get_dict(key)
yield q.put(obj)
if cursor is None:
break
q.put(PausingQueueCloseMarker())
|
from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
contact_keys = yield model_proxy.index_keys_page(
'user_account', user_account_key, max_results=max_results,
continuation=cursor)
except VumiRiakError:
raise CollectionUsageError(
"Riak error, possible invalid cursor: %r" % (cursor,))
cursor = contact_keys.continuation
returnValue((cursor, contact_keys))
@inlineCallbacks
def _fill_queue(q, get_page, get_dict):
keys_deferred = get_page(None)
while True:
cursor, keys = yield keys_deferred
if cursor is not None:
# Get the next page of keys while we fetch the contacts
keys_deferred = get_page(cursor)
for key in keys:
contact = yield get_dict(key)
yield q.put(contact)
if cursor is None:
break
q.put(PausingQueueCloseMarker())
|
Append missing slash to fix expert request URL.
|
// @ngInject
export default function expertRequestsService(baseServiceClass, $q, $http, ENV) {
let ServiceClass = baseServiceClass.extend({
filterByCustomer: false,
init: function () {
this._super();
this.endpoint = '/expert-requests/';
},
create: function (expertRequest) {
return $http.post(`${ENV.apiEndpoint}api${this.endpoint}`, expertRequest)
.then(response => response.data);
},
cancel: function (expertRequest) {
return $http.post(`${expertRequest.url}cancel/`)
.then(response => response.data);
},
getConfiguration: function () {
return $http.get(`${ENV.apiEndpoint}api${this.endpoint}configured/`)
.then(response => response.data);
}
});
return new ServiceClass();
}
|
// @ngInject
export default function expertRequestsService(baseServiceClass, $q, $http, ENV) {
let ServiceClass = baseServiceClass.extend({
filterByCustomer: false,
init: function () {
this._super();
this.endpoint = '/expert-requests/';
},
create: function (expertRequest) {
return $http.post(`${ENV.apiEndpoint}api${this.endpoint}`, expertRequest)
.then(response => response.data);
},
cancel: function (expertRequest) {
return $http.post(`${expertRequest.url}cancel/`)
.then(response => response.data);
},
getConfiguration: function () {
return $http.get(`${ENV.apiEndpoint}api${this.endpoint}configured`)
.then(response => response.data);
}
});
return new ServiceClass();
}
|
Remove duplicate default progress condition.
|
package de.iani.cubequest.quests;
import de.iani.cubequest.Reward;
import de.iani.cubequest.conditions.ServerFlagCondition;
public abstract class EconomyInfluencingAmountQuest extends AmountQuest {
public static final String SURVIVAL_ECONOMY_TAG = "survival_economy";
public EconomyInfluencingAmountQuest(int id, String name, String displayMessage,
String giveMessage, String successMessage, Reward successReward, int amount) {
super(id, name, displayMessage, giveMessage, successMessage, successReward, amount);
init();
}
public EconomyInfluencingAmountQuest(int id, String name, String displayMessage,
String giveMessage, String successMessage, Reward successReward) {
super(id, name, displayMessage, giveMessage, successMessage, successReward, 0);
init();
}
public EconomyInfluencingAmountQuest(int id) {
super(id);
init();
}
private void init() {
addQuestProgressCondition(new ServerFlagCondition(false, SURVIVAL_ECONOMY_TAG), false);
}
}
|
package de.iani.cubequest.quests;
import de.iani.cubequest.Reward;
import de.iani.cubequest.conditions.GameModeCondition;
import de.iani.cubequest.conditions.ServerFlagCondition;
import org.bukkit.GameMode;
public abstract class EconomyInfluencingAmountQuest extends AmountQuest {
public static final String SURVIVAL_ECONOMY_TAG = "survival_economy";
public EconomyInfluencingAmountQuest(int id, String name, String displayMessage,
String giveMessage, String successMessage, Reward successReward, int amount) {
super(id, name, displayMessage, giveMessage, successMessage, successReward, amount);
init();
}
public EconomyInfluencingAmountQuest(int id, String name, String displayMessage,
String giveMessage, String successMessage, Reward successReward) {
super(id, name, displayMessage, giveMessage, successMessage, successReward, 0);
init();
}
public EconomyInfluencingAmountQuest(int id) {
super(id);
init();
}
private void init() {
addQuestProgressCondition(new ServerFlagCondition(false, SURVIVAL_ECONOMY_TAG), false);
addQuestProgressCondition(new GameModeCondition(false, GameMode.SURVIVAL), false);
}
}
|
Fix and add tests for datastore.inmemory
|
import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
class TestDataStoreNestableInMemoryAutoValue(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemoryAutoValue
|
import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
|
Fix bug: replace static::class by get_class()
|
<?php namespace ThibaudDauce\MoloquentInheritance;
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;
class MoloquentInheritanceScope implements ScopeInterface {
/**
* All of the extensions to be added to the builder.
*
* @var array
*/
protected $extensions = ['OnlyParent'];
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function apply(Builder $builder)
{
$model = $builder->getModel();
$builder->where('parent_classes', 'all', [get_class($model)]);
}
/**
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function remove(Builder $builder)
{
}
/**
* Extend the query builder with the needed functions.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function extend(Builder $builder)
{
}
/**
* Add the only-trashed extension to the builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
protected function addOnlyParent(Builder $builder)
{
}
}
|
<?php namespace ThibaudDauce\MoloquentInheritance;
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;
class MoloquentInheritanceScope implements ScopeInterface {
/**
* All of the extensions to be added to the builder.
*
* @var array
*/
protected $extensions = ['OnlyParent'];
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function apply(Builder $builder)
{
$builder->where('parent_classes', 'all', [static::class]);
}
/**
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function remove(Builder $builder)
{
}
/**
* Extend the query builder with the needed functions.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function extend(Builder $builder)
{
}
/**
* Add the only-trashed extension to the builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
protected function addOnlyParent(Builder $builder)
{
}
}
|
Implement OPTIONS verb API handler
|
/*
* Copyright 2015 - 2016 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.api;
import javax.annotation.security.PermitAll;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
public class BaseResource {
@javax.ws.rs.core.Context
private SecurityContext securityContext;
protected long getUserId() {
UserPrincipal principal = (UserPrincipal) securityContext.getUserPrincipal();
if (principal != null) {
return principal.getUserId();
}
return 0;
}
@PermitAll
@OPTIONS
public Response options() {
return Response.noContent().build();
}
}
|
/*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.api;
import javax.ws.rs.core.SecurityContext;
public class BaseResource {
@javax.ws.rs.core.Context
private SecurityContext securityContext;
protected long getUserId() {
UserPrincipal principal = (UserPrincipal) securityContext.getUserPrincipal();
if (principal != null) {
return principal.getUserId();
}
return 0;
}
}
|
Copy and paste is the devil
|
package stream.flarebot.flarebot.mod.modlog;
public enum ModAction {
BAN(true, ModlogEvent.USER_BANNED),
FORCE_BAN(true, ModlogEvent.USER_BANNED),
TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED),
UNBAN(false, ModlogEvent.USER_UNBANNED),
KICK(true, ModlogEvent.USER_KICKED),
TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED),
MUTE(true, ModlogEvent.USER_MUTED),
UNMUTE(false, ModlogEvent.USER_UNMUTED),
WARN(true, ModlogEvent.USER_WARN);
private boolean infraction;
private ModlogEvent event;
ModAction(boolean infraction, ModlogEvent modlogEvent) {
this.infraction = infraction;
this.event = modlogEvent;
}
public boolean isInfraction() {
return infraction;
}
@Override
public String toString() {
return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " ");
}
public String getLowercaseName() {
return toString().toLowerCase();
}
public ModlogEvent getEvent() {
return event;
}
}
|
package stream.flarebot.flarebot.mod.modlog;
public enum ModAction {
BAN(true, ModlogEvent.USER_BANNED),
FORCE_BAN(true, ModlogEvent.USER_BANNED),
TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED),
UNBAN(false, ModlogEvent.USER_UNBANNED),
KICK(true, ModlogEvent.USER_KICKED),
TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED),
MUTE(true, ModlogEvent.USER_TEMP_MUTED),
UNMUTE(false, ModlogEvent.USER_TEMP_MUTED),
WARN(true, ModlogEvent.USER_TEMP_MUTED);
private boolean infraction;
private ModlogEvent event;
ModAction(boolean infraction, ModlogEvent modlogEvent) {
this.infraction = infraction;
this.event = modlogEvent;
}
public boolean isInfraction() {
return infraction;
}
@Override
public String toString() {
return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " ");
}
public String getLowercaseName() {
return toString().toLowerCase();
}
public ModlogEvent getEvent() {
return event;
}
}
|
Add 'comment_id' parameter in 'delete_comment' url
|
# Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/(?P<comment_id>\d+)/delete/$', views.delete_comment, name='delete_comment'),
]
|
# Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
|
Enable '-h' help option from the pdtools root level.
|
"""
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
CONTEXT_SETTINGS = dict(
# Options can be parsed from PDTOOLS_* environment variables.
auto_envvar_prefix = 'PDTOOLS',
# Respond to both -h and --help for all commands.
help_option_names = ['-h', '--help'],
obj = {
'pdserver_url': PDSERVER_URL
}
)
@click.group(context_settings=CONTEXT_SETTINGS)
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
pass
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
|
"""
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
@click.group()
@click.pass_context
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
# Options can be parsed from PDTOOLS_* environment variables.
ctx.auto_envvar_prefix = 'PDTOOLS'
# Respond to both -h and --help for all commands.
ctx.help_option_names = ['-h', '--help']
ctx.obj = {
'pdserver_url': PDSERVER_URL
}
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
|
Use isinstance to check type
This should also allow to use subtypes like a SortedDict
to pass in headers.
|
from __future__ import absolute_import
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None):
self.queryset = queryset
if headers is None:
fields = queryset.model._meta.fields
self.header_list = [field.name for field in fields]
self.attr_list = self.header_list
elif isinstance(headers, dict):
self.header_dict = headers
self.header_list = self.header_dict.keys()
self.attr_list = self.header_dict.values()
elif isinstance(headers, list):
self.header_list = headers
self.attr_list = headers
super(SimpleDataset, self).__init__()
|
from __future__ import absolute_import
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None):
self.queryset = queryset
if headers is None:
fields = queryset.model._meta.fields
self.header_list = [field.name for field in fields]
self.attr_list = self.header_list
elif type(headers) is dict:
self.header_dict = headers
self.header_list = self.header_dict.keys()
self.attr_list = self.header_dict.values()
elif type(headers) is list:
self.header_list = headers
self.attr_list = headers
super(SimpleDataset, self).__init__()
|
Fix Google Translator request & processing
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import requests
import json
def save_google_translation(queue, source_text, translate_from='et', translate_to='en'):
translation = ''
try:
begin = time.time()
translation = google_translation(source_text,
translate_from=translate_from,
translate_to=translate_to)
end = time.time()
print("Google", end - begin)
except Exception as e:
print("Google failed!", e)
queue.put({'translation_google': translation})
return None
def google_translation(text, translate_from='et', translate_to='en'):
response = requests.get(url)
json_response = json.loads(response.text)
translation = json_response['data']['translations'][0]['translatedText']
return translation
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import requests
def save_google_translation(queue, source_text, client_id, client_secret, translate_from='et', translate_to='en'):
translation = ''
try:
begin = time.time()
translation = google_translation(source_text,
translate_from=translate_from,
translate_to=translate_to)
end = time.time()
print("Google", end - begin)
except Exception as e:
print("Google failed!", e)
queue.put({'translation_google': translation})
return None
def google_translation(text, translate_from='et', translate_to='en'):
response = requests.get(url)
translation = response['data']['translations'][0]['translatedText']
print("Test", translation)
return translation
|
Prepare for adding to pypi
|
from setuptools import setup, find_packages
version = '0.2'
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = "Whitespace interpreter written in Python 3"
setup(
name='whitepy',
version=version,
author='Yasser Nabi',
author_email='yassersaleemi@gmail.com',
packages=['whitepy'],
scripts=['whitepycli'],
package_data={'README.md': ['README.md']},
url='https://github.com/yasn77/whitepy',
download_url='https://github.com/yasn77/whitepy/archive/{}.tar.gz'.format(version),
license='LICENSE.txt',
description='Whitespace interpreter written in Python 3',
long_description=long_description,
install_requires=[
"click == 6.7",
"readchar == 0.7",
],
)
|
from setuptools import setup, find_packages
try:
import pypandoc
long_description=pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = "Whitespace interpreter written in Python 3"
setup(
name='whitepy',
version='0.0.1',
author='Yasser Nabi',
author_email='yassersaleemi@gmail.com',
packages=['whitepy'],
scripts=['whitepycli'],
package_data={'README.md': ['README.md']},
url='http://pypi.python.org/pypi/whitepy/',
license='LICENSE.txt',
description='Whitespace interpreter written in Python 3',
long_description=long_description,
install_requires=[
"click == 6.7",
"readchar == 0.7",
],
)
|
Set default user name on persistent URLs
|
/*
* Copyright (C) 2015 SUSE Linux
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE.txt file for details.
*/
(function () {
'use strict';
angular.module('janusHangouts')
.service('StatesService', StatesService);
StatesService.$inject = ['$q', '$stateParams', 'RoomService', 'UserService'];
function StatesService($q, $stateParams, RoomService, UserService) {
/**
* Sets the current user and room according to params and/or cookies.
*/
this.setRoomAndUser = function() {
var deferred = $q.defer();
// Set user
var userName = $stateParams.user || UserService.getSetting("lastUsername");
if (userName !== undefined) {
UserService.signin(userName);
}
// Set room
var roomId = parseInt($stateParams.room);
if (Number.isNaN(roomId)) {
RoomService.setRoom(null);
deferred.resolve();
} else {
RoomService.getRooms().then(function(rooms) {
var result = _.find(rooms, function(room) { return room.id === roomId; });
RoomService.setRoom(result || null);
deferred.resolve();
});
}
return deferred.promise;
};
}
})();
|
/*
* Copyright (C) 2015 SUSE Linux
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE.txt file for details.
*/
(function () {
'use strict';
angular.module('janusHangouts')
.service('StatesService', StatesService);
StatesService.$inject = ['$q', '$stateParams', 'RoomService', 'UserService'];
function StatesService($q, $stateParams, RoomService, UserService) {
/**
* Sets the current user and room according to params and/or cookies.
*/
this.setRoomAndUser = function() {
var deferred = $q.defer();
// Set user
// TODO: Read userName from a cookie if not received as param
var userName = $stateParams.user;
if (userName !== undefined) {
UserService.signin(userName);
}
// Set room
var roomId = parseInt($stateParams.room);
if (Number.isNaN(roomId)) {
RoomService.setRoom(null);
deferred.resolve();
} else {
RoomService.getRooms().then(function(rooms) {
var result = _.find(rooms, function(room) { return room.id === roomId; });
RoomService.setRoom(result || null);
deferred.resolve();
});
}
return deferred.promise;
};
}
})();
|
Update version number to 0.1.2
|
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='llvmcpy',
version='0.1.2',
description='Python bindings for LLVM auto-generated from the LLVM-C API',
long_description=long_description,
url='https://rev.ng/llvmcpy',
author='Alessandro Di Federico',
author_email='ale+llvmcpy@clearmind.me',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
keywords='llvm',
packages=['llvmcpy'],
install_requires=[
'cffi>=1.0.0',
'pycparser',
'appdirs',
'shutilwhich'
],
test_suite="llvmcpy.test.TestSuite",
)
|
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='llvmcpy',
version='0.1.1',
description='Python bindings for LLVM auto-generated from the LLVM-C API',
long_description=long_description,
url='https://rev.ng/llvmcpy',
author='Alessandro Di Federico',
author_email='ale+llvmcpy@clearmind.me',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
keywords='llvm',
packages=['llvmcpy'],
install_requires=[
'cffi>=1.0.0',
'pycparser',
'appdirs',
'shutilwhich'
],
test_suite="llvmcpy.test.TestSuite",
)
|
Modify export of FileIcons singleton
|
'use babel';
import fs from 'fs-plus';
import path from 'path';
class FileIcons {
constructor() {
this.service = null;
}
setService(service) {
this.service = service;
}
resetService() {
this.service = null;
}
getIconClassForPath(filePath) {
return this.service
? this.service.iconClassForPath(filePath)
: defaultIconClassForPath(filePath);
}
}
// ref: atom/tree-view/blob/master/lib/default-file-icons.coffee
function defaultIconClassForPath(filePath) {
if (fs.isSymbolicLinkSync(filePath)) {
return 'icon-file-symlink-file';
}
if (fs.isReadmePath(filePath)) {
return 'icon-book';
}
const extension = path.extname(filePath);
if (fs.isCompressedExtension(extension)) {
return 'icon-file-zip';
}
if (fs.isImageExtension(extension)) {
return 'icon-file-media';
}
if (fs.isPdfExtension(extension)) {
return 'icon-file-pdf';
}
if (fs.isBinaryExtension(extension)) {
return 'icon-file-binary';
}
return 'icon-file';
}
export default new FileIcons();
|
'use babel';
import fs from 'fs-plus';
import path from 'path';
class FileIcons {
constructor() {
this.service = null;
}
setService(service) {
this.service = service;
}
resetService() {
this.service = null;
}
getIconClassForPath(filePath) {
return this.service
? this.service.iconClassForPath(filePath)
: defaultIconClassForPath(filePath);
}
}
// ref: atom/tree-view/blob/master/lib/default-file-icons.coffee
function defaultIconClassForPath(filePath) {
if (fs.isSymbolicLinkSync(filePath)) {
return 'icon-file-symlink-file';
}
if (fs.isReadmePath(filePath)) {
return 'icon-book';
}
const extension = path.extname(filePath);
if (fs.isCompressedExtension(extension)) {
return 'icon-file-zip';
}
if (fs.isImageExtension(extension)) {
return 'icon-file-media';
}
if (fs.isPdfExtension(extension)) {
return 'icon-file-pdf';
}
if (fs.isBinaryExtension(extension)) {
return 'icon-file-binary';
}
return 'icon-file';
}
const singleton = new FileIcons();
export default singleton;
|
Update javascript to use native API
|
function do_command(item, command, val) {
var data = {};
if (val != undefined) {
data["val"] = val;
}
$.get("/api/item/" + item + "/command/" + command, data);
}
function do_scene(scene, action) {
$.get("/api/scene/" + scene + "/command/" + (action?action:""));
}
$(function() {
$(".command").each(function() {
var elm = $(this);
elm.on(elm.data("event"), function() {
if (elm.data("use-val")) {
do_command(elm.data("item"), elm.data("command"), elm.val());
} else {
do_command(elm.data("item"), elm.data("command"));
}
});
});
$(".scene-control").each(function() {
var elm = $(this);
elm.click(function(evt) {
do_scene(elm.data("scene"), elm.data("action"));
});
});
});
|
function do_command(item, command, val) {
var data = {};
data[item] = command;
if (val != undefined) {
data["value"] = val;
}
$.get("/CMD", data);
}
function do_scene(scene, action) {
$.get("/api/scene/" + scene + "/command/" + (action?action:""));
}
$(function() {
$(".command").each(function() {
var elm = $(this);
elm.on(elm.data("event"), function() {
if (elm.data("use-val") == "true") {
do_command(elm.data("item"), elm.data("command"), elm.val());
} else {
do_command(elm.data("item"), elm.data("command"));
}
});
});
$(".scene-control").each(function() {
var elm = $(this);
elm.click(function(evt) {
do_scene(elm.data("scene"), elm.data("action"));
});
});
});
|
Rename url -> expected_url; Add URLsMixin
|
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLsMixin(object):
"""A TestCase Mixin with a check_url helper method for testing urls"""
def check_url(self, view_class, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the correct view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
resolved_view_class = resolve(expected_url).func.cls
self.assertEqual(resolved_view_class, view_class)
class URLsTestCase(URLsMixin, TestCase):
pass
|
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLsTestCase(TestCase):
"""A TestCase with a check_url helper method for testing urls"""
def check_url(self, view_class, url, url_name, url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated url.
Check the url resolves to the correct view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, url)
resolved_view_class = resolve(url).func.cls
self.assertEqual(resolved_view_class, view_class)
|
[REMOVE] Remove unused FormLogin in admin app
|
from django.contrib.auth.models import User
from django import forms
from apps.categories.models import *
from apps.books.models import *
class CategoryForm(forms.ModelForm):
"""docstring for CategoryForm"""
class Meta:
model = Category
fields = '__all__'
class BookForm(forms.ModelForm):
"""docstring for BookForm"""
class Meta:
model = Book
fields = ('title', 'description', 'slug', 'categories',
'pages', 'author', 'publish_date', 'cover', 'price')
widgets = {
'categories': forms.widgets.SelectMultiple(
attrs={'class': 'form-control select2',
'style': 'width: 100%;',
'multiple': "multiple"}),
}
|
from django.contrib.auth.models import User
from django import forms
from apps.categories.models import *
from apps.books.models import *
class LoginForm(forms.ModelForm):
"""docstring for LoginForm"""
class Meta:
model = User
fields = ['username', 'password']
class CategoryForm(forms.ModelForm):
"""docstring for CategoryForm"""
class Meta:
model = Category
fields = '__all__'
class BookForm(forms.ModelForm):
"""docstring for BookForm"""
class Meta:
model = Book
fields = ('title', 'description', 'slug', 'categories',
'pages', 'author', 'publish_date', 'cover', 'price')
widgets = {
'categories': forms.widgets.SelectMultiple(
attrs={'class': 'form-control select2',
'style': 'width: 100%;',
'multiple': "multiple"}),
}
|
Fix error with no space before tag
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)]
if __name__ == '__main__':
toJSONFilter(figref)
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(known_labels[kind][label])] + [Str(end)]
if __name__ == '__main__':
toJSONFilter(figref)
|
Fix python object searilization problem in yaml
|
import io
import glob
import yaml
import logging
import os
from uuid import uuid4
from jinja2 import Template
logger = logging.getLogger(__name__)
def create_dir(dir_path):
logger.debug(u'Creating directory %s', dir_path)
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
def yaml_load(file_path):
with io.open(file_path) as f:
result = yaml.load(f)
return result
def yaml_dump(yaml_data):
return yaml.safe_dump(yaml_data, default_flow_style=False)
def write_to_file(data, file_path):
with open(file_path, 'w') as f:
f.write(data)
def yaml_dump_to(data, file_path):
write_to_file(yaml_dump(data), file_path)
def find_by_mask(mask):
for file_path in glob.glob(mask):
yield os.path.abspath(file_path)
def load_by_mask(mask):
result = []
for file_path in find_by_mask(mask):
result.append(yaml_load(file_path))
return result
def generate_uuid():
return str(uuid4())
def render_template(template_path, params):
with io.open(template_path) as f:
temp = Template(f.read())
return temp.render(**params)
def read_config():
return yaml_load('/vagrant/config.yml')
|
import io
import glob
import yaml
import logging
import os
from uuid import uuid4
from jinja2 import Template
logger = logging.getLogger(__name__)
def create_dir(dir_path):
logger.debug(u'Creating directory %s', dir_path)
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
def yaml_load(file_path):
with io.open(file_path) as f:
result = yaml.load(f)
return result
def yaml_dump(yaml_data):
return yaml.dump(yaml_data, default_flow_style=False)
def write_to_file(data, file_path):
with open(file_path, 'w') as f:
f.write(data)
def yaml_dump_to(data, file_path):
write_to_file(yaml_dump(data), file_path)
def find_by_mask(mask):
for file_path in glob.glob(mask):
yield os.path.abspath(file_path)
def load_by_mask(mask):
result = []
for file_path in find_by_mask(mask):
result.append(yaml_load(file_path))
return result
def generate_uuid():
return str(uuid4())
def render_template(template_path, params):
with io.open(template_path) as f:
temp = Template(f.read())
return temp.render(**params)
def read_config():
return yaml_load('/vagrant/config.yml')
|
Support for pushing to a queue via observer.
|
var Rx = require('rx'),
_ = require('lodash');
function receiveMessage(sqs, params, callback) {
sqs.receiveMessage(params, function (err, data) {
callback(err, data);
receiveMessage(sqs, params, callback);
});
}
exports.observerFromQueue = function (sqs, params) {
return Rx.Observer.create(function (messageParams) {
sqs.sendMessage(_.defaults(messageParams, params), function (err, data) {
});
});
};
exports.observableFromQueue = function (sqs, params) {
return Rx.Observable.create(function (observer) {
receiveMessage(sqs, params, function (err, data) {
if (err) {
observer.onError(err);
} else if (data && data.Messages) {
_.forEach(data.Messages, function (message) {
observer.onNext(message);
});
}
return function () {
/* Clean up */
};
});
});
};
|
var Rx = require('rx'),
_ = require('lodash');
function readMessage(sqs, params, callback) {
sqs.receiveMessage(params, function (err, data) {
callback(err, data);
readMessage(sqs, params, callback);
});
}
exports.observableFromQueue = function (sqs, params) {
return Rx.Observable.create(function (observer) {
readMessage(sqs, params, function (err, data) {
if (err) {
observer.onError(err);
} else if (data && data.Messages) {
_.forEach(data.Messages, function (message) {
observer.onNext(message);
});
}
return function () {
/* Clean up */
};
});
});
};
|
Fix bug, use instance and not classes as storage
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import os
import angus.service
import angus.storage
PORT = os.environ.get('PORT', 9000)
LOGGER = logging.getLogger('dummy')
def compute(resource, data):
if 'echo' in data:
resource['echo'] = data['echo']
else:
resource['echo'] = "echo"
def main():
logging.basicConfig(level=logging.DEBUG)
service = angus.service.Service(
'dummy', 1,
PORT,
compute,
resource_storage=angus.storage.MemoryStorage(), threads=1
)
service.start()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import os
import angus.service
import angus.storage
PORT = os.environ.get('PORT', 9000)
LOGGER = logging.getLogger('dummy')
def compute(resource, data):
if 'echo' in data:
resource['echo'] = data['echo']
else:
resource['echo'] = "echo"
def main():
logging.basicConfig(level=logging.DEBUG)
service = angus.service.Service(
'dummy', 1,
PORT,
compute,
resource_storage=angus.storage.MemoryStorage, threads=1
)
service.start()
if __name__ == '__main__':
main()
|
Telemetry: Add name attribute to each Page in ServiceWorkerPageSet
ServiceWorkerPerfTest loads the same page three times, but these should
have different characteristics because ServiceWorker works differently.
This patch gives each page load a name so we can track them separately.
BUG=
TEST=tools/perf/run_benchmark service_worker.service_worker
Review URL: https://codereview.chromium.org/1086813003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#325802}
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page
from telemetry.page import page_set as page_set
archive_data_file_path = 'data/service_worker.json'
class ServiceWorkerPageSet(page_set.PageSet):
"""Page set of applications using ServiceWorker"""
def __init__(self):
super(ServiceWorkerPageSet, self).__init__(
archive_data_file=archive_data_file_path,
bucket=page_set.PARTNER_BUCKET)
# Why: the first application using ServiceWorker
# 1st time: registration
self.AddUserStory(page.Page(
'https://jakearchibald.github.io/trained-to-thrill/', self,
name='first_load', make_javascript_deterministic=False))
# 2st time: 1st onfetch with caching
self.AddUserStory(page.Page(
'https://jakearchibald.github.io/trained-to-thrill/', self,
name='second_load', make_javascript_deterministic=False))
# 3rd time: 2nd onfetch from cache
self.AddUserStory(page.Page(
'https://jakearchibald.github.io/trained-to-thrill/', self,
name='third_load', make_javascript_deterministic=False))
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page
from telemetry.page import page_set as page_set
archive_data_file_path = 'data/service_worker.json'
class ServiceWorkerPageSet(page_set.PageSet):
"""Page set of applications using ServiceWorker"""
def __init__(self):
super(ServiceWorkerPageSet, self).__init__(
archive_data_file=archive_data_file_path,
bucket=page_set.PARTNER_BUCKET)
# Why: the first application using ServiceWorker
# 1st time: registration
self.AddUserStory(page.Page(
'https://jakearchibald.github.io/trained-to-thrill/', self,
make_javascript_deterministic=False))
# 2st time: 1st onfetch with caching
self.AddUserStory(page.Page(
'https://jakearchibald.github.io/trained-to-thrill/', self,
make_javascript_deterministic=False))
# 3rd time: 2nd onfetch from cache
self.AddUserStory(page.Page(
'https://jakearchibald.github.io/trained-to-thrill/', self,
make_javascript_deterministic=False))
|
Load includes from within the api directory
|
<?php
/*
* Show debug code.
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
/*
* Load Composer requirements.
*/
require 'vendor/autoload.php';
/*
* Establish our routing table.
*/
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';
$router['bounce'] = 'bounce';
/*
* Identify which method is being requested, and whether any parameters are being passed to that
* method.
*/
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{
$tmp = explode('/', $method);
$method = $tmp[0];
if (!empty($tmp[1]))
{
$parameter = $tmp[1];
}
}
/*
* If our method is invalid, fail with a 404.
*/
if ( ($method === FALSE) || !isset($router[$method]) )
{
header("HTTP/1.0 404 Not Found");
echo '404 Not Found';
exit();
}
/*
* Enable cross-origin resource sharing (CORS).
*/
header("Access-Control-Allow-Origin: *");
/*
* Pass off the request to the relevant router.
*/
include 'includes/' . $router[$method] . '.inc.php';
|
<?php
/*
* Show debug code.
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
/*
* Load Composer requirements.
*/
require 'vendor/autoload.php';
/*
* Establish our routing table.
*/
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';
$router['bounce'] = 'bounce';
/*
* Identify which method is being requested, and whether any parameters are being passed to that
* method.
*/
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{
$tmp = explode('/', $method);
$method = $tmp[0];
if (!empty($tmp[1]))
{
$parameter = $tmp[1];
}
}
/*
* If our method is invalid, fail with a 404.
*/
if ( ($method === FALSE) || !isset($router[$method]) )
{
header("HTTP/1.0 404 Not Found");
echo '404 Not Found';
exit();
}
/*
* Enable cross-origin resource sharing (CORS).
*/
header("Access-Control-Allow-Origin: *");
/*
* Pass off the request to the relevant router.
*/
include '../includes/' . $router[$method] . '.inc.php';
|
Replace markdown lib in test config
|
'use strict';
module.exports = function(config) {
var files = [];
[
'jquery-1.8.2-min.js',
'angular.js',
'angular-resource.js',
'angular-mocks.js',
'angular-ui-states.js',
'lodash.js',
'markdown/marked.js'
].forEach(function(file) {
files.push('app/vendor/' + file);
});
files.push('app/scripts/*.js');
files.push('app/scripts/**/*.js');
files.push('tmp/scripts/**/*.js');
files.push('test/**/*.js');
config.set({
basePath: '',
frameworks: ['jasmine'],
files: files,
exclude: [],
port: 7070,
logLevel: config.LOG_INFO,
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS']
});
};
|
'use strict';
module.exports = function(config) {
var files = [];
[
'jquery-1.8.2-min.js',
'angular.js',
'angular-resource.js',
'angular-mocks.js',
'angular-ui-states.js',
'lodash.js'
].forEach(function(file) {
files.push('app/vendor/' + file);
});
files.push('app/scripts/*.js');
files.push('app/scripts/**/*.js');
files.push('tmp/scripts/**/*.js');
files.push('test/**/*.js');
config.set({
basePath: '',
frameworks: ['jasmine'],
files: files,
exclude: [],
port: 7070,
logLevel: config.LOG_INFO,
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS']
});
};
|
Add a fix so users can touch the text in the boxes with out me getting
in the way.
|
// ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">This is a test wow. such test</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
$('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes();
|
// ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">This is a test wow. such test</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
$('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes();
|
Allow for the failure of getServiceInfo(). Not sure why it's happening,
though.
|
from Zeroconf import *
import socket
class MyListener(object):
def __init__(self):
self.r = Zeroconf()
pass
def removeService(self, zeroconf, type, name):
print "Service", name, "removed"
def addService(self, zeroconf, type, name):
print "Service", name, "added"
print "Type is", type
info = self.r.getServiceInfo(type, name)
if info:
print "Address is", str(socket.inet_ntoa(info.getAddress()))
print "Port is", info.getPort()
print "Weight is", info.getWeight()
print "Priority is", info.getPriority()
print "Server is", info.getServer()
print "Text is", info.getText()
print "Properties are", info.getProperties()
if __name__ == '__main__':
print "Multicast DNS Service Discovery for Python Browser test"
r = Zeroconf()
print "1. Testing browsing for a service..."
type = "_http._tcp.local."
listener = MyListener()
browser = ServiceBrowser(r, type, listener)
|
from Zeroconf import *
import socket
class MyListener(object):
def __init__(self):
self.r = Zeroconf()
pass
def removeService(self, zeroconf, type, name):
print "Service", name, "removed"
def addService(self, zeroconf, type, name):
print "Service", name, "added"
print "Type is", type
info = self.r.getServiceInfo(type, name)
print "Address is", str(socket.inet_ntoa(info.getAddress()))
print "Port is", info.getPort()
print "Weight is", info.getWeight()
print "Priority is", info.getPriority()
print "Server is", info.getServer()
print "Text is", info.getText()
print "Properties are", info.getProperties()
if __name__ == '__main__':
print "Multicast DNS Service Discovery for Python Browser test"
r = Zeroconf()
print "1. Testing browsing for a service..."
type = "_http._tcp.local."
listener = MyListener()
browser = ServiceBrowser(r, type, listener)
|
Fix node to set sentAuth whenever the object was generated
|
package network.thunder.core.communication;
import network.thunder.core.communication.objects.subobjects.AuthenticationObject;
public class Node {
private byte[] pubkey;
private boolean isAuth;
private boolean sentAuth;
private boolean authFinished;
private boolean isReady;
private boolean hasOpenChannel;
public boolean processAuthentication (AuthenticationObject authentication) {
//TODO: Check authentication based on the supplied pubkey
isAuth = true;
if (sentAuth) {
authFinished = true;
}
return true;
}
public AuthenticationObject getAuthenticationObject () {
//TODO: Produce a proper authentication object..
sentAuth = true;
return new AuthenticationObject();
}
public boolean hasSentAuth () {
return sentAuth;
}
public boolean isAuth () {
return isAuth;
}
public boolean allowsAuth () {
return !isAuth;
}
public void finishAuth () {
authFinished = true;
}
public boolean isAuthFinished () {
return authFinished;
}
}
|
package network.thunder.core.communication;
import network.thunder.core.communication.objects.subobjects.AuthenticationObject;
public class Node {
private byte[] pubkey;
private boolean isAuth;
private boolean sentAuth;
private boolean authFinished;
private boolean isReady;
private boolean hasOpenChannel;
public boolean processAuthentication (AuthenticationObject authentication) {
//TODO: Check authentication based on the supplied pubkey
return true;
}
public AuthenticationObject getAuthenticationObject () {
//TODO: Produce a proper authentication object..
return new AuthenticationObject();
}
public boolean hasSentAuth () {
return sentAuth;
}
public boolean isAuth () {
return isAuth;
}
public boolean allowsAuth () {
return !isAuth;
}
public void finishAuth () {
authFinished = true;
}
public boolean isAuthFinished () {
return authFinished;
}
}
|
Fix dispatcher stopping bug when using <Listener> component
|
const React = require("react")
const {merge} = require("./util")
export class Listener extends React.Component {
constructor(props) {
super(props)
const {dispatcher, initialState} = this.props
const ffux = dispatcher(initialState)
this.state = {
ffux,
model: {
state: ffux.getInitialState(),
actions: ffux.getActions()
}
}
}
componentWillMount() {
this.setState(merge(this.state, {
stop: this.state.ffux.listen(model => this.setState(merge(this.state, {model})))
}))
}
componentWillReceiveProps(nextProps) {
const {dispatcher} = nextProps
const prevDispatcher = this.state.dispatcher
if (dispatcher !== prevDispatcher) {
if (this.state.stop) {
this.state.stop()
}
const ffux = dispatcher(this.state.model.state)
this.setState(merge(this.state, {
ffux,
dispatcher,
stop: ffux.listen(model => this.setState(merge(this.state, {model})))
}))
}
}
render() {
return React.cloneElement(this.props.children, this.state.model)
}
}
|
const React = require("react")
const {merge} = require("./util")
export class Listener extends React.Component {
constructor(props) {
super(props)
const {dispatcher, initialState} = this.props
const ffux = dispatcher(initialState)
this.state = {
ffux,
model: {
state: ffux.getInitialState(),
actions: ffux.getActions()
}
}
}
componentWillMount() {
this.state.stop = this.state.ffux.listen(model => this.setState(merge(this.state, {model})))
}
componentWillReceiveProps(nextProps) {
const {dispatcher} = nextProps
if (this.state.stop) {
this.state.stop()
}
const ffux = dispatcher(this.state.model.state)
this.state.stop = ffux.listen(model => this.setState(merge(this.state, {model})))
}
render() {
return React.cloneElement(this.props.children, this.state.model)
}
}
|
Make the item creation operation its own method. It was getting a bit convoluted as an inline callback
|
jsio('from common.javascript import Class')
jsio('import tasks.panels.Panel')
jsio('import ui.Button')
exports = Class(tasks.panels.Panel, function(supr) {
this._className += ' ListPanel'
this._width = 260
this._left = 150
this._createContent = function() {
supr(this, '_createContent')
var taskButton = new ui.Button('Create new task')
taskButton.subscribe('Click', bind(this, '_createItem'))
taskButton.appendTo(this._element)
this.hide()
}
this._createItem = function() {
fin.createItem({ type: 'task', user: gUser.getId() }, function(item) {
gItemPanel.setItem(item)
})
}
this.loadList = function(listView) {
if (this._listView) { logger.warn("TODO: release current list view")}
this._content.innerHTML = ''
this._listView = listView
this._listView.appendTo(this._content)
this._listView.subscribe('Click', bind(this, '_onCellClick'))
this.show()
}
this._onCellClick = function(itemCell) {
var item = fin.getItem(itemCell.getId())
gItemPanel.setItem(item)
}
})
|
jsio('from common.javascript import Class')
jsio('import tasks.panels.Panel')
jsio('import ui.Button')
exports = Class(tasks.panels.Panel, function(supr) {
this._className += ' ListPanel'
this._width = 260
this._left = 150
this._createContent = function() {
supr(this, '_createContent')
var taskButton = new ui.Button('Create new task')
taskButton.subscribe('Click', bind(fin, 'createItem', { type: 'task' }, function(item) {
gItemPanel.setItem(item)
}))
taskButton.appendTo(this._element)
this.hide()
}
this.loadList = function(listView) {
if (this._listView) { logger.warn("TODO: release current list view")}
this._content.innerHTML = ''
this._listView = listView
this._listView.appendTo(this._content)
this._listView.subscribe('Click', bind(this, '_onCellClick'))
this.show()
}
this._onCellClick = function(itemCell) {
var item = fin.getItem(itemCell.getId())
gItemPanel.setItem(item)
}
})
|
Fix alembic revision after merge master
|
"""text to JSON
Revision ID: 151b2f642877
Revises: ac115763654
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'ac115763654'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
def downgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
|
"""text to JSON
Revision ID: 151b2f642877
Revises: aee7291c81
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'aee7291c81'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
def downgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
|
Add a space between end of text output
|
<?php
namespace exussum12\CoverageChecker\Outputs;
use exussum12\CoverageChecker\Output;
class Text implements Output
{
public function output($coverage, $percent, $minimumPercent)
{
printf("%.2f%% Covered\n", $percent);
$output = '';
foreach ($coverage as $filename => $lines) {
$output .= "\n\n'$filename' has no coverage for the following lines:\n";
foreach ($lines as $line => $message) {
$output .= $this->generateOutputLine($line, $message);
}
}
echo trim($output) . "\n";
}
private function generateOutputLine($line, $message)
{
$output = "Line $line:\n";
if (!empty($message)) {
foreach ($message as $part) {
$output .= "\t$part\n";
}
}
return $output . "\n";
}
}
|
<?php
namespace exussum12\CoverageChecker\Outputs;
use exussum12\CoverageChecker\Output;
class Text implements Output
{
public function output($coverage, $percent, $minimumPercent)
{
printf("%.2f%% Covered\n", $percent);
$output = '';
foreach ($coverage as $filename => $lines) {
$output .= "\n\n'$filename' has no coverage for the following lines:\n";
foreach ($lines as $line => $message) {
$output .= $this->generateOutputLine($line, $message);
}
}
echo trim($output);
}
private function generateOutputLine($line, $message)
{
$output = "Line $line:\n";
if (!empty($message)) {
foreach ($message as $part) {
$output .= "\t$part\n";
}
}
return $output . "\n";
}
}
|
Use the environment secret key instead of default one
|
<?php
$config = array();
// Generals
$config['db_dsnw'] = 'sqlite:////data/roundcube.db';
$config['des_key'] = getenv('SECRET_KEY');
$config['identities_level'] = 3;
$config['reply_all_mode'] = 1;
// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
'archive',
'zipdownload',
'markasjunk'
);
// Mail servers
$config['default_host'] = 'tls://imap';
$config['default_port'] = 143;
$config['smtp_server'] = 'tls://smtp';
$config['smtp_port'] = 587;
$config['smtp_user'] = '%u';
$config['smtp_pass'] = '%p';
// We access the IMAP and SMTP servers locally with internal names, SSL
// will obviously fail but this sounds better than allowing insecure login
// from the outter world
$ssl_no_check = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
);
$config['imap_conn_options'] = $ssl_no_check;
$config['smtp_conn_options'] = $ssl_no_check;
// skin name: folder from skins/
$config['skin'] = 'larry';
|
<?php
$config = array();
// Generals
$config['db_dsnw'] = 'sqlite:////data/roundcube.db';
$config['des_key'] = 'rcmail-!24ByteDESkey*Str';
$config['identities_level'] = 3;
$config['reply_all_mode'] = 1;
// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
'archive',
'zipdownload',
'markasjunk'
);
// Mail servers
$config['default_host'] = 'tls://imap';
$config['default_port'] = 143;
$config['smtp_server'] = 'tls://smtp';
$config['smtp_port'] = 587;
$config['smtp_user'] = '%u';
$config['smtp_pass'] = '%p';
// We access the IMAP and SMTP servers locally with internal names, SSL
// will obviously fail but this sounds better than allowing insecure login
// from the outter world
$ssl_no_check = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
);
$config['imap_conn_options'] = $ssl_no_check;
$config['smtp_conn_options'] = $ssl_no_check;
// skin name: folder from skins/
$config['skin'] = 'larry';
|
Fix missing parameter to pass tests
|
const express = require('express')
const ERRORS = require('../../errors')
const User = require('../../models/User')
const utils = require('../../utils')
const router = express.Router()
router.post('/', register)
function register(req, res, next) {
const { body: { username, password } } = req
if (!username || !password) {
next(ERRORS.MISSING_PARAMETERS(['username', 'password']))
} else {
User.register(username, password)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user.id),
createdAt: user.createdAt
}))
.then(data => {
res.status(201)
res.json(data)
})
.catch(err => next(ERRORS.REGISTRATION_FAILED(err)))
}
}
module.exports = router
|
const express = require('express')
const ERRORS = require('../../errors')
const User = require('../../models/User')
const utils = require('../../utils')
const router = express.Router()
router.post('/', register)
function register(req, res, next) {
const { body: { username, password } } = req
if (!username || !password) {
next(ERRORS.MISSING_PARAMETERS(['username', 'password']))
} else {
User.register(username, password)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user.id)
}))
.then(data => {
res.status(201)
res.json(data)
})
.catch(err => next(ERRORS.REGISTRATION_FAILED(err)))
}
}
module.exports = router
|
Update bower @ Uninstall angular-material-data-table
|
/**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})();
|
/**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
'md.data.table',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})();
|
Fix test on Django 1.9
|
from django import template
from django.utils.safestring import mark_safe
from lazy_tags.decorators import lazy_tag
register = template.Library()
@register.simple_tag
def test():
return mark_safe('<p>hello world</p>')
@register.simple_tag
@lazy_tag
def test_decorator():
return 'Success!'
@register.simple_tag
@lazy_tag
def test_simple_dec_args(arg, kwarg=None):
return '{0} {1}'.format(arg, kwarg)
@register.inclusion_tag('tests/decorator_tag_with_args.html')
@lazy_tag
def test_decorator_with_args(arg, kwarg=None):
return {
'arg': arg,
'kwarg': kwarg
}
@register.simple_tag
def test_with_sleep():
import time
time.sleep(2)
return '<ul style="text-align: left;"><li>Steve Jobs</li><li>Bill Gates</li><li>Elon Musk</li></ul>'
@register.inclusion_tag('tests/inclusion_tag_with_args.html')
def test_with_args(arg, kwarg=None):
return {
'arg': arg,
'kwarg': kwarg
}
@register.simple_tag
def test_orm(user):
return '<p>{} | {}</p>'.format(user.username, user.email)
@register.inclusion_tag('tests/inclusion_tag.html')
def inclusion():
return {'test': 'hello world'}
|
from django import template
from lazy_tags.decorators import lazy_tag
register = template.Library()
@register.simple_tag
def test():
return '<p>hello world</p>'
@register.simple_tag
@lazy_tag
def test_decorator():
return 'Success!'
@register.simple_tag
@lazy_tag
def test_simple_dec_args(arg, kwarg=None):
return '{0} {1}'.format(arg, kwarg)
@register.inclusion_tag('tests/decorator_tag_with_args.html')
@lazy_tag
def test_decorator_with_args(arg, kwarg=None):
return {
'arg': arg,
'kwarg': kwarg
}
@register.simple_tag
def test_with_sleep():
import time
time.sleep(2)
return '<ul style="text-align: left;"><li>Steve Jobs</li><li>Bill Gates</li><li>Elon Musk</li></ul>'
@register.inclusion_tag('tests/inclusion_tag_with_args.html')
def test_with_args(arg, kwarg=None):
return {
'arg': arg,
'kwarg': kwarg
}
@register.simple_tag
def test_orm(user):
return '<p>{} | {}</p>'.format(user.username, user.email)
@register.inclusion_tag('tests/inclusion_tag.html')
def inclusion():
return {'test': 'hello world'}
|
Change worker stats api url
|
import Promise from 'bluebird';
import request from 'superagent';
import camelcase from 'camelcase';
import snakecase from 'snake-case';
import _ from 'lodash';
Promise.promisifyAll(request);
export function transformForFrontend(payload) {
_.forOwn(payload, (value, key) => {
if (camelcase(key) !== key) {
delete payload[key];
payload[camelcase(key)] = value;
}
});
return payload;
}
export function transformForBackend(payload) {
_.forOwn(payload, (value, key) => {
if (snakecase(key) !== key) {
delete payload[key];
payload[snakecase(key)] = value;
}
});
return payload;
}
const http = {
get: url => {
if (!/\/$/.test(url)) {
url += '/';
}
return request
.get(url)
.endAsync()
.then(transformForFrontend);
},
};
export default http;
export function getUser() {
return http.get('/api/users/me');
}
export function getBuilds(slug) {
const url = '/api/builds/';
return http.get(slug ? url + slug : url);
}
export function getBuild(slug) {
return http.get('/api/builds/' + slug);
}
export function getWorkerStats() {
return http.get('/api/stats');
}
|
import Promise from 'bluebird';
import request from 'superagent';
import camelcase from 'camelcase';
import snakecase from 'snake-case';
import _ from 'lodash';
Promise.promisifyAll(request);
export function transformForFrontend(payload) {
_.forOwn(payload, (value, key) => {
if (camelcase(key) !== key) {
delete payload[key];
payload[camelcase(key)] = value;
}
});
return payload;
}
export function transformForBackend(payload) {
_.forOwn(payload, (value, key) => {
if (snakecase(key) !== key) {
delete payload[key];
payload[snakecase(key)] = value;
}
});
return payload;
}
const http = {
get: url => {
if (!/\/$/.test(url)) {
url += '/';
}
return request
.get(url)
.endAsync()
.then(transformForFrontend);
},
};
export default http;
export function getUser() {
return http.get('/api/users/me');
}
export function getBuilds(slug) {
const url = '/api/builds/';
return http.get(slug ? url + slug : url);
}
export function getBuild(slug) {
return http.get('/api/builds/' + slug);
}
export function getWorkerStats() {
return http.get('https://jobs.frigg.io/stats');
}
|
Enable disk and memory caching
|
package de.eightbitboy.hijacr;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import io.fabric.sdk.android.Fabric;
public class HijacrApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
//TODO experiment with bitmap config
//.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.memoryCacheExtraOptions(2048, 2048)
//TODO use getFilesDir?
.diskCache(new UnlimitedDiskCache(getCacheDir()))
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
.defaultDisplayImageOptions(options)
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
}
}
|
package de.eightbitboy.hijacr;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import io.fabric.sdk.android.Fabric;
public class HijacrApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.memoryCacheExtraOptions(2048, 2048)
//TODO use getFilesDir?
.diskCache(new UnlimitedDiskCache(getCacheDir()))
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
//.defaultDisplayImageOptions()
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
}
}
|
Allow for specifying a subclass of GeocodedLocation
|
/*
*
* * Licensed to the Apache Software Foundation (ASF) under one or more
* * contributor license agreements. See the NOTICE file distributed with
* * this work for additional information regarding copyright ownership.
* * The ASF licenses this file to You under the Apache License, Version 2.0
* * (the "License"); you may not use this file except in compliance with
* * the License. You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.vaadin.addons.locationtextfield;
import java.io.Serializable;
import java.util.Collection;
/**
* Inteface providing {@link GeocodedLocation}s based on an address
*/
public interface LocationProvider<T extends GeocodedLocation> extends Serializable {
Collection<T> geocode(String address) throws GeocodingException;
}
|
/*
*
* * Licensed to the Apache Software Foundation (ASF) under one or more
* * contributor license agreements. See the NOTICE file distributed with
* * this work for additional information regarding copyright ownership.
* * The ASF licenses this file to You under the Apache License, Version 2.0
* * (the "License"); you may not use this file except in compliance with
* * the License. You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.vaadin.addons.locationtextfield;
import java.io.Serializable;
import java.util.Collection;
/**
* Inteface providing {@link GeocodedLocation}s based on an address
*/
public interface LocationProvider extends Serializable {
Collection<GeocodedLocation> geocode(String address) throws GeocodingException;
}
|
Add role property to mark item.
|
import Bounds from './Bounds';
import GroupItem from './GroupItem';
export default function Scenegraph() {
this.root = createMark({
marktype: 'group',
interactive: false
});
this.root.items = [new GroupItem(this.root)];
}
var prototype = Scenegraph.prototype;
prototype.select = function(path, markdef) {
var items = this.root.items[0],
node, i, n;
for (i=0, n=path.length-1; i<n; ++i) {
items = items.items[path[i]];
if (!items) error('Invalid scenegraph path: ' + path);
}
items = items.items;
if (!(node = items[path[n]])) {
if (markdef) items[path[n]] = node = createMark(markdef);
else error('Invalid scenegraph path: ' + path);
}
return node;
};
function error(msg) {
throw Error(msg);
}
function createMark(def) {
return {
bounds: new Bounds(),
clip: !!def.clip,
interactive: def.interactive === false ? false : true,
items: [],
marktype: def.marktype,
role: def.role || null
};
}
|
import Bounds from './Bounds';
import GroupItem from './GroupItem';
export default function Scenegraph() {
this.root = createMark({
marktype: 'group',
interactive: false
});
this.root.items = [new GroupItem(this.root)];
}
var prototype = Scenegraph.prototype;
prototype.select = function(path, markdef) {
var items = this.root.items[0],
node, i, n;
for (i=0, n=path.length-1; i<n; ++i) {
items = items.items[path[i]];
if (!items) error('Invalid scenegraph path: ' + path);
}
items = items.items;
if (!(node = items[path[n]])) {
if (markdef) items[path[n]] = node = createMark(markdef);
else error('Invalid scenegraph path: ' + path);
}
return node;
};
function error(msg) {
throw Error(msg);
}
function createMark(def) {
return {
bounds: new Bounds(),
clip: !!def.clip,
interactive: def.interactive === false ? false : true,
items: [],
marktype: def.marktype
};
}
|
Fix tests so they complete without auth info.
|
var vows = require('vows');
var assert = require('assert');
var winston = require('winston');
var helpers = require('winston/test/helpers');
var SQS = require('../lib/winston-sqs').SQS;
var transport = new (SQS)({
aws_queueurl: "queueurl",
aws_accesskeyid: "publickey",
aws_secretaccesskey: "secretkey"
});
function assertSQS (transport) {
assert.instanceOf(transport, SQS);
assert.isFunction(transport.log);
}
vows.describe('winston-sqs').addBatch({
"An instance of the Amazon SQS Transport": {
"should have the proper methods defined": function () {
assertSQS(transport);
}
/* Uncomment this test when correct AWS credentials and queue URL are applied above.
,"the log() method": helpers.testNpmLevels(transport, "should log messages to Amazon SQS", function (ign, err, logged) {
assert.isTrue(!err);
assert.isTrue(logged);
})*/
}
}).export(module);
|
var vows = require('vows');
var assert = require('assert');
var winston = require('winston');
var helpers = require('winston/test/helpers');
var SQS = require('../lib/winston-sqs').SQS;
var transport = new (SQS)({
aws_queueurl: "queueurl",
aws_accesskeyid: "publickey",
aws_secretaccesskey: "secretkey"
});
function assertSQS (transport) {
assert.instanceOf(transport, SQS);
assert.isFunction(transport.log);
}
vows.describe('winston-sqs').addBatch({
"An instance of the Amazon SQS Transport": {
"should have the proper methods defined": function () {
assertSQS(transport);
},
"the log() method": helpers.testNpmLevels(transport, "should log messages to Amazon SQS", function (ign, err, logged) {
assert.isTrue(!err);
assert.isTrue(logged);
})
}
}).export(module);
|
:crescent_moon: Enable 'dark mode' by default
|
import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: true,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(true);
const [uiIsLoading, setUiIsLoading] = useState(false);
const [uiIsAnimating, setUiIsAnimating] = useState(false);
return (
<UiContext.Provider
value={{
uiDarkMode,
setUiDarkMode,
uiIsLoading,
setUiIsLoading,
uiIsAnimating,
setUiIsAnimating,
}}
>
{children}
</UiContext.Provider>
);
};
UiProvider.propTypes = {
children: PropTypes.node,
};
export { UiContext, UiProvider };
|
import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: false,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(false);
const [uiIsLoading, setUiIsLoading] = useState(false);
const [uiIsAnimating, setUiIsAnimating] = useState(false);
return (
<UiContext.Provider
value={{
uiDarkMode,
setUiDarkMode,
uiIsLoading,
setUiIsLoading,
uiIsAnimating,
setUiIsAnimating,
}}
>
{children}
</UiContext.Provider>
);
};
UiProvider.propTypes = {
children: PropTypes.node,
};
export { UiContext, UiProvider };
|
Remove course from courses list when refunded
|
import { find } from 'lodash';
import moment from 'moment';
import {
BaseModel, identifiedBy, field, identifier, belongsTo, computed, observable,
} from '../base';
import Courses from '../courses-map';
import { TimeStore } from '../../flux/time';
@identifiedBy('purchase/product')
class Product extends BaseModel {
@identifier uuid;
@field name;
@field price;
}
@identifiedBy('purchase')
export default class Purchase extends BaseModel {
static URL = observable.shallowBox('');;
@identifier identifier;
@field product_instance_uuid;
@field is_refunded;
@field sales_tax;
@field total;
@field({ type: 'date' }) updated_at;
@field({ type: 'date' }) purchased_at;
@belongsTo({ model: Product }) product;
@computed get course() {
return find(Courses.array, c =>
c.userStudentRecord && c.userStudentRecord.uuid == this.product_instance_uuid);
}
@computed get isRefundable() {
return !this.is_refunded &&
moment(this.purchased_at).add(14, 'days').isAfter(TimeStore.getNow());
}
@computed get invoiceURL() {
return Purchase.URL.get() + '/invoice/' + this.identifier;
}
refund() {
return { item_uuid: this.product_instance_uuid };
}
onRefunded() {
this.is_refunded = true;
if (this.course) {
Courses.delete(this.course.id);
}
}
}
|
import { find } from 'lodash';
import moment from 'moment';
import {
BaseModel, identifiedBy, field, identifier, belongsTo, computed, observable,
} from '../base';
import { TimeStore } from '../../flux/time';
@identifiedBy('purchase/product')
class Product extends BaseModel {
@identifier uuid;
@field name;
@field price;
}
@identifiedBy('purchase')
export default class Purchase extends BaseModel {
static URL = observable.shallowBox('');;
@identifier identifier;
@field product_instance_uuid;
@field is_refunded;
@field sales_tax;
@field total;
@field({ type: 'date' }) updated_at;
@field({ type: 'date' }) purchased_at;
@belongsTo({ model: Product }) product;
@computed get isRefundable() {
return !this.is_refunded &&
moment(this.purchased_at).add(14, 'days').isAfter(TimeStore.getNow());
}
@computed get invoiceURL() {
return Purchase.URL.get() + '/invoice/' + this.identifier;
}
refund() {
return { item_uuid: this.product_instance_uuid };
}
onRefunded() {
this.is_refunded = true;
}
}
|
Add string representation for colors
|
class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __repr__(self):
return '%s,%s,%s' % (self.r, self.g, self.b)
__unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
|
class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
|
Add organization_set field in UserF
|
from datetime import timedelta
from django.utils import timezone
from locarise_drf_oauth2_support.users.models import User
try:
import factory
class UserF(factory.DjangoModelFactory):
first_name = factory.Sequence(lambda n: "first_name%s" % n)
last_name = factory.Sequence(lambda n: "last_name%s" % n)
email = factory.Sequence(lambda n: "email%s@example.com" % n)
is_staff = False
is_active = True
is_superuser = False
last_login = timezone.now() - timedelta(days=2)
password = factory.PostGenerationMethodCall('set_password', 'pass')
organization_set = [{
"uid": "6tbgzDKyZYLCMzDarN7ga8",
"name": "Organization Demo",
"role": "organization-manager",
"is_active": True
}]
class Meta:
model = User
except ImportError: # pragma: no cover
pass
|
from datetime import timedelta
from django.utils import timezone
from locarise_drf_oauth2_support.users.models import User
try:
import factory
class UserF(factory.DjangoModelFactory):
first_name = factory.Sequence(lambda n: "first_name%s" % n)
last_name = factory.Sequence(lambda n: "last_name%s" % n)
email = factory.Sequence(lambda n: "email%s@example.com" % n)
is_staff = False
is_active = True
is_superuser = False
last_login = timezone.now() - timedelta(days=2)
password = factory.PostGenerationMethodCall('set_password', 'pass')
class Meta:
model = User
except ImportError: # pragma: no cover
pass
|
Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1.
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
Validate UK phone numbers correctly.
|
<?php namespace VotingApp\Providers;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider {
/**
* The validator instance
*
* @var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->validator = $this->app->make('validator');
$this->validator->extend('phone', function($attribute, $value, $parameters)
{
$phoneRegex = '/^(?:\+?([0-9]{1,3})([\-\s\.]{1})?)?\(?([0-9]{3})\)?(?:[\-\s\.]{1})?([0-9]{3})(?:[\-\s\.]{1})?([0-9]{4})/';
return preg_match($phoneRegex, $value);
}, 'The :attribute must be a valid phone number.');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
|
<?php namespace VotingApp\Providers;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider {
/**
* The validator instance
*
* @var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->validator = $this->app->make('validator');
$this->validator->extend('phone', function($attribute, $value, $parameters)
{
$phoneRegex = '/^((1)?([\-\s\.]{1})?)?\(?([0-9]{3})\)?(?:[\-\s\.]{1})?([0-9]{3})(?:[\-\s\.]{1})?([0-9]{4})/';
return preg_match($phoneRegex, $value);
}, 'The :attribute must be a valid phone number.');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
|
Add "box.text" back to namespaced package
|
# coding: utf-8
from __future__ import unicode_literals
from setuptools import setup, find_packages
from os.path import dirname, join
def main():
base_dir = dirname(__file__)
setup(
name='genty',
version='0.0.1',
description='Allows you to run a test with multiple data sets',
long_description=open(join(base_dir, 'README.rst')).read(),
author='Box',
author_email='oss@box.com',
url='https://github.com/box/genty',
license=open(join(base_dir, 'LICENSE')).read(),
packages=find_packages(exclude=['test']),
namespace_packages=[b'box', b'box.test'],
test_suite='test',
zip_safe=False,
)
if __name__ == '__main__':
main()
|
# coding: utf-8
from __future__ import unicode_literals
from setuptools import setup, find_packages
from os.path import dirname, join
def main():
base_dir = dirname(__file__)
setup(
name='genty',
version='0.0.1',
description='Allows you to run a test with multiple data sets',
long_description=open(join(base_dir, 'README.rst')).read(),
author='Box',
author_email='oss@box.com',
url='https://github.com/box/genty',
license=open(join(base_dir, 'LICENSE')).read(),
packages=find_packages(exclude=['test']),
namespace_packages=[b'box'], # , b'box.test'],
test_suite='test',
zip_safe=False,
)
if __name__ == '__main__':
main()
|
Fix parsing irc messages with empty list of parameters
|
from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command must be non-empty
if len(command) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
|
from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command and params must be non-empty
if len(command) == 0 or len(params) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
|
Use bootstrap input styles to shrink quantity field width
|
# -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(WishListForm, self).__init__(*args, **kwargs)
self.instance.owner = user
class Meta:
model = WishList
fields = ('name', )
class WishListLineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(WishListLineForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs['class'] = 'input-mini'
LineFormset = inlineformset_factory(
WishList, Line, fields=('quantity', ), form=WishListLineForm,
extra=0, can_delete=False)
|
# -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(WishListForm, self).__init__(*args, **kwargs)
self.instance.owner = user
class Meta:
model = WishList
fields = ('name', )
class WishListLineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(WishListLineForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs['size'] = 2
LineFormset = inlineformset_factory(
WishList, Line, fields=('quantity', ), form=WishListLineForm,
extra=0, can_delete=False)
|
Tweak comment text for clarity
|
import urllib
import urlparse
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
parameters already exist with the same name, they will be
overwritten. Return the modified URL as a string.
"""
# If any of the additional parameters have empty values,
# ignore them
params = dict([(k, v) for k, v in params.items() if v])
parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(parts[4]))
query.update(params)
parts[4] = urllib.urlencode(query)
url = urlparse.urlunparse(parts)
return url
def is_scheme_https(url):
"""
Test the scheme of the parameter URL to see if it is HTTPS. If
it is HTTPS return True, otherwise return False.
"""
return 'https' == urlparse.urlparse(url).scheme
|
import urllib
import urlparse
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
existing parameters already exist with the same name, they
will be overwritten.
Return the modified URL as a string.
"""
# If any of the additional parameters have empty values,
# ignore them
params = dict([(k, v) for k, v in params.items() if v])
parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(parts[4]))
query.update(params)
parts[4] = urllib.urlencode(query)
url = urlparse.urlunparse(parts)
return url
def is_scheme_https(url):
"""
Test the scheme of the parameter URL to see if it is HTTPS. If
it is HTTPS return True, otherwise return False.
"""
return 'https' == urlparse.urlparse(url).scheme
|
Fix teardown of resize handler in content management screen
refs #5659 ([comment](https://github.com/TryGhost/Ghost/issues/5659#issuecomment-137114898))
- cleans up resize handler on willDestroy hook of gh-content-view-container
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
_resizeListener: null,
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
this.set('previewIsHidden', !this.$('.content-preview').is(':visible'));
}
},
didInsertElement: function () {
this._super(...arguments);
this._resizeListener = Ember.run.bind(this, this.calculatePreviewIsHidden);
this.get('resizeService').on('debouncedDidResize', this._resizeListener);
this.calculatePreviewIsHidden();
},
willDestroy: function () {
this.get('resizeService').off('debouncedDidResize', this._resizeListener);
}
});
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
this.set('previewIsHidden', !this.$('.content-preview').is(':visible'));
}
},
didInsertElement: function () {
this._super(...arguments);
this.calculatePreviewIsHidden();
this.get('resizeService').on('debouncedDidResize',
Ember.run.bind(this, this.calculatePreviewIsHidden));
}
});
|
Increase the timeout for Redis connections
|
package org.icij.extract.cli.factory;
import org.apache.commons.cli.CommandLine;
import org.redisson.Config;
/**
* Factory methods for creating Redis configuration.
*
* @author Matthew Caruana Galizia <mcaruana@icij.org>
* @since 1.0.0-beta
*/
public class RedisConfigFactory {
/**
* Create a new Redis configuration object from commandline parameters.
*
* @param cmd the commandline object containing supplied parameters
* @return the generated configuration object
*/
public static Object createConfig(final CommandLine cmd) {
final Config config = new Config();
final Object serverConfig;
// TODO: support all the other types supported by the ConnectionManagerFactory.
serverConfig = config.useSingleServer()
.setAddress(cmd.getOptionValue("redis-address", "127.0.0.1:6379"))
.setTimeout(60000);
return serverConfig;
}
}
|
package org.icij.extract.cli.factory;
import org.apache.commons.cli.CommandLine;
import org.redisson.Config;
/**
* Factory methods for creating Redis configuration.
*
* @author Matthew Caruana Galizia <mcaruana@icij.org>
* @since 1.0.0-beta
*/
public class RedisConfigFactory {
/**
* Create a new Redis configuration object from commandline parameters.
*
* @param cmd the commandline object containing supplied parameters
* @return the generated configuration object
*/
public static Object createConfig(final CommandLine cmd) {
final Config config = new Config();
final Object serverConfig;
// TODO: support all the other types supported by the ConnectionManagerFactory.
serverConfig = config.useSingleServer()
.setAddress(cmd.getOptionValue("redis-address", "127.0.0.1:6379"))
.setTimeout(5000);
return serverConfig;
}
}
|
Remove the encode password. Cannot find a way to get this to work properly unfortunately.
|
<?php
/**
* This file is part of the LdapTools package.
*
* (c) Chad Sikorra <Chad.Sikorra@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\LdapTools\AttributeConverter;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class EncodeWindowsPasswordSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('LdapTools\AttributeConverter\EncodeWindowsPassword');
}
function it_should_implement_AttributeConverterInferface()
{
$this->shouldImplement('\LdapTools\AttributeConverter\AttributeConverterInterface');
}
function it_should_not_return_anything_when_calling_fromLdap()
{
$this->fromLdap('foo')->shouldBeNull();
}
public function getMatchers()
{
return [
'haveEncoding' => function($subject, $encoding) {
return (bool) mb_detect_encoding($subject, $encoding);
}
];
}
}
|
<?php
/**
* This file is part of the LdapTools package.
*
* (c) Chad Sikorra <Chad.Sikorra@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\LdapTools\AttributeConverter;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class EncodeWindowsPasswordSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('LdapTools\AttributeConverter\EncodeWindowsPassword');
}
function it_should_implement_AttributeConverterInferface()
{
$this->shouldImplement('\LdapTools\AttributeConverter\AttributeConverterInterface');
}
function it_should_not_return_anything_when_calling_fromLdap()
{
$this->fromLdap('foo')->shouldBeNull();
}
/**
* Possible phpspec issue? This seems to always convert
*/
function it_should_encode_a_password_with_double_quotes_and_utf16le_encoding()
{
//$this->toLdap('test')->shouldHaveEncoding('UTF-16LE');
}
public function getMatchers()
{
return [
'haveEncoding' => function($subject, $encoding) {
return (bool) mb_detect_encoding($subject, $encoding);
}
];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.