text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add test forecast.io API call | import juliet_module
from pygame import Rect
from time import time
import forecastio
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
__forecast = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()[:-1]
lat = 40.7127
lng = 74.0059
forecastio.load_forecast(self.__api, lat, lng, units = "us", callback=self.request_callback)
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def request_callback(self, forecast):
self.__forecast = forecast
print(self.__forecast.daily().summary)
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
| import juliet_module
from pygame import Rect
from time import time
from os import getcwd
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
|
Add sample output in comments. | /* Detect object's properties being used */
// Object to be spied, can be Modernizr library for example
var user = { name: 'Maciej', surname: 'Smolinski', fullName: 'Maciej Smolinski' };
// Spy Function
function spyProperties (debugNamespace, objectReference) {
Object.keys(objectReference).forEach(function (property) {
// 1. Store original value as __<propertyName>
user['__' + property] = user[property];
// 1. Reset property to undefined
user[property] = undefined;
// 2. Define spy (will write debug info into console and return original value)
Object.defineProperty(user, property, {
get: function () {
// 2.1. Write debug info into console
console.debug('[Property Usage] %debugNamespace.%property'.replace('%debugNamespace', debugNamespace).replace('%property', property));
// 2.2. Return original value
return user['__' + property];
}
});
});
}
// Spy Properties of user object, debug info to be namespaced with 'user'
spyProperties('user', user);
// Use object properties in a regular manner
console.log('Full Name is: ' + user.name + ' ' + user.surname);
// [Property Usage] user.name
// [Property Usage] user.surname | /* Detect object's properties being used */
// Object to be spied, can be Modernizr library for example
var user = { name: 'Maciej', surname: 'Smolinski', fullName: 'Maciej Smolinski' };
// Spy Function
function spyProperties (debugNamespace, objectReference) {
Object.keys(objectReference).forEach(function (property) {
// 1. Store original value as __<propertyName>
user['__' + property] = user[property];
// 1. Reset property to undefined
user[property] = undefined;
// 2. Define spy (will write debug info into console and return original value)
Object.defineProperty(user, property, {
get: function () {
// 2.1. Write debug info into console
console.debug('[Property Usage] %debugNamespace.%property'.replace('%debugNamespace', debugNamespace).replace('%property', property));
// 2.2. Return original value
return user['__' + property];
}
});
});
}
// Spy Properties of user object, debug info to be namespaced with 'user'
spyProperties('user', user);
// Use object properties in a regular manner
console.log('Full Name is: ' + user.name + ' ' + user.surname); |
Make marker visible on android | // @flow
import * as React from 'react';
import { Icon, StyleSheet } from '@kiwicom/react-native-app-shared';
import Color from '../Color';
type Props = {|
size?: number,
|};
const createStyles = (size: number) =>
StyleSheet.create({
icon: {
ios: {
position: 'absolute',
left: -size / 2,
top: -size,
},
android: {},
},
});
/**
* This drop marker is always pointing to the (0,0) coordinate. It's because
* the marker itself is always absolutely shifted to the left-top corner as
* shown on the following picture:
*
* .-.
* \O/
* v
* .-------.
* | |
* | x |
* | |
* `-------`
*/
export default function DropMarker({ size = 50 }: Props) {
const styles = createStyles(size);
return (
<Icon name="place" size={size} color={Color.brand} style={styles.icon} />
);
}
| // @flow
import * as React from 'react';
import { StyleSheet } from 'react-native';
import { Icon } from '@kiwicom/react-native-app-shared';
import Color from '../Color';
type Props = {|
size?: number,
|};
const createStyles = (size: number) =>
StyleSheet.create({
icon: {
position: 'absolute',
left: -size / 2,
top: -size,
},
});
/**
* This drop marker is always pointing to the (0,0) coordinate. It's because
* the marker itself is always absolutely shifted to the left-top corner as
* shown on the following picture:
*
* .-.
* \O/
* v
* .-------.
* | |
* | x |
* | |
* `-------`
*/
export default function DropMarker({ size = 50 }: Props) {
const styles = createStyles(size);
return (
<Icon name="place" size={size} color={Color.brand} style={styles.icon} />
);
}
|
Change the REST API so adding a flow is using path "/add/json"
instead of "/add/{flow}/json", because now we use POST mechanism
to add a flow. | package net.floodlightcontroller.flowcache.web;
import net.floodlightcontroller.restserver.RestletRoutable;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.routing.Router;
public class FlowWebRoutable implements RestletRoutable {
/**
* Create the Restlet router and bind to the proper resources.
*/
@Override
public Restlet getRestlet(Context context) {
Router router = new Router(context);
router.attach("/add/json", AddFlowResource.class);
router.attach("/delete/{flow-id}/json", DeleteFlowResource.class);
router.attach("/get/{flow-id}/json", GetFlowByIdResource.class);
router.attach("/get/{installer-id}/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json", GetFlowByInstallerIdResource.class);
router.attach("/getall/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json", GetAllFlowsByEndpointsResource.class);
router.attach("/getall/json", GetAllFlowsResource.class);
return router;
}
/**
* Set the base path for the Topology
*/
@Override
public String basePath() {
return "/wm/flow";
}
}
| package net.floodlightcontroller.flowcache.web;
import net.floodlightcontroller.restserver.RestletRoutable;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.routing.Router;
public class FlowWebRoutable implements RestletRoutable {
/**
* Create the Restlet router and bind to the proper resources.
*/
@Override
public Restlet getRestlet(Context context) {
Router router = new Router(context);
router.attach("/add/{flow}/json", AddFlowResource.class);
router.attach("/delete/{flow-id}/json", DeleteFlowResource.class);
router.attach("/get/{flow-id}/json", GetFlowByIdResource.class);
router.attach("/get/{installer-id}/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json", GetFlowByInstallerIdResource.class);
router.attach("/getall/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json", GetAllFlowsByEndpointsResource.class);
router.attach("/getall/json", GetAllFlowsResource.class);
return router;
}
/**
* Set the base path for the Topology
*/
@Override
public String basePath() {
return "/wm/flow";
}
}
|
Add some nose.tools to testing imports. | """The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from neuroimaging.testing import funcfile
>>> from neuroimaging.core.image import image
>>> img = image.load(funcfile)
>>> img.shape
(20, 2, 20, 20)
Notes
-----
BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder
until we build a proper anatomical test image.
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
from nose.tools import assert_true, assert_false
| """The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from neuroimaging.testing import funcfile
>>> from neuroimaging.core.image import image
>>> img = image.load(funcfile)
>>> img.shape
(20, 2, 20, 20)
Notes
-----
BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder
until we build a proper anatomical test image.
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
|
Clean up item price updating (1/2 runtime!) | const mongo = require('../../helpers/mongo.js')
const api = require('../../helpers/api.js')
const async = require('gw2e-async-promises')
const transformPrices = require('./_transformPrices.js')
const config = require('../../config/application.js')
async function itemPrices (job, done) {
job.log(`Starting job`)
let collection = mongo.collection('items')
let prices = await api().commerce().prices().all()
job.log(`Fetched prices for ${prices.length} tradingpost items`)
var items = await updatePrices(prices)
job.log(`Updated ${items.length} item prices`)
let updateFunctions = items.map(item =>
() => collection.updateMany({id: item.id}, {$set: item})
)
job.log(`Created update functions`)
await async.parallel(updateFunctions)
job.log(`Updated item prices`)
done()
}
async function updatePrices (prices) {
let collection = mongo.collection('items')
let items = await collection.find(
{id: {$in: prices.map(p => p.id)}, tradable: true, lang: config.server.defaultLanguage},
{_id: 0, id: 1, buy: 1, sell: 1, vendor_price: 1, craftingWithoutPrecursors: 1, crafting: 1}
).toArray()
let priceMap = {}
prices.map(price => priceMap[price.id] = price)
items = items.map(item => {
return {id: item.id, ...transformPrices(item, priceMap[item.id])}
})
return items
}
module.exports = itemPrices
| const mongo = require('../../helpers/mongo.js')
const api = require('../../helpers/api.js')
const async = require('gw2e-async-promises')
const transformPrices = require('./_transformPrices.js')
async function itemPrices (job, done) {
job.log(`Starting job`)
let prices = await api().commerce().prices().all()
let collection = mongo.collection('items')
job.log(`Fetched prices for ${prices.length} tradingpost items`)
let updateFunctions = prices.map(price => async () => {
// Find the item matching the price, update the price based on the first match
// and then overwrite the prices for all matches (= all languages)
let item = await collection.find({id: price.id, tradable: true}).limit(1).next()
if (!item) {
return
}
item = transformPrices(item, price)
await collection.updateMany({id: price.id}, {$set: item})
})
job.log(`Created update functions`)
await async.parallel(updateFunctions)
job.log(`Updated item prices`)
done()
}
module.exports = itemPrices
|
Fix class name according to filename. | <?php namespace Pingpong\Whoops;
use Illuminate\Support\ServiceProvider;
class WhoopsServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = false;
/**
* Register the service provider.
*/
public function register()
{
$this->app->singleton(
'Illuminate\Contracts\Debug\ExceptionHandler',
'Pingpong\Whoops\WhoopsHandler'
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['Illuminate\Contracts\Debug\ExceptionHandler'];
}
}
| <?php namespace Pingpong\Whoops;
use Illuminate\Support\ServiceProvider;
class ServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = false;
/**
* Register the service provider.
*/
public function register()
{
$this->app->singleton(
'Illuminate\Contracts\Debug\ExceptionHandler',
'Pingpong\Whoops\WhoopsHandler'
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['Illuminate\Contracts\Debug\ExceptionHandler'];
}
}
|
Write in terms of test operation | /*
* Copyright 2015 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.tooling.events.test;
import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.tooling.events.OperationDescriptor;
/**
* Describes a test operation for which an event has occurred.
*
* @since 2.4
*/
@Incubating
public interface TestOperationDescriptor extends OperationDescriptor {
/**
* Returns the name of the test operation.
*
* @return The name of the test operation.
*/
@Override
String getName();
/**
* Returns a human consumable display name for the test operation.
*
* @return The display name of the test operation.
*/
@Override
String getDisplayName();
/**
* Returns the parent of the test operation, if any.
*
* @return The parent of the test operation.
*/
@Override
@Nullable
OperationDescriptor getParent();
}
| /*
* Copyright 2015 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.tooling.events.test;
import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.tooling.events.OperationDescriptor;
/**
* Describes a test for which an event has occurred.
*
* @since 2.4
*/
@Incubating
public interface TestOperationDescriptor extends OperationDescriptor {
/**
* Returns the name of the test.
*
* @return The name of the test.
*/
@Override
String getName();
/**
* Returns the parent of this test, if any.
*
* @return The parent of this test.
*/
@Override
@Nullable
OperationDescriptor getParent();
}
|
Add distanceBetween function, event listener for 'faceLocation' on Tomato | const util = require('util');
const EventEmitter = require('events');
function Tomato(context, center, direction, speed) {
EventEmitter.call(this);
this.context = context;
this.center = center || { x: center.x, y: center.y };
this.size = 10;
this.direction = direction || 0;
this.speed = speed || 3;
}
util.inherits(Tomato, EventEmitter);
Tomato.prototype.draw = function() {
this.context.fillStyle = 'red';
this.context.beginPath();
this.context.arc(this.center.x, this.center.y, this.size, 0, Math.PI * 2, true);
this.context.closePath();
this.context.fill();
return this;
};
Tomato.prototype.velocity = function () {
return {xv: Math.cos(this.direction) * this.speed, yv: Math.sin(this.direction) * this.speed}
}
Tomato.prototype.updatePosition = function () {
this.center.x += this.velocity().xv;
this.center.y += this.velocity().yv;
return this;
}
function distanceBetween(coordinateObject, otherCoordinateObject) {
xDistance = coordinateObject.x - otherCoordinateObject.x;
yDistance = coordinateObject.y - otherCoordinateObject.y;
return (Math.sqrt((xDistance * xDistance) + (yDistance * yDistance)));
}
//Checks for collision with the face. Emits a 'collision' event if detected.
Tomato.prototype.on('faceLocation', function (position, faceSize) {
if ( distanceBetween(this.center, position) < (this.size + faceSize) ) {
this.emit('collision');
}
})
module.exports = Tomato;
| const util = require('util');
const EventEmitter = require('events');
function Tomato(context, center, direction, speed) {
EventEmitter.call(this);
this.context = context;
this.center = center || { x: center.x, y: center.y };
this.size = 10;
this.direction = direction || 0;
this.speed = speed || 3;
}
util.inherits(Tomato, EventEmitter);
Tomato.prototype.draw = function() {
this.context.fillStyle = 'red';
this.context.beginPath();
this.context.arc(this.center.x, this.center.y, this.size, 0, Math.PI * 2, true);
this.context.closePath();
this.context.fill();
return this;
};
Tomato.prototype.velocity = function () {
return {xv: Math.cos(this.direction) * this.speed, yv: Math.sin(this.direction) * this.speed}
}
Tomato.prototype.updatePosition = function () {
this.center.x += this.velocity().xv;
this.center.y += this.velocity().yv;
return this;
}
module.exports = Tomato;
|
Remove sparkline from spec (not needed anymore) | module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai-jquery', 'jquery-2.1.0', 'chai', 'sinon-chai', 'fixture'],
files: [
'public/javascripts/vendor/d3.v3.min.js',
'public/javascripts/vendor/raphael-min.js',
'public/javascripts/vendor/morris.min.js',
'public/javascripts/helpers/helper.js',
'public/javascripts/traffic.js',
'tests/**/*Spec.js',
'tests/fixtures/**/*'
],
exclude: [
'**/*.swp'
],
preprocessors: {
'public/javascripts/*.js': ['coverage'],
'tests/**/*.json' : ['json_fixtures']
},
jsonFixturesPreprocessor: {
variableName: '__json__'
},
reporters: ['progress', 'coverage', 'coveralls'],
coverageReporter: {
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'lcov-report' },
],
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
});
};
| module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai-jquery', 'jquery-2.1.0', 'chai', 'sinon-chai', 'fixture'],
files: [
'public/javascripts/vendor/d3.v3.min.js',
'public/javascripts/vendor/raphael-min.js',
'public/javascripts/vendor/morris.min.js',
'public/javascripts/helpers/helper.js',
'public/javascripts/traffic.js',
'public/javascripts/sparkline.js',
'tests/**/*Spec.js',
'tests/fixtures/**/*'
],
exclude: [
'**/*.swp'
],
preprocessors: {
'public/javascripts/*.js': ['coverage'],
'tests/**/*.json' : ['json_fixtures']
},
jsonFixturesPreprocessor: {
variableName: '__json__'
},
reporters: ['progress', 'coverage', 'coveralls'],
coverageReporter: {
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'lcov-report' },
],
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
});
};
|
Add 1-hour expiry to requests_cache (formerly 5 minutes). | """
Top-level Flask application for HXL Proxy
David Megginson
January 2015
License: Public Domain
Documentation: http://hxlstandard.org
"""
import os
import requests_cache
from flask import Flask, g, request
from flask_cache import Cache
import werkzeug.datastructures
# Main application object
app = Flask(__name__)
app.config.from_object('hxl_proxy.default_config')
if os.environ.get('HXL_PROXY_CONFIG'):
app.config.from_envvar('HXL_PROXY_CONFIG')
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
# Set up cache
cache = Cache(app,config={
'CACHE_TYPE': 'filesystem',
'CACHE_DIR': app.config.get('CACHE_DIR', '/tmp/'),
'CACHE_THRESHOLD': app.config.get('CACHE_MAX_ITEMS', 1000),
'CACHE_DEFAULT_TIMEOUT': app.config.get('CACHE_DEFAULT_TIMEOUT_SECONDS', 3600)
})
requests_cache.install_cache('/tmp/hxl_proxy_requests', expire_after=3600)
# Needed to register annotations
import hxl_proxy.controllers
# end
| """
Top-level Flask application for HXL Proxy
David Megginson
January 2015
License: Public Domain
Documentation: http://hxlstandard.org
"""
import os
import requests_cache
from flask import Flask, g, request
from flask_cache import Cache
import werkzeug.datastructures
# Main application object
app = Flask(__name__)
app.config.from_object('hxl_proxy.default_config')
if os.environ.get('HXL_PROXY_CONFIG'):
app.config.from_envvar('HXL_PROXY_CONFIG')
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
# Set up cache
cache = Cache(app,config={
'CACHE_TYPE': 'filesystem',
'CACHE_DIR': app.config.get('CACHE_DIR', '/tmp/'),
'CACHE_THRESHOLD': app.config.get('CACHE_MAX_ITEMS', 1000),
'CACHE_DEFAULT_TIMEOUT': app.config.get('CACHE_DEFAULT_TIMEOUT_SECONDS', 3600)
})
requests_cache.install_cache('/tmp/hxl_proxy_requests')
# Needed to register annotations
import hxl_proxy.controllers
# end
|
Adjust elements' height for window size | /* global $ */
'use strict';
angular.module('memoApp')
.controller('MemoEditCtrl', function ($scope, $routeParams, memoService) {
$('.nav li').removeClass('active');
$('#nav-memos').addClass('active');
function resize() {
var height = (window.innerHeight - $('#md_area').offset().top - 100) + 'px';
// console.log(height);
$('#md_area').height(height);
$('#html_area').height(height);
}
window.onresize = resize;
resize();
$scope.file = $routeParams.file + '.md';
// console.log($scope.file);
var file = 'memos/' + $scope.file;
var index = file.lastIndexOf('/');
if (index !== -1) {
$scope.dir = file.substr(0, index);
$scope.dirSplit = memoService.getDirSplit($scope.dir);
}
$scope.memo = null;
memoService.watch($scope.file);
memoService.load($scope.file, function (memo) {
// console.log(memo);
$scope.memo = memo;
$scope.$apply();
});
$('#save').click(function () {
// console.log('Save');
memoService.save($scope.file, $scope.memo);
});
});
| /* global $ */
'use strict';
angular.module('memoApp')
.controller('MemoEditCtrl', function ($scope, $routeParams, memoService) {
$('.nav li').removeClass('active');
$('#nav-memos').addClass('active');
var height = (window.innerHeight - $('#md_area').offset().top - 100) + 'px';
// console.log(height);
$('#md_area').height(height);
$('#html_area').height(height);
$scope.file = $routeParams.file + '.md';
// console.log($scope.file);
var file = 'memos/' + $scope.file;
var index = file.lastIndexOf('/');
if (index !== -1) {
$scope.dir = file.substr(0, index);
$scope.dirSplit = memoService.getDirSplit($scope.dir);
}
$scope.memo = null;
memoService.watch($scope.file);
memoService.load($scope.file, function (memo) {
// console.log(memo);
$scope.memo = memo;
$scope.$apply();
});
$('#save').click(function () {
// console.log('Save');
memoService.save($scope.file, $scope.memo);
});
});
|
Make comments collection load only when loading a post | Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return Meteor.subscribe('posts');
}
});
Router.route('/', { name: 'postsList'});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return Meteor.subscribe('comments', this.params._id);
},
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
| Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return [Meteor.subscribe('posts'), Meteor.subscribe('comments')];
}
});
Router.route('/', { name: 'postsList'});
Router.route('/posts/:_id', {
name: 'postPage',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
|
Fix Turkish abbreviation for "minutes"
In Turkish, the abbreviation of "dakika" (minute) is "dk". | (function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'));
} else {
factory(jQuery);
}
}(function (jQuery) {
// Turkish shortened
jQuery.timeago.settings.strings = {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "",
suffixFromNow: "",
seconds: "1dk",
minute: "1dk",
minutes: "%ddk",
hour: "1s",
hours: "%ds",
day: "1g",
days: "%dg",
month: "1ay",
months: "%day",
year: "1y",
years: "%dy",
wordSeparator: " ",
numbers: []
};
}));
| (function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'));
} else {
factory(jQuery);
}
}(function (jQuery) {
// Turkish shortened
jQuery.timeago.settings.strings = {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "",
suffixFromNow: "",
seconds: "1dk",
minute: "1d",
minutes: "%dd",
hour: "1s",
hours: "%ds",
day: "1g",
days: "%dg",
month: "1ay",
months: "%day",
year: "1y",
years: "%dy",
wordSeparator: " ",
numbers: []
};
}));
|
Make $METEOR_NPM_REBUILD_FLAGS override default flags. | // Command-line arguments passed to npm when rebuilding binary packages.
var args = [
"rebuild",
// The --no-bin-links flag tells npm not to create symlinks in the
// node_modules/.bin/ directory when rebuilding packages, which helps
// avoid problems like https://github.com/meteor/meteor/issues/7401.
"--no-bin-links",
// The --update-binary flag tells node-pre-gyp to replace previously
// installed local binaries with remote binaries:
// https://github.com/mapbox/node-pre-gyp#options
"--update-binary"
];
// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
// environment variable.
var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
if (flags) {
args = ["rebuild"];
flags.split(/\s+/g).forEach(function (flag) {
if (flag) {
args.push(flag);
}
});
}
exports.get = function () {
// Make a defensive copy.
return args.slice(0);
};
| // Command-line arguments passed to npm when rebuilding binary packages.
var args = [
"rebuild",
// The --no-bin-links flag tells npm not to create symlinks in the
// node_modules/.bin/ directory when rebuilding packages, which helps
// avoid problems like https://github.com/meteor/meteor/issues/7401.
"--no-bin-links",
// The --update-binary flag tells node-pre-gyp to replace previously
// installed local binaries with remote binaries:
// https://github.com/mapbox/node-pre-gyp#options
"--update-binary"
];
// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
// environment variable.
var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
if (flags) {
args.push.apply(args, flags.split(/\s+/g));
}
exports.get = function () {
// Make a defensive copy.
return args.slice(0);
};
|
Update pubkey servlet to s/signers/keyring | # -*- coding: utf-8 -*-
# Copyright 2014 matrix.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from twisted.web.resource import Resource
import json
import nacl.encoding
class Ed25519Servlet(Resource):
isLeaf = True
def __init__(self, syd):
self.sydent = syd
def render_GET(self, request):
pubKey = self.sydent.keyring.ed25519.verify_key
pubKeyHex = pubKey.encode(encoder=nacl.encoding.HexEncoder)
return json.dumps({'public_key':pubKeyHex})
| # -*- coding: utf-8 -*-
# Copyright 2014 matrix.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from twisted.web.resource import Resource
import json
import nacl.encoding
class Ed25519Servlet(Resource):
isLeaf = True
def __init__(self, syd):
self.sydent = syd
def render_GET(self, request):
pubKey = self.sydent.signers.ed25519.signing_key.verify_key
pubKeyHex = pubKey.encode(encoder=nacl.encoding.HexEncoder)
return json.dumps({'public_key':pubKeyHex})
|
refactor: Change location of regex compilation | import re
url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)")
purge_re = re.compile("(purge) (\d+)")
list_re = re.compile("list")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = url_re.search(message)
if answer is not None:
answer = answer.group(1).strip()
return answer
def to_bot(message, bot_id):
bot_re = "^<@" + bot_id + '>'
to_bot_re = re.compile(bot_re)
bot_found = to_bot_re.search(message)
return bot_found is not None
def is_list_request(message):
list_found = list_re.search(message)
return list_found is not None
def purge_request(message):
index_found = purge_re.search(message)
if index_found is None:
return None
return int(index_found.group(2))
| import re
url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = url_re.search(message)
if answer is not None:
answer = answer.group(1).strip()
return answer
def to_bot(message, bot_id):
bot_re = "^<@" + bot_id + '>'
to_bot_re = re.compile(bot_re)
bot_found = to_bot_re.search(message)
return bot_found is not None
def is_list_request(message):
list_re = re.compile("list")
list_found = list_re.search(message)
return list_found is not None
def purge_request(message):
purge_re = re.compile("(purge) (\d+)")
index_found = purge_re.search(message)
if index_found is None:
return None
return int(index_found.group(2))
|
Replace tabs with spaces, use parens to get rid of backslashes | from yacron import config
def test_mergedicts():
assert dict(config.mergedicts({"a": 1}, {"b": 2})) == {"a": 1, "b": 2}
def test_mergedicts_nested():
assert (dict(config.mergedicts(
{"a": {'x': 1, 'y': 2, 'z': 3}},
{'a': {'y': 10}, "b": 2}
)) == {"a": {'x': 1, 'y': 10, 'z': 3}, "b": 2})
def test_mergedicts_right_none():
assert (dict(config.mergedicts(
{"a": {'x': 1}},
{"a": None, "b": 2}
)) == {"a": {'x': 1}, "b": 2})
def test_mergedicts_lists():
assert (dict(config.mergedicts(
{"env": [{'key': 'FOO'}]},
{"env": [{'key': 'BAR'}]}
)) == {"env": [{'key': 'FOO'}, {'key': 'BAR'}]})
| from yacron import config
def test_mergedicts():
assert dict(config.mergedicts({"a": 1}, {"b": 2})) == {"a": 1, "b": 2}
def test_mergedicts_nested():
assert dict(config.mergedicts(
{"a": {'x': 1, 'y': 2, 'z': 3}},
{'a': {'y': 10}, "b": 2})) == \
{"a": {'x': 1, 'y': 10, 'z': 3}, "b": 2}
def test_mergedicts_right_none():
assert dict(config.mergedicts(
{"a": {'x': 1}},
{"a": None, "b": 2})) == \
{"a": {'x': 1}, "b": 2}
def test_mergedicts_lists():
assert dict(config.mergedicts(
{"env": [{'key': 'FOO'}]},
{"env": [{'key': 'BAR'}]})) \
== \
{"env": [{'key': 'FOO'}, {'key': 'BAR'}]}
|
provider/common: Add more rationale to the doc comments for EnvFullName and MachineFullName. | // Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package common
import (
"fmt"
"github.com/juju/names"
"github.com/juju/juju/environs"
)
// EnvFullName returns a string based on the provided environment
// that is suitable for identifying the env on a provider. The resuling
// string clearly associates the value with juju, whereas the
// environment's UUID alone isn't very distinctive for humans. This
// benefits users by helping them quickly identify in their hosting
// management tools which instances are juju related.
func EnvFullName(env environs.Environ) string {
envUUID, _ := env.Config().UUID() // Env should have validated this.
return fmt.Sprintf("juju-%s", envUUID)
}
// MachineFullName returns a string based on the provided environment
// and machine ID that is suitable for identifying instances on a
// provider. See EnvFullName for an explanation on how this function
// helps juju users.
func MachineFullName(env environs.Environ, machineId string) string {
envstr := EnvFullName(env)
machineTag := names.NewMachineTag(machineId)
return fmt.Sprintf("%s-%s", envstr, machineTag)
}
| // Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package common
import (
"fmt"
"github.com/juju/names"
"github.com/juju/juju/environs"
)
// EnvFullName returns a string based on the provided environment
// that is suitable for identifying the env on a provider.
func EnvFullName(env environs.Environ) string {
envUUID, _ := env.Config().UUID() // Env should have validated this.
return fmt.Sprintf("juju-%s", envUUID)
}
// MachineFullName returns a string based on the provided environment
// and machine ID that is suitable for identifying instances on a
// provider.
func MachineFullName(env environs.Environ, machineId string) string {
envstr := EnvFullName(env)
machineTag := names.NewMachineTag(machineId)
return fmt.Sprintf("%s-%s", envstr, machineTag)
}
|
Fix command line usage options | """Calculate the number of Pomodori available within a time period.
Usage:
get-pomodori [--from=<time>] [--break=<minutes>] [--long-break=<minutes>] <end-time>
get-pomodori (-h | --help | --version)
Options:
--version show program's version number and exit.
-h, --help show this help message and exit.
-f, --from=<time> calculate available Pomodori from this time [default: now].
-b, --break=<minutes> the amount of minutes between each Pomodori [default: 5].
-l, --long-break=<minutes> the amount of minutes between every four Pomodori [default: 15].
"""
from docopt import docopt
def main():
docopt(__doc__, version='0.2')
if __name__ == '__main__':
main()
| """Calculate the number of Pomodori available within a time period.
Usage:
get-pomodori [--from=<time>] [--break=<minutes>] [--long-break=<minutes>] <end-time>
get-pomodori (-h | --help | --version)
Options:
--version show program's version number and exit.
-h, --help show this help message and exit.
-f, --from=<time> calculate available pomodori from this time [default: now].
-b, --break=<minutes> the amount of minutes between each pomodori [default: 5].
-l, --long-break=<minutes> the amount of mintues between every five pomodori [default: 15].
"""
from docopt import docopt
def main():
docopt(__doc__, version='0.2')
if __name__ == '__main__':
main()
|
Make example work with refactored code. | require.paths.unshift('../lib')
var inflect = require('inflect');
var options = {
type: 'client',
jid: 'user@example.com',
password: 'secret',
host: 'example.com',
port: 5222
};
var connection = inflect.createConnection(options);
connection.use(inflect.logger());
connection.use(inflect.serviceDiscovery([ { category: 'client', type: 'bot' } ],
['http://jabber.org/protocol/disco#info']));
connection.use(inflect.serviceUnavailable());
connection.use(inflect.errorHandler());
connection.on('online', function() {
console.log('ONLINE!');
connection.send(new inflect.Element('presence'));
});
connection.on('error', function(err) {
console.log('ERROR: ' + err);
});
| require.paths.unshift('../lib')
var xmpp = require('node-xmpp');
var inflect = require('inflect');
var options = {
type: 'client',
jid: 'user@example.com',
password: 'secret',
host: 'example.com',
port: 5222
};
var connection = inflect.createConnection(options);
connection.use(inflect.logger);
connection.use(inflect.serviceDiscovery, [ { category: 'client', type: 'bot' } ],
['http://jabber.org/protocol/disco#info'] );
connection.use(inflect.serviceUnavailable);
connection.use(inflect.errorHandler);
connection.on('online', function() {
console.log('ONLINE!');
connection.send(new xmpp.Element('presence'));
});
connection.on('error', function(err) {
console.log('ERROR: ' + err);
});
|
Downgrade de version bump to a minor one | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
author_email='op.serenatadeamor@gmail.com',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
zip_safe=False,
install_requires=[
'aiofiles',
'aiohttp',
'boto3',
'beautifulsoup4>=4.4',
'lxml>=3.6',
'pandas>=0.18',
'tqdm'
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=[
'serenata_toolbox.federal_senate',
'serenata_toolbox.chamber_of_deputies',
'serenata_toolbox.datasets'
],
url=REPO_URL,
version='12.3.2'
)
| from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
author_email='op.serenatadeamor@gmail.com',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
zip_safe=False,
install_requires=[
'aiofiles',
'aiohttp',
'boto3',
'beautifulsoup4>=4.4',
'lxml>=3.6',
'pandas>=0.18',
'tqdm'
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=[
'serenata_toolbox.federal_senate',
'serenata_toolbox.chamber_of_deputies',
'serenata_toolbox.datasets'
],
url=REPO_URL,
version='12.4.1'
)
|
Add helper for container “created”-status checking | var exec = require('child_process').exec,
_ = require('lodash')
module.exports.asyncIterate = function(array, callback, done) {
function iterate(idx) {
var current = array[idx]
if (current) {
callback(current, function() { iterate(idx+1) }, function(err) { done(err) })
} else {
done()
}
}
iterate(0)
}
module.exports.checkRunning = function(container, callback) {
exec('docker inspect ' + container.name, function(err, stdout) {
if (err) {
callback(false)
} else {
var info = _.head(JSON.parse(stdout))
var isRunning = info && info.State ? !!info.State.Running : false
callback(isRunning)
}
})
}
module.exports.checkCreated = function(container, callback) {
exec('docker inspect ' + container.name, function(err) {
var isCreated = err ? false : true
callback(isCreated)
})
}
| var exec = require('child_process').exec,
_ = require('lodash')
module.exports.asyncIterate = function(array, callback, done) {
function iterate(idx) {
var current = array[idx]
if (current) {
callback(current, function() { iterate(idx+1) }, function(err) { done(err) })
} else {
done()
}
}
iterate(0)
}
module.exports.checkRunning = function(container, callback) {
exec('docker inspect ' + container.name, function(err, stdout) {
if (err) {
callback(false)
} else {
var info = _.head(JSON.parse(stdout))
var isRunning = info && info.State ? !!info.State.Running : false
callback(isRunning)
}
})
}
|
Test apply on a non-existing method | <?php
use Jade\Compiler;
class StatementsBugCompiler extends Compiler {
public function __construct() {
$this->createStatements();
}
}
class ApplyBugCompiler extends Compiler {
public function __construct() {
$this->apply('foo', array());
}
}
class JadeCompilerExceptionsTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException Exception
*/
public function testHandleEmptyCode() {
$compiler = new Compiler();
$compiler->handleCode('');
}
/**
* @expectedException Exception
*/
public function testNonStringInHandleCode() {
$compiler = new Compiler();
$compiler->handleCode(array());
}
/**
* @expectedException Exception
*/
public function testMissingClosure() {
$compiler = new Compiler();
$compiler->handleCode('["foo"');
}
/**
* @expectedException Exception
*/
public function testCreateEmptyStatement() {
new StatementsBugCompiler();
}
/**
* @expectedException Exception
*/
public function testBadMethodApply() {
new ApplyBugCompiler();
}
}
| <?php
use Jade\Compiler;
class BugCompiler extends Compiler {
public function __construct() {
$this->createStatements();
}
}
class JadeCompilerExceptionsTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException Exception
*/
public function testHandleEmptyCode() {
$compiler = new Compiler();
$compiler->handleCode('');
}
/**
* @expectedException Exception
*/
public function testNonStringInHandleCode() {
$compiler = new Compiler();
$compiler->handleCode(array());
}
/**
* @expectedException Exception
*/
public function testMissingClosure() {
$compiler = new Compiler();
$compiler->handleCode('["foo"');
}
/**
* @expectedException Exception
*/
public function testCreateEmptyStatement() {
new BugCompiler();
}
}
|
Create object MenuItem that wraps functions to create a call stack | class MenuItem(object):
def __init__(self, func=None):
if func: self.function = func
# Wrapper for child.function() that creates a call stack
def run(self, ret=None):
self.function()
if ret: ret()
class Menu(MenuItem):
def __init__(self, dialog, items, title):
self.d = dialog
self.entries = []
self.dispatch_table = {}
tag = 1
self.title = title
for entry, func in items:
self.entries.append(tuple([str(tag), entry]))
self.dispatch_table[str(tag)] = func
tag += 1
def function(self):
code, tag = self.d.menu(self.title, choices=self.entries)
if code == self.d.OK: self._dispatch(tag)
def _dispatch(self, tag):
if tag in self.dispatch_table:
func = self.dispatch_table[tag]
if isinstance(func, MenuItem):
func.run(ret=self.run)
else: func()
| class Menu(object):
def __init__(self, dialog, items, title, caller = None):
self.d = dialog
self.caller = caller
self.entries = []
self.dispatch_table = {}
tag = 1
self.title = title
for entry, func in items:
self.entries.append(tuple([str(tag), entry]))
self.dispatch_table[str(tag)] = func
tag += 1
def run(self, ret=None):
code, tag = self.d.menu(self.title, choices=self.entries)
if code == self.d.OK: self.dispatch(tag)
if ret: ret()
def dispatch(self, tag):
if tag in self.dispatch_table:
func = self.dispatch_table[tag]
if isinstance(func, Menu):
func.run(ret=self.run)
else: func()
|
Fix the map file name
git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@1330 46e82423-29d8-e211-989e-002590a4cdd4 | <?
# $Id: graphclick.php,v 1.1.2.2 2002-04-20 04:55:50 dan Exp $
#
$cache_dir = "/tmp/";
if (!isset($id)) $id=0;
$map = file($cache_dir."FreshPorts.graph".$id.".map");
if (count($map) == 0) {
die("GRAPH: invalid id");
}
foreach ($map as $m) {
list($y,$p) = split(":",$m);
$map_y[] = $y;
$map_p[] = $p;
}
$i = 0;
while ($i < count($map) && $graph_y>$map_y[$i]) {
$i++;
}
// click out of bars (too high or too low)
if ($i==0 || $i==count($map)) {
if (!isset($HTTP_REFERER) || $HTTP_REFERER=="") {
header("Location: http://".$_SERVER['HTTP_HOST']);
} else {
header("Location: $HTTP_REFERER");
}
exit;
}
$URL = $map_p[$i-1];
header("Location: http://"
.$_SERVER['HTTP_HOST']
."$URL");
?>
| <?
# $Id: graphclick.php,v 1.1.2.1 2002-04-19 20:26:05 dan Exp $
#
$cache_dir = "/tmp/";
if (!isset($id)) $id=0;
$map = file($cache_dir."graph".$id.".map");
if (count($map) == 0) {
die("GRAPH: invalid id");
}
foreach ($map as $m) {
list($y,$p) = split(":",$m);
$map_y[] = $y;
$map_p[] = $p;
}
$i = 0;
while ($i < count($map) && $graph_y>$map_y[$i]) {
$i++;
}
// click out of bars (too high or too low)
if ($i==0 || $i==count($map)) {
if (!isset($HTTP_REFERER) || $HTTP_REFERER=="") {
header("Location: http://".$_SERVER['HTTP_HOST']);
} else {
header("Location: $HTTP_REFERER");
}
exit;
}
$URL = $map_p[$i-1];
header("Location: http://"
.$_SERVER['HTTP_HOST']
."$URL");
?>
|
Create a new variable in the php-proxy and set to the default proxyParam value | <?php
// Set this to true if you want to be able to load images from a url that doesn't
// end in an image file extension. E.g. through another proxy of kinds.
define('ALLOW_NO_EXT', false);
$proxyParam = 'camanProxyUrl';
if (!$_GET[$proxyParam]) {
exit;
}
// Grab the URL
$url = trim(urldecode($_GET[$proxyParam]));
$urlinfo = parse_url($url, PHP_URL_PATH);
$ext = array_reverse(explode(".", $urlinfo));
$ctype = null;
switch ($ext[0]) {
case 'gif': $ctype = 'image/gif'; break;
case 'png': $ctype = 'image/png'; break;
case 'jpeg':
case 'jpg': $ctype = 'image/jpg'; break;
default:
if (ALLOW_NO_EXT) {
$ctype = 'application/octet-stream';
} else {
exit;
}
}
// Route the image through this script
header("Content-Type: $ctype");
readfile($url); | <?php
// Set this to true if you want to be able to load images from a url that doesn't
// end in an image file extension. E.g. through another proxy of kinds.
define('ALLOW_NO_EXT', false);
if (!$_GET['url']) {
exit;
}
// Grab the URL
$url = trim(urldecode($_GET['url']));
$urlinfo = parse_url($url, PHP_URL_PATH);
$ext = array_reverse(explode(".", $urlinfo));
$ctype = null;
switch ($ext[0]) {
case 'gif': $ctype = 'image/gif'; break;
case 'png': $ctype = 'image/png'; break;
case 'jpeg':
case 'jpg': $ctype = 'image/jpg'; break;
default:
if (ALLOW_NO_EXT) {
$ctype = 'application/octet-stream';
} else {
exit;
}
}
// Route the image through this script
header("Content-Type: $ctype");
readfile($url); |
Fix platform status url of webkit | 'use strict';
const assert = require('assert');
const url = require('url');
/**
* @param engine {string}
* @param id {string}
* @returns {string}
*/
function getPlatformStatusId(engine, id) {
return engine + '-' + encodeURIComponent(id);
}
const PLATFORM_STATUS_URL_MAP = new Map([
['chromium', 'https://www.chromestatus.com/features/'],
['edge', 'https://developer.microsoft.com/en-us/microsoft-edge/platform/status/'],
['webkit', 'https://webkit.org/status/#'],
['gecko', 'https://platform-status.mozilla.org/#'],
]);
/**
* @param engine {string}
* @param id {string}
* @returns {string}
*/
function getPlatformStatusUrl(engine, id) {
assert(PLATFORM_STATUS_URL_MAP.has(engine));
const baseUrl = PLATFORM_STATUS_URL_MAP.get(engine);
return baseUrl + encodeURIComponent(id);
}
/**
* @param urlString {string}
* @returns {string}
*/
function getHost(urlString) {
return url.parse(urlString).host;
}
module.exports = {
getPlatformStatusId: getPlatformStatusId,
getPlatformStatusUrl: getPlatformStatusUrl,
getHost: getHost,
};
| 'use strict';
const assert = require('assert');
const url = require('url');
/**
* @param engine {string}
* @param id {string}
* @returns {string}
*/
function getPlatformStatusId(engine, id) {
return engine + '-' + encodeURIComponent(id);
}
const PLATFORM_STATUS_URL_MAP = new Map([
['chromium', 'https://www.chromestatus.com/features/'],
['edge', 'https://developer.microsoft.com/en-us/microsoft-edge/platform/status/'],
['webkit', 'https://webkit.org/status/#feature-'],
['gecko', 'https://platform-status.mozilla.org/#'],
]);
/**
* @param engine {string}
* @param id {string}
* @returns {string}
*/
function getPlatformStatusUrl(engine, id) {
assert(PLATFORM_STATUS_URL_MAP.has(engine));
const baseUrl = PLATFORM_STATUS_URL_MAP.get(engine);
return baseUrl + encodeURIComponent(id);
}
/**
* @param urlString {string}
* @returns {string}
*/
function getHost(urlString) {
return url.parse(urlString).host;
}
module.exports = {
getPlatformStatusId: getPlatformStatusId,
getPlatformStatusUrl: getPlatformStatusUrl,
getHost: getHost,
};
|
Enable animations in bridgeless mode on iOS
Reviewed By: ejanzer
Differential Revision: D21465166
fbshipit-source-id: b34e8e97330b897e20d9a4b05dba1826df569e16 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import Platform from '../../Utilities/Platform';
import typeof AnimatedFlatList from './components/AnimatedFlatList';
import typeof AnimatedImage from './components/AnimatedImage';
import typeof AnimatedScrollView from './components/AnimatedScrollView';
import typeof AnimatedSectionList from './components/AnimatedSectionList';
import typeof AnimatedText from './components/AnimatedText';
import typeof AnimatedView from './components/AnimatedView';
const AnimatedMock = require('./AnimatedMock');
const AnimatedImplementation = require('./AnimatedImplementation');
const Animated = ((Platform.isTesting
? AnimatedMock
: AnimatedImplementation): typeof AnimatedMock);
module.exports = {
get FlatList(): AnimatedFlatList {
return require('./components/AnimatedFlatList');
},
get Image(): AnimatedImage {
return require('./components/AnimatedImage');
},
get ScrollView(): AnimatedScrollView {
return require('./components/AnimatedScrollView');
},
get SectionList(): AnimatedSectionList {
return require('./components/AnimatedSectionList');
},
get Text(): AnimatedText {
return require('./components/AnimatedText');
},
get View(): AnimatedView {
return require('./components/AnimatedView');
},
...Animated,
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import Platform from '../../Utilities/Platform';
import typeof AnimatedFlatList from './components/AnimatedFlatList';
import typeof AnimatedImage from './components/AnimatedImage';
import typeof AnimatedScrollView from './components/AnimatedScrollView';
import typeof AnimatedSectionList from './components/AnimatedSectionList';
import typeof AnimatedText from './components/AnimatedText';
import typeof AnimatedView from './components/AnimatedView';
const AnimatedMock = require('./AnimatedMock');
const AnimatedImplementation = require('./AnimatedImplementation');
//TODO(T57411659): Remove the bridgeless check when Animated perf regressions are fixed.
const Animated = ((Platform.isTesting ||
(global.RN$Bridgeless && Platform.OS === 'ios')
? AnimatedMock
: AnimatedImplementation): typeof AnimatedMock);
module.exports = {
get FlatList(): AnimatedFlatList {
return require('./components/AnimatedFlatList');
},
get Image(): AnimatedImage {
return require('./components/AnimatedImage');
},
get ScrollView(): AnimatedScrollView {
return require('./components/AnimatedScrollView');
},
get SectionList(): AnimatedSectionList {
return require('./components/AnimatedSectionList');
},
get Text(): AnimatedText {
return require('./components/AnimatedText');
},
get View(): AnimatedView {
return require('./components/AnimatedView');
},
...Animated,
};
|
Add branch and state check on CD server. | // Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { urlencoded } = require('body-parser')
const hostname = '127.0.0.1'
const port = 80
const server = createServer((req, res) => {
const { headers, method, url } = req
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
req
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
req.body = Buffer.concat(body).toString()
urlencoded({ extended: true })(req)
console.log(req.body)
if (req.body.payload) {
const passed = req.body.payload.state == 'passed'
const master = req.body.payload.branch == 'master'
if (passed && master) {
process.exit(0)
}
}
})
}
res.statusCode = 404
res.end()
}).listen(port)
| // Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { urlencoded } = require('body-parser')
const hostname = '127.0.0.1'
const port = 80
const server = createServer((req, res) => {
const { headers, method, url } = req
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
req
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
req.body = Buffer.concat(body).toString()
const data = urlencoded({ extended: true })(req)
console.log(req.body.payload)
if (req.body.payload) {
const passed = req.body.payload.state == 'passed'
const master = req.body.payload.branch == 'master'
process.exit(0)
}
})
}
res.statusCode = 404
res.end()
}).listen(port)
|
Implement proposed changes + add `== null` check | import store from '../../store';
export default (key, params = null) => {
if (!store.getters['localisation/isInitialised']) {
return key;
}
let translation = store.getters['localisation/__'](key);
if (typeof translation === 'undefined' || translation == null) {
translation = key;
if (store.state.localisation.keyCollector) {
store.dispatch('localisation/addMissingKey', key);
}
}
return !!params && typeof params === 'object'
? translation.replace(/:(\w*)/g, (e, key) => {
if (typeof params[key.toLowerCase()] === 'undefined') {
return key;
}
const param = params[key.toLowerCase()];
if(key === key.toUpperCase()) {
return param.toUpperCase();
}
return key[0] === key[0].toUpperCase()
? param.charAt(0).toUpperCase() + param.slice(1)
: param;
})
: translation;
}
| import store from '../../store';
const __ = store.getters[ 'localisation/__' ];
export default function (key, params) {
if (!store.getters[ 'localisation/isInitialised' ]) {
return key;
}
let translation = __(key);
if (typeof translation === 'undefined'
&& store.state.localisation.keyCollector) {
store.dispatch('localisation/addMissingKey', key);
}
translation = translation || key;
if(params) {
translation = translation.replace(/:(\w*)/g, function(e, key) {
let param = params[key.toLowerCase()] || key;
if(key === key.toUpperCase()) { // param is uppercased
param = param.toUpperCase();
} else if(key[0] === key[0].toUpperCase()) { // first letter is uppercased
param = param.charAt(0).toUpperCase() + param.slice(1);
}
return param;
});
}
return translation;
}
|
Increment version to 0.4.0 for release | from setuptools import setup
version = "0.4.0"
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
'pytest-runner',
],
tests_require=[
"pytest",
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| from setuptools import setup
version = "0.3.1"
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
'pytest-runner',
],
tests_require=[
"pytest",
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
|
Add Audience group job failed type: AUDIENCE_GROUP_AUDIENCE_INSUFFICIENT | /*
* Copyright 2020 LINE Corporation
*
* LINE Corporation 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 com.linecorp.bot.model.manageaudience;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
public enum AudienceGroupJobFailedType {
/**
* Internal server error.
*/
INTERNAL_ERROR,
/**
* Audience is insufficient.
*/
AUDIENCE_GROUP_AUDIENCE_INSUFFICIENT,
@JsonEnumDefaultValue
UNKNOWN
}
| /*
* Copyright 2020 LINE Corporation
*
* LINE Corporation 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 com.linecorp.bot.model.manageaudience;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
public enum AudienceGroupJobFailedType {
/**
* Internal server error.
*/
INTERNAL_ERROR,
@JsonEnumDefaultValue
UNKNOWN
}
|
Enhance the dotted name lookup functionality. | # -*- coding: utf-8 -*-
import os
import pkgutil
from mako.lookup import TemplateLookup
from mako.template import Template
class DottedTemplateLookup(TemplateLookup):
def __init__(self, pkg):
self.dfltpkg = pkg
def adjust_uri(self, uri, relto):
return uri
def get_template(self, name):
div = name.rfind('.')
# Break apart name into a package and base file name
if div >= 0:
pkg = name[:div]
basename = name[div + 1:]
else:
pkg = self.dfltpkg
basename = name
# Attempt to load the template
src = pkgutil.get_data(pkg, basename + '.mako')
if not src:
raise RuntimeError('Template "{}" not found'.format(name))
return Template(src, lookup=self)
| # -*- coding: utf-8 -*-
import os
import pkgutil
from mako.lookup import TemplateLookup
from mako.template import Template
class DottedTemplateLookup(TemplateLookup):
def __init__(self, pkg):
self.dfltpkg = pkg
def adjust_uri(self, uri, relto):
return uri
def get_template(self, name):
div = name.rfind('.')
# Break apart name into a package and base file name
if div >= 0:
pkg = name[:div]
basename = name[div + 1:]
else:
pkg = self.dfltpkg
basename = name
# Attempt to load the template
try:
tpl = pkgutil.get_data(pkg, basename + '.mako')
return Template(tpl, lookup=self)
except IOError:
raise RuntimeError('Template "{}" not found'.format(name))
|
feat: Add actions for add expense form | import Ember from 'ember';
// import $ from 'jquery';
export default Ember.Component.extend({
expense: {
sum: null,
category: '',
name: ''
},
currency: '£',
expenseCategories: [
'Charity',
'Clothing',
'Education',
'Events',
'Food',
'Gifts',
'Healthcare',
'Household',
'Leisure',
'Hobbies',
'Trasportation',
'Utilities',
'Vacation'
],
didInsertElement () {
componentHandler.upgradeAllRegistered();
},
actions: {
clearInputs () {
this.$('.mdl-textfield input[type=text]').val('');
this.$('.mdl-textfield').removeClass('is-dirty');
},
addExpense () {
console.log(this.get('expense'));
}
}
});
| import Ember from 'ember';
import $ from 'jquery';
export default Ember.Component.extend({
expense: {
sum: null,
category: '',
name: ''
},
currency: '£',
expenseCategories: [
'Charity',
'Clothing',
'Education',
'Events',
'Food',
'Gifts',
'Healthcare',
'Household',
'Leisure',
'Hobbies',
'Trasportation',
'Utilities',
'Vacation'
],
didInsertElement () {
var dialog = document.getElementById(this.$().attr('id'));
var showDialogButton = $('[dialog-open]');
console.log(dialog, showDialogButton);
if (!dialog.showModal) {
dialogPolyfill.registerDialog(dialog);
}
showDialogButton.click(function () {
dialog.showModal();
});
// dialog.querySelector('.close').addEventListener('click', function () {
// dialog.close();
// });
$(dialog).on('click', function () {
dialog.close();
});
componentHandler.upgradeAllRegistered()
}
});
|
Add version flag to usage info
Closes #8 | #!/usr/bin/env node
var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2), {
alias: {
v: 'version'
}
});
if (argv.version) {
console.log(require('../package.json').version);
return;
}
// no args
if (!argv._.length) {
var usage = [
'Shield generator for your current project.',
'',
'Usage:',
' shields [travis] [gemnasium]',
' shields -v | --version',
'',
'Options:',
' -v --version Show version'
];
console.log(usage.join('\n'));
return;
}
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
}); | #!/usr/bin/env node
var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2), {
alias: {
v: 'version'
}
});
if (argv.version) {
console.log(require('../package.json').version);
return;
}
// no args
if (!argv._.length) {
var usage = [
'Shield generator for your current project.',
'',
'Usage:',
' shields [travis] [gemnasium]'
];
console.log(usage.join('\n'));
return;
}
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
}); |
Update script to remove empty line | const fs = require('fs');
const components = process.argv.slice(2);
const componentDefaultContent = componentName =>
`import React, {
Component,
PropTypes,
} from 'react';
class ${componentName} extends Component {
render() {
return (
<div></div>
);
}
}
export default ${componentName};
`;
const indexDefaultContent = componentName =>
`import ${componentName} from './${componentName}';
export default ${componentName};
`;
const createFile = (fileName, contents) => fs.writeFile(fileName, contents, err => {
if (err) {
return console.log(err);
}
});
components.forEach(component => {
const componentName = component.charAt(0).toUpperCase() + component.slice(1);
const folderPrefix = `${component}/`;
fs.existsSync(componentName) || fs.mkdirSync(componentName);
createFile(`${folderPrefix + componentName}.js`, componentDefaultContent(componentName));
createFile(`${folderPrefix + componentName}.scss`, '');
createFile(`${folderPrefix}index.js`, indexDefaultContent(componentName));
console.log('Successfully created '+componentName+' component!');
});
| #!/usr/bin/env node
const fs = require('fs');
const components = process.argv.slice(2);
const componentDefaultContent = componentName => `
import React, {
Component,
PropTypes,
} from 'react';
class ${componentName} extends Component {
render() {
return (
<div></div>
);
}
}
export default ${componentName};
`;
const indexDefaultContent = componentName => `
import ${componentName} from './${componentName}';
export default ${componentName};
`;
const createFile = (fileName, contents) => fs.writeFile(fileName, contents, err => {
if (err) {
return console.log(err);
}
});
components.forEach(component => {
const componentName = component.charAt(0).toUpperCase() + component.slice(1);
const folderPrefix = `${component}/`;
fs.existsSync(componentName) || fs.mkdirSync(componentName);
createFile(`${folderPrefix + componentName}.js`, componentDefaultContent(componentName));
createFile(`${folderPrefix + componentName}.scss`, '');
createFile(`${folderPrefix}index.js`, indexDefaultContent(componentName));
console.log('Successfully created '+componentName+' component!');
});
|
Clear config on configVersion change:
A v7 test failed when we restore the full config object.
Try restoring only the two fields that get changed.
[#1702476450](https://www.pivotaltracker.com/story/show/170247645)
Authored-by: Eric Promislow <6c389fa4d719bbeec88fea52ca3b2497804923ad@suse.com> | package isolated
import (
helpers "code.cloudfoundry.org/cli/integration/helpers"
"code.cloudfoundry.org/cli/util/configv3"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Config", func() {
Describe("Version Management", func() {
var oldTarget string
var oldVersion int
BeforeEach(func() {
config := helpers.GetConfig()
oldTarget = config.Target()
oldVersion = config.ConfigFile.ConfigVersion
})
AfterEach(func() {
helpers.SetConfig(func(config *configv3.Config) {
config.ConfigFile.ConfigVersion = oldVersion
config.ConfigFile.Target = oldTarget
})
})
It("reset config to default if version mismatch", func() {
helpers.SetConfig(func(config *configv3.Config) {
config.ConfigFile.ConfigVersion = configv3.CurrentConfigVersion - 1
config.ConfigFile.Target = "api.my-target"
})
helpers.LoginCF()
config := helpers.GetConfig()
Expect(config.ConfigFile.ConfigVersion).To(Equal(configv3.CurrentConfigVersion))
Expect(config.ConfigFile.Target).To(Equal(""))
})
})
})
| package isolated
import (
helpers "code.cloudfoundry.org/cli/integration/helpers"
"code.cloudfoundry.org/cli/util/configv3"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Config", func() {
Describe("Version Management", func() {
var oldConfig *configv3.Config
BeforeEach(func() {
oldConfig = helpers.GetConfig()
})
AfterEach(func() {
helpers.SetConfig(func(config *configv3.Config) {
config.ConfigFile = oldConfig.ConfigFile
})
})
It("reset config to default if version mismatch", func() {
helpers.SetConfig(func(config *configv3.Config) {
config.ConfigFile.ConfigVersion = configv3.CurrentConfigVersion - 1
config.ConfigFile.Target = "api.my-target"
})
helpers.LoginCF()
config := helpers.GetConfig()
Expect(config.ConfigFile.ConfigVersion).To(Equal(configv3.CurrentConfigVersion))
Expect(config.ConfigFile.Target).To(Equal(""))
})
})
})
|
Revert "Revert "Added nickname and punct, removed parens""
This reverts commit ab4e279a6866d432cd1f58a07879e219360b4911. | import random
ateball = [
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes, definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful.",
]
def run(data, settings):
if '8ball' in data['payload']:
say = '{nick}: {fortune}'.format(nick=data['nick'],
fortune=random.choice(ateball))
return say
| import random
ateball = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
]
def run(data, settings):
if ('8ball' in data['payload']):
return random.choice(ateball)
|
Add a fake prices endpoint | "use strict";
var express = require("express");
module.exports = function () {
var app = express();
// Allow all domains to request data (see CORS for more details)
app.use(function (req, res, next) {
res.set("Access-Control-Allow-Origin", "*");
next();
});
// fake handler for the books endpoints
app.get("/books/:isbn", function (req, res) {
var isbn = req.param("isbn");
res.jsonp({
isbn: isbn,
title: "Title of " + isbn,
author: "Author of " + isbn,
});
});
// fake handler for the books endpoints
app.get("/books/:isbn/prices", function (req, res) {
var isbn = req.param("isbn");
res.jsonp([
{ price: 56.78 },
{ price: 12.34 },
{ price: 34.56 },
]);
});
// 404 everything
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
return app;
};
| "use strict";
var express = require("express");
module.exports = function () {
var app = express();
// Allow all domains to request data (see CORS for more details)
app.use(function (req, res, next) {
res.set("Access-Control-Allow-Origin", "*");
next();
});
// fake handler for the books endpoints
app.get("/books/:isbn", function (req, res) {
var isbn = req.param("isbn");
res.jsonp({
isbn: isbn,
title: "Title of " + isbn,
author: "Author of " + isbn,
});
});
// 404 everything
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
return app;
};
|
Revert "small refactor: use _.once only for watch"
This reverts commit 6de0d1f1cc11374b412bf26103ab5c29afbeee0a. | 'use strict';
const _ = require('lodash/fp');
const webpack = require('webpack');
const wpConfig = require('../../config/webpack.config.specs');
const {watchMode} = require('../utils');
module.exports = (gulp, plugins) => {
gulp.task('bundle:specs', done => {
plugins.util.log('Bundling specs with Webpack');
const compiler = webpack(wpConfig);
const callback = _.compose(_.once(done), printErrors);
if (watchMode()) {
compiler.watch({}, callback);
} else {
compiler.run(callback);
}
});
function printErrors(err, stats) {
const message = err ?
err.toString() :
stats.toString({
colors: true,
hash: false,
chunks: false,
assets: false,
children: false
});
plugins.util.log(message);
if (err || stats.hasErrors()) {
return message;
}
}
};
| 'use strict';
const _ = require('lodash/fp');
const webpack = require('webpack');
const wpConfig = require('../../config/webpack.config.specs');
const {watchMode} = require('../utils');
module.exports = (gulp, plugins) => {
gulp.task('bundle:specs', done => {
plugins.util.log('Bundling specs with Webpack');
const compiler = webpack(wpConfig);
const callback = _.compose(done, printErrors);
if (watchMode()) {
compiler.watch({}, _.once(callback));
} else {
compiler.run(callback);
}
});
function printErrors(err, stats) {
const message = err ?
err.toString() :
stats.toString({
colors: true,
hash: false,
chunks: false,
assets: false,
children: false
});
plugins.util.log(message);
if (err || stats.hasErrors()) {
return message;
}
}
};
|
Hide loading icon for unauthorized
Fixes #44 | // Ensure namespace housing exists
var housing = housing || {};
/**
* housing.app
*
* This is the entry point for the housing selection application.
* This function sets up elements on the page for the housing library
* functions in housing.js so that changes can be made to the page
* template HTML without interfering with the operation of the
* housing.js library.
*/
housing.app = function(authorized) {
// Select active elements of page
// These are regions that will be filled by housing.js
var nav = d3.select("#floornav");
if(authorized) {
// If authorized, clear the navigation bar and the SVG element
nav.html(null);
var svg = d3.select("#selection")
.html(null)
.append("svg")
.attr("width",768)
.attr("height",609);
housing.client.load(svg,nav);
} else {
// If not signed in, clear navigation and insert signin button.
nav.html(null);
nav.append("a")
.classed("button",true)
.text("Sign In")
.on("click",housing.auth.click);
$("#loading").hide();
}
}
| // Ensure namespace housing exists
var housing = housing || {};
/**
* housing.app
*
* This is the entry point for the housing selection application.
* This function sets up elements on the page for the housing library
* functions in housing.js so that changes can be made to the page
* template HTML without interfering with the operation of the
* housing.js library.
*/
housing.app = function(authorized) {
// Select active elements of page
// These are regions that will be filled by housing.js
var nav = d3.select("#floornav");
if(authorized) {
// If authorized, clear the navigation bar and the SVG element
nav.html(null);
var svg = d3.select("#selection")
.html(null)
.append("svg")
.attr("width",768)
.attr("height",609);
housing.client.load(svg,nav);
} else {
// If not signed in, clear navigation and insert signin button.
nav.html(null);
nav.append("a")
.classed("button",true)
.text("Sign In")
.on("click",housing.auth.click);
}
}
|
Update new recs view and controller 2 | craftEd.controller('RecsController', ['$scope', '$http', '$location', function($scope, $http, $location){
var config = {
headers: {
'content-type': 'application/json'
}
};
var tokens = {
headers: {
"access-token": window.sessionStorage.token,
"token-type": "Bearer",
"client": window.sessionStorage.client,
"expiry": window.sessionStorage.expiry,
"uid": window.sessionStorage.uid
}
};
var tokensConfig = {
headers: {
'content-type': 'application/json',
"access-token": window.sessionStorage.token,
"token-type": "Bearer",
"client": window.sessionStorage.client,
"expiry": window.sessionStorage.expiry,
"uid": window.sessionStorage.uid
}
};
$http.get(rootUrl + '/users/:id/beer_types/rec_new', tokens)
.then(function(response){
$scope.allNewRecs= response.data
$scope.rootUrl= rootUrl
});
$scope.selectBeer = function(newRecId){
$http.get(rootUrl +'/users/:user_id/beer_types/' + newRecId + '/tried_beer_ratings/new', tokens)
$location.path('/rating');
}
}]);
| craftEd.controller('RecsController', ['$scope', '$http', '$location', function($scope, $http, $location){
var config = {
headers: {
'content-type': 'application/json'
}
};
var tokens = {
headers: {
"access-token": window.sessionStorage.token,
"token-type": "Bearer",
"client": window.sessionStorage.client,
"expiry": window.sessionStorage.expiry,
"uid": window.sessionStorage.uid
}
};
var tokensConfig = {
headers: {
'content-type': 'application/json',
"access-token": window.sessionStorage.token,
"token-type": "Bearer",
"client": window.sessionStorage.client,
"expiry": window.sessionStorage.expiry,
"uid": window.sessionStorage.uid
}
};
$http.get(rootUrl + '/users/:id/beer_types/rec_new', tokens)
.then(function(response){
$scope.allNewRecs= response.data
$scope.rootUrl= rootUrl
});
$scope.selectBeer = function(newRecId){
console.log(rootUrl +'/users/:user_id/beer_types/' + newRecId + '/tried_beer_ratings/new')
$http.get(rootUrl +'/users/:user_id/beer_types/' + newRecId + '/tried_beer_ratings/new', tokens)
$location.path('/rating');
}
}]);
|
Print error if the composition file cannot be found | package eu.netide.core.management.cli;
import eu.netide.core.api.IBackendManager;
import eu.netide.core.management.ManagementHandler;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Created by arne on 04.02.16.
*/
@Command(scope = "netide", name = "loadComposition", description = "Load a composition XML file")
public class LoadComposition extends OsgiCommandSupport {
@Argument(index = 0, name = "compositionFile", description = "The composition xml file to load", required = true, multiValued = false)
String compositionFile;
@Override
protected Object doExecute() throws Exception {
try {
Path path = Paths.get(compositionFile).toAbsolutePath();
String spec = new String(Files.readAllBytes(path));
ManagementHandler.setConfigurationValue("eu.netide.core.caos", "compositionSpecification", spec);
} catch (java.nio.file.NoSuchFileException nsf) {
System.out.printf("Composititon file %s not found.\n", compositionFile);
}
return null;
}
}
| package eu.netide.core.management.cli;
import eu.netide.core.api.IBackendManager;
import eu.netide.core.management.ManagementHandler;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Created by arne on 04.02.16.
*/
@Command(scope = "netide", name = "loadComposition", description = "Load a composition XML file")
public class LoadComposition extends OsgiCommandSupport {
@Argument(index = 0, name = "compositionFile", description = "The composition xml file to load", required = true, multiValued = false)
String compositionFile;
@Override
protected Object doExecute() throws Exception {
Path path = Paths.get(compositionFile).toAbsolutePath();
String spec = new String(Files.readAllBytes(path));
ManagementHandler.setConfigurationValue("eu.netide.core.caos", "compositionSpecification", spec);
return null;
}
}
|
Fix fetch api when returning non-JSON | export default class HttpApi {
constructor (prefix = '') {
this.prefix = prefix
this.opts = {
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json',
})
}
return this.callApi
}
callApi = (method, url, opts = {}) => {
opts = Object.assign({}, this.opts, opts)
opts.method = method
if (typeof opts.body === 'object') {
opts.body = JSON.stringify(opts.body)
}
return fetch(`/api/${this.prefix}${url}`, opts)
.then(res => {
if (res.ok) {
const type = res.headers.get('Content-Type')
return (type && type.includes('application/json')) ? res.json() : res
}
// error
return res.text().then(txt => {
return Promise.reject(new Error(txt))
})
})
}
}
| export default class HttpApi {
constructor (prefix = '') {
this.prefix = prefix
this.opts = {
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json',
})
}
return this.callApi
}
callApi = (method, url, opts = {}) => {
opts = Object.assign({}, this.opts, opts)
opts.method = method
if (typeof opts.body === 'object') {
opts.body = JSON.stringify(opts.body)
}
return fetch(`/api/${this.prefix}${url}`, opts)
.then(res => {
if (res.ok) {
const type = res.headers.get('Content-Type')
return (type && type.includes('application/json')) ? res.json() : res.text()
}
// error
return res.text().then(txt => {
return Promise.reject(new Error(txt))
})
})
}
}
|
Remove extraneous quote in asserter dockstring | from pprint import pformat
def assert_calls_equal(expected, actual):
"""
Check whether the given mock object (or mock method) calls are equal and
return a nicely formatted message.
"""
if not expected == actual:
raise_calls_differ_error(expected, actual)
def raise_calls_differ_error(expected, actual):
"""
Raise an AssertionError with pretty print format for the given expected
and actual mock calls in order to ensure consistent print style for better
readability.
"""
expected_str = pformat(expected)
actual_str = pformat(actual)
msg = '\nMock calls differ!\nExpected calls:\n%s\nActual calls:\n%s' % (expected_str,
actual_str)
raise AssertionError(msg)
def assert_calls_equal_unsorted(expected, actual):
"""
Raises an AssertionError if the two iterables do not contain the same items.
The order of the items is ignored
"""
for expected in expected:
if expected not in actual:
raise_calls_differ_error(expected, actual)
| from pprint import pformat
def assert_calls_equal(expected, actual):
"""
Check whether the given mock object (or mock method) calls are equal and
return a nicely formatted message.
"""
if not expected == actual:
raise_calls_differ_error(expected, actual)
def raise_calls_differ_error(expected, actual):
""""
Raise an AssertionError with pretty print format for the given expected
and actual mock calls in order to ensure consistent print style for better
readability.
"""
expected_str = pformat(expected)
actual_str = pformat(actual)
msg = '\nMock calls differ!\nExpected calls:\n%s\nActual calls:\n%s' % (expected_str,
actual_str)
raise AssertionError(msg)
def assert_calls_equal_unsorted(expected, actual):
"""
Raises an AssertionError if the two iterables do not contain the same items.
The order of the items is ignored
"""
for expected in expected:
if expected not in actual:
raise_calls_differ_error(expected, actual)
|
Save selected theme in localStorage | 'use strict';
var $themeIcons = null;
var $themeLink = null;
var storage = (function () {
var key = 'theme';
return {
load: function () {
return window.localStorage[key];
},
save: function (name) {
window.localStorage[key] = name;
}
};
}());
var loadTheme = function (theme) {
$themeLink.href = theme.src;
};
var putIcon = (function () {
var newIcon = function () {
var div = document.createElement('div');
div.className = 'icon';
$themeIcons.appendChild(div);
return div;
};
return function (color) {
var icon = newIcon();
icon.style.backgroundColor = color;
return icon;
};
}());
var installTheme = function (theme) {
var icon = putIcon(theme.icon);
icon.title = 'Change theme: ' + theme.name;
icon.addEventListener('click', function () {
loadTheme(theme);
storage.save(theme.name);
});
};
exports.init = function () {
$themeIcons = document.getElementById('theme-icons');
$themeLink = document.getElementById('theme');
var themes = require('../themes.json');
var themeByName = Object.create(null);
themes.reverse().forEach(function (theme) {
installTheme(theme);
themeByName[theme.name] = theme;
});
var savedTheme = storage.load();
if (savedTheme && themeByName[savedTheme]) {
loadTheme(themeByName[savedTheme]);
}
};
| 'use strict';
var themeIcons = null;
var themeLink = null;
var loadTheme = function (src) {
themeLink.href = src;
};
var putIcon = (function () {
var newIcon = function () {
var div = document.createElement('div');
div.className = 'icon';
themeIcons.appendChild(div);
return div;
};
return function (color) {
var icon = newIcon();
icon.style.backgroundColor = color;
return icon;
};
}());
var installTheme = function (theme) {
var icon = putIcon(theme.icon);
icon.title = 'Change theme: ' + theme.name;
icon.addEventListener('click', loadTheme.bind(null, theme.src));
};
exports.init = function () {
themeIcons = document.getElementById('theme-icons');
themeLink = document.getElementById('theme');
var themes = require('../themes.json');
themes.reverse().forEach(installTheme);
};
|
Set collected css classes on set operators | var RoundNode = require("./RoundNode");
module.exports = (function () {
var radius = 40;
var o = function (graph) {
RoundNode.apply(this, arguments);
var that = this,
superHoverHighlightingFunction = that.setHoverHighlighting,
superPostDrawActions = that.postDrawActions;
this.radius(radius);
this.setHoverHighlighting = function (enable) {
superHoverHighlightingFunction(enable);
// Highlight connected links when hovering the set operator
d3.selectAll(".link ." + that.cssClassOfNode()).classed("hovered", enable);
};
this.draw = function (element) {
that.nodeElement(element);
element.append("circle")
.attr("class", that.collectCssClasses().join(" "))
.classed("class", true)
.classed("dashed", true)
.attr("r", that.actualRadius());
};
this.postDrawActions = function () {
superPostDrawActions();
that.textBlock().clear();
that.textBlock().addInstanceCount(that.individuals().length);
that.textBlock().setTranslation(0, 10);
};
};
o.prototype = Object.create(RoundNode.prototype);
o.prototype.constructor = o;
return o;
}());
| var RoundNode = require("./RoundNode");
module.exports = (function () {
var radius = 40;
var o = function (graph) {
RoundNode.apply(this, arguments);
var that = this,
superHoverHighlightingFunction = that.setHoverHighlighting,
superPostDrawActions = that.postDrawActions;
this.radius(radius);
this.setHoverHighlighting = function (enable) {
superHoverHighlightingFunction(enable);
// Highlight connected links when hovering the set operator
d3.selectAll(".link ." + that.cssClassOfNode()).classed("hovered", enable);
};
this.draw = function (element) {
that.nodeElement(element);
element.append("circle")
.attr("class", that.type())
.classed("class", true)
.classed("dashed", true)
.attr("r", that.actualRadius());
};
this.postDrawActions = function () {
superPostDrawActions();
that.textBlock().clear();
that.textBlock().addInstanceCount(that.individuals().length);
that.textBlock().setTranslation(0, 10);
};
};
o.prototype = Object.create(RoundNode.prototype);
o.prototype.constructor = o;
return o;
}());
|
Disable INFO messages and down when running test suite | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import nose
import logging
logging.disable(logging.INFO) # Disable debug logging when running the test suite.
def start(argv=None):
sys.exitfunc = lambda: sys.stderr.write('Shutting down...\n')
if argv is None:
argv = [
'nosetests',
'--verbose',
'--with-coverage',
'--cover-html', '--cover-html-dir=.htmlcov',
'--cover-erase',
'--cover-branches',
'--cover-package=chemtrails',
]
nose.run_exit(argv=argv, defaultTest=os.path.abspath(os.path.dirname(__file__)))
if __name__ == '__main__':
start(sys.argv)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import nose
import logging
logging.disable(logging.DEBUG) # Disable debug logging when running the test suite.
def start(argv=None):
sys.exitfunc = lambda: sys.stderr.write('Shutting down...\n')
if argv is None:
argv = [
'nosetests',
'--verbose',
'--with-coverage',
'--cover-html', '--cover-html-dir=.htmlcov',
'--cover-erase',
'--cover-branches',
'--cover-package=chemtrails',
]
nose.run_exit(argv=argv, defaultTest=os.path.abspath(os.path.dirname(__file__)))
if __name__ == '__main__':
start(sys.argv)
|
Fix the issue that xip.io can not be set in catalog | import Component from '@ember/component';
import { next } from '@ember/runloop';
import { get, set, observer } from '@ember/object'
import layout from './template';
import { inject as service } from '@ember/service';
import C from 'shared/utils/constants';
export default Component.extend({
settings: service(),
layout,
value: '',
mode: 'automatic',
init() {
this._super(...arguments);
const xip = get(this, `settings.${C.SETTING.INGRESS_IP_DOMAIN}`);
const host = get(this, 'value');
if ( host && host === xip ) {
set(this, 'mode', 'automatic');
} else if ( host ) {
set(this, 'mode', 'manual');
}
next(() => {
this.modeChanged();
});
},
modeChanged: observer('mode', function() {
const mode = get(this, 'mode');
const xip = get(this, `settings.${C.SETTING.INGRESS_IP_DOMAIN}`);
if ( mode === 'automatic' ) {
set(this, 'value', xip);
} else {
if ( get(this, 'value') === xip ) {
set(this, 'value', '');
}
}
}),
});
| import Component from '@ember/component';
import { get, set, observer } from '@ember/object'
import layout from './template';
import { inject as service } from '@ember/service';
import C from 'shared/utils/constants';
export default Component.extend({
settings: service(),
layout,
value: '',
mode: 'automatic',
init() {
this._super(...arguments);
const xip = get(this, `settings.${C.SETTING.INGRESS_IP_DOMAIN}`);
const host = get(this, 'value');
if ( host && host === xip ) {
set(this, 'mode', 'automatic');
} else if ( host ) {
set(this, 'mode', 'manual');
}
this.modeChanged();
},
modeChanged: observer('mode', function() {
const mode = get(this, 'mode');
const xip = get(this, `settings.${C.SETTING.INGRESS_IP_DOMAIN}`);
if ( mode === 'automatic' ) {
set(this, 'value', xip);
} else {
if ( get(this, 'value') === xip ) {
set(this, 'value', '');
}
}
}),
});
|
Add route recursive for open all level trad | 'use strict'
/**
* @ngdoc overview
* @name serinaApp
* @description
* # serinaApp
*
* Main module of the application.
*/
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.when('/lang/:lang/:group*', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
})
| 'use strict'
/**
* @ngdoc overview
* @name serinaApp
* @description
* # serinaApp
*
* Main module of the application.
*/
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
})
|
Move User/Group/Company management to plugin-id | package org.ligoj.app.resource.message;
import org.ligoj.app.api.NodeVo;
import org.ligoj.app.api.SimpleUser;
import org.ligoj.app.model.Message;
import org.ligoj.app.plugin.id.resource.ContainerWithScopeVo;
import org.ligoj.app.resource.project.ProjectLightVo;
import lombok.Getter;
import lombok.Setter;
/**
* A message to target audience and with detailed information from the source.
*/
@Getter
@Setter
public class MessageVo extends Message {
/**
* SID
*/
private static final long serialVersionUID = 1L;
/**
* Optional project targeted by this message.
*/
private ProjectLightVo project;
/**
* Optional user details source of this message.
*/
private SimpleUser from;
/**
* Optional user targeted by this message.
*/
private SimpleUser user;
/**
* Optional node details targeted by this message.
*/
private NodeVo node;
/**
* Optional group details targeted by this message.
*/
private ContainerWithScopeVo group;
/**
* Optional company details targeted by this message.
*/
private ContainerWithScopeVo company;
/**
* Message state. When <code>true</code> this message is new for a specific message.
*/
private boolean unread;
}
| package org.ligoj.app.resource.message;
import org.ligoj.app.api.NodeVo;
import org.ligoj.app.api.SimpleUser;
import org.ligoj.app.model.Message;
import org.ligoj.app.plugin.id.resource.ContainerWithTypeVo;
import org.ligoj.app.resource.project.ProjectLightVo;
import lombok.Getter;
import lombok.Setter;
/**
* A message to target audience and with detailed information from the source.
*/
@Getter
@Setter
public class MessageVo extends Message {
/**
* SID
*/
private static final long serialVersionUID = 1L;
/**
* Optional project targeted by this message.
*/
private ProjectLightVo project;
/**
* Optional user details source of this message.
*/
private SimpleUser from;
/**
* Optional user targeted by this message.
*/
private SimpleUser user;
/**
* Optional node details targeted by this message.
*/
private NodeVo node;
/**
* Optional group details targeted by this message.
*/
private ContainerWithTypeVo group;
/**
* Optional company details targeted by this message.
*/
private ContainerWithTypeVo company;
/**
* Message state. When <code>true</code> this message is new for a specific message.
*/
private boolean unread;
}
|
Use file path to find catalog.xml file | package au.gov.ga.geodesy.support.spring;
import java.io.FileNotFoundException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import au.gov.ga.geodesy.domain.model.SynchronousEventPublisher;
import au.gov.ga.geodesy.domain.model.event.EventPublisher;
import au.gov.ga.geodesy.port.adapter.geodesyml.GeodesyMLValidator;
@Configuration
public class GeodesyServiceTestConfig extends GeodesyServiceConfig {
@Bean
@Override
public EventPublisher eventPublisher() {
return new SynchronousEventPublisher();
}
@Bean
public GeodesyMLValidator getGeodesyMLValidator() throws FileNotFoundException {
String catalog = ResourceUtils.getFile("file:target/generated-resources/xsd/geodesyml-1.0.0-SNAPSHOT/catalog.xml").getAbsolutePath();
return new GeodesyMLValidator(catalog);
}
}
| package au.gov.ga.geodesy.support.spring;
import java.io.FileNotFoundException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import au.gov.ga.geodesy.domain.model.SynchronousEventPublisher;
import au.gov.ga.geodesy.domain.model.event.EventPublisher;
import au.gov.ga.geodesy.port.adapter.geodesyml.GeodesyMLValidator;
@Configuration
public class GeodesyServiceTestConfig extends GeodesyServiceConfig {
@Bean
@Override
public EventPublisher eventPublisher() {
return new SynchronousEventPublisher();
}
@Bean
public GeodesyMLValidator getGeodesyMLValidator() throws FileNotFoundException {
String catalog = ResourceUtils.getFile("classpath:xsd/geodesyml-1.0.0-SNAPSHOT/catalog.xml").getAbsolutePath();
return new GeodesyMLValidator(catalog);
}
}
|
Change name separator of the endpoint (can't use pipe duh). | var semver = require('semver');
var createError = require('./createError');
function decompose(endpoint) {
var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)=)?([^\|#]+)(?:#(.*))?$/;
var matches = endpoint.match(regExp);
if (!matches) {
throw createError('Invalid endpoint: "' + endpoint + '"', 'EINVEND');
}
return {
name: matches[1] || '',
source: matches[2],
target: matches[3] || '*'
};
}
function compose(decEndpoint) {
var composed = '';
if (decEndpoint.name) {
composed += decEndpoint.name + '=';
}
composed += decEndpoint.source;
if (decEndpoint.target) {
composed += '#' + decEndpoint.target;
}
return composed;
}
function json2decomposed(key, value) {
var endpoint = key + '=';
if (semver.valid(value) != null || semver.validRange(value) != null) {
endpoint += key + '#' + value;
} else {
endpoint += value;
}
return decompose(endpoint);
}
module.exports.decompose = decompose;
module.exports.compose = compose;
module.exports.json2decomposed = json2decomposed;
| var semver = require('semver');
var createError = require('./createError');
function decompose(endpoint) {
var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)\|)?([^\|#]+)(?:#(.*))?$/;
var matches = endpoint.match(regExp);
if (!matches) {
throw createError('Invalid endpoint: "' + endpoint + '"', 'EINVEND');
}
return {
name: matches[1] || '',
source: matches[2],
target: matches[3] || '*'
};
}
function compose(decEndpoint) {
var composed = '';
if (decEndpoint.name) {
composed += decEndpoint.name + '|';
}
composed += decEndpoint.source;
if (decEndpoint.target) {
composed += '#' + decEndpoint.target;
}
return composed;
}
function json2decomposed(key, value) {
var endpoint = key + '|';
if (semver.valid(value) != null || semver.validRange(value) != null) {
endpoint += key + '#' + value;
} else {
endpoint += value;
}
return decompose(endpoint);
}
module.exports.decompose = decompose;
module.exports.compose = compose;
module.exports.json2decomposed = json2decomposed;
|
Clean up pulling README.rst and CHANGELOG.rst into the long_description | #!/usr/bin/env python
import twelve
import twelve.adapters
import twelve.services
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="twelve",
version=twelve.__version__,
description="12factor inspired settings for a variety of backing services archetypes.",
long_description="\n\n".join([open("README.rst").read(), open("CHANGELOG.rst").read()]),
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
url="https://crate.io/packages/twelve/",
packages=[
"twelve",
],
package_data={"": ["LICENSE"]},
include_package_data=True,
install_requires=[
"extensions"
],
license=open("LICENSE").read(),
classifiers=(
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
),
)
| #!/usr/bin/env python
import twelve
import twelve.adapters
import twelve.services
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="twelve",
version=twelve.__version__,
description="12factor inspired settings for a variety of backing services archetypes.",
long_description=open("README.rst").read() + '\n\n' +
open("CHANGELOG.rst").read(),
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
url="https://crate.io/packages/twelve/",
packages=[
"twelve",
],
package_data={"": ["LICENSE"]},
include_package_data=True,
install_requires=[
"extensions"
],
license=open("LICENSE").read(),
classifiers=(
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
),
)
|
examples: Add missing uppy.socket call to S3 example | const uppy = require('uppy-server')
const app = require('express')()
app.use(require('cors')())
app.use(require('body-parser').json())
const options = {
providerOptions: {
s3: {
getKey: (req, filename) =>
`whatever/${Math.random().toString(32).slice(2)}/${filename}`,
key: process.env.UPPYSERVER_AWS_KEY,
secret: process.env.UPPYSERVER_AWS_SECRET,
bucket: process.env.UPPYSERVER_AWS_BUCKET,
region: process.env.UPPYSERVER_AWS_REGION
}
},
server: { host: 'localhost:3020' }
}
app.use(uppy.app(options))
const server = app.listen(3020, () => {
console.log('listening on port 3020')
})
uppy.socket(server, options)
| const uppy = require('uppy-server')
const app = require('express')()
app.use(require('cors')())
app.use(require('body-parser').json())
app.use(uppy.app({
providerOptions: {
s3: {
getKey: (req, filename) =>
`whatever/${Math.random().toString(32).slice(2)}/${filename}`,
key: process.env.UPPYSERVER_AWS_KEY,
secret: process.env.UPPYSERVER_AWS_SECRET,
bucket: process.env.UPPYSERVER_AWS_BUCKET,
region: process.env.UPPYSERVER_AWS_REGION
}
},
server: { host: 'localhost:3020' }
}))
app.listen(3020, () => {
console.log('listening on port 3020')
})
|
Add missing id fields in readings and events
Signed-off-by: Federico Claramonte <9aaaa8bfe6a7a51765b462c528e1446dcf049286@caviumnetworks.com> | //
// Copyright (c) 2017 Mainflux
//
// SPDX-License-Identifier: Apache-2.0
//
package export
// Message - Encapsulating / wrapper message object that contains Event
// to be exported and the client export registration details
type Message struct {
Registration Registration
Evt Event
}
// Event - packet of Readings
type Event struct {
ID string `json:"id,omitempty"`
Pushed int64 `json:"pushed"`
Device string `json:"device,omitempty"`
Readings []Reading `json:"readings,omitempty"`
Created int64 `json:"created"`
Modified int64 `json:"modified"`
Origin int64 `json:"origin"`
}
// Reading - Sensor measurement
type Reading struct {
ID string `json:"id,omitempty"`
Pushed int64 `json:"pushed"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
Device string `json:"device,omitempty"`
Created int64 `json:"created"`
Modified int64 `json:"modified"`
Origin int64 `json:"origin"`
}
| //
// Copyright (c) 2017 Mainflux
//
// SPDX-License-Identifier: Apache-2.0
//
package export
// Message - Encapsulating / wrapper message object that contains Event
// to be exported and the client export registration details
type Message struct {
Registration Registration
Evt Event
}
// Event - packet of Readings
type Event struct {
Pushed int64 `json:"pushed"`
Device string `json:"device,omitempty"`
Readings []Reading `json:"readings,omitempty"`
Created int64 `json:"created"`
Modified int64 `json:"modified"`
Origin int64 `json:"origin"`
}
// Reading - Sensor measurement
type Reading struct {
Pushed int64 `json:"pushed"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
Device string `json:"device,omitempty"`
Created int64 `json:"created"`
Modified int64 `json:"modified"`
Origin int64 `json:"origin"`
}
|
Fix on teeny tiny little typo... Also remember to write commit messages in the present tense. | people = 30
cars = 40
buses = 55
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
# Study Drills
if (buses > cars and cars > people):
print "The buses out number us... DECEPTICONS!!"
elif (buses > cars and cars < people):
print "This line won't print... just trust me. *peers through console*"
else:
print "If this line actually prints, I'll go to bed. I dare you to try."
| people = 30
cars = 40
buses = 55
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
# Study Drills
if (buses > cars and cars > people):
print "The buses out numbers us... DECEPTICONS!!"
elif (buses > cars and cars < people):
print "This line won't print... just trust me. *peers through console*"
else:
print "If this line actually prints, I'll go to bed. I dare you to try."
|
Store the player keys in the preserved games | from persistent_dict import *
class PreservedGame():
def __init__(self, game):
self.rules = game.rules # .clone?
self.player = [None, game.player[1].key(), game.player[2].key()]
self.move_history = game.move_history[:]
def game_name(self):
return "Freddo" # TODO
class AllPreservedGames():
def __init__(self, filename):
self.games = PersistentDict(filename, 'c', format='pickle')
def add_game(self, pg):
self.games[pg.game_name()] = pg
self.games.sync()
def preserving(self):
return cfp
'''
# TODO
with PersistentDict('/tmp/demo.json', 'c', format='json') as d:
print(d, 'start')
d['abc'] = '123'
d['rand'] = random.randrange(10000)
print(d, 'updated')
# Show what the file looks like on disk
with open('/tmp/demo.json', 'rb') as f:
print(f.read())
'''
| from persistent_dict import *
class PreservedGame():
def game_name(self):
return "Freddo" # TODO
class AllPreservedGames():
def __init__(self, filename):
self.games = PersistentDict(filename, 'c', format='pickle')
def add_game(self, pg):
self.games[pg.game_name()] = pg
self.games.sync()
'''
# TODO
with PersistentDict('/tmp/demo.json', 'c', format='json') as d:
print(d, 'start')
d['abc'] = '123'
d['rand'] = random.randrange(10000)
print(d, 'updated')
# Show what the file looks like on disk
with open('/tmp/demo.json', 'rb') as f:
print(f.read())
'''
|
Add login failed flash message | from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(r):
c = {}
if r.POST:
username = r.POST['username']
password = r.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
auth_login(r, user)
if not Cloud.objects.filter(account=user).exists():
return HttpResponseRedirect(reverse('connect-view'))
return HttpResponseRedirect(reverse('myservers-view'))
c['errors'] = "Login failed, please try again"
return render(r, 'auth.html', c)
def logout(request):
auth_logout(request)
return HttpResponseRedirect(reverse('index-view'))
@login_required
def connect(request):
return render(request, 'connect.html')
| from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(r):
if r.POST:
username = r.POST['username']
password = r.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
auth_login(r, user)
if not Cloud.objects.filter(account=user).exists():
return HttpResponseRedirect(reverse('connect-view'))
return HttpResponseRedirect(reverse('myservers-view'))
return render(r, 'auth.html')
def logout(request):
auth_logout(request)
return HttpResponseRedirect(reverse('index-view'))
@login_required
def connect(request):
return render(request, 'connect.html')
|
Fix flake8 error in travis | from flask import abort, Blueprint, jsonify
from httpobs import SOURCE_URL, VERSION
from httpobs.database import get_cursor
monitoring_api = Blueprint('monitoring-api', __name__)
@monitoring_api.route('/__heartbeat__')
def heartbeat():
# TODO: check celery status
try:
# Check the database
with get_cursor() as _: # noqa
pass
except:
abort(500)
return jsonify({'database': 'OK'})
@monitoring_api.route('/__lbheartbeat__')
def lbheartbeat():
return ''
@monitoring_api.route('/__version__')
def version():
return jsonify({'source': SOURCE_URL,
'version': VERSION})
| from flask import abort, Blueprint, jsonify
from httpobs import SOURCE_URL, VERSION
from httpobs.conf import BROKER_URL
from httpobs.database import get_cursor
import kombu
monitoring_api = Blueprint('monitoring-api', __name__)
@monitoring_api.route('/__heartbeat__')
def heartbeat():
# TODO: check celery status
try:
# Check the database
with get_cursor() as _: # noqa
pass
except:
abort(500)
return jsonify({'database': 'OK'})
@monitoring_api.route('/__lbheartbeat__')
def lbheartbeat():
return ''
@monitoring_api.route('/__version__')
def version():
return jsonify({'source': SOURCE_URL,
'version': VERSION})
|
Fix the "skip over files beginning with a dot" feature | <?php
/**
* Functions file
*
* This file is for general purpose functions required by the front controller
* and any other output-related features.
*
* @version 1.0.3
* @author Teppo Koivula <teppo.koivula@gmail.com>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License, version 2
*/
/**
* Fetch a list of files recursively
*
* @param string $path Base directory
* @param string $ext File extension
* @return stdClass
*/
function getFilesRecursive($path, $ext) {
$files = array();
foreach (glob($path) as $file) {
$name = basename($file);
if (strpos($name, ".") === 0) continue;
if (is_dir($file)) {
$files[$name] = getFilesRecursive("{$file}/*", $ext);
} else if (strrpos($name, $ext) === strlen($name)-strlen($ext)) {
$files[substr($name, 0, strrpos($name, "."))] = $file;
}
}
return (object) $files;
}
| <?php
/**
* Functions file
*
* This file is for general purpose functions required by the front controller
* and any other output-related features.
*
* @version 1.0.2
* @author Teppo Koivula <teppo.koivula@gmail.com>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License, version 2
*/
/**
* Fetch a list of files recursively
*
* @param string $path Base directory
* @param string $ext File extension
* @return stdClass
*/
function getFilesRecursive($path, $ext) {
$files = array();
foreach (glob($path) as $file) {
if (strpos($name, ".") === 0) continue;
$name = basename($file);
if (is_dir($file)) {
$files[$name] = getFilesRecursive("{$file}/*", $ext);
} else if (strrpos($name, $ext) === strlen($name)-strlen($ext)) {
$files[substr($name, 0, strrpos($name, "."))] = $file;
}
}
return (object) $files;
}
|
Add missing preventDefault when opening links in _blank window | $(document).on('click', 'a', function(event) {
var lnk = event.currentTarget;
//for backwards compatibility
var rels = lnk.rel.split(' ');
$.each(rels, function() {
if (this.match(/^popup/)) {
var relProperties = this.split('_');
//$(lnk).addClass('webLinkPopup');
if (relProperties[1] == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', relProperties[1]);
}
event.preventDefault();
}
});
if ($(lnk).data('kwc-popup')) {
if ($(lnk).data('kwc-popup') == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', $(lnk).data('kwc-popup'));
}
event.preventDefault();
}
});
| $(document).on('click', 'a', function(event) {
var lnk = event.currentTarget;
//for backwards compatibility
var rels = lnk.rel.split(' ');
$.each(rels, function() {
if (this.match(/^popup/)) {
var relProperties = this.split('_');
//$(lnk).addClass('webLinkPopup');
if (relProperties[1] == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', relProperties[1]);
}
event.preventDefault();
}
});
if ($(lnk).data('kwc-popup')) {
if ($(lnk).data('kwc-popup') == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', $(lnk).data('kwc-popup'));
}
}
});
|
Split the version metric out to its own package | /*
Copyright 2016 The Kubernetes 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 main
import (
"github.com/spf13/pflag"
"k8s.io/kubernetes/cmd/kube-dns/app"
"k8s.io/kubernetes/cmd/kube-dns/app/options"
_ "k8s.io/kubernetes/pkg/client/metrics/prometheus" // for client metric registration
"k8s.io/kubernetes/pkg/util/flag"
"k8s.io/kubernetes/pkg/util/logs"
_ "k8s.io/kubernetes/pkg/version/prometheus" // for version metric registration
"k8s.io/kubernetes/pkg/version/verflag"
)
func main() {
config := options.NewKubeDNSConfig()
config.AddFlags(pflag.CommandLine)
flag.InitFlags()
logs.InitLogs()
defer logs.FlushLogs()
verflag.PrintAndExitIfRequested()
server := app.NewKubeDNSServerDefault(config)
server.Run()
}
| /*
Copyright 2016 The Kubernetes 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 main
import (
"github.com/spf13/pflag"
"k8s.io/kubernetes/cmd/kube-dns/app"
"k8s.io/kubernetes/cmd/kube-dns/app/options"
_ "k8s.io/kubernetes/pkg/client/metrics/prometheus" // for client metric registration
"k8s.io/kubernetes/pkg/util/flag"
"k8s.io/kubernetes/pkg/util/logs"
"k8s.io/kubernetes/pkg/version/verflag"
)
func main() {
config := options.NewKubeDNSConfig()
config.AddFlags(pflag.CommandLine)
flag.InitFlags()
logs.InitLogs()
defer logs.FlushLogs()
verflag.PrintAndExitIfRequested()
server := app.NewKubeDNSServerDefault(config)
server.Run()
}
|
Set the final version number | """Rachiopy setup script."""
from setuptools import find_packages, setup
from datetime import datetime
VERSION = "1.0.0"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy"
GITHUB_PATH = f"{GITHUB_USERNAME}/{GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{VERSION}.tar.gz"
PROJECT_URLS = {"Bug Reports": f"{GITHUB_URL}/issues"}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
setup(
name="RachioPy",
version=VERSION,
author="Robbert Verbruggen",
author_email="rfverbruggen@icloud.com",
packages=PACKAGES,
install_requires=["requests"],
url=GITHUB_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
license="MIT",
description="A Python module for the Rachio API.",
platforms="Cross Platform",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
],
)
| """Rachiopy setup script."""
from setuptools import find_packages, setup
from datetime import datetime
NOW = datetime.now().strftime("%m/%d/%Y%H%M%S")
VERSION = f"1.0.0-dev{NOW}"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy"
GITHUB_PATH = f"{GITHUB_USERNAME}/{GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{VERSION}.tar.gz"
PROJECT_URLS = {"Bug Reports": f"{GITHUB_URL}/issues"}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
setup(
name="RachioPy",
version=VERSION,
author="Robbert Verbruggen",
author_email="rfverbruggen@icloud.com",
packages=PACKAGES,
install_requires=["requests"],
url=GITHUB_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
license="MIT",
description="A Python module for the Rachio API.",
platforms="Cross Platform",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
],
)
|
Fix issue with startsWith not existing(?) | /* global angular */
angular.module('app')
.factory('Storage', function ($window) {
'use strict';
function getItem(key) {
var value = $window.localStorage.getItem(key);
if (value) {
return JSON.parse(value);
} else {
return null;
}
}
function setItem(key, value) {
$window.localStorage.setItem(key, JSON.stringify(value, function (key, value) {
if (key.slice(0, 2) === '$$') {
return undefined;
}
if (key === 'eventsource') {
return undefined;
}
return value;
}));
}
function removeItem(key) {
$window.localStorage.removeItem(key);
}
return {
getItem: getItem,
setItem: setItem,
removeItem: removeItem
};
});
| /* global angular */
angular.module('app')
.factory('Storage', function ($window) {
'use strict';
function getItem(key) {
var value = $window.localStorage.getItem(key);
if (value) {
return JSON.parse(value);
} else {
return null;
}
}
function setItem(key, value) {
$window.localStorage.setItem(key, JSON.stringify(value, function (key, value) {
if (key.startsWith('$$')) {
return undefined;
}
if (key === 'eventsource') {
return undefined;
}
return value;
}));
}
function removeItem(key) {
$window.localStorage.removeItem(key);
}
return {
getItem: getItem,
setItem: setItem,
removeItem: removeItem
};
});
|
Remove explicit named export from rollup | import babel from 'rollup-plugin-babel'
import babelrc from 'babelrc-rollup'
import replace from 'rollup-plugin-replace'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
let pkg = require('./package.json')
let external = Object.keys(pkg.peerDependencies)
const config = {
entry: 'src/index.js',
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
}),
resolve({
module: true,
jsnext: true,
main: true,
}),
commonjs(),
babel(babelrc({})),
],
external: external,
targets: [
{
dest: pkg.main,
format: 'umd',
moduleName: 'monthlyQuizDucks',
sourceMap: true,
},
{
dest: pkg.module,
format: 'es',
sourceMap: true,
},
],
}
export default config
| import babel from 'rollup-plugin-babel'
import babelrc from 'babelrc-rollup'
import replace from 'rollup-plugin-replace'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
let pkg = require('./package.json')
let external = Object.keys(pkg.peerDependencies)
const config = {
entry: 'src/index.js',
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
}),
resolve({
module: true,
jsnext: true,
main: true,
}),
commonjs({
namedExports: {
'node_modules/transducers.js/transducers.js': ['into', 'map'],
},
}),
babel(babelrc({})),
],
external: external,
targets: [
{
dest: pkg.main,
format: 'umd',
moduleName: 'monthlyQuizDucks',
sourceMap: true,
},
{
dest: pkg.module,
format: 'es',
sourceMap: true,
},
],
}
export default config
|
Fix BC for older PHPCodeCoverage versions | <?php
namespace Paraunit\Proxy\Coverage;
use Paraunit\Configuration\OutputFile;
use SebastianBergmann\CodeCoverage\Report\Text;
/**
* Class TextResult
* @package Paraunit\Proxy\Coverage
*/
class TextResult
{
/** @var Text */
private $text;
/**
* TextResult constructor.
*/
public function __construct()
{
$this->text = new Text(50, 90, false, false);
}
/**
* @param CodeCoverage $coverage
* @param bool $showColors
* @return string The actual text coverage
*/
public function process(CodeCoverage $coverage, $showColors = false)
{
return $this->text->process($coverage, $showColors);
}
/**
* @param CodeCoverage $coverage
* @param OutputFile $outputFile
* @throws \RuntimeException
*/
public function writeToFile(CodeCoverage $coverage, OutputFile $outputFile)
{
file_put_contents($outputFile->getFilePath(), $this->text->process($coverage, false));
}
}
| <?php
namespace Paraunit\Proxy\Coverage;
use Paraunit\Configuration\OutputFile;
use SebastianBergmann\CodeCoverage\Report\Text;
/**
* Class TextResult
* @package Paraunit\Proxy\Coverage
*/
class TextResult
{
/** @var Text */
private $text;
/**
* TextResult constructor.
*/
public function __construct()
{
$this->text = new Text();
}
/**
* @param CodeCoverage $coverage
* @param bool $showColors
* @return string The actual text coverage
*/
public function process(CodeCoverage $coverage, $showColors = false)
{
return $this->text->process($coverage, $showColors);
}
/**
* @param CodeCoverage $coverage
* @param OutputFile $outputFile
* @throws \RuntimeException
*/
public function writeToFile(CodeCoverage $coverage, OutputFile $outputFile)
{
file_put_contents($outputFile->getFilePath(), $this->text->process($coverage, false));
}
}
|
Fix deprecation notice: The method bindCallback will require a new argument in next major version
back_consumer_1 | consumer1 | [2019-05-24 12:57:13] php.INFO: User
Deprecated: The "Enqueue\Consumption\QueueConsumer::bindCallback()"
method will require a new "string|InteropQueue $queueName" argument in
the next major version of its parent class
"Enqueue\Consumption\QueueConsumerInterface", not defining it is
deprecated. {"exception":"[object] (ErrorException(code: 0): User
Deprecated: The \"Enqueue\\Consumption\\QueueConsumer::bindCallback()\"
method will require a new \"string|InteropQueue $queueName\" argument in
the next major version of its parent class
\"Enqueue\\Consumption\\QueueConsumerInterface\", not defining it is
deprecated. at /app/vendor/symfony/debug/DebugClassLoader.php:199)"} [] | <?php
namespace Enqueue\Consumption;
use Interop\Queue\Context;
use Interop\Queue\Processor;
use Interop\Queue\Queue as InteropQueue;
interface QueueConsumerInterface
{
/**
* In milliseconds.
*/
public function setReceiveTimeout(int $timeout): void;
/**
* In milliseconds.
*/
public function getReceiveTimeout(): int;
public function getContext(): Context;
/**
* @param string|InteropQueue $queueName
*/
public function bind($queueName, Processor $processor): self;
/**
* @param string|InteropQueue $queueName
*/
public function bindCallback($queueName, callable $processor): self;
/**
* Runtime extension - is an extension or a collection of extensions which could be set on runtime.
* Here's a good example: @see LimitsExtensionsCommandTrait.
*
* @param ExtensionInterface|null $runtimeExtension
*
* @throws \Exception
*/
public function consume(ExtensionInterface $runtimeExtension = null): void;
}
| <?php
namespace Enqueue\Consumption;
use Interop\Queue\Context;
use Interop\Queue\Processor;
use Interop\Queue\Queue as InteropQueue;
interface QueueConsumerInterface
{
/**
* In milliseconds.
*/
public function setReceiveTimeout(int $timeout): void;
/**
* In milliseconds.
*/
public function getReceiveTimeout(): int;
public function getContext(): Context;
/**
* @param string|InteropQueue $queueName
*/
public function bind($queueName, Processor $processor): self;
/**
* @param string|InteropQueue $queueName
* @param mixed $queue
*/
public function bindCallback($queue, callable $processor): self;
/**
* Runtime extension - is an extension or a collection of extensions which could be set on runtime.
* Here's a good example: @see LimitsExtensionsCommandTrait.
*
* @param ExtensionInterface|null $runtimeExtension
*
* @throws \Exception
*/
public function consume(ExtensionInterface $runtimeExtension = null): void;
}
|
Check that Apache Commons DBCP2 is on the classpath before trying to use it. | package org.springframework.cloud.service.relational;
import javax.sql.DataSource;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;
import static org.springframework.cloud.service.Util.hasClass;
/**
*
* @author Ramnivas Laddad
* @author Scott Frederick
*
* @param <SI> the {@link RelationalServiceInfo} type for the underlying database service
*/
public class BasicDbcpPooledDataSourceCreator<SI extends RelationalServiceInfo> extends DbcpLikePooledDataSourceCreator<SI> {
static final String DBCP2_BASIC_DATASOURCE = "org.apache.commons.dbcp2.BasicDataSource";
@Override
public DataSource create(RelationalServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig,
String driverClassName, String validationQuery) {
if (hasClass(DBCP2_BASIC_DATASOURCE)) {
logger.info("Found DBCP2 on the classpath. Using it for DataSource connection pooling.");
org.apache.commons.dbcp2.BasicDataSource ds = new org.apache.commons.dbcp2.BasicDataSource();
setBasicDataSourceProperties(ds, serviceInfo, serviceConnectorConfig, driverClassName, validationQuery);
return new UrlDecodingDataSource(ds, "url");
}
return null;
}
}
| package org.springframework.cloud.service.relational;
import javax.sql.DataSource;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;
/**
*
* @author Ramnivas Laddad
* @author Scott Frederick
*
* @param <SI> the {@link RelationalServiceInfo} type for the underlying database service
*/
public class BasicDbcpPooledDataSourceCreator<SI extends RelationalServiceInfo> extends DbcpLikePooledDataSourceCreator<SI> {
static final String DBCP2_BASIC_DATASOURCE = "org.apache.commons.dbcp2.BasicDataSource";
@Override
public DataSource create(RelationalServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig,
String driverClassName, String validationQuery) {
logger.info("Found DBCP2 on the classpath. Using it for DataSource connection pooling.");
org.apache.commons.dbcp2.BasicDataSource ds = new org.apache.commons.dbcp2.BasicDataSource();
setBasicDataSourceProperties(ds, serviceInfo, serviceConnectorConfig, driverClassName, validationQuery);
return new UrlDecodingDataSource(ds, "url");
}
}
|
Add feature: error handling for paste command | package me.jacobcrofts.simplestructureloader.commands;
import java.io.IOException;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.json.simple.parser.ParseException;
import me.jacobcrofts.simplestructureloader.api.StructureAPI;
import me.jacobcrofts.simplestructureloader.util.Selection;
public class CmdPasteStructure implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (player.getGameMode() == GameMode.CREATIVE && player.isOp()) {
Selection selection;
try {
selection = new Selection(StructureAPI.readFromFile("plugins/structures/" + args[0] + ".json"));
StructureAPI.placeStructure(selection, player.getLocation());
} catch (IOException | ParseException e) {
e.printStackTrace();
}
} else {
player.sendMessage(ChatColor.RED + "You do not have permission to execute this command.");
}
return true;
} else {
sender.sendMessage("Only players may perform this command.");
}
return false;
}
}
| package me.jacobcrofts.simplestructureloader.commands;
import java.io.IOException;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.json.simple.parser.ParseException;
import me.jacobcrofts.simplestructureloader.api.StructureAPI;
import me.jacobcrofts.simplestructureloader.util.Selection;
public class CmdPasteStructure implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Selection selection;
try {
selection = new Selection(StructureAPI.readFromFile("plugins/structures/" + args[0] + ".json"));
StructureAPI.placeStructure(selection, ((Player) sender).getLocation());
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return true;
}
return false;
}
}
|
Add query for deleting a migration | 'use strict';
module.exports = {
CREATE_MIGRATIONS_TABLE: `CREATE TABLE "_migrations" (
id SERIAL UNIQUE PRIMARY KEY,
version VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
date TIMESTAMP DEFAULT now()
);`,
CHECK_MIGRATIONS_TABLE_EXISTENCE: `SELECT EXISTS (
SELECT 1
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public'
AND c.relname = '_migrations'
AND c.relkind = 'r'
);`,
GET_LAST_VERSION_AND_MIGRATION: `SELECT
version,
name
FROM "_migrations"
ORDER BY id DESC
LIMIT 1`,
INSERT_MIGRATION: `INSERT INTO "_migrations"(version, name) VALUES ($1, $2);`,
DELETE_MIGRATION: `DELETE FROM "_migrations" WHERE version = $1 AND name = $2;`
};
| 'use strict';
module.exports = {
CREATE_MIGRATIONS_TABLE: `CREATE TABLE "_migrations" (
id SERIAL UNIQUE PRIMARY KEY,
version VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
date TIMESTAMP DEFAULT now()
);`,
CHECK_MIGRATIONS_TABLE_EXISTENCE: `SELECT EXISTS (
SELECT 1
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public'
AND c.relname = '_migrations'
AND c.relkind = 'r'
);`,
GET_LAST_VERSION_AND_MIGRATION: `SELECT
version,
name
FROM "_migrations"
ORDER BY id DESC
LIMIT 1`,
INSERT_MIGRATION: `INSERT INTO "_migrations"(version, name) VALUES ($1, $2);`
};
|
Fix the second parameter passing to onUpdate | /**
* @jsx React.DOM
*/
'use strict';
var React = require('react/addons');
var cx = React.addons.classSet;
var FormMixin = require('./FormMixin');
var FormFor = require('./FormFor');
var v = require('./validation');
var Form = React.createClass({
mixins: [FormMixin],
propTypes: {
component: React.PropTypes.component,
onChange: React.PropTypes.func,
onUpdate: React.PropTypes.func
},
render: function() {
var component = this.props.component;
var className = cx({
'rf-Form': true,
'rf-Form--invalid': v.isFailure(this.value().validation)
});
return this.transferPropsTo(
<component className={className}>
<FormFor />
</component>
);
},
getDefaultProps: function() {
return {component: React.DOM.form};
},
valueUpdated: function(value) {
var isSuccess = v.isSuccess(value.validation);
if (this.props.onUpdate) {
this.props.onUpdate(value.value, isSuccess);
}
if (this.props.onChange && isSuccess) {
this.props.onChange(value.value);
}
}
});
module.exports = Form;
| /**
* @jsx React.DOM
*/
'use strict';
var React = require('react/addons');
var cx = React.addons.classSet;
var FormMixin = require('./FormMixin');
var FormFor = require('./FormFor');
var v = require('./validation');
var Form = React.createClass({
mixins: [FormMixin],
propTypes: {
component: React.PropTypes.component,
onChange: React.PropTypes.func,
onUpdate: React.PropTypes.func
},
render: function() {
var component = this.props.component;
var className = cx({
'rf-Form': true,
'rf-Form--invalid': v.isFailure(this.value().validation)
});
return this.transferPropsTo(
<component className={className}>
<FormFor />
</component>
);
},
getDefaultProps: function() {
return {component: React.DOM.form};
},
valueUpdated: function(value) {
if (this.props.onUpdate) {
this.props.onUpdate(value.value, value);
}
if (this.props.onChange && v.isSuccess(value.validation)) {
this.props.onChange(value.value, value);
}
}
});
module.exports = Form;
|
Allow dynamicObject update only when session is of type admin | <?php
/**
* @package plugins.metadata
* @subpackage model
*/
class MetadataDynamicObjectPeer extends MetadataPeer implements IMetadataPeer
{
public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage)
{
/** @var MetadataProfileField $profileField */
$subMetadataProfileId = $profileField->getRelatedMetadataProfileId();
$subMetadataProfile = MetadataProfilePeer::retrieveByPK($subMetadataProfileId);
if (!$subMetadataProfile)
{
$errorMessage = 'Sub metadata profile ' . $subMetadataProfileId . ' was not found';
return false;
}
$subMetadataObjects = MetadataPeer::retrieveByObjects($subMetadataProfileId, $subMetadataProfile->getObjectType(), $objectIds);
if (count($subMetadataObjects) != count($objectIds))
{
$errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found for profile '.$subMetadataProfileId;
return false;
}
return true;
}
public static function getEntry($objectId)
{
return null;
}
public static function validateMetadataObjectAccess($objectId, $objectType)
{
return kCurrentContext::$is_admin_session;
}
}
| <?php
/**
* @package plugins.metadata
* @subpackage model
*/
class MetadataDynamicObjectPeer extends MetadataPeer implements IMetadataPeer
{
public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage)
{
/** @var MetadataProfileField $profileField */
$subMetadataProfileId = $profileField->getRelatedMetadataProfileId();
$subMetadataProfile = MetadataProfilePeer::retrieveByPK($subMetadataProfileId);
if (!$subMetadataProfile)
{
$errorMessage = 'Sub metadata profile ' . $subMetadataProfileId . ' was not found';
return false;
}
$subMetadataObjects = MetadataPeer::retrieveByObjects($subMetadataProfileId, $subMetadataProfile->getObjectType(), $objectIds);
if (count($subMetadataObjects) != count($objectIds))
{
$errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found for profile '.$subMetadataProfileId;
return false;
}
return true;
}
public static function getEntry($objectId)
{
return null;
}
public static function validateMetadataObjectAccess($objectId, $objectType)
{
return true;
}
}
|
Add reminder comment on wheel creation | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from aldryn_categories import __version__
# git tag '[version]'
# git push --tags origin master
# python setup.py sdist upload
# python setup.py bdist_wheel upload
setup(
name='aldryn-categories',
version=__version__,
url='https://github.com/aldryn/aldryn-categories',
license='BSD License',
description='Heirarchical categories/taxonomies for your Django project',
author='Divio AG',
author_email='info@divio.ch',
package_data={},
packages=find_packages(),
platforms=['OS Independent'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
],
install_requires=[
'django-parler>=1.2.1',
'django-treebeard>=2.0',
],
include_package_data=True,
zip_safe=False
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from aldryn_categories import __version__
# git tag '[version]'
# git push --tags origin master
# python setup.py sdist upload
setup(
name='aldryn-categories',
version=__version__,
url='https://github.com/aldryn/aldryn-categories',
license='BSD License',
description='Heirarchical categories/taxonomies for your Django project',
author='Divio AG',
author_email='info@divio.ch',
package_data={},
packages=find_packages(),
platforms=['OS Independent'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
],
install_requires=[
'django-parler>=1.2.1',
'django-treebeard>=2.0',
],
include_package_data=True,
zip_safe=False
)
|
Make exception more specific when retrieving a calendar type that does not exist in the calendar factory. | <?php
namespace Plummer\Calendarful\Calendar;
class CalendarFactory implements CalendarFactoryInterface
{
private $calendarTypes = [];
public function addCalendarType($type, $calendarType)
{
if(is_string($calendarType) and !class_exists($calendarType)) {
throw new \InvalidArgumentException("Class {$calendarType} des not exist.");
}
else if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType, false))) {
throw new \InvalidArgumentException('File or File path required.');
}
$this->calendarTypes[$type] = is_string($calendarType) ?
$calendarType :
get_class($calendarType);
}
public function getCalendarTypes()
{
return $this->calendarTypes;
}
public function createCalendar($type)
{
if(!isset($this->calendarTypes[$type])) {
throw new \OutOfBoundsException("A calendar type called {$type} does not exist within the factory.");
}
$calendar = new $this->calendarTypes[$type]();
return $calendar;
}
} | <?php
namespace Plummer\Calendarful\Calendar;
class CalendarFactory implements CalendarFactoryInterface
{
private $calendarTypes = [];
public function addCalendarType($type, $calendarType)
{
if(is_string($calendarType) and !class_exists($calendarType)) {
throw new \InvalidArgumentException("Class {$calendarType} des not exist.");
}
else if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType, false))) {
throw new \InvalidArgumentException('File or File path required.');
}
$this->calendarTypes[$type] = is_string($calendarType) ?
$calendarType :
get_class($calendarType);
}
public function getCalendarTypes()
{
return $this->calendarTypes;
}
public function createCalendar($type)
{
if(!isset($this->calendarTypes[$type])) {
throw new \Exception('The type passed does not exist.');
}
$calendar = new $this->calendarTypes[$type]();
return $calendar;
}
} |
Use this.ui.write instead of console.log. | /* eslint-env node */
const path = require('path');
let TsPreprocessor;
try {
TsPreprocessor = require('./lib/typescript-preprocessor');
} catch (ex) {
// Do nothing; we just won't have the plugin available. This means that if you
// somehow end up in a state where it doesn't load, the preprocessor *will*
// fail, but this is necessary because the preprocessor depends on packages
// which aren't installed until the
}
module.exports = {
name: 'ember-cli-typescript',
included(app) {
this._super.included.apply(this, arguments);
this.app = app;
},
blueprintsPath() {
return path.join(__dirname, 'blueprints');
},
setupPreprocessorRegistry: function(type, registry) {
if (!TsPreprocessor) {
this.ui.write(
'Note: TypeScript preprocessor not available -- some dependencies not installed. ' +
'(If this is during installation of the add-on, this is as expected. If it is ' +
'while building, serving, or testing the application, this is an error.)'
);
return;
}
try {
const plugin = new TsPreprocessor({ includeExtensions: ['.ts', '.js'] });
registry.add('js', plugin);
} catch (ex) {
this.ui.write(
'Missing or invalid tsconfig.json, please fix or run `ember generate ember-cli-typescript`.'
);
this.ui.write(' ' + ex.toString());
}
},
};
| /* eslint-env node */
'use strict';
var path = require('path');
var process = require('process');
let TsPreprocessor;
try {
TsPreprocessor = require('./lib/typescript-preprocessor');
} catch ( ex ) {
// Do nothing; we just won't have the plugin available. This means that if you
// somehow end up in a state where it doesn't load, the preprocessor *will*
// fail, but this is necessary because the preprocessor depends on packages
// which aren't installed until the
}
module.exports = {
name: 'ember-cli-typescript',
included: function(app) {
this._super.included.apply(this, arguments);
this.app = app;
},
blueprintsPath: function() {
return path.join(__dirname, 'blueprints');
},
setupPreprocessorRegistry: function(type, registry) {
if (!TsPreprocessor) {
console.log("Note: TypeScript preprocessor not available -- some dependencies not installed. (If this is during installation of the add-on, this is as expected. If it is while building, serving, or testing the application, this is an error.)");
return;
}
try {
var plugin = new TsPreprocessor({includeExtensions: ['.ts','.js']});
registry.add('js', plugin);
} catch ( ex ) {
console.log( "Missing or invalid tsconfig.json, please fix or run `ember generate ember-cli-typescript`." );
console.log( ' ' + ex.toString());
}
}
};
|
Allow empty properties in Property action. | /*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.bladecoder.engine.actions;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
@ActionDescription("Sets a global game property. Properties are created by the user but the next ones always exists: SAVED_GAME_VERSION, PREVIOUS_SCENE, CURRENT_CHAPTER, PLATFORM")
public class PropertyAction implements Action {
@ActionProperty(required = true)
@ActionPropertyDescription("Property name")
private String prop;
@ActionProperty
@ActionPropertyDescription("Property value")
private String value;
private World w;
@Override
public void init(World w) {
this.w = w;
}
@Override
public boolean run(VerbRunner cb) {
w.setCustomProperty(prop, value);
return false;
}
}
| /*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.bladecoder.engine.actions;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
@ActionDescription("Sets a global game property. Properties are created by the user but the next ones always exists: SAVED_GAME_VERSION, PREVIOUS_SCENE, CURRENT_CHAPTER, PLATFORM")
public class PropertyAction implements Action {
@ActionProperty(required = true)
@ActionPropertyDescription("Property name")
private String prop;
@ActionProperty(required = true)
@ActionPropertyDescription("Property value")
private String value;
private World w;
@Override
public void init(World w) {
this.w = w;
}
@Override
public boolean run(VerbRunner cb) {
w.setCustomProperty(prop, value);
return false;
}
}
|
Use container-sm on the index page also | @extends('layouts.master')
@section('title', 'Do you know the way?')
@section('content')
<div class="container-sm text-center">
<p>{{ env('DOMAIN') }} is a private file hosting website.</p>
<p>Accounts are given with approval from {{ env('OWNER_NAME') }} <<a
href="mailto:{{ env('OWNER_EMAIL') }}">{{ env('OWNER_EMAIL') }}</a>>.</p>
<p>Your request will NOT be accepted if I don't know you or I'm not expecting your request prior to you making
it.</p>
<p>In other words, random requests are not welcome and will not be accepted.</p>
<a href="{{ route('login') }}" role="button" class="btn btn-primary">Login</a>
<a href="{{ route('register') }}" role="button" class="btn btn-primary">Request Account</a>
</div>
@stop | @extends('layouts.master')
@section('title', 'Do you know the way?')
@section('content')
<div class="text-center">
<p>{{ env('DOMAIN') }} is a private file hosting website.</p>
<p>Accounts are given with approval from {{ env('OWNER_NAME') }} <<a
href="mailto:{{ env('OWNER_EMAIL') }}">{{ env('OWNER_EMAIL') }}</a>>.</p>
<p>Your request will NOT be accepted if I don't know you or I'm not expecting your request prior to you making
it.</p>
<p>In other words, random requests are not welcome and will not be accepted.</p>
<a href="{{ route('login') }}" role="button" class="btn btn-primary">Login</a>
<a href="{{ route('register') }}" role="button" class="btn btn-primary">Request Account</a>
</div>
@stop |
Add test for tiles (correct number) | <?php
namespace Tests\AppBundle\API;
use AppBundle\API\FlowerColor;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class FlowerColorTest extends KernelTestCase
{
/**
* @var \Doctrine\Bundle\DoctrineBundle\Registry
*/
private $doctrine;
private $flowerColor;
/**
* {@inheritDoc}
*/
protected function setUp()
{
self::bootKernel();
$this->doctrine = static::$kernel->getContainer()
->get('doctrine');
$this->flowerColor = new FlowerColor($this->doctrine);
}
public function testDescription()
{
$desc = $this->flowerColor->getDesc();
$this->assertEquals($desc['description']['en'], 'Assign flower colors to plants.');
$this->assertEquals($desc['label']['en'], 'Flower Color');
$this->assertEquals($desc['icon'], 'https://wikidatagame.iimog.org/assets/img/marguerite-1154604_960_720.jpg');
}
public function testTiles()
{
$tiles = $this->flowerColor->getTiles(5);
$this->assertEquals(count($tiles), 5);
}
} | <?php
namespace Tests\AppBundle\API;
use AppBundle\API\FlowerColor;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class FlowerColorTest extends KernelTestCase
{
/**
* @var \Doctrine\Bundle\DoctrineBundle\Registry
*/
private $doctrine;
private $flowerColor;
/**
* {@inheritDoc}
*/
protected function setUp()
{
self::bootKernel();
$this->doctrine = static::$kernel->getContainer()
->get('doctrine');
$this->flowerColor = new FlowerColor($this->doctrine);
}
public function testDescription()
{
$desc = $this->flowerColor->getDesc();
$this->assertEquals($desc['description']['en'], 'Assign flower colors to plants.');
$this->assertEquals($desc['label']['en'], 'Flower Color');
$this->assertEquals($desc['icon'], 'https://wikidatagame.iimog.org/assets/img/marguerite-1154604_960_720.jpg');
}
} |
Add another polling command test. | package org.jenkinsci.plugins.visualworks_store;
import hudson.util.ArgumentListBuilder;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class StoreSCMTest {
@Test
public void preparesPollingCommandForSinglePundle() {
List<PundleSpec> pundles = Arrays.asList(new PundleSpec("Package"));
StoreSCM scm = new StoreSCM("Repo", pundles, "\\d+", "Development", false, "");
ArgumentListBuilder builder = scm.preparePollingCommand("storeScript");
assertEquals("storeScript -repository Repo -packages Package -versionRegex \\d+ -blessedAtLeast Development",
builder.toStringWithQuote());
}
@Test
public void preparesPollingCommandForMultiplePundles() {
List<PundleSpec> pundles = Arrays.asList(new PundleSpec("Package"), new PundleSpec("OtherPackage"), new PundleSpec("Package with Spaces"));
StoreSCM scm = new StoreSCM("Repo", pundles, "\\d+", "Development", false, "");
ArgumentListBuilder builder = scm.preparePollingCommand("storeScript");
final String commandLine = builder.toStringWithQuote();
assertTrue("Command line (" + commandLine + ") doesn't contain expected text",
commandLine.contains("-packages Package OtherPackage \"Package with Spaces\""));
}
}
| package org.jenkinsci.plugins.visualworks_store;
import hudson.util.ArgumentListBuilder;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class StoreSCMTest {
@Test
public void preparesPollingCommandForSinglePundle() {
List<PundleSpec> pundles = Arrays.asList(new PundleSpec("Package"));
StoreSCM scm = new StoreSCM("Repo", pundles, "\\d+", "Development", false, "");
ArgumentListBuilder builder = scm.preparePollingCommand("storeScript");
assertEquals("storeScript -repository Repo -packages Package -versionRegex \\d+ -blessedAtLeast Development",
builder.toStringWithQuote());
}
}
|
Set default priority level to None | from __future__ import unicode_literals
from functools import total_ordering
from binary_heap import BinaryHeap
@total_ordering # Will build out the remaining comparison methods
class QNode(object):
"""A class for a queue node."""
def __init__(self, val, priority=None):
super(QNode, self).__init__()
self.val = val
self.priority = priority
def __repr__(self):
"""Print representation of node."""
return "{val}".format(val=self.val)
def __eq__(self, other):
"""Implement this and following two methods with logic to compare
priority and value appropiately.
"""
pass
def __lt__(self, other):
"""Implement in tandem with __eq__."""
pass
class PriorityQ(object):
"""A class for a priority queue. Compose this from BinaryHeap."""
def __init__(self, iterable=()):
pass
def insert(item):
"""Insert an item into the queue."""
pass
def pop():
"""Remove the most importan item from the queue."""
pass
def peek():
"""Returns the most important item from queue without removal."""
| from __future__ import unicode_literals
from functools import total_ordering
from binary_heap import BinaryHeap
@total_ordering # Will build out the remaining comparison methods
class QNode(object):
"""A class for a queue node."""
def __init__(self, val, priority):
super(QNode, self).__init__()
self.val = val
self.priority = priority
def __repr__(self):
"""Print representation of node."""
return "{val}".format(val=self.val)
def __eq__(self, other):
"""Implement this and following two methods with logic to compare
priority and value appropiately.
"""
pass
def __lt__(self, other):
"""Implement in tandem with __eq__."""
pass
class PriorityQ(object):
"""A class for a priority queue. Compose this from BinaryHeap."""
def __init__(self, iterable=()):
pass
def insert(item):
"""Insert an item into the queue."""
pass
def pop():
"""Remove the most importan item from the queue."""
pass
def peek():
"""Returns the most important item from queue without removal."""
|
Fix type mismatch in default API version JSDoc. | /**
* index.js
* Client entry point.
*
* @author Francis Brito <fr.br94@gmail.com>
* @license MIT
*/
'use strict';
/**
* Client
* Provides methods to access PrintHouse's API.
*
* @param {String} apiKey API key identifying account owner.
* @param {Object} opts Contains options to be passed to the client
*/
var Client = function Client(apiKey, opts) {
opts = opts || {};
if (!apiKey) {
throw new Error('No API key provided.');
}
this._endpoint = opts.endpoint || Client.DEFAULT_API_URL;
this._version = opts.version || Client.DEFAULT_API_VERSION;
};
/**
* Default API endpoint.
* Used if no API endpoint is passed in opts parameter when constructing a client.
*
* @type {String}
*/
Client.DEFAULT_API_URL = 'http://printhouse.io/api';
/**
* Default API version.
* Used if no API version is passed in opts parameter when constructing a client.
*
* @type {Number}
*/
Client.DEFAULT_API_VERSION = 1;
module.exports = {
Client: Client
};
| /**
* index.js
* Client entry point.
*
* @author Francis Brito <fr.br94@gmail.com>
* @license MIT
*/
'use strict';
/**
* Client
* Provides methods to access PrintHouse's API.
*
* @param {String} apiKey API key identifying account owner.
* @param {Object} opts Contains options to be passed to the client
*/
var Client = function Client(apiKey, opts) {
opts = opts || {};
if (!apiKey) {
throw new Error('No API key provided.');
}
this._endpoint = opts.endpoint || Client.DEFAULT_API_URL;
this._version = opts.version || Client.DEFAULT_API_VERSION;
};
/**
* Default API endpoint.
* Used if no API endpoint is passed in opts parameter when constructing a client.
*
* @type {String}
*/
Client.DEFAULT_API_URL = 'http://printhouse.io/api';
/**
* Default API version.
* Used if no API version is passed in opts parameter when constructing a client.
*
* @type {String}
*/
Client.DEFAULT_API_VERSION = 1;
module.exports = {
Client: Client
};
|
Reformat code and optimize imports. | package org.ops4j.pax.web.service.internal.model;
import javax.servlet.Filter;
public class FilterModel extends BasicModel
{
private final Filter m_filter;
private final String[] m_urlPatterns;
private final String[] m_servletNames;
public FilterModel( final Filter filter,
final String[] urlPatterns,
final String[] servletNames,
final ContextModel contextModel )
{
super( contextModel );
if( urlPatterns == null && servletNames == null )
{
throw new IllegalArgumentException(
"Registered filter must have at least one url pattern or servlet mapping"
);
}
m_filter = filter;
m_urlPatterns = urlPatterns;
m_servletNames = servletNames;
}
public Filter getFilter()
{
return m_filter;
}
public String[] getUrlPatterns()
{
return m_urlPatterns;
}
public String[] getServletNames()
{
return m_servletNames;
}
}
| package org.ops4j.pax.web.service.internal.model;
import javax.servlet.Filter;
public class FilterModel extends BasicModel
{
private final Filter m_filter;
private final String[] m_urlPatterns;
private final String[] m_servletNames;
public FilterModel( final Filter filter,
final String[] urlPatterns,
final String[] servletNames,
final ContextModel contextModel )
{
super( contextModel );
if( urlPatterns == null && servletNames == null )
{
throw new IllegalArgumentException(
"Registered filter must have at least one url pattern or servlet mapping"
);
}
m_filter = filter;
m_urlPatterns = urlPatterns;
m_servletNames = servletNames;
}
public Filter getFilter()
{
return m_filter;
}
public String[] getUrlPatterns()
{
return m_urlPatterns;
}
public String[] getServletNames()
{
return m_servletNames;
}
}
|
Add cDatePublic to indexed search result constructor
Former-commit-id: 5c4c6da19612c683470a11ed997e515bed375b7f | <?
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedSearchResult {
public function __construct($id, $name, $description, $score, $cPath, $content, $cDatePublic = false) {
$this->cID = $id;
$this->cName = $name;
$this->cDescription = $description;
$this->score = $score;
$this->cPath = $cPath;
$this->content = $content;
if ($cDatePublic) {
$this->setDate($cDatePublic);
}
$this->nh = Loader::helper('navigation');
}
public function getID() {return $this->cID;}
public function getName() {return $this->cName;}
public function getDescription() {return $this->cDescription;}
public function getScore() {return $this->score;}
public function getCollectionPath() {return $this->cPath;}
public function getCpath() {return $this->cPath;}
public function getBodyContent() {return $this->content;}
public function getDate($mask = '') {
if ($mask == '') {
$mask = t('Y-m-d H:i:s');
}
return date($mask, strtotime($this->cDate));
}
public function getPath() {
$c = Page::getByID($this->cID);
return $this->nh->getLinkToCollection($c, true);
}
public function setDate($date) { $this->cDate = $date;}
}
| <?
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedSearchResult {
public function __construct($id, $name, $description, $score, $cPath, $content) {
$this->cID = $id;
$this->cName = $name;
$this->cDescription = $description;
$this->score = $score;
$this->cPath = $cPath;
$this->content = $content;
$this->nh = Loader::helper('navigation');
}
public function getID() {return $this->cID;}
public function getName() {return $this->cName;}
public function getDescription() {return $this->cDescription;}
public function getScore() {return $this->score;}
public function getCollectionPath() {return $this->cPath;}
public function getCpath() {return $this->cPath;}
public function getBodyContent() {return $this->content;}
public function getDate($mask = '') {
if ($mask == '') {
$mask = t('Y-m-d H:i:s');
}
return date($mask, strtotime($this->cDate));
}
public function getPath() {
$c = Page::getByID($this->cID);
return $this->nh->getLinkToCollection($c, true);
}
public function setDate($date) { $this->cDate = $date;}
}
|
Fix CommentModel m2m null warning | # -*- coding: utf-8 -*-
import os
from django.db import models
from django.conf import settings
class UserModel(models.Model):
name = models.CharField(max_length=20)
upload_to = os.path.join(settings.FILE_STORAGE_DIR, 'test_serializers')
class CommentModel(models.Model):
user = models.ForeignKey(
UserModel,
related_name='comments',
on_delete=models.CASCADE,
)
users_liked = models.ManyToManyField(UserModel, blank=True)
title = models.CharField(max_length=20)
text = models.CharField(max_length=200)
attachment = models.FileField(
upload_to=upload_to, blank=True, null=True, max_length=500)
hidden_text = models.CharField(max_length=200, blank=True, null=True)
| # -*- coding: utf-8 -*-
import os
from django.db import models
from django.conf import settings
class UserModel(models.Model):
name = models.CharField(max_length=20)
upload_to = os.path.join(settings.FILE_STORAGE_DIR, 'test_serializers')
class CommentModel(models.Model):
user = models.ForeignKey(
UserModel,
related_name='comments',
on_delete=models.CASCADE,
)
users_liked = models.ManyToManyField(UserModel, blank=True, null=True)
title = models.CharField(max_length=20)
text = models.CharField(max_length=200)
attachment = models.FileField(
upload_to=upload_to, blank=True, null=True, max_length=500)
hidden_text = models.CharField(max_length=200, blank=True, null=True)
|
Change the default number of engines to 4.
Only 4 are needed for our current tests. | """
Simple runner for `ipcluster start` or `ipcluster stop` on Python 2 or 3, as
appropriate.
"""
import sys
import six
from subprocess import Popen, PIPE
if six.PY2:
ipcluster_cmd = 'ipcluster'
elif six.PY3:
ipcluster_cmd = 'ipcluster3'
else:
raise NotImplementedError("Not run with Python 2 *or* 3?")
def start(n=4):
"""Convenient way to start an ipcluster for testing.
You have to wait for it to start, however.
"""
# FIXME: This should be reimplemented to signal when the cluster has
# successfully started
engines = "--engines=MPIEngineSetLauncher"
Popen([ipcluster_cmd, 'start', '-n', str(n), engines, str('&')],
stdout=PIPE, stderr=PIPE)
def stop():
"""Convenient way to stop an ipcluster."""
Popen([ipcluster_cmd, 'stop'], stdout=PIPE, stderr=PIPE)
if __name__ == '__main__':
cmd = sys.argv[1]
fn = eval(cmd)
fn()
| """
Simple runner for `ipcluster start` or `ipcluster stop` on Python 2 or 3, as
appropriate.
"""
import sys
import six
from subprocess import Popen, PIPE
if six.PY2:
ipcluster_cmd = 'ipcluster'
elif six.PY3:
ipcluster_cmd = 'ipcluster3'
else:
raise NotImplementedError("Not run with Python 2 *or* 3?")
def start(n=12):
"""Convenient way to start an ipcluster for testing.
You have to wait for it to start, however.
"""
# FIXME: This should be reimplemented to signal when the cluster has
# successfully started
engines = "--engines=MPIEngineSetLauncher"
Popen([ipcluster_cmd, 'start', '-n', str(n), engines, str('&')],
stdout=PIPE, stderr=PIPE)
def stop():
"""Convenient way to stop an ipcluster."""
Popen([ipcluster_cmd, 'stop'], stdout=PIPE, stderr=PIPE)
if __name__ == '__main__':
cmd = sys.argv[1]
fn = eval(cmd)
fn()
|
Update documentation for Route53 service | /**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
var AWS = require('../core');
AWS.Route53 = AWS.Service.defineService('route53', ['2012-12-12'], {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
/**
* @api private
*/
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
},
/**
* @api private
*/
setEndpoint: function setEndpoint(endpoint) {
if (endpoint) {
AWS.Service.prototype.setEndpoint(endpoint);
} else {
var opts = {sslEnabled: true}; // SSL is always enabled for Route53
this.endpoint = new AWS.Endpoint(this.api.globalEndpoint, opts);
}
}
});
module.exports = AWS.Route53;
| /**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
var AWS = require('../core');
AWS.Route53 = AWS.Service.defineService('route53', ['2012-12-12'], {
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
},
setEndpoint: function setEndpoint(endpoint) {
if (endpoint) {
AWS.Service.prototype.setEndpoint(endpoint);
} else {
var opts = {sslEnabled: true}; // SSL is always enabled for Route53
this.endpoint = new AWS.Endpoint(this.api.globalEndpoint, opts);
}
}
});
module.exports = AWS.Route53;
|
Add method to count filled bytes
Calculate the sum of element's filledBytes(). | package net.ihiroky.niotty.buffer;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
/**
* @author Hiroki Itoh
*/
public class EncodeBufferGroup implements Iterable<EncodeBuffer> {
private Deque<EncodeBuffer> group = new ArrayDeque<>();
public void addLast(EncodeBuffer encodeBuffer) {
group.addLast(encodeBuffer);
}
public void addFirst(EncodeBuffer encodeBuffer) {
group.addFirst(encodeBuffer);
}
public EncodeBuffer pollFirst() {
return group.pollFirst();
}
public EncodeBuffer pollLast() {
return group.pollLast();
}
@Override
public Iterator<EncodeBuffer> iterator() {
return group.iterator();
}
public int filledBytes() {
int sum = 0;
for (EncodeBuffer encodeBuffer : group) {
sum += encodeBuffer.filledBytes();
}
return sum;
}
}
| package net.ihiroky.niotty.buffer;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
/**
* @author Hiroki Itoh
*/
public class EncodeBufferGroup implements Iterable<EncodeBuffer> {
private Deque<EncodeBuffer> group = new ArrayDeque<>();
public void addLast(EncodeBuffer encodeBuffer) {
group.addLast(encodeBuffer);
}
public void addFirst(EncodeBuffer encodeBuffer) {
group.addFirst(encodeBuffer);
}
public EncodeBuffer pollFirst() {
return group.pollFirst();
}
public EncodeBuffer pollLast() {
return group.pollLast();
}
@Override
public Iterator<EncodeBuffer> iterator() {
return group.iterator();
}
}
|
Switch ordering of short-circuited OR on line 12. | /*global require:true*/
var gutil = require('gulp-util');
var Grunticon = require( 'grunticon-lib' );
module.exports = function( files, config ) {
"use strict";
return function(callback) {
// get the config
config.logger = {
verbose: config.verbose || function() {},
fatal: function() {},
ok: function() {}
};
// just a quick starting message
gutil.log( "Look, it's a gulpicon!" );
files = files.filter( function( file ){
return file.match( /png|svg/ );
});
if( files.length === 0 ){
gutil.log( "Grunticon has no files to read!" );
callback( false );
return;
}
var output = config.dest;
if( !output || output && output === "" ){
gutil.log("The destination must be a directory");
callback( false );
}
var gicon = new Grunticon(files, config.dest, config);
gicon.process( callback );
};
};
| /*global require:true*/
var gutil = require('gulp-util');
var Grunticon = require( 'grunticon-lib' );
module.exports = function( files, config ) {
"use strict";
return function(callback) {
// get the config
config.logger = {
verbose: function() {} || config.verbose,
fatal: function() {},
ok: function() {}
};
// just a quick starting message
gutil.log( "Look, it's a gulpicon!" );
files = files.filter( function( file ){
return file.match( /png|svg/ );
});
if( files.length === 0 ){
gutil.log( "Grunticon has no files to read!" );
callback( false );
return;
}
var output = config.dest;
if( !output || output && output === "" ){
gutil.log("The destination must be a directory");
callback( false );
}
var gicon = new Grunticon(files, config.dest, config);
gicon.process( callback );
};
};
|
Remove output expect when there is an error. | '''
Main command which is meant to be run daily to get the information
from various social networks into the local db.
'''
import traceback
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ImproperlyConfigured
from socializr.base import get_socializr_configs
class Command(BaseCommand):
help = 'Performs the oauth2 dance and save the creds for future use.'
def handle(self, *args, **options):
configs = get_socializr_configs()
for config_class in configs:
config_obj = config_class()
try:
config_obj.collect()
except Exception:
self.stderr.write("There was an exception processing {}".format(config_class.__name__))
traceback.print_exc()
| '''
Main command which is meant to be run daily to get the information
from various social networks into the local db.
'''
import traceback
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ImproperlyConfigured
from socializr.base import get_socializr_configs
class Command(BaseCommand):
help = 'Performs the oauth2 dance and save the creds for future use.'
def handle(self, *args, **options):
configs = get_socializr_configs()
for config_class in configs:
config_obj = config_class()
self.stdout.write("Processing {}".format(config_class.__name__))
try:
config_obj.collect()
except Exception:
self.stderr.write("There was an exception processing {}".format(config_class.__name__))
traceback.print_exc()
|
Use array of TimeRanges to store availability | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.data;
public final class Tutor {
private String name;
private String email;
private String[] skills;
private TimeRange[] availability;
public Tutor(String name, String email, String[] skills, TimeRange[] availability) {
this.name = name;
this.email = email;
this.skills = skills;
this.availability = availability;
}
public String getName() {
return this.name;
}
public String getEmail() {
return this.email;
}
public String[] getSkills() {
return this.skills;
}
public TimeRange[] getAvailability() {
return this.availability;
}
}
| // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
public final class Tutor {
private String name;
private String email;
private String[] skills;
private String[] availability;
public Tutor(String name, String email, String[] skills, String[] availability) {
this.name = name;
this.email = email;
this.skills = skills;
this.availability = availability;
}
public String getName() {
return this.name;
}
public String getEmail() {
return this.email;
}
public String[] getSkills() {
return this.skills;
}
public String[] getAvailability() {
return this.availability;
}
}
|
Add try for catching server error | from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = IntField()
# serialNumber = CharField()
# typeCategory = CharField()
# description = TextField()
# issues = TextField()
# photo = CharField()
# quality = CharField()
@app.route('/')
def index():
# http://flask.pocoo.org/snippets/15/
if 'username' in session:
return render_template('inventory.html', inventoryData="", deviceLogData="")
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
try:
return url_for('index')
except Exception, e:
return e
return '''<form action="" method="post"><p><input type=text name=username><p><input type=submit value=Login></form>'''
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('index'))
if __name__ == '__main__':
db.connect()
app.run()
| from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = IntField()
# serialNumber = CharField()
# typeCategory = CharField()
# description = TextField()
# issues = TextField()
# photo = CharField()
# quality = CharField()
@app.route('/')
def index():
# http://flask.pocoo.org/snippets/15/
if 'username' in session:
return render_template('inventory.html', inventoryData="", deviceLogData="")
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return url_for('index')
return '''<form action="" method="post"><p><input type=text name=username><p><input type=submit value=Login></form>'''
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('index'))
if __name__ == '__main__':
db.connect()
app.run()
|
Fix version warning when react isn't installed
https://github.com/fusionjs/eslint-config-fusion/pull/140 | // @flow
module.exports = {
extends: [
'plugin:flowtype/recommended',
'plugin:react/recommended',
'plugin:jest/recommended',
'./rules/imports.js',
// This comes last so that prettier-config can turn off appropriate rules given the order of precedence by eslint 'extends'
require.resolve('eslint-config-uber-universal-stage-3'),
],
plugins: [
'eslint-plugin-flowtype',
'eslint-plugin-react',
'eslint-plugin-react-hooks',
],
rules: {
// Enforce flow file declarations
'flowtype/require-valid-file-annotation': ['error', 'always'],
// We should be using flow rather than propTypes
'react/prop-types': 'off',
// Enforces consistent spacing within generic type annotation parameters.
// https://github.com/gajus/eslint-plugin-flowtype/blob/master/.README/rules/generic-spacing.md
'flowtype/generic-spacing': 'off',
// Enforce hook rules
// https://reactjs.org/docs/hooks-faq.html#what-exactly-do-the-lint-rules-enforce
'react-hooks/rules-of-hooks': 'error',
// https://github.com/facebook/react/issues/14920
'react-hooks/exhaustive-deps': 'warn',
},
settings: {
react: {
version: 'latest',
},
},
};
| // @flow
module.exports = {
extends: [
'plugin:flowtype/recommended',
'plugin:react/recommended',
'plugin:jest/recommended',
'./rules/imports.js',
// This comes last so that prettier-config can turn off appropriate rules given the order of precedence by eslint 'extends'
require.resolve('eslint-config-uber-universal-stage-3'),
],
plugins: [
'eslint-plugin-flowtype',
'eslint-plugin-react',
'eslint-plugin-react-hooks',
],
rules: {
// Enforce flow file declarations
'flowtype/require-valid-file-annotation': ['error', 'always'],
// We should be using flow rather than propTypes
'react/prop-types': 'off',
// Enforces consistent spacing within generic type annotation parameters.
// https://github.com/gajus/eslint-plugin-flowtype/blob/master/.README/rules/generic-spacing.md
'flowtype/generic-spacing': 'off',
// Enforce hook rules
// https://reactjs.org/docs/hooks-faq.html#what-exactly-do-the-lint-rules-enforce
'react-hooks/rules-of-hooks': 'error',
// https://github.com/facebook/react/issues/14920
'react-hooks/exhaustive-deps': 'warn',
},
settings: {
react: {
version: 'detect',
},
},
};
|
Replace value even if not change event is triggered | /**
* @class CM_FormField_Text
* @extends CM_FormField_Abstract
*/
var CM_FormField_Text = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Text',
/** @type Boolean */
_skipTriggerChange: false,
/** @type String */
_valueLast: null,
events: {
'blur input, textarea': function() {
this.trigger('blur');
},
'focus input, textarea': function() {
this.trigger('focus');
},
'change input, textarea': function() {
this.triggerChange();
}
},
ready: function() {
this._valueLast = this.getInput().val();
},
/**
* @param {String} value
*/
setValue: function(value) {
this._skipTriggerChange = true;
this.$('input, textarea').val(value);
this._skipTriggerChange = false;
},
/**
* @return {Boolean}
*/
hasFocus: function() {
return this.getInput().is(':focus');
},
triggerChange: function() {
var valueCurrent = this.getInput().val();
if (this._valueLast !== valueCurrent) {
this._valueLast = valueCurrent;
if (!this._skipTriggerChange) {
this.trigger('change');
}
}
},
enableTriggerChangeOnInput: function() {
// `propertychange` and `keyup` needed for IE9
this.getInput().on('input propertychange keyup', this.triggerChange.bind(this));
}
});
| /**
* @class CM_FormField_Text
* @extends CM_FormField_Abstract
*/
var CM_FormField_Text = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Text',
/** @type Boolean */
_skipTriggerChange: false,
/** @type String */
_valueLast: null,
events: {
'blur input, textarea': function() {
this.trigger('blur');
},
'focus input, textarea': function() {
this.trigger('focus');
},
'change input, textarea': function() {
this.triggerChange();
}
},
ready: function() {
this._valueLast = this.getInput().val();
},
/**
* @param {String} value
*/
setValue: function(value) {
this._skipTriggerChange = true;
this.$('input, textarea').val(value);
this._skipTriggerChange = false;
},
/**
* @return {Boolean}
*/
hasFocus: function() {
return this.getInput().is(':focus');
},
triggerChange: function() {
if (this._skipTriggerChange) {
return;
}
var valueCurrent = this.getInput().val();
if (this._valueLast !== valueCurrent) {
this._valueLast = valueCurrent;
this.trigger('change');
}
},
enableTriggerChangeOnInput: function() {
// `propertychange` and `keyup` needed for IE9
this.getInput().on('input propertychange keyup', this.triggerChange.bind(this));
}
});
|
Fix the blocking problem of NMSI with 2PC. | package fr.inria.jessy.protocol;
import java.util.Set;
import fr.inria.jessy.communication.JessyGroupManager;
import fr.inria.jessy.store.DataStore;
import fr.inria.jessy.transaction.ExecutionHistory;
import fr.inria.jessy.transaction.termination.TwoPhaseCommit;
import fr.inria.jessy.transaction.termination.vote.Vote;
/**
* This class implements Non-Monotonic Snapshot Isolation consistency criterion.
*
* @author Masoud Saeida Ardekani
*
*/
public class NMSI_PDV_2PC extends NMSI_PDV_GC {
public NMSI_PDV_2PC(JessyGroupManager m, DataStore dataStore) {
super(m, dataStore);
}
/**
* Coordinator needs to only wait for the vote from the 2PC manager.
*
*/
@Override
public Set<String> getVotersToJessyProxy(
Set<String> termincationRequestReceivers,
ExecutionHistory executionHistory) {
termincationRequestReceivers.clear();
termincationRequestReceivers.add(TwoPhaseCommit.getCoordinatorId(executionHistory,manager.getPartitioner()));
return termincationRequestReceivers;
}
@Override
public void voteReceived(Vote vote) {
/*
* if vote.getVotePiggyBack() is null, it means that it is preemptively aborted in DistributedTermination, and
* DistributedTermination sets votePiggyback to null.
*
*/
if (vote.getVotePiggyBack()==null ){
return;
}
super.voteReceived(vote);
}
}
| package fr.inria.jessy.protocol;
import java.util.Set;
import fr.inria.jessy.communication.JessyGroupManager;
import fr.inria.jessy.store.DataStore;
import fr.inria.jessy.transaction.ExecutionHistory;
import fr.inria.jessy.transaction.termination.TwoPhaseCommit;
/**
* This class implements Non-Monotonic Snapshot Isolation consistency criterion.
*
* @author Masoud Saeida Ardekani
*
*/
public class NMSI_PDV_2PC extends NMSI_PDV_GC {
public NMSI_PDV_2PC(JessyGroupManager m, DataStore dataStore) {
super(m, dataStore);
}
/**
* Coordinator needs to only wait for the vote from the 2PC manager.
*
*/
@Override
public Set<String> getVotersToJessyProxy(
Set<String> termincationRequestReceivers,
ExecutionHistory executionHistory) {
termincationRequestReceivers.clear();
termincationRequestReceivers.add(TwoPhaseCommit.getCoordinatorId(executionHistory,manager.getPartitioner()));
return termincationRequestReceivers;
}
}
|
Fix issue with extension point | from setuptools import setup, find_packages
setup(name='pygments-hackasm-lexer',
version='0.1',
description='Pygments lexer for the Nand2Tetris Hack Assembler',
packages = setuptools.find_packages(),
url='https://github.com/cprieto/pygments_hack_asm',
author='Cristian Prieto',
author_email='me@cprieto.com',
license='MIT',
install_requires = ['pygments'],
keywords = [
'syntax highlighting',
'pygments',
'lexer',
'hack',
'assembler',
'nand2tetris'],
classifiers =[
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Environment :: Plugins'],
entry_points = {
'pygments.lexers': [
'hack_asm=hackasmlexer:HackAsmLexer']
})
| from setuptools import setup, find_packages
setup(name='pygments-hackasm-lexer',
version='0.1',
description='Pygments lexer for the Nand2Tetris Hack Assembler',
packages = setuptools.find_packages(),
url='https://github.com/cprieto/pygments_hack_asm',
author='Cristian Prieto',
author_email='me@cprieto.com',
license='MIT',
install_requires = ['pygments'],
keywords = [
'syntax highlighting',
'pygments',
'lexer',
'hack',
'assembler',
'nand2tetris'],
classifiers =[
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Environment :: Plugins'])
|
Disable template cache if directory is not writable | <?php
Class TemplateParser {
static function find_template($template) {
if (!file_exists($template)) {
throw new Exception('\''.$template.'\' template not found.');
}
return preg_replace('/.+\//', '', $template);
}
static function parse($data, $template) {
$template = self::find_template($template);
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('templates');
$cache = is_writable('app/_cache/templates') ? 'app/_cache/templates' : false;
$twig = new Twig_Environment($loader, array(
'cache' => $cache,
'auto_reload' => true,
'autoescape' => false
));
$twig->addExtension(new Stacey_Twig_Extension());
return $twig->render($template, array('page' => $data));
}
}
?> | <?php
Class TemplateParser {
static function find_template($template) {
if (!file_exists($template)) {
throw new Exception('\''.$template.'\' template not found.');
}
return preg_replace('/.+\//', '', $template);
}
static function parse($data, $template) {
$template = self::find_template($template);
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
'cache' => 'app/_cache/templates',
'auto_reload' => true,
'autoescape' => false
));
$twig->addExtension(new Stacey_Twig_Extension());
return $twig->render($template, array('page' => $data));
}
}
?> |
Remove run player. Fix output | #!/usr/bin/env node
'use strict';
import program from 'commander';
import animeDl from 'anime-dl';
import chalk from 'chalk';
import updateNotifier from 'update-notifier';
import pkg from '../package.json';
updateNotifier({pkg}).notify();
program
.version(pkg.version)
.usage('-a <anime> -c <chapter>')
.description('CLI for get chapter link')
.option('-a, --anime [anime]', 'Add name')
.option('-c, --chapter [chapter]', 'Add chapter')
.parse(process.argv);
if (program.anime && program.chapter) {
console.log(chalk.green('Searching...'));
animeDl.getLinksByNameAndChapter(program.anime, program.chapter).then((data) => {
if (data.urls.length === 0) return console.log(chalk.red('Not found a link'));
console.log(chalk.green('Run any this links in your video player'));
for (let url of data.urls) {
console.log(chalk.green(url));
}
}).catch((err) => console.log(chalk.red(`Error: ${err.message}`)));
} else {
program.help();
}
| #!/usr/bin/env node
'use strict';
import {spawn} from 'child_process';
import program from 'commander';
import animeDl from 'anime-dl';
import chalk from 'chalk';
import updateNotifier from 'update-notifier';
import pkg from '../package.json';
updateNotifier({pkg}).notify();
program
.version(pkg.version)
.usage('-a <anime> -c <chapter>')
.description('CLI for get chapter link')
.option('-a, --anime [anime]', 'Add name')
.option('-c, --chapter [chapter]', 'Add chapter')
.option('-p, --player', 'Run player (optional). Availables: mpv|vlc|mplayer|omxplayer|smplayer|cvlc. Default: mpv', /(mpv|vlc|mplayer|omxplayer|smplayer|cvlc)/i, 'mpv')
.parse(process.argv);
if (program.anime && program.chapter) {
animeDl.getLinksByNameAndChapter(program.anime, program.chapter).then((data) => {
if (data.urls.length === 0) return console.log(chalk.red('Not found a link'));
const chapter = data.urls[data.urls.length - 1];
if (program.player) {
console.log(chalk.green(`Wait running ${program.player} ${chapter} ...`));
spawn(program.player, [chapter], {detached: true, stdio: 'ignore'});
} else {
console.log(chalk.green(`Run ${chapter} in any player`));
}
}).catch((err) => console.log(chalk.red(`Error: ${err.message}`)));
} else {
program.help();
}
|
Add postgres as response processing for travis | DEBUG = False
BROKER_URL = 'amqp://guest@localhost'
RECORD_HTTP_TRANSACTIONS = False
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
RAW_PROCESSING = ['cassandra', 'postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres']
RESPONSE_PROCESSING = 'postgres'
SENTRY_DSN = None
USE_FLUENTD = False
CASSANDRA_URI = ['127.0.0.1']
CASSANDRA_KEYSPACE = 'scrapi'
ELASTIC_URI = 'localhost:9200'
ELASTIC_TIMEOUT = 10
ELASTIC_INDEX = 'share'
PLOS_API_KEY = 'fakekey'
HARVARD_DATAVERSE_API_KEY = 'anotherfakekey'
disabled = ['stepic', 'shareok']
FRONTEND_KEYS = [
u'description',
u'contributors',
u'tags',
u'raw',
u'title',
u'id',
u'source',
u'dateUpdated'
]
| DEBUG = False
BROKER_URL = 'amqp://guest@localhost'
RECORD_HTTP_TRANSACTIONS = False
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
RAW_PROCESSING = ['cassandra', 'postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres']
RESPONSE_PROCESSING = None
SENTRY_DSN = None
USE_FLUENTD = False
CASSANDRA_URI = ['127.0.0.1']
CASSANDRA_KEYSPACE = 'scrapi'
ELASTIC_URI = 'localhost:9200'
ELASTIC_TIMEOUT = 10
ELASTIC_INDEX = 'share'
PLOS_API_KEY = 'fakekey'
HARVARD_DATAVERSE_API_KEY = 'anotherfakekey'
disabled = ['stepic', 'shareok']
FRONTEND_KEYS = [
u'description',
u'contributors',
u'tags',
u'raw',
u'title',
u'id',
u'source',
u'dateUpdated'
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.