text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Revert escape nickname, desc, etc in user profile | # encoding: utf-8
from django import forms
from seahub.profile.models import Profile, DetailedProfile
class ProfileForm(forms.Form):
nickname = forms.CharField(max_length=64, required=False)
intro = forms.CharField(max_length=256, required=False)
def save(self, username):
nickname = self.cleaned_data['nickname']
intro = self.cleaned_data['intro']
Profile.objects.add_or_update(username, nickname, intro)
class DetailedProfileForm(ProfileForm):
department = forms.CharField(max_length=512, required=False)
telephone = forms.CharField(max_length=100, required=False)
def save(self, username):
super(DetailedProfileForm, self).save(username)
department = self.cleaned_data['department']
telephone = self.cleaned_data['telephone']
DetailedProfile.objects.add_or_update(username, department, telephone)
| # encoding: utf-8
from django import forms
from django.utils.html import escape
from seahub.profile.models import Profile, DetailedProfile
class ProfileForm(forms.Form):
nickname = forms.CharField(max_length=64, required=False)
intro = forms.CharField(max_length=256, required=False)
def save(self, username):
nickname = escape(self.cleaned_data['nickname'])
intro = escape(self.cleaned_data['intro'])
Profile.objects.add_or_update(username, nickname, intro)
class DetailedProfileForm(ProfileForm):
department = forms.CharField(max_length=512, required=False)
telephone = forms.CharField(max_length=100, required=False)
def save(self, username):
super(DetailedProfileForm, self).save(username)
department = escape(self.cleaned_data['department'])
telephone = escape(self.cleaned_data['telephone'])
DetailedProfile.objects.add_or_update(username, department, telephone)
|
Move short option tests into top level tests | var child = require('child_process');
var http = require('http');
var test = require('tape');
var fs = require('fs');
var path = require('path');
var url = require('url');
var version = [
'-V',
'--version',
];
version.forEach(function (arg) {
var args = ['bin/amok.js', arg];
test(args.join(' '), function (test) {
test.plan(2);
var cli = child.spawn('node', args);
cli.stdout.on('data', function (data) {
var message = data.toString();
test.equal(message, require('../package.json').version + '\n');
});
cli.on('close', function (code) {
test.equal(code, 0);
});
});
});
var help = [
'-h',
'--help'
];
help.forEach(function (arg) {
var args = ['bin/amok.js', arg];
test('bin print help', function (test) {
test.plan(2);
test.comment(args.join(' '));
var cli = child.spawn('node', args);
cli.stdout.on('data', function (data) {
var message = data.toString();
test.ok(message.indexOf('Usage:') > -1);
});
cli.on('close', function (code) {
test.equal(code, 0);
});
});
}); | var child = require('child_process');
var http = require('http');
var test = require('tape');
var fs = require('fs');
var path = require('path');
var url = require('url');
test('bin print version', function (test) {
test.plan(4);
var options = [
'-V',
'--version'
];
options.forEach(function (option) {
var args = ['bin/amok.js', option];
test.comment(args.join(' '));
var cli = child.spawn('node', args);
cli.stdout.on('data', function (data) {
var message = data.toString();
test.equal(message, require('../package.json').version + '\n');
});
cli.on('close', function (code) {
test.equal(code, 0);
});
});
});
test('bin print help', function (test) {
test.plan(4);
var options = [
'-h',
'--help'
];
options.forEach(function (option) {
var args = ['./bin/amok.js', option];
test.comment(args.join(' '));
var cli = child.spawn('node', args);
cli.stdout.on('data', function (data) {
var message = data.toString();
test.ok(message.indexOf('Usage:') > -1);
});
cli.on('close', function (code) {
test.equal(code, 0);
});
});
}); |
Fix route for create version | var users = require('./controllers/usersController.js');
var recipes = require('./controllers/recipesController.js');
var branches = require('./controllers/branchesController.js');
var versions = require('./controllers/versionsController.js');
module.exports = function(app, express) {
// /*** Sign up / Sign in / Logout ***/
// app.post('/user/signup', users.signup);
// app.post('/user/login', users.login);
// app.get('/user/logout', users.logout);
// /*** Users ***/
app.get('/:username/profile', users.getProfile); //gets recipes
// app.put('/:username/profile', users.updateProfile);
// /*** Recipes ***/
app.post('/:username/create-recipe', recipes.createRecipe);
app.get('/:username/:recipe', recipes.getRecipe);
app.delete('/:username/:recipe', recipes.deleteRecipe);
// /*** Branches ***/
app.post('/:username/:recipe/:branch', branches.createBranch);
app.get('/:username/:recipe/:branch', branches.getBranch);
app.delete('/:username/:recipe/:branch', branches.deleteBranch);
/*** Versions ***/
app.post('/:username/:recipe/:branch/create-version', versions.createVersion);
app.get('/:username/:recipe/:branch/:version', versions.getVersion);
app.delete('/:username/:recipe/:branch/:version', versions.deleteVersion);
}; | var users = require('./controllers/usersController.js');
var recipes = require('./controllers/recipesController.js');
var branches = require('./controllers/branchesController.js');
var versions = require('./controllers/versionsController.js');
module.exports = function(app, express) {
// /*** Sign up / Sign in / Logout ***/
// app.post('/user/signup', users.signup);
// app.post('/user/login', users.login);
// app.get('/user/logout', users.logout);
// /*** Users ***/
app.get('/:username/profile', users.getProfile); //gets recipes
// app.put('/:username/profile', users.updateProfile);
// /*** Recipes ***/
app.post('/:username/create-recipe', recipes.createRecipe);
app.get('/:username/:recipe', recipes.getRecipe);
app.delete('/:username/:recipe', recipes.deleteRecipe);
// /*** Branches ***/
app.post('/:username/:recipe/:branch', branches.createBranch);
app.get('/:username/:recipe/:branch', branches.getBranch);
app.delete('/:username/:recipe/:branch', branches.deleteBranch);
/*** Versions ***/
app.post('/:username/:recipe/:branch/:version', versions.createVersion);
app.get('/:username/:recipe/:branch/:version', versions.getVersion);
app.delete('/:username/:recipe/:branch/:version', versions.deleteVersion);
}; |
Modify script to allow warnings | var page = require('webpage').create()
page.onConsoleMessage = function(arg) {
var parts = arg.split('`')
var msg = parts[1] || '[LOG] ' + arg
console.log(color(msg, parts[0]))
if (msg === 'END') {
var result = page.evaluate(function() {
return result
})
if (result.error.count + result.fail.count) {
phantom.exit(1)
} else {
phantom.exit(0)
}
}
}
var system = require('system')
var address = system.args[1]
page.open(address, function(status) {
if (status !== 'success') {
console.log(color('FAIL to load this address: ' + address, fail))
}
})
// https://github.com/loopj/commonjs-ansi-color/blob/master/lib/ansi-color.js
var ANSI_CODES = {
'fail': 31, // red
'error': 31, // red
'pass': 32, // green
'info': 37 // white
}
function color(str, type) {
return '\033[' +
(ANSI_CODES[type] || ANSI_CODES['info']) + 'm '
+ str + '\033[0m'
} | var page = require('webpage').create()
page.onConsoleMessage = function(arg) {
var parts = arg.split('`')
var msg = parts[1] || '[LOG] ' + arg
console.log(color(msg, parts[0]))
if (msg === 'END') {
var result = page.evaluate(function() {
return result
})
if (result.error.count + result.fail.count + result.warn.count) {
phantom.exit(1)
} else {
phantom.exit(0)
}
}
}
var system = require('system')
var address = system.args[1]
page.open(address, function(status) {
if (status !== 'success') {
console.log(color('FAIL to load this address: ' + address, fail))
}
})
// https://github.com/loopj/commonjs-ansi-color/blob/master/lib/ansi-color.js
var ANSI_CODES = {
'fail': 31, // red
'error': 31, // red
'pass': 32, // green
'info': 37 // white
}
function color(str, type) {
return '\033[' +
(ANSI_CODES[type] || ANSI_CODES['info']) + 'm '
+ str + '\033[0m'
} |
Fix config api class again | from ..cw_controller import CWController
# Class for /company/configurations
from . import configuration
class ConfigurationsAPI(CWController):
def __init__(self):
self.module_url = 'company'
self.module = 'configurations'
self._class = configuration.Configuration
super().__init__() # instance gets passed to parent object
def get_configurations(self):
return super()._get()
def create_configuration(self, a_configuration):
return super()._create(a_configuration)
def get_configurations_count(self):
return super()._get_count()
def get_configuration_by_id(self, configuration_id):
return super()._get_by_id(configuration_id)
def delete_configuration_by_id(self, configuration_id):
super()._delete_by_id(configuration_id)
def replace_configuration(self, configuration_id):
pass
def update_configuration(self, configuration_id, key, value):
return super()._update(configuration_id, key, value)
| from ..cw_controller import CWController
# Class for /company/configurations
from connectpyse.company import configuration
class ConfigurationsAPI(CWController):
def __init__(self):
self.module_url = 'company'
self.module = 'configurations'
self._class = configuration.Configuration
super().__init__() # instance gets passed to parent object
def get_configurations(self):
return super()._get()
def create_configuration(self, a_configuration):
return super()._create(a_configuration)
def get_configurations_count(self):
return super()._get_count()
def get_configuration_by_id(self, configuration_id):
return super()._get_by_id(configuration_id)
def delete_configuration_by_id(self, configuration_id):
super()._delete_by_id(configuration_id)
def replace_configuration(self, configuration_id):
pass
def update_configuration(self, configuration_id, key, value):
return super()._update(configuration_id, key, value)
|
Add service flag for NODE_NETWORK_LIMITED (BIP159) | <?php
function format_bytes( $size, $precision = 2 ) {
$base = log( $size, 1024 );
$suffixes = array( '', 'KB', 'MB', 'GB', 'TB' );
return round( pow( 1024, $base - floor( $base ) ), $precision ) .' '. $suffixes[ floor( $base ) ];
}
// https://stackoverflow.com/a/19680778
function seconds_to_time($seconds) {
$dtF = new \DateTime('@0');
$dtT = new \DateTime("@$seconds");
return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
function decode_services( $flags ) {
$set = '';
$services = [
['NONE', 0],
['NETWORK', (1 << 0)],
['GETUTXO', (1 << 1)],
['BLOOM', (1 << 2)],
['WITNESS', (1 << 3)],
['XTHIN', (1 << 4)],
['NETWORK_LIMITED', (1 << 10)],
];
foreach( $services as $service ) {
if( ($flags & $service[1] ) != 0 ) {
$set .= $service[0].' ';
}
}
return $set;
}
| <?php
function format_bytes( $size, $precision = 2 ) {
$base = log( $size, 1024 );
$suffixes = array( '', 'KB', 'MB', 'GB', 'TB' );
return round( pow( 1024, $base - floor( $base ) ), $precision ) .' '. $suffixes[ floor( $base ) ];
}
// https://stackoverflow.com/a/19680778
function seconds_to_time($seconds) {
$dtF = new \DateTime('@0');
$dtT = new \DateTime("@$seconds");
return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
function decode_services( $flags ) {
$set = '';
$services = [
['NONE', 0],
['NETWORK', (1 << 0)],
['GETUTXO', (1 << 1)],
['BLOOM', (1 << 2)],
['WITNESS', (1 << 3)],
['XTHIN', (1 << 4)],
];
foreach( $services as $service ) {
if( ($flags & $service[1] ) != 0 ) {
$set .= $service[0].' ';
}
}
return $set;
}
|
Make Serializer work with nest API
This fixes the root resource name to match what the API expects. | import DS from "ember-data";
import Ember from 'ember';
var dasherize = Ember.String.dasherize;
var pluralize = Ember.String.pluralize;
export default DS.RESTSerializer.extend({
normalize: function(type, hash, prop) {
var links = hash.links;
for (var key in links) {
var linkedData = links[key];
if (linkedData.href) {
hash[key] = linkedData.href;
} else if (linkedData.ids) {
hash[key] = linkedData.ids;
} else {
hash[key + '_id'] = linkedData.id;
}
}
delete hash.links;
return this._super(type, hash, prop);
},
normalizePayload: function(payload) {
if (payload.linked) {
var store = Ember.get(this, 'store');
this.pushPayload(store, payload.linked);
delete payload.linked;
}
return this._super(payload);
},
keyForRelationship: function(key, relationship) {
if (relationship === 'belongsTo') {
return key + '_id';
}
return key;
},
serializeIntoHash: function(data, type, record, options) {
var root = dasherize(pluralize(type.typeKey));
data[root] = this.serialize(record, options);
}
});
| import DS from "ember-data";
import Ember from 'ember';
var singularize = Ember.String.singularize;
var camelize = Ember.String.camelize;
export default DS.RESTSerializer.extend({
normalize: function(type, hash, prop) {
var links = hash.links;
for (var key in links) {
var linkedData = links[key];
if (linkedData.href) {
hash[key] = linkedData.href;
} else if (linkedData.ids) {
hash[key] = linkedData.ids;
} else {
hash[key + '_id'] = linkedData.id;
}
}
delete hash.links;
return this._super(type, hash, prop);
},
normalizePayload: function(payload) {
if (payload.linked) {
var store = Ember.get(this, 'store');
this.pushPayload(store, payload.linked);
delete payload.linked;
}
return this._super(payload);
},
keyForRelationship: function(key, relationship) {
if (relationship === 'belongsTo') {
return key + '_id';
}
return key;
}
});
|
Fix invalid column error in membership seeder | module.exports = {
up: (queryInterface) => {
return queryInterface.bulkInsert('Memberships',
[
{
memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5',
groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440',
userRole: 'admin',
createdAt: new Date(),
updatedAt: new Date()
},
{
memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978',
groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440',
userRole: 'member',
createdAt: new Date(),
updatedAt: new Date()
}
], {});
},
down: (queryInterface) => {
return queryInterface.bulkDelete('Memberships', null, {});
}
};
| module.exports = {
up: (queryInterface) => {
return queryInterface.bulkInsert('Memberships',
[
{
memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5',
groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440',
memberRole: 'admin',
createdAt: new Date(),
updatedAt: new Date()
},
{
memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978',
groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440',
memberRole: 'member',
createdAt: new Date(),
updatedAt: new Date()
}
], {});
},
down: (queryInterface) => {
return queryInterface.bulkDelete('Memberships', null, {});
}
};
|
Remove logging in overview data parser | 'use strict';
const D3 = require('D3');
exports.parser = function(rows) {
var overviewResponse = rows;
var overview = D3.nest()
.key(function(d) {
return d.region_code;
})
.rollup(function(v) {
return {
'region_code': v[0].region_code,
'region_name': v[0].region_name,
'current_total': v[0].current_total,
'delayed_total': v[0].delayed_total,
'days_to_payment': v[0].days_to_payment
}
})
.entries(overviewResponse)
.map(function(d) {
return d.value;
});
var data = {
'overview': overview
};
return data;
};
| 'use strict';
const D3 = require('D3');
exports.parser = function(rows) {
var overviewResponse = rows;
var overview = D3.nest()
.key(function(d) {
return d.region_code;
})
.rollup(function(v) {
console.log(v)
return {
'region_code': v[0].region_code,
'region_name': v[0].region_name,
'current_total': v[0].current_total,
'delayed_total': v[0].delayed_total,
'days_to_payment': v[0].days_to_payment
}
})
.entries(overviewResponse)
.map(function(d) {
return d.value;
});
var data = {
'overview': overview
};
return data;
};
|
Revert modules update to file in app directory | import Ember from 'ember';
import ENV from '../config/environment';
const { computed, Service } = Ember;
function computedFromConfig(prop) {
return computed(function(){
return ENV['ember-modal-dialog'] && ENV['ember-modal-dialog'][prop];
});
}
export default Service.extend({
hasEmberTether: computedFromConfig('hasEmberTether'),
hasLiquidWormhole: computedFromConfig('hasLiquidWormhole'),
hasLiquidTether: computedFromConfig('hasLiquidTether'),
destinationElementId: computed(function() {
/*
everywhere except test, this property will be overwritten
by the initializer that appends the modal container div
to the DOM. because initializers don't run in unit/integration
tests, this is a nice fallback.
*/
if (ENV.environment === 'test') {
return 'ember-testing';
}
})
});
| import { computed } from '@ember/object';
import Service from '@ember/service';
import ENV from '../config/environment';
function computedFromConfig(prop) {
return computed(function(){
return ENV['ember-modal-dialog'] && ENV['ember-modal-dialog'][prop];
});
}
export default Service.extend({
hasEmberTether: computedFromConfig('hasEmberTether'),
hasLiquidWormhole: computedFromConfig('hasLiquidWormhole'),
hasLiquidTether: computedFromConfig('hasLiquidTether'),
destinationElementId: computed(function() {
/*
everywhere except test, this property will be overwritten
by the initializer that appends the modal container div
to the DOM. because initializers don't run in unit/integration
tests, this is a nice fallback.
*/
if (ENV.environment === 'test') {
return 'ember-testing';
}
})
});
|
Add deprecated >= 1.2.0 to install_requires | from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='gopay',
version='1.2.4',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/gopaycommunity/gopay-python-sdk',
author='GoPay',
author_email='integrace@gopay.cz',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
"Topic :: Software Development :: Libraries :: Python Modules",
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: PyPy',
],
keywords='gopay payments sdk rest api',
packages=['gopay'],
install_requires=['requests', 'deprecated>=1.2.0'],
)
| from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='gopay',
version='1.2.4',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/gopaycommunity/gopay-python-sdk',
author='GoPay',
author_email='integrace@gopay.cz',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
"Topic :: Software Development :: Libraries :: Python Modules",
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: PyPy',
],
keywords='gopay payments sdk rest api',
packages=['gopay'],
install_requires=['requests'],
)
|
Remove permission check on backend | var flash = require('connect-flash');
module.exports = function (app, security) {
var isAuthenticated = security.middleware.isAuthenticated({redirect:'/backend/login'});
var hasPermission = security.middleware.hasPermission;
// update install before requesting permissions
// hasPermission(['backend:login'], {redirect:'/backend/login'})
app.get('/', [isAuthenticated], function (req, res) {
res.render(__dirname + '/build/templates/index.ejs', { env: process.env.NODE_ENV, username: req.user.username });
});
// Login Form
app.get('/login', function (req, res) {
if (req.user) return res.redirect('/backend/');
res.render(__dirname + '/templates/login.ejs', { error: req.flash('error'), info: req.flash('info') });
});
// Logout request
app.get('/logout', function (req, res) {
flash('info','Logged out');
req.logout();
req.session.user = null;
res.redirect('/backend/login');
});
} | var flash = require('connect-flash');
module.exports = function (app, security) {
var isAuthenticated = security.middleware.isAuthenticated({redirect:'/backend/login'});
var hasPermission = security.middleware.hasPermission;
app.get('/', [isAuthenticated, hasPermission(['backend:login'], {redirect:'/backend/login'})], function (req, res) {
res.render(__dirname + '/build/templates/index.ejs', { env: process.env.NODE_ENV, username: req.user.username });
});
// Login Form
app.get('/login', function (req, res) {
if (req.user) return res.redirect('/backend/');
res.render(__dirname + '/templates/login.ejs', { error: req.flash('error'), info: req.flash('info') });
});
// Logout request
app.get('/logout', function (req, res) {
flash('info','Logged out');
req.logout();
req.session.user = null;
res.redirect('/backend/login');
});
} |
Use the new notation for collections to get elements by key | <?php
use Galahad\LaravelAddressing\AdministrativeArea;
use Galahad\LaravelAddressing\Country;
/**
* Class CountryTest
*
* @author Junior Grossi <juniorgro@gmail.com>
*/
class CountryTest extends PHPUnit_Framework_TestCase
{
public function testFindByCodeAndName()
{
$country = new Country;
$us = $country->findByName('United States');
$br = $country->findByName('Brazil');
$brazil = $country->findByCode('BR');
$this->assertEquals($us->getCode(), 'US');
$this->assertEquals($br->getCode(), 'BR');
$this->assertEquals($brazil->getName(), 'Brazil');
}
public function testGetAdministrativeAreasFirstRow()
{
$country = new Country;
$brazil = $country->findByCode('BR');
$acState = $brazil->getAdministrativeAreas()->getByKey(0);
$us = $country->findByCode('US');
$alabamaState = $us->getAdministrativeAreas()->getByKey(0);
$coloradoState = $us->getAdministrativeAreas()->getByKey(9);
$this->assertEquals($acState->getName(), 'Acre');
$this->assertEquals($alabamaState->getName(), 'Alabama');
$this->assertEquals($coloradoState->getName(), 'Colorado');
}
} | <?php
use Galahad\LaravelAddressing\AdministrativeArea;
use Galahad\LaravelAddressing\Country;
/**
* Class CountryTest
*
* @author Junior Grossi <juniorgro@gmail.com>
*/
class CountryTest extends PHPUnit_Framework_TestCase
{
public function testFindByCodeAndName()
{
$country = new Country;
$us = $country->findByName('United States');
$br = $country->findByName('Brazil');
$brazil = $country->findByCode('BR');
$this->assertEquals($us->getCode(), 'US');
$this->assertEquals($br->getCode(), 'BR');
$this->assertEquals($brazil->getName(), 'Brazil');
}
public function testGetAdministrativeAreasFirstRow()
{
$country = new Country;
$brazil = $country->findByCode('BR');
$acState = $brazil->getAdministrativeAreas()->offsetGet(0);
$us = $country->findByCode('US');
$alabamaState = $us->getAdministrativeAreas()->offsetGet(0);
$coloradoState = $us->getAdministrativeAreas()->offsetGet(9);
$this->assertEquals($acState->getName(), 'Acre');
$this->assertEquals($alabamaState->getName(), 'Alabama');
$this->assertEquals($coloradoState->getName(), 'Colorado');
}
} |
Mark unsigned hyper as unsigned | import Long from 'long';
import includeIoMixin from './io-mixin';
export class UnsignedHyper extends Long {
static read(io) {
let high = io.readInt32BE();
let low = io.readInt32BE();
return this.fromBits(low, high);
}
static write(value, io) {
if(!(value instanceof this)) {
throw new Error(
`XDR Write Error: ${value} is not an UnsignedHyper`
);
}
io.writeInt32BE(value.high);
io.writeInt32BE(value.low);
}
static fromString(string) {
let result = super.fromString(string, true);
return new this(result.low, result.high);
}
static fromBits(low, high) {
let result = super.fromBits(low, high, true);
return new this(result.low, result.high);
}
static isValid(value) {
return value instanceof this;
}
constructor(low, high) {
super(low, high, true);
}
}
includeIoMixin(UnsignedHyper);
UnsignedHyper.MAX_VALUE = new UnsignedHyper(
Long.MAX_UNSIGNED_VALUE.low,
Long.MAX_UNSIGNED_VALUE.high
);
UnsignedHyper.MIN_VALUE = new UnsignedHyper(
Long.MIN_VALUE.low,
Long.MIN_VALUE.high
);
| import Long from 'long';
import includeIoMixin from './io-mixin';
export class UnsignedHyper extends Long {
static read(io) {
let high = io.readInt32BE();
let low = io.readInt32BE();
return this.fromBits(low, high);
}
static write(value, io) {
if(!(value instanceof this)) {
throw new Error(
`XDR Write Error: ${value} is not an UnsignedHyper`
);
}
io.writeInt32BE(value.high);
io.writeInt32BE(value.low);
}
static fromString(string) {
let result = super.fromString(string, true);
return new this(result.low, result.high);
}
static fromBits(low, high) {
let result = super.fromBits(low, high, true);
return new this(result.low, result.high);
}
static isValid(value) {
return value instanceof this;
}
constructor(low, high) {
super(low, high, false);
}
}
includeIoMixin(UnsignedHyper);
UnsignedHyper.MAX_VALUE = new UnsignedHyper(
Long.MAX_UNSIGNED_VALUE.low,
Long.MAX_UNSIGNED_VALUE.high
);
UnsignedHyper.MIN_VALUE = new UnsignedHyper(
Long.MIN_VALUE.low,
Long.MIN_VALUE.high
);
|
Fix invalid properties for default value of argument | #!/usr/bin/env node
const ArgumentParser = require('argparse').ArgumentParser
const opn = require('opn')
const packageJson = require('../package.json')
const { createServer } = require('../lib/backend')
if (process.env.NODE_ENV === 'production') {
console.error(clc.red('Do not run this in production!'))
process.exit(1)
}
const parser = new ArgumentParser({
description: packageJson.description,
version: packageJson.version,
})
parser.addArgument(['-o', '--open'], {
action: 'storeTrue',
help: 'Open server URL in default browser on start',
})
parser.addArgument(['-p', '--port'], {
type: 'int',
defaultValue: 8001,
help: 'Port to run on (default: 8001)',
})
const args = parser.parseArgs()
console.log('dynamodb-admin')
const app = createServer();
const port = process.env.PORT || args.port
const server = app.listen(port);
server.on('listening', () => {
const address = server.address();
const url = `http://0.0.0.0:${address.port}`;
console.log(` listening on ${url}`);
if (args.open) {
opn(url)
}
});
| #!/usr/bin/env node
const ArgumentParser = require('argparse').ArgumentParser
const opn = require('opn')
const packageJson = require('../package.json')
const { createServer } = require('../lib/backend')
if (process.env.NODE_ENV === 'production') {
console.error(clc.red('Do not run this in production!'))
process.exit(1)
}
const parser = new ArgumentParser({
description: packageJson.description,
version: packageJson.version,
})
parser.addArgument(['-o', '--open'], {
action: 'storeTrue',
help: 'Open server URL in default browser on start',
})
parser.addArgument(['-p', '--port'], {
type: 'int',
default: 8001,
help: 'Port to run on (default: 8001)',
})
const args = parser.parseArgs()
console.log('dynamodb-admin')
const app = createServer();
const port = process.env.PORT || args.port
const server = app.listen(port);
server.on('listening', () => {
const address = server.address();
const url = `http://0.0.0.0:${address.port}`;
console.log(` listening on ${url}`);
if (args.open) {
opn(url)
}
});
|
tests: Increase timout of autofuzz @FuzzTest | // Copyright 2022 Code Intelligence GmbH
//
// 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.example;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import com.code_intelligence.jazzer.junit.FuzzTest;
class AutofuzzFuzzTests {
private static class IntHolder {
private final int i;
IntHolder(int i) {
this.i = i;
}
public int getI() {
return i;
}
}
@FuzzTest(maxDuration = "5m")
void autofuzz(String str, IntHolder holder) {
assumeTrue(holder != null);
if (holder.getI() == 1234 && "jazzer".equals(str)) {
throw new RuntimeException();
}
}
@FuzzTest(seedCorpus = "AutofuzzSeedCorpus")
void autofuzzWithCorpus(String str, int i) {
if ("jazzer".equals(str) && i == 1234) {
throw new RuntimeException();
}
}
}
| // Copyright 2022 Code Intelligence GmbH
//
// 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.example;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import com.code_intelligence.jazzer.junit.FuzzTest;
class AutofuzzFuzzTests {
private static class IntHolder {
private final int i;
IntHolder(int i) {
this.i = i;
}
public int getI() {
return i;
}
}
@FuzzTest
void autofuzz(String str, IntHolder holder) {
assumeTrue(holder != null);
if (holder.getI() == 1234 && "jazzer".equals(str)) {
throw new RuntimeException();
}
}
@FuzzTest(seedCorpus = "AutofuzzSeedCorpus")
void autofuzzWithCorpus(String str, int i) {
if ("jazzer".equals(str) && i == 1234) {
throw new RuntimeException();
}
}
}
|
Add height is not absoulte note | var WebPage = require('webpage'),
System = require('system'),
address = System.args[1],
index = 0;
// All the sizes to screenshot.
// Note: PhantomJs uses the heights specified here as a min-height criteria
var screenshots = [
{"dimensions" : [970,300],
"filename": './screenshots/screenshot_l.png'},
{"dimensions" : [720,300],
"filename": './screenshots/screenshot_m.png'},
{"dimensions" : [400,200],
"filename": './screenshots/screenshot_s.png'}
];
var capturescreen = function(dimensions, filename){
var page = WebPage.create();
page.viewportSize = {
width: dimensions[0],
height: dimensions[1]
};
page.open(address);
page.onLoadFinished = setTimeout(function() {
page.render(filename);
page.close();
index++;
// Give it a second before calling next.
// Phantom runs into some sort of race condition without this
setTimeout(nextPage, 1000);
}, 3000);
}
var nextPage = function(){
if(!screenshots[index]){
phantom.exit();
}
capturescreen(screenshots[index].dimensions, screenshots[index].filename);
}
nextPage(); | var WebPage = require('webpage');
var System = require('system');
address = System.args[1];
var index = 0;
var screenshots = [
{"dimensions" : [975,500],
"filename": './screenshots/screenshot_l.png'},
{"dimensions" : [720,400],
"filename": './screenshots/screenshot_m.png'},
{"dimensions" : [400,200],
"filename": './screenshots/screenshot_s.png'}
];
var capturescreen = function(dimensions, filename){
var page = WebPage.create();
page.viewportSize = {
width: dimensions[0],
height: dimensions[1]
};
page.open(address);
page.onLoadFinished = setTimeout(function() {
page.render(filename);
page.close();
index++;
// Give it a second before calling next.
// Phantom runs into some sort of race condition without this
setTimeout(nextPage, 1000);
}, 3000);
}
var nextPage = function(){
if(!screenshots[index]){
phantom.exit();
}
capturescreen(screenshots[index].dimensions, screenshots[index].filename);
}
nextPage(); |
Fix Message for PHP-FPM / PHP-FCGI | <?php
//-- unixman
ini_set('display_errors', '1'); // display runtime errors
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED); // error reporting
ini_set('html_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', 'data/logs/phperrors.log'); // record them to a log
ini_set('default_charset', 'UTF-8'); // default charset UTF-8
//--
//-- This makes our life easier when dealing with paths. Everything is relative to the application root now.
chdir(dirname(__DIR__));
if((php_sapi_name() === 'fpm-fcgi') || (php_sapi_name() === 'cgi-fcgi')) {
die('Zend Framework 2 with PHP-FPM or PHP-FCGI requires a Virtual Host to be set !<br>Alternatively, for development as http://127.0.0.1:8888, go to the zf2/public and type in a terminal: php -S 127.0.0.1:8888 -t ./');
} //end if
//-- Decline static file requests back to the PHP built-in webserver
if(php_sapi_name() === 'cli-server' && is_file(__DIR__.parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
return false;
} //end if
//-- Setup autoloading
require('init_autoloader.php');
//-- Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
//--
//end of php code
?> | <?php
//-- unixman
ini_set('display_errors', '1'); // display runtime errors
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED); // error reporting
ini_set('html_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', 'data/logs/phperrors.log'); // record them to a log
ini_set('default_charset', 'UTF-8'); // default charset UTF-8
//--
//-- This makes our life easier when dealing with paths. Everything is relative to the application root now.
chdir(dirname(__DIR__));
//-- Decline static file requests back to the PHP built-in webserver
if(php_sapi_name() === 'cli-server' && is_file(__DIR__.parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
return false;
} //end if
//-- Setup autoloading
require('init_autoloader.php');
//-- Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
//--
//end of php code
?> |
Make the rotating direction go back and forth | (function (PIXI) {
'use strict';
var stage = new PIXI.Stage(0x66FF99);
var renderer = PIXI.autoDetectRenderer(400, 300);
document.body.appendChild(renderer.view);
window.requestAnimationFrame(animate);
var texture = PIXI.Texture.fromImage('bunny.png');
var bunny = new PIXI.Sprite(texture);
var direction = 1;
bunny.anchor.x = 0.5;
bunny.anchor.y = 0.5;
bunny.position.x = 50;
bunny.position.y = 50;
stage.addChild(bunny);
function animate() {
window.requestAnimationFrame(animate);
direction = backAndForth(0, bunny.position.x, 400);
bunny.rotation += direction * 0.05;
bunny.position.x += direction * 1;
renderer.render(stage);
}
})(window.PIXI);
function backAndForth(lowest, current, highest) {
var threshold = 25;
this.forth = (typeof this.forth === 'undefined') ? true : this.forth;
this.forth = this.forth && current < highest - threshold || current < lowest + threshold;
return this.forth ? 1 : -1;
}
| (function (PIXI) {
'use strict';
var stage = new PIXI.Stage(0x66FF99);
var renderer = PIXI.autoDetectRenderer(400, 300);
document.body.appendChild(renderer.view);
window.requestAnimationFrame(animate);
var texture = PIXI.Texture.fromImage('bunny.png');
var bunny = new PIXI.Sprite(texture);
bunny.anchor.x = 0.5;
bunny.anchor.y = 0.5;
bunny.position.x = 50;
bunny.position.y = 50;
stage.addChild(bunny);
function animate() {
window.requestAnimationFrame(animate);
bunny.rotation -= 0.05;
bunny.position.x += backAndForth(0, bunny.position.x, 400);
renderer.render(stage);
}
})(window.PIXI);
function backAndForth(lowest, current, highest) {
var threshold = 25;
this.forth = (typeof this.forth === 'undefined') ? true : this.forth;
this.forth = this.forth && current < highest - threshold || current < lowest + threshold;
return this.forth ? 1 : -1;
}
|
Fix bug left over from the namespacing | from django.db.models import Q
from django.core.urlresolvers import reverse
class TeamDefaultHookset(object):
def build_team_url(self, url_name, team_slug):
return reverse(url_name, args=[team_slug])
def get_autocomplete_result(self, user):
return {"pk": user.pk, "email": user.email, "name": user.get_full_name()}
def search_queryset(self, query, users):
return users.filter(
Q(email__icontains=query) |
Q(username__icontains=query) |
Q(first_name__icontains=query) |
Q(last_name__icontains=query)
)
class HookProxy(object):
def __getattr__(self, attr):
from pinax.teams.conf import settings
return getattr(settings.TEAMS_HOOKSET, attr)
hookset = HookProxy()
| from django.db.models import Q
from django.core.urlresolvers import reverse
class TeamDefaultHookset(object):
def build_team_url(self, url_name, team_slug):
return reverse(url_name, args=[team_slug])
def get_autocomplete_result(self, user):
return {"pk": user.pk, "email": user.email, "name": user.get_full_name()}
def search_queryset(self, query, users):
return users.filter(
Q(email__icontains=query) |
Q(username__icontains=query) |
Q(first_name__icontains=query) |
Q(last_name__icontains=query)
)
class HookProxy(object):
def __getattr__(self, attr):
from teams.conf import settings
return getattr(settings.TEAMS_HOOKSET, attr)
hookset = HookProxy()
|
Support loose option on readFile | 'use strict';
var compact = require('es5-ext/array/#/compact')
, callable = require('es5-ext/object/valid-callable')
, path = require('path')
, common = require('path2/common')
, defaultReadFile = require('fs2/read-file')
, dirname = path.dirname, resolve = path.resolve;
module.exports = function (indexPath/*, options */) {
var rootPath, indexDir, options = Object(arguments[1])
, readFile = options.readFile || defaultReadFile
, pathProxy = options.pathProxy;
indexPath = resolve(indexPath);
indexDir = dirname(indexPath);
if (pathProxy !== undefined) callable(pathProxy);
return readFile(indexPath, 'utf8')(function (content) {
var filenames = content.trim().split('\n').filter(Boolean).map(function (name) {
var filename = resolve(indexDir, name);
if (pathProxy) filename = pathProxy(name, filename);
return filename;
});
rootPath = common.apply(null, filenames);
return filenames;
}).map(function (filename) {
return readFile(filename, 'utf8', { loose: options.loose })(function (content) {
if (content == null) return null;
return {
filename: filename.slice(rootPath.length + 1),
content: content
};
}, function (e) {
if (e.code !== 'ENOENT') throw e;
throw new TypeError("Bad paths in " + indexPath + " -> " + e.message);
});
}).invoke(compact);
};
| 'use strict';
var callable = require('es5-ext/object/valid-callable')
, path = require('path')
, common = require('path2/common')
, defaultReadFile = require('fs2/read-file')
, dirname = path.dirname, resolve = path.resolve;
module.exports = function (indexPath/*, options */) {
var rootPath, indexDir, options = Object(arguments[1])
, readFile = options.readFile || defaultReadFile
, pathProxy = options.pathProxy;
indexPath = resolve(indexPath);
indexDir = dirname(indexPath);
if (pathProxy !== undefined) callable(pathProxy);
return readFile(indexPath, 'utf8')(function (content) {
var filenames = content.trim().split('\n').filter(Boolean).map(function (name) {
var filename = resolve(indexDir, name);
if (pathProxy) filename = pathProxy(name, filename);
return filename;
});
rootPath = common.apply(null, filenames);
return filenames;
}).map(function (filename) {
return readFile(filename, 'utf8')(function (content) {
return {
filename: filename.slice(rootPath.length + 1),
content: content
};
}, function (e) {
if (e.code !== 'ENOENT') throw e;
throw new TypeError("Bad paths in " + indexPath + " -> " + e.message);
});
});
};
|
Change to cb_story, clean up TZ handling some more | """
Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format
WARNING: you must have PyXML installed as part of your python installation
in order for this plugin to work
Place this plugin early in your load_plugins list, so that the w3cdate will
be available to subsequent plugins
"""
__author__ = "Ted Leung <twl@sauria.com>"
__version__ = "$Id:"
__copyright__ = "Copyright (c) 2003 Ted Leung"
__license__ = "Python"
import xml.utils.iso8601
import time
from Pyblosxom import tools
def cb_story(args):
request = tools.get_registry()["request"]
data = request.getData()
entry_list = data['entry_list']
for i in range(len(entry_list)):
entry = entry_list[i]
t = entry['timetuple']
# adjust for daylight savings time
tzoffset = 0
if time.timezone != 0:
tzoffset = time.altzone
entry['w3cdate'] = xml.utils.iso8601.tostring(time.mktime(t),tzoffset)
| """
Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format
WARNING: you must have PyXML installed as part of your python installation
in order for this plugin to work
Place this plugin early in your load_plugins list, so that the w3cdate will
be available to subsequent plugins
"""
__author__ = "Ted Leung <twl@sauria.com>"
__version__ = "$Id:"
__copyright__ = "Copyright (c) 2003 Ted Leung"
__license__ = "Python"
import xml.utils.iso8601
import time
def cb_prepare(args):
request = args["request"]
form = request.getHttp()['form']
config = request.getConfiguration()
data = request.getData()
entry_list = data['entry_list']
for i in range(len(entry_list)):
entry = entry_list[i]
t = entry['timetuple']
# adjust for daylight savings time
t = t[0],t[1],t[2],t[3]+time.localtime()[-1],t[4],t[5],t[6],t[7],t[8]
entry['w3cdate'] = xml.utils.iso8601.ctime(time.mktime(t))
|
Fix update on fake slot | package openmods.container;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class FakeSlot extends Slot implements ICustomSlot {
private final boolean keepSize;
public FakeSlot(IInventory inventory, int slot, int x, int y, boolean keepSize) {
super(inventory, slot, x, y);
this.keepSize = keepSize;
}
@Override
public ItemStack onClick(EntityPlayer player, int button, int modifier) {
if (button == 2 && player.capabilities.isCreativeMode) {
ItemStack contents = getStack();
if (contents != null) {
ItemStack tmp = contents.copy();
tmp.stackSize = tmp.getMaxStackSize();
player.inventory.setItemStack(tmp);
return tmp;
}
}
ItemStack held = player.inventory.getItemStack();
ItemStack place = null;
if (held != null) {
place = held.copy();
if (!keepSize) place.stackSize = 1;
}
inventory.setInventorySlotContents(slotNumber, place);
onSlotChanged();
return place;
}
@Override
public boolean canDrag() {
return false;
}
@Override
public boolean canTransferItemsOut() {
return false;
}
@Override
public boolean canTransferItemsIn() {
return false;
}
}
| package openmods.container;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class FakeSlot extends Slot implements ICustomSlot {
private final boolean keepSize;
public FakeSlot(IInventory inventory, int slot, int x, int y, boolean keepSize) {
super(inventory, slot, x, y);
this.keepSize = keepSize;
}
@Override
public ItemStack onClick(EntityPlayer player, int button, int modifier) {
if (button == 2 && player.capabilities.isCreativeMode) {
ItemStack contents = getStack();
if (contents != null) {
ItemStack tmp = contents.copy();
tmp.stackSize = tmp.getMaxStackSize();
player.inventory.setItemStack(tmp);
return tmp;
}
}
ItemStack held = player.inventory.getItemStack();
ItemStack place = null;
if (held != null) {
place = held.copy();
if (!keepSize) place.stackSize = 1;
}
inventory.setInventorySlotContents(slotNumber, place);
return place;
}
@Override
public boolean canDrag() {
return false;
}
@Override
public boolean canTransferItemsOut() {
return false;
}
@Override
public boolean canTransferItemsIn() {
return false;
}
}
|
Convert main to a verticle | package net.trajano.ms.engine.sample;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import net.trajano.ms.engine.JaxRsRoute;
public class Main extends AbstractVerticle {
public static void main(final String[] args) {
final VertxOptions options = new VertxOptions();
Vertx.clusteredVertx(options, event -> {
final Vertx vertx = event.result();
vertx.deployVerticle(new Main());
});
//final Vertx vertx = Vertx.vertx();
}
@Override
public void start() throws Exception {
final Router router = Router.router(vertx);
final HttpServer http = vertx.createHttpServer();
JaxRsRoute.route(vertx, router, MyApp.class);
http.requestHandler(req -> router.accept(req)).listen(8280);
}
}
| package net.trajano.ms.engine.sample;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import net.trajano.ms.engine.JaxRsRoute;
public class Main {
public static void main(final String[] args) {
final VertxOptions options = new VertxOptions();
Vertx.clusteredVertx(options, event -> {
final Vertx vertx = event.result();
final Router router = Router.router(vertx);
final HttpServer http = vertx.createHttpServer();
JaxRsRoute.route(vertx, router, MyApp.class);
http.requestHandler(req -> router.accept(req)).listen(8280);
});
//final Vertx vertx = Vertx.vertx();
}
}
|
Tweak artisan command output lines | <?php
declare(strict_types=1);
namespace Cortex\Fort\Console\Commands;
use Illuminate\Console\Command;
class InstallCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:install:fort';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install Cortex Fort Module.';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->warn($this->description);
$this->call('cortex:migrate:fort');
$this->call('cortex:seed:fort');
$this->call('cortex:publish:fort');
}
}
| <?php
declare(strict_types=1);
namespace Cortex\Fort\Console\Commands;
use Illuminate\Console\Command;
class InstallCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:install:fort';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install Cortex Fort Module.';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->warn('Install cortex/fort:');
$this->call('cortex:migrate:fort');
$this->call('cortex:seed:fort');
$this->call('cortex:publish:fort');
}
}
|
Update packaging script to include uninstall.php file. | /**
* External dependencies
*/
import gulp from 'gulp';
import del from 'del';
gulp.task( 'copy', () => {
del.sync( [ './release/**/*' ] );
gulp.src(
[
'readme.txt',
'google-site-kit.php',
'uninstall.php',
'dist/*.js',
'dist/assets/**/*',
'bin/**/*',
'includes/**/*',
'third-party/**/*',
'!third-party/**/**/{tests,Tests,doc?(s),examples}/**/*',
'!third-party/**/**/{*.md,*.yml,phpunit.*}',
'!**/*.map',
'!bin/local-env/**/*',
'!bin/local-env/',
'!dist/admin.js',
'!dist/adminbar.js',
'!dist/wpdashboard.js',
],
{ base: '.' }
)
.pipe( gulp.dest( 'release' ) );
} );
| /**
* External dependencies
*/
import gulp from 'gulp';
import del from 'del';
gulp.task( 'copy', () => {
del.sync( [ './release/**/*' ] );
gulp.src(
[
'readme.txt',
'google-site-kit.php',
'dist/*.js',
'dist/assets/**/*',
'bin/**/*',
'includes/**/*',
'third-party/**/*',
'!third-party/**/**/{tests,Tests,doc?(s),examples}/**/*',
'!third-party/**/**/{*.md,*.yml,phpunit.*}',
'!**/*.map',
'!bin/local-env/**/*',
'!bin/local-env/',
'!dist/admin.js',
'!dist/adminbar.js',
'!dist/wpdashboard.js',
],
{ base: '.' }
)
.pipe( gulp.dest( 'release' ) );
} );
|
Refactor template assignment of top menu + isFileWritable() | <?php
/**
* Piwik - Open source web analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
* @category Piwik_Plugins
* @package Piwik_SecurityInfo
*/
/**
* @package Piwik_SecurityInfo
*/
class Piwik_SecurityInfo_Controller extends Piwik_Controller_Admin
{
function index()
{
Piwik::checkUserIsSuperUser();
require_once(dirname(__FILE__) . '/PhpSecInfo/PhpSecInfo.php');
// instantiate the class
$psi = new PhpSecInfo();
// load and run all tests
$psi->loadAndRun();
// grab the results as a multidimensional array
$results = $psi->getResultsAsArray();
// suppress results
unset($results['test_results']['Core']['memory_limit']);
unset($results['test_results']['Core']['post_max_size']);
unset($results['test_results']['Core']['upload_max_filesize']);
$view = new Piwik_View('@SecurityInfo/index');
$this->setBasicVariablesView($view);
$view->results = $results;
echo $view->render();
}
}
| <?php
/**
* Piwik - Open source web analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
* @category Piwik_Plugins
* @package Piwik_SecurityInfo
*/
/**
* @package Piwik_SecurityInfo
*/
class Piwik_SecurityInfo_Controller extends Piwik_Controller_Admin
{
function index()
{
Piwik::checkUserIsSuperUser();
require_once(dirname(__FILE__) . '/PhpSecInfo/PhpSecInfo.php');
// instantiate the class
$psi = new PhpSecInfo();
// load and run all tests
$psi->loadAndRun();
// grab the results as a multidimensional array
$results = $psi->getResultsAsArray();
// suppress results
unset($results['test_results']['Core']['memory_limit']);
unset($results['test_results']['Core']['post_max_size']);
unset($results['test_results']['Core']['upload_max_filesize']);
$view = new Piwik_View('@SecurityInfo/index');
$this->setBasicVariablesView($view);
$view->menu = Piwik_GetAdminMenu();
$view->results = $results;
echo $view->render();
}
}
|
Check that notification onclick is a function before calling | const { ipcRenderer } = require('electron');
const uuidV1 = require('uuid/v1');
class Notification {
static permission = 'granted';
constructor(title = '', options = {}) {
this.title = title;
this.options = options;
this.notificationId = uuidV1();
ipcRenderer.sendToHost('notification', this.onNotify({
title: this.title,
options: this.options,
notificationId: this.notificationId,
}));
ipcRenderer.once(`notification-onclick:${this.notificationId}`, () => {
if (typeof this.onclick === 'function') {
this.onclick();
}
});
}
static requestPermission(cb = null) {
if (!cb) {
return new Promise((resolve) => {
resolve(Notification.permission);
});
}
if (typeof (cb) === 'function') {
return cb(Notification.permission);
}
return Notification.permission;
}
onNotify(data) {
return data;
}
onClick() {}
close() {}
}
window.Notification = Notification;
| const { ipcRenderer } = require('electron');
const uuidV1 = require('uuid/v1');
class Notification {
static permission = 'granted';
constructor(title = '', options = {}) {
this.title = title;
this.options = options;
this.notificationId = uuidV1();
ipcRenderer.sendToHost('notification', this.onNotify({
title: this.title,
options: this.options,
notificationId: this.notificationId,
}));
ipcRenderer.once(`notification-onclick:${this.notificationId}`, () => {
this.onclick();
});
}
static requestPermission(cb = null) {
if (!cb) {
return new Promise((resolve) => {
resolve(Notification.permission);
});
}
if (typeof (cb) === 'function') {
return cb(Notification.permission);
}
return Notification.permission;
}
onNotify(data) {
return data;
}
onClick() {}
close() {}
}
window.Notification = Notification;
|
Fix inclusion of server hook to use proper relative path | #!/usr/bin/env node
// Modules
var connect = require('connect'),
fs = require('fs'),
http = require('http'),
path = require('path'),
serveStatic = require('serve-static'),
serveIndex = require('serve-index');
// Variables
var app = connect(),
hookFile = 'web-server-hook.js';
function main(port, rootPath, indexFile) {
var hook = {
config: function() {},
postConfig: function() {}
};
rootPath = path.resolve(rootPath);
if (fs.existsSync(path.resolve(hookFile))) {
hook = require('./' + hookFile);
}
if (undefined !== hook.config) {
hook.config(app, port, rootPath);
}
app.use(serveStatic(rootPath, {'index': [indexFile]}));
app.use(serveIndex(rootPath, {'icons': true, 'view': 'details'}));
if (undefined !== hook.postConfig) {
hook.postConfig(app, port, rootPath);
}
if (undefined != hook.createServer) {
hook.createServer(app, port, rootPath);
} else {
http.createServer(app).listen(port, function() {
console.log('Static server started at http://localhost:%d/', port);
});
}
}
module.exports = main;
| #!/usr/bin/env node
// Modules
var connect = require('connect'),
fs = require('fs'),
http = require('http'),
path = require('path'),
serveStatic = require('serve-static'),
serveIndex = require('serve-index');
// Variables
var app = connect(),
hookFile = 'web-server-hook.js';
function main(port, rootPath, indexFile) {
var hook = {
config: function() {},
postConfig: function() {}
};
rootPath = path.resolve(rootPath);
if (fs.existsSync(path.resolve(hookFile))) {
hook = require(hookFile);
}
if (undefined !== hook.config) {
hook.config(app, port, rootPath);
}
app.use(serveStatic(rootPath, {'index': [indexFile]}));
app.use(serveIndex(rootPath, {'icons': true, 'view': 'details'}));
if (undefined !== hook.postConfig) {
hook.postConfig(app, port, rootPath);
}
if (undefined != hook.createServer) {
hook.createServer(app, port, rootPath);
} else {
http.createServer(app).listen(port, function() {
console.log('Static server started at http://localhost:%d/', port);
});
}
}
module.exports = main;
|
Set y-axis min to 0 | boilerplate = {
'chart': {
'renderTo': 'container',
'plotBackgroundColor': 'none',
'backgroundColor': 'none',
'spacingTop': 5
},
'title': {'text': None},
'subtitle': {'text': None},
'yAxis': {
'min': 0,
'title':{
'text': None
},
'gridLineColor': 'rgba(255, 255, 255, .1)'
},
"xAxis": {
"lineColor": "rgba(0,0,0,0)"
},
'credits': {
'enabled': False
},
'plotOptions': {
'series': {
'marker': {
'enabled': False
}
}
},
} | boilerplate = {
'chart': {
'renderTo': 'container',
'plotBackgroundColor': 'none',
'backgroundColor': 'none',
'spacingTop': 5
},
'title': {'text': None},
'subtitle': {'text': None},
'yAxis': {
'title':{
'text': None
},
'gridLineColor': 'rgba(255, 255, 255, .1)'
},
"xAxis": {
"lineColor": "rgba(0,0,0,0)"
},
'credits': {
'enabled': False
},
'plotOptions': {
'series': {
'marker': {
'enabled': False
}
}
},
} |
Make remove first array element logic less complex than it needs to be | <?php
function backTrace($backtrace)
{
require_once 'plugins/sourcetag/geshi.php';
foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if ($args) {
$args .= ', ';
}
if (in_array(strtolower($bt['function']), array('rawquery', 'query', 'fetchresult')) && !$args)
if (is_array($a))
$args .= var_export(array_merge(array("..."), array_slice($a, 1)), true);
else if (is_string($a))
$args .= "'...'";
else
$args .= '???';
else
$args .= var_export($a, true);
}
$output .= "<td>{$bt['file']}<td>{$bt['line']}<td>";
$output .= geshi_highlight("{$bt['class']}{$bt['type']}{$bt['function']}($args)", 'scala', null, true);
$output .= "<tr class=cell0>";
}
return $output;
}
function var_format($v) // pretty-print var_export
{
return (str_replace(array("\n"," ","array"),
array("<br>"," "," <i>array</i>"),
var_export($v,true))."<br>");
}
| <?php
function var_export_callback($object) {
return var_export($object, true);
}
function backTrace($backtrace)
{
require_once 'plugins/sourcetag/geshi.php';
foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if ($args) {
$args .= ', ';
}
if (in_array(strtolower($bt['function']), array('rawquery', 'query', 'fetchresult')) && !$args)
if (is_array($a))
$args .= "array(".implode(', ', array_merge(array("'...'"), array_map('var_export_callback', array_slice($a, 1)))).")";
else if (is_string($a))
$args .= "'...'";
else
$args .= '???';
else
$args .= var_export($a, true);
}
$output .= "<td>{$bt['file']}<td>{$bt['line']}<td>";
$output .= geshi_highlight("{$bt['class']}{$bt['type']}{$bt['function']}($args)", 'scala', null, true);
$output .= "<tr class=cell0>";
}
return $output;
}
function var_format($v) // pretty-print var_export
{
return (str_replace(array("\n"," ","array"),
array("<br>"," "," <i>array</i>"),
var_export($v,true))."<br>");
}
|
Add an 'ANY' object type | package object
type Type string
const (
/* Internal Types */
RETURN_VALUE Type = "<return value>"
FUNCTION Type = "<function>"
NEXT Type = "<next>"
BREAK Type = "<break>"
APL_BLOCK Type = "<applied block>"
/* Special Types */
COLLECTION Type = "<collection>"
CONTAINER Type = "<container>"
HASHER Type = "<hasher>"
ANY Type = "<any>"
/* Normal Types */
NUMBER Type = "<number>"
BOOLEAN Type = "<boolean>"
STRING Type = "<string>"
CHAR Type = "<char>"
ARRAY Type = "<array>"
NULL Type = "<null>"
BLOCK Type = "<block>"
TUPLE Type = "<tuple>"
MAP Type = "<map>"
CLASS Type = "<class>"
INIT Type = "<init method>"
METHOD Type = "<method>"
INSTANCE Type = "<instance>"
)
func is(obj Object, t Type) bool {
if t == ANY {
return true
}
if t == COLLECTION {
_, ok := obj.(Collection)
return ok
}
if t == CONTAINER {
_, ok := obj.(Container)
return ok
}
if t == HASHER {
_, ok := obj.(Hasher)
return ok
}
return obj.Type() == t
}
| package object
type Type string
const (
/* Internal Types */
RETURN_VALUE Type = "<return value>"
FUNCTION Type = "<function>"
NEXT Type = "<next>"
BREAK Type = "<break>"
APL_BLOCK Type = "<applied block>"
/* Special Types */
COLLECTION Type = "<collection>"
CONTAINER Type = "<container>"
HASHER Type = "<hasher>"
/* Normal Types */
NUMBER Type = "<number>"
BOOLEAN Type = "<boolean>"
STRING Type = "<string>"
CHAR Type = "<char>"
ARRAY Type = "<array>"
NULL Type = "<null>"
BLOCK Type = "<block>"
TUPLE Type = "<tuple>"
MAP Type = "<map>"
CLASS Type = "<class>"
INIT Type = "<init method>"
METHOD Type = "<method>"
INSTANCE Type = "<instance>"
)
func is(obj Object, t Type) bool {
if t == COLLECTION {
_, ok := obj.(Collection)
return ok
}
if t == CONTAINER {
_, ok := obj.(Container)
return ok
}
if t == HASHER {
_, ok := obj.(Hasher)
return ok
}
if obj.Type() == t {
return true
}
return false
}
|
hack: Print date in fr_CA locale | # -*- encoding:utf-8 -*-
# Template tag
from django.template.defaultfilters import stringfilter
from datetime import datetime, timedelta
from django import template
import locale
register = template.Library()
@register.filter
def event_time(start, end):
today = datetime.today ()
result = ""
# Hack! get the correct user local from the request
loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, 'fr_CA.UTF8')
if start == today:
result += "Aujourd'hui "
else:
result += "Le %s " % start.strftime ("%A %d %B %Y")
if start.day == end.day and start.month == end.month and start.year == end.year:
result += "de %s " % start.strftime ("%H:%M")
result += "à %s " % end.strftime ("%H:%M")
else:
result += "à %s" % start.strftime ("%H:%M")
result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M")
locale.setlocale(locale.LC_ALL, loc)
return result
| # -*- encoding:utf-8 -*-
# Template tag
from django.template.defaultfilters import stringfilter
from datetime import datetime, timedelta
from django import template
register = template.Library()
@register.filter
def event_time(start, end):
today = datetime.today ()
result = ""
if start == today:
result += "aujourd'hui "
else:
result += "le %s " % start.strftime ("%A %d %B %Y")
if start.day == end.day and start.month == end.month and start.year == end.year:
result += "de %s " % start.strftime ("%H:%M")
result += "à %s " % end.strftime ("%H:%M")
else:
result += "à %s" % start.strftime ("%H:%M")
result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M")
return result
|
Fix test missing the container element | $(document).ready(function() {
module("Canvas presentations");
test("Check Canvas Presentations", function() {
expect(1);
ok(MITHGrid.Presentation.RaphSVG !== undefined, "RaphSVG Presentation exists");
});
test("Check Canvas availability", function() {
var presentation;
expect(3);
try {
presentation = MITHGrid.Presentation.RaphSVG.initPresentation($('test-158603'), {
dataView: MITHGrid.Data.initView({
dataStore: MITHGrid.Data.initStore({})
}),
cWidth: 1,
cHeight: 1,
lenses: {}
});
ok(true, "Presentation object created");
}
catch(e) {
ok(false, "Presentation object not created: " + e);
}
ok(presentation !== undefined, "Presentation object exists");
ok(presentation.canvas !== undefined && presentation.canvas.canvas !== undefined &&
presentation.canvas.canvas.localName === "svg", "presentation canvas svg element is good");
});
}); | $(document).ready(function() {
module("Canvas presentations");
test("Check Canvas Presentations", function() {
expect(1);
ok(MITHGrid.Presentation.RaphSVG !== undefined, "RaphSVG Presentation exists");
//ok(MITHGrid.Presentation.SVGRect !== undefined, "SVGRect Presentation exists");
});
test("Check Canvas availability", function() {
expect(2);
var container = $("#test-158603");
var svg, presentation;
presentation = MITHGrid.Presentation.RaphSVG.initPresentation(container, {
dataView: MITHGrid.Data.initView({
dataStore: MITHGrid.Data.initStore({})
}),
cWidth: 1,
cHeight: 1,
lenses: {}
});
ok(presentation !== undefined, "Presentation object exists");
ok(presentation.canvas !== undefined && presentation.canvas.canvas !== undefined &&
presentation.canvas.canvas.localName === "svg", "presentation canvas svg element is good");
});
/*
module("Canvas");
test("Check namespace", function() {
expect(2);
ok(MITHGrid.Application.Canvas !== undefined, "MITHGrid.Application.Canvas exists");
ok($.isFunction(MITHGrid.Application.Canvas.namespace), "MITHGrid.Application.Canvas.namespace is a function");
});
module("Canvas.initApp");
test("Check initApp", function() {
expect(1);
ok(MITHGrid.Application.Canvas.initApp !== undefined, "Canvas.initApp defined and is a function");
});
*/
}); |
Set standard iri for literal. | package de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Node_Types;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Standard_Iris;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Vowl_Lang;
import de.uni_stuttgart.vis.vowl.owl2vowl.export.JsonGeneratorVisitor;
public class RdfsLiteral extends BaseDatatype {
public RdfsLiteral() {
setType(Node_Types.TYPE_LITERAL);
setID();
getLabels().put(Vowl_Lang.LANG_DEFAULT, "Literal");
setIri(Standard_Iris.GENERIC_LITERAL_URI);
}
@Override
protected void setID() {
id = "literal" + counterObjects;
counterObjects++;
}
@Override
public void accept(JsonGeneratorVisitor visitor) {
super.accept(visitor);
visitor.visit(this);
}
}
| package de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Node_Types;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Vowl_Lang;
import de.uni_stuttgart.vis.vowl.owl2vowl.export.JsonGeneratorVisitor;
public class RdfsLiteral extends BaseDatatype {
public RdfsLiteral() {
setType(Node_Types.TYPE_LITERAL);
setID();
getLabels().put(Vowl_Lang.LANG_DEFAULT, "Literal");
}
@Override
protected void setID() {
id = "literal" + counterObjects;
counterObjects++;
}
@Override
public void accept(JsonGeneratorVisitor visitor) {
super.accept(visitor);
visitor.visit(this);
}
}
|
Fix issue where 24h format needed additional configuration for the plugin | $(document).on('ajaxComplete ready', function () {
// Initialize inputs
$('input[data-provides="anomaly.field_type.datetime"]:not([data-initialized])').each(function () {
var $this = $(this);
var inputMode = $this.data('input-mode');
var options = {
altInput: true,
allowInput: true,
minuteIncrement: $this.data('step') || 1,
dateFormat: $this.data('datetime-format'),
time_24hr: Boolean($this.data('datetime-format').match(/[GH]/)),
enableTime: inputMode !== 'date',
noCalendar: inputMode === 'time'
};
$this.attr('data-initialized', '').flatpickr(options);
});
});
| $(document).on('ajaxComplete ready', function () {
// Initialize inputs
$('input[data-provides="anomaly.field_type.datetime"]:not([data-initialized])').each(function () {
var $this = $(this);
var inputMode = $this.data('input-mode');
var options = {
altInput: true,
allowInput: true,
minuteIncrement: $this.data('step') || 1,
dateFormat: $this.data('datetime-format'),
enableTime: inputMode !== 'date',
noCalendar: inputMode === 'time'
};
$this.attr('data-initialized', '').flatpickr(options);
});
});
|
Fix errors revealed by tests | <?php
namespace TheCrypticAce\Suitey\Steps;
use Closure;
use TheCrypticAce\Suitey\IO;
use TheCrypticAce\Suitey\Process;
class Migrate implements Step
{
public function __construct($database = null, $path = null)
{
$this->path = $path;
$this->database = $database;
}
public function name()
{
return $this->database
? "Migrate {$this->database}"
: "Migrate database";
}
public function handle(IO $io, Closure $next)
{
$arguments = [];
if ($this->path) {
$arguments[] = "--path={$this->path}";
}
if ($this->database) {
$arguments[] = "--database={$this->database}";
}
Process::artisan("migrate")->quiet()->run($arguments);
$exitCode = $next($io);
Process::artisan("migrate:rollback")->quiet()->run($arguments);
return $exitCode;
}
}
| <?php
namespace TheCrypticAce\Suitey\Steps;
use Closure;
use TheCrypticAce\Suitey\IO;
use TheCrypticAce\Suitey\Process;
class Migrate implements Step
{
public function __construct($database = null, $path = null)
{
$this->path = $path;
$this->database = $database;
}
public function name()
{
return $this->database
? "Migrate {$this->database}"
: "Migrate database";
}
public function handle(IO $io, Closure $next)
{
Process::artisan("migrate")->quiet()->run([
"--path={$this->path}",
"--database={$this->database}",
]);
$exitCode = $next($io);
Process::artisan("migrate:rollback")->quiet()->run([
"--path={$this->path}",
"--database={$this->database}",
]);
return $exitCode;
}
}
|
Test work of API communication | (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
userVm.newSession = false;
userVm.username = "";
userVm.sessionId = sessionService.getSessionId();
sessionService
.sessionExists(userVm.sessionId)
.then(function(data) {
userVm.newSession = true;
});
console.log(userVm.newSession);
//scope method assignments
userVm.createAndJoinSession = createAndJoinSession;
userVm.joinExistingSession = joinExistingSession;
//scope method definitions
function createAndJoinSession() {
sessionService.createSession();
userService.addUserToSession(userVm.username, userVm.sessionId);
}
function joinExistingSession() {
userService.addUserToSession(userVm.username, userVm.sessionId);
}
}
})();
| (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
userVm.newSession = false;
userVm.username = "";
userVm.sessionId = sessionService.getSessionId();
sessionService
.sessionExists(userVm.sessionId)
.then(function(data) {
userVm.newSession = data;
});
console.log(userVm.newSession);
//scope method assignments
userVm.createAndJoinSession = createAndJoinSession;
userVm.joinExistingSession = joinExistingSession;
//scope method definitions
function createAndJoinSession() {
sessionService.createSession();
userService.addUserToSession(userVm.username, userVm.sessionId);
}
function joinExistingSession() {
userService.addUserToSession(userVm.username, userVm.sessionId);
}
}
})();
|
Resolve path names relatives to cwd when using via CLI | #!/usr/bin/env node
var path = require('path')
var express = require('express')
var app = express()
var dafuq = require('./')
var argv = require('yargs')
.usage('$0 Leverages command-based api')
.describe('commands', 'the path to commands directory')
.alias('commands', 'c')
.alias('commands', 'path')
.alias('commands', 'directory')
.demand('commands')
.describe('shebang', 'the interpreter to use when running the command files')
.default('shebang', '')
.describe('port', 'the port where to listen for api call')
.alias('port', 'p')
.default('port', 3000)
.help('help')
.alias('help', 'h')
.argv;
// Resolve full path when executing via CLI
if (require.main === module)
argv.commands = path.resolve(process.pwd(), argv.commands)
app.use(dafuq({
path: argv.commands,
shebang: argv.shebang
}))
app.listen(argv.port)
| #!/usr/bin/env node
var express = require('express')
var app = express()
var dafuq = require('./')
var argv = require('yargs')
.usage('$0 Leverages command-based api')
.describe('commands', 'the path to commands directory')
.alias('commands', 'c')
.alias('commands', 'path')
.alias('commands', 'directory')
.demand('commands')
.describe('shebang', 'the interpreter to use when running the command files')
.default('shebang', '')
.describe('port', 'the port where to listen for api call')
.alias('port', 'p')
.default('port', 3000)
.help('help')
.alias('help', 'h')
.argv;
app.use(dafuq({
path: argv.commands,
shebang: argv.shebang
}))
app.listen(argv.port)
|
Add new work time value - 3/8 | // User roles
app.constant('USER_ROLES', {
all: ['ROLES_ADMIN', 'ROLES_LEADER', 'ROLES_WORKER'],
admin: 'ROLES_ADMIN',
worker: 'ROLES_WORKER',
leader: 'ROLES_LEADER'
});
// Authentication events
app.constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
badRequest: 'auth-bad-request',
logoutSuccess: 'auth-logout-success',
sessionCreated: 'auth-session-created',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized',
refreshNeeded: 'app-refresh-needed'
});
app.constant('PROGRESS_BAR_EVENTS', {
stop: "progress_bar_stop",
start: "progress_bar_start",
once: "progress_bar_once",
stop_once: "progress_bar_stop_once"
});
// Cookie expiration time
app.constant('COOKIE_EXP_TIME', 86400000); //set to 1 day
app.constant('WORK_TIMES', ['1', '7/8', '4/5', '3/4', '3/5', '1/2', '2/5', '3/8', '1/4', '1/5', '1/8', '1/16']);
| // User roles
app.constant('USER_ROLES', {
all: ['ROLES_ADMIN', 'ROLES_LEADER', 'ROLES_WORKER'],
admin: 'ROLES_ADMIN',
worker: 'ROLES_WORKER',
leader: 'ROLES_LEADER'
});
// Authentication events
app.constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
badRequest: 'auth-bad-request',
logoutSuccess: 'auth-logout-success',
sessionCreated: 'auth-session-created',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized',
refreshNeeded: 'app-refresh-needed'
});
app.constant('PROGRESS_BAR_EVENTS', {
stop: "progress_bar_stop",
start: "progress_bar_start",
once: "progress_bar_once",
stop_once: "progress_bar_stop_once"
});
// Cookie expiration time
app.constant('COOKIE_EXP_TIME', 86400000); //set to 1 day
app.constant('WORK_TIMES', ['1', '7/8', '4/5', '3/4', '3/5', '1/2', '2/5', '1/4', '1/5', '1/8', '1/16']);
|
Add the company to the main controller | <?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use common\models\Company;
class MainController extends Controller
{
private $company;
public function init()
{
parent::init();
// Set the language
if (isset($_GET['lang'])) {
\Yii::$app->language = $_GET['lang'];
\Yii::$app->session['lang'] = \Yii::$app->language;
} else
if (isset(\Yii::$app->session['lang'])) {
\Yii::$app->session['lang'] = \Yii::$app->language;
}
// Set the timezone
date_default_timezone_set('Europe/Helsinki');
if(!yii::$app->user->isGuest){
$this->company = Company::findOne(yii::$app->user->identity->company_id);
}
}
protected function getCompany(){
if($this->company)
{
return $this->company;
}
}
}
?> | <?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
class MainController extends Controller
{
public function init()
{
parent::init();
// Set the language
if (isset($_GET['lang'])) {
\Yii::$app->language = $_GET['lang'];
\Yii::$app->session['lang'] = \Yii::$app->language;
} else
if (isset(\Yii::$app->session['lang'])) {
\Yii::$app->session['lang'] = \Yii::$app->language;
}
// Set the timezone
date_default_timezone_set('Europe/Helsinki');
}
}
?> |
Add back operators_in_feed from feedinfo response | import Ember from 'ember';
export default Ember.Route.extend({
createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'),
beforeModel: function(transition) {
var controller = this;
var feedModel = this.get('createFeedFromGtfsService').feedModel;
var url = feedModel.get('url');
var adapter = this.get('store').adapterFor('feeds');
var fetch_info_url = adapter.urlPrefix()+'/feeds/fetch_info';
var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}});
promise.then(function(response) {
if (response.status == 'complete') {
feedModel.set('id', response.feed.onestop_id);
feedModel.set('operators_in_feed', response.feed.operators_in_feed);
response.operators.map(function(operator){feedModel.addOperator(operator)});
return feedModel;
} else if (response.status == 'processing') {
transition.abort();
return Ember.run.later(controller, function(){
transition.retry();
}, 1000);
}
}).catch(function() {
feedModel.get('errors').add('url','The feed URL is invalid. Please check the link and try again.');
});
return promise
},
model: function() {
return this.get('createFeedFromGtfsService').feedModel;
}
});
| import Ember from 'ember';
export default Ember.Route.extend({
createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'),
beforeModel: function(transition) {
var controller = this;
var feedModel = this.get('createFeedFromGtfsService').feedModel;
var url = feedModel.get('url');
var adapter = this.get('store').adapterFor('feeds');
var fetch_info_url = adapter.urlPrefix()+'/feeds/fetch_info';
var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}});
promise.then(function(response) {
if (response.status == 'complete') {
feedModel.set('id', response.feed.onestop_id);
response.operators.map(function(operator){feedModel.addOperator(operator)});
return feedModel;
} else if (response.status == 'processing') {
transition.abort();
return Ember.run.later(controller, function(){
transition.retry();
}, 1000);
}
}).catch(function() {
feedModel.get('errors').add('url','The feed URL is invalid. Please check the link and try again.');
});
return promise
},
model: function() {
return this.get('createFeedFromGtfsService').feedModel;
}
});
|
Use raw strings for regexp URLs. |
from django.conf.urls.defaults import patterns, url
from django.views.generic import ListView
from review import views
from extensions.models import ExtensionVersion, STATUS_LOCKED
urlpatterns = patterns('',
url(r'^$', ListView.as_view(queryset=ExtensionVersion.objects.filter(status=STATUS_LOCKED),
context_object_name="versions",
template_name="review/list.html"), name='review-list'),
url(r'^ajax/v/(?P<pk>\d+)', views.AjaxGetFilesView.as_view(), name='review-ajax-files'),
url(r'^submit/(?P<pk>\d+)', views.SubmitReviewView.as_view(), name='review-submit'),
url(r'^(?P<pk>\d+)', views.ReviewVersionView.as_view(), name='review-version'),
)
|
from django.conf.urls.defaults import patterns, url
from django.views.generic import ListView
from review import views
from extensions.models import ExtensionVersion, STATUS_LOCKED
urlpatterns = patterns('',
url(r'^$', ListView.as_view(queryset=ExtensionVersion.objects.filter(status=STATUS_LOCKED),
context_object_name="versions",
template_name="review/list.html"), name='review-list'),
url('^ajax/v/(?P<pk>\d+)', views.AjaxGetFilesView.as_view(), name='review-ajax-files'),
url('^submit/(?P<pk>\d+)', views.SubmitReviewView.as_view(), name='review-submit'),
url('^(?P<pk>\d+)', views.ReviewVersionView.as_view(), name='review-version'),
)
|
FIX public attribute issue while creating defect | <?php
namespace Solidifier\Visitors\Property;
use Solidifier\Visitors\AbstractClassVisitor;
use PhpParser\Node;
use PhpParser\Node\Stmt\Property;
class PublicAttributes extends AbstractClassVisitor
{
public function enterNode(Node $node)
{
parent::enterNode($node);
if($node instanceof Property)
{
if($node->isPublic())
{
foreach($node->props as $property)
{
$this->dispatch(
new \Solidifier\Defects\PublicAttribute($this->currentClass, $property->name, $node)
);
}
}
}
}
} | <?php
namespace Solidifier\Visitors\Property;
use Solidifier\Visitors\AbstractClassVisitor;
use PhpParser\Node;
use PhpParser\Node\Stmt\Property;
class PublicAttributes extends AbstractClassVisitor
{
public function enterNode(Node $node)
{
parent::enterNode($node);
if($node instanceof Property)
{
if($node->isPublic())
{
foreach($node->props as $property)
{
$this->dispatch(
new \Solidifier\Defects\PublicAttribute($this->currentClass, $property, $node)
);
}
}
}
}
} |
Fix uploader when there is nothing to upload | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import glob
import os
import requests
import stoneridge
class StoneRidgeUploader(object):
"""Takes the upload files created by the collator and uploads them to the
graph server
"""
def __init__(self):
self.url = stoneridge.get_config('upload', 'url')
def run(self):
file_pattern = os.path.join(stoneridge.outdir, 'upload_*.json')
upload_files = glob.glob(file_pattern)
if not upload_files:
# Nothing to do, so forget it!
return
files = {os.path.basename(fname): open(fname, 'rb')
for fname in upload_files}
requests.post(self.url, files=files)
for f in files.values():
f.close()
@stoneridge.main
def main():
parser = stoneridge.ArgumentParser()
args = parser.parse_args()
uploader = StoneRidgeUploader()
uploader.run()
| #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import glob
import os
import requests
import stoneridge
class StoneRidgeUploader(object):
"""Takes the upload files created by the collator and uploads them to the
graph server
"""
def __init__(self):
self.url = stoneridge.get_config('upload', 'url')
def run(self):
file_pattern = os.path.join(stoneridge.outdir, 'upload_*.json')
upload_files = glob.glob(file_pattern)
files = {os.path.basename(fname): open(fname, 'rb')
for fname in upload_files}
requests.post(self.url, files=files)
for f in files.values():
f.close()
@stoneridge.main
def main():
parser = stoneridge.ArgumentParser()
args = parser.parse_args()
uploader = StoneRidgeUploader()
uploader.run()
|
Revise doc string with highlighting "weighted" graph | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def dijkstra(weighted_graph_d, start_vertex):
"""Dijkstra algorithm for "weighted" graph.
Finds shortest path in a weighted graph from a particular node
to all vertices that are reachable from it.
"""
pass
def main():
weighted_graph_d = {
'u': {'v': 2, 'w': 5, 'x': 1},
'v': {'u': 2, 'w': 3, 'x': 2},
'w': {'u': 5, 'v': 3, 'x': 3, 'y': 1, 'z': 5},
'x': {'u': 1, 'v': 2, 'w': 3, 'y': 1},
'y': {'w': 1, 'x': 1, 'z': 1},
'z': {'w': 5, 'y': 1}
}
start_vertex = 'x'
print('weighted_graph_d: {}'.format(weighted_graph_d))
print('Dijkstra shortest path from {}:'.format(start_vertex))
shortest_path_d, vertex_lookup_d = dijkstra(
weighted_graph_d, start_vertex)
print('shortest_path_d: {}'.format(shortest_path_d))
print('vertex_lookup_d: {}'.format(vertex_lookup_d))
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def dijkstra(weighted_graph_d, start_vertex):
"""Dijkstra algorithm for weighted graph.
Finds shortest path in a weighted graph from a particular node
to all vertices that are reachable from it.
"""
pass
def main():
weighted_graph_d = {
'u': {'v': 2, 'w': 5, 'x': 1},
'v': {'u': 2, 'w': 3, 'x': 2},
'w': {'u': 5, 'v': 3, 'x': 3, 'y': 1, 'z': 5},
'x': {'u': 1, 'v': 2, 'w': 3, 'y': 1},
'y': {'w': 1, 'x': 1, 'z': 1},
'z': {'w': 5, 'y': 1}
}
start_vertex = 'x'
print('weighted_graph_d: {}'.format(weighted_graph_d))
print('Dijkstra shortest path from {}:'.format(start_vertex))
shortest_path_d, vertex_lookup_d = dijkstra(
weighted_graph_d, start_vertex)
print('shortest_path_d: {}'.format(shortest_path_d))
print('vertex_lookup_d: {}'.format(vertex_lookup_d))
if __name__ == '__main__':
main()
|
Add clone function, required by chunk. | function d3_treemap_rect(x, y, width, height) {
var rect = {};
rect.clone = function() {
return d3_treemap_rect(x, y, width, height);
}
rect.x = function(_) {
if (!arguments.length) return x;
x = _;
return rect;
};
rect.y = function(_) {
if (!arguments.length) return y;
y = _;
return rect;
};
rect.width = function(_) {
if (!arguments.length) return width;
width = _;
return rect;
};
rect.height = function(_) {
if (!arguments.length) return height;
height = _;
return rect;
};
rect.toPojo = function() {
return { x: x, y: y, width: width, height: height };
}
return rect;
}
| function d3_treemap_rect(x, y, width, height) {
var rect = {};
rect.x = function(_) {
if (!arguments.length) return x;
x = _;
return rect;
};
rect.y = function(_) {
if (!arguments.length) return y;
y = _;
return rect;
};
rect.width = function(_) {
if (!arguments.length) return width;
width = _;
return rect;
};
rect.height = function(_) {
if (!arguments.length) return height;
height = _;
return rect;
};
rect.toPojo = function() {
return { x: x, y: y, width: width, height: height };
}
return rect;
}
|
Fix formatting of config errors. | package com.yammer.dropwizard.config;
import java.io.File;
/**
* An exception thrown where there is an error parsing a configuration object.
*/
public class ConfigurationException extends Exception {
private static final long serialVersionUID = 5325162099634227047L;
/**
* Creates a new {@link ConfigurationException} for the given file with the given errors.
*
* @param file the bad configuration file
* @param errors the errors in the file
*/
public ConfigurationException(File file, Iterable<String> errors) {
super(formatMessage(file, errors));
}
private static String formatMessage(File file, Iterable<String> errors) {
final StringBuilder msg = new StringBuilder(file.toString())
.append(" has the following errors:\n");
for (String error : errors) {
msg.append(" * ").append(error).append('\n');
}
return msg.toString();
}
}
| package com.yammer.dropwizard.config;
import java.io.File;
/**
* An exception thrown where there is an error parsing a configuration object.
*/
public class ConfigurationException extends Exception {
private static final long serialVersionUID = 5325162099634227047L;
/**
* Creates a new {@link ConfigurationException} for the given file with the given errors.
*
* @param file the bad configuration file
* @param errors the errors in the file
*/
public ConfigurationException(File file, Iterable<String> errors) {
super(formatMessage(file, errors));
}
private static String formatMessage(File file, Iterable<String> errors) {
final StringBuilder msg = new StringBuilder(file.toString())
.append(" has the following errors:\n");
for (String error : errors) {
msg.append(" * ").append(error);
}
return msg.toString();
}
}
|
Add javadoc for authentication utility | package util;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class UserAuthUtil {
/**
* Returns a boolean for the user's login status
* @return user login status
*/
public static boolean isUserLoggedIn() {
UserService userServ = UserServiceFactory.getUserService();
return userServ.isUserLoggedIn();
}
/**
* @param redirect URL for webpage to return to after login
* @return URL for user to click to login
*/
public static String getLoginURL(String redirect) {
UserService userServ = UserServiceFactory.getUserService();
return userServ.createLoginURL(redirect);
}
/**
* @param redirect URL for webpage to return to after logout
* @return URL for user to click to logout
*/
public static String getLogoutURL(String redirect) {
return UserServiceFactory.getUserService().createLogoutURL(redirect);
}
/**
* Helper method to return a User object
*/
public static User getUser() {
return UserServiceFactory.getUserService().getCurrentUser();
}
/**
* Determines whether a user is authorized to use the requested resource
* @return true when the user's email domain is "google.com"
*/
public static boolean isUserAuthorized() {
return getDomainName().equals("google.com");
}
/**
* @return domain name from a user's email address
*/
private static String getDomainName() {
String email = getUser().getEmail();
return email.substring(email.indexOf('@') + 1);
}
} | package util;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class UserAuthUtil {
/**
* Returns a boolean for the user's login status
* @return user login status
*/
public static boolean isUserLoggedIn() {
UserService userServ = UserServiceFactory.getUserService();
return userServ.isUserLoggedIn();
}
/**
* @param redirect URL for webpage to return to after login
* @return
*/
public static String getLoginURL(String redirect) {
UserService userServ = UserServiceFactory.getUserService();
return userServ.createLoginURL(redirect);
}
public static String getLogoutURL(String redirect) {
return UserServiceFactory.getUserService().createLogoutURL(redirect);
}
public static User getUser() {
return UserServiceFactory.getUserService().getCurrentUser();
}
public static boolean isUserAuthorized() {
return getDomainName().equals("google.com");
}
private static String getDomainName() {
String email = getUser().getEmail();
return email.substring(email.indexOf('@') + 1);
}
} |
[TaxationBundle] Add event subscriber AddCodeFormSubscriber to TaxRateType and TaxCategoryType
[TaxationBundle] Add validation for filed 'code' from TaxRate and TaxCategory
[Taxation] Add field 'code' to TaxCategory and TaxRate, TaxCategoryInterface and TaxRateInterface extend AwareCodeInterface
[WebBundle] Add code filed to TaxCategory views and to TaxRate views | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Shipping\Model;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface ShippingCategoryInterface extends CodeAwareInterface, TimestampableInterface, ResourceInterface
{
/**
* @return mixed
*/
public function getId();
/**
* @return string
*/
public function getName();
/**
* @param string $name
*/
public function setName($name);
/**
* @return string
*/
public function getDescription();
/**
* @param string $description
*/
public function setDescription($description);
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Shipping\Model;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface ShippingCategoryInterface extends CodeAwareInterface, TimestampableInterface, ResourceInterface
{
/**
* @return mixed
*/
public function getId();
/**
* @return string
*/
public function getName();
/**
* @param string $name
*/
public function setName($name);
/**
* @return string
*/
public function getDescription();
/**
* @param string $description
*/
public function setDescription($description);
}
|
FIX: Set REQUEST_URI to go back to page requested before logging in | <?php
namespace phorkie;
/**
* security levels + login requirement:
*/
if (!isset($GLOBALS['phorkie']['auth']['secure'])) {
//not set? highest level of security
$GLOBALS['phorkie']['auth']['secure'] = 2;
}
if ($GLOBALS['phorkie']['auth']['secure'] == 0) {
//everyone may do everything
return;
}
$logged_in = false;
if (!isset($_SESSION['identity'])) {
//not logged in
} else if ($GLOBALS['phorkie']['auth']['userlist']) {
if (in_array($_SESSION['identity'], $GLOBALS['phorkie']['users'])) {
$logged_in = true;
}
} else {
//session identity exists, no special checks required
$logged_in = true;
}
if ($pageRequiresLogin >= $GLOBALS['phorkie']['auth']['secure']) {
if ($logged_in) {
return;
}
} else {
return;
}
// p / G / log_in = disp
// 0 / 1 / true = return
// 0 / 1 / false = block
// 0 / 2 / true = return
// 0 / 2 / false = return
// 1 / 1 / true = return
// 1 / 1 / false = block
// 1 / 2 / true = return
// 1 / 2 / false = block
$_SESSION['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
require 'forbidden.php';
?>
| <?php
namespace phorkie;
/**
* security levels + login requirement:
*/
if (!isset($GLOBALS['phorkie']['auth']['secure'])) {
//not set? highest level of security
$GLOBALS['phorkie']['auth']['secure'] = 2;
}
if ($GLOBALS['phorkie']['auth']['secure'] == 0) {
//everyone may do everything
return;
}
$logged_in = false;
if (!isset($_SESSION['identity'])) {
//not logged in
} else if ($GLOBALS['phorkie']['auth']['userlist']) {
if (in_array($_SESSION['identity'], $GLOBALS['phorkie']['users'])) {
$logged_in = true;
}
} else {
//session identity exists, no special checks required
$logged_in = true;
}
if ($pageRequiresLogin >= $GLOBALS['phorkie']['auth']['secure']) {
if ($logged_in) {
return;
}
} else {
return;
}
// p / G / log_in = disp
// 0 / 1 / true = return
// 0 / 1 / false = block
// 0 / 2 / true = return
// 0 / 2 / false = return
// 1 / 1 / true = return
// 1 / 1 / false = block
// 1 / 2 / true = return
// 1 / 2 / false = block
require 'forbidden.php';
?>
|
Improve the way that import middlewares | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from flask import Flask
from werkzeug.utils import import_string
from me_api.middleware.me import me
from me_api.cache import cache
middlewares = {
'douban': 'me_api.middleware.douban:douban_api',
'github': 'me_api.middleware.github:github_api',
'instagram': 'me_api.middleware.instagram:instagram_api',
'keybase': 'me_api.middleware.keybase:keybase_api',
'medium': 'me_api.middleware.medium:medium_api',
'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
blueprint = import_string(middlewares[module])
app.register_blueprint(blueprint)
return app
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from flask import Flask
from .middleware.me import me
from .cache import cache
def _register_module(app, module):
if module == 'douban':
from .middleware import douban
app.register_blueprint(douban.douban_api)
elif module == 'github':
from .middleware import github
app.register_blueprint(github.github_api)
elif module == 'instagram':
from .middleware import instagram
app.register_blueprint(instagram.instagram_api)
elif module == 'keybase':
from .middleware import keybase
app.register_blueprint(keybase.keybase_api)
elif module == 'medium':
from .middleware import medium
app.register_blueprint(medium.medium_api)
elif module == 'stackoverflow':
from .middleware import stackoverflow
app.register_blueprint(stackoverflow.stackoverflow_api)
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
_register_module(app, module)
return app
|
Change font of ASCII to Courier | import tkinter as tk
from time import sleep
from movie01 import reel
window = tk.Tk()
def main():
window.title("Tkinter Movie Player")
button = tk.Button(window, text = "Play", command = processPlay)
button.pack()
window.mainloop()
def processPlay():
TIME_STEP = 0.3
label = tk.Label(window, text = "", font = ("Courier"))
label.pack()
count = 0
while count < len(reel):
s = ""
frame = reel[count]
for line in frame:
s += line + "\n"
count += 1
label["text"] = s
label.pack()
window.update()
sleep(TIME_STEP)
main() | import tkinter as tk
from time import sleep
from movie01 import reel
window = tk.Tk()
def main():
window.title("Tkinter Movie Player")
button = tk.Button(window, text = "Play", command = processPlay)
button.pack()
window.mainloop()
def processPlay():
TIME_STEP = 0.3
label = tk.Label(window, text = "")
label.pack()
count = 0
while count < len(reel):
s = ""
frame = reel[count]
for line in frame:
s += line + "\n"
count += 1
label["text"] = s
label.pack()
window.update()
sleep(TIME_STEP)
main() |
Create form: prevent refresh, clean forms after enter. | var createBetNotification = function(bet){
var bet = Bets.findOne({ _id: bet });
BetNotifications.insert({
toNotify: bet.bettors[1],
betBy: bet.bettors[0]
});
}
Template.createBetForm.events({
"submit .create-bet" : function(event){
event.preventDefault();
var status = "open",
title = event.target.betTitle.value;
wager = event.target.betWager.value;
user = Meteor.user(),
defender_requested = event.target.defender.value;
defender = Meteor.users.findOne({ username: defender_requested });
var bet = Bets.insert({
bettors: [ user.username, defender.username ],
status: status,
title: title,
wager: wager
});
event.target.betTitle.value = '';
event.target.betWager.value = '';
event.target.defender.value = '';
createBetNotification(bet);
}
});
| var createBetNotification = function(bet){
var bet = Bets.findOne({ _id: bet });
BetNotifications.insert({
toNotify: bet.bettors[1],
betBy: bet.bettors[0]
});
}
Template.createBetForm.events({
"submit .create-bet" : function(event){
var status = "open",
title = event.target.betTitle.value;
wager = event.target.betWager.value;
user = Meteor.user(),
defender_requested = event.target.defender.value;
defender = Meteor.users.findOne({ username: defender_requested });
var bet = Bets.insert({
bettors: [ user.username, defender.username ],
status: status,
title: title,
wager: wager
});
createBetNotification(bet);
}
});
|
Modify createdAt and updatedAt field type to dateonly | 'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
queryInterface.createTable('Documents', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
accessType: {
type: Sequelize.STRING
},
content: {
type: Sequelize.TEXT
},
owner: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATEONLY
},
updatedAt: {
allowNull: false,
type: Sequelize.DATEONLY
},
userId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id',
as: 'userId',
},
},
});
},
down: (queryInterface, Sequelize) => {
queryInterface.dropTable('Documents');
}
};
| 'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
queryInterface.createTable('Documents', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
accessType: {
type: Sequelize.STRING
},
content: {
type: Sequelize.TEXT
},
owner: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
userId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id',
as: 'userId',
},
},
});
},
down: (queryInterface, Sequelize) => {
queryInterface.dropTable('Documents');
}
};
|
Fix bug issue in Settings Ctrl | (function() {
var SettingsCtrl = function($scope, $ionicModal, Auth) {
var vm = this
$ionicModal
.fromTemplateUrl("js/modules/tabs/settings/views/login.html", {
scope: $scope,
animation: "slide-in-up"
})
.then(function(modal) {
vm.loginModal = modal;
})
vm.openModal = openModal
vm.closeModal = closeModal
vm.login = login
//////////////////////
function openModal() {
vm.loginModal.show();
};
function closeModal(){
vm.loginModal.hide();
}
function login(){
Restangular.all('users').all('login').post( vm.username, vm.password )
.then(function(err, result){
if (err) throw
Auth.setAuthToken( result.user.username, result.sessionsToken, result.user );
})
}
};
SettingsCtrl
.$inject = ['$scope', '$ionicModal', 'Auth'];
angular
.module('app.modules.tabs.settings.controllers', [])
.controller('SettingsCtrl', SettingsCtrl);
})();
| (function() {
var SettingsCtrl = function($scope, $ionicModal, Auth) {
var vm = this
$ionicModal
.fromTemplateUrl("js/modules/tabs/settings/views/login.html", {
scope: $scope,
animation: "slide-in-up"
})
.then(function(modal) {
vm.loginModal = modal;
})
vm.openModal = openModal
vm.closeModal = closeModal
vm.login = login
//////////////////////
function openModal() {
vm.loginModal.show();
};
function closeModal(){
vm.loginModal.hide();
}
function login(){
Auth.setAuthToken( vm.username, vm.password );
}
};
SettingsCtrl
.$inject = ['$scope', '$ionicModal', 'Auth'];
angular
.module('app.modules.tabs.settings.controllers', [])
.controller('SettingsCtrl', SettingsCtrl);
})();
|
Test all the code paths | import unittest
import cbs
class AttrSettings():
PROJECT_NAME = 'fancy_project'
class MethodSettings():
def PROJECT_NAME(self):
return 'fancy_project'
class TestApply(unittest.TestCase):
def test_apply_settings_attr(self):
g = {}
cbs.apply(AttrSettings, g)
self.assertEqual(g['PROJECT_NAME'], 'fancy_project')
def test_apply_settings_method(self):
g = {}
cbs.apply(MethodSettings, g)
self.assertEqual(g['PROJECT_NAME'], 'fancy_project')
def test_apply_settings_string_local(self):
g = {'AttrSettings': AttrSettings}
cbs.apply('AttrSettings', g)
self.assertEqual(g['PROJECT_NAME'], 'fancy_project')
def test_apply_settings_string_reference(self):
g = {}
cbs.apply(__name__ + '.AttrSettings', g)
self.assertEqual(g['PROJECT_NAME'], 'fancy_project')
def test_apply_settings_invalid_string_local(self):
self.assertRaises(ValueError, cbs.apply, 'LocalSettings', {})
def test_apply_settings_invalid_string_reference(self):
self.assertRaises(ImportError, cbs.apply, 'invalid.Class', {})
| import unittest
import cbs
class AttrSettings():
PROJECT_NAME = 'fancy_project'
class MethodSettings():
def PROJECT_NAME(self):
return 'fancy_project'
class TestApply(unittest.TestCase):
def test_apply_settings_attr(self):
g = {}
cbs.apply(AttrSettings, g)
self.assertEqual(g['PROJECT_NAME'], 'fancy_project')
def test_apply_settings_method(self):
g = {}
cbs.apply(MethodSettings, g)
self.assertEqual(g['PROJECT_NAME'], 'fancy_project')
def test_apply_settings_string_reference(self):
g = {}
cbs.apply(__name__ + '.AttrSettings', g)
self.assertEqual(g['PROJECT_NAME'], 'fancy_project')
def test_apply_settings_invalid_string_reference(self):
self.assertRaises(ImportError, cbs.apply, 'invalid.Class', {})
|
Access the base file in the JAR. | package com.github.googlei18n.tachyfont;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class TachyFontServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
String jarFilename = "fonts/noto/sans/NotoSansJP-Thin_subset_smp.TachyFont.jar";
JarFile jarFile = new JarFile("WEB-INF/" + jarFilename);
resp.getWriter().println("Jar file: " + jarFilename);
Enumeration<JarEntry> enumEntries = jarFile.entries();
resp.getWriter().println("jar file entries:");
while (enumEntries.hasMoreElements()) {
JarEntry jarEntry = enumEntries.nextElement();
resp.getWriter().println(" " + jarEntry.getName());
}
JarEntry base = jarFile.getJarEntry("base");
InputStream baseStream = jarFile.getInputStream(base);
JarEntry closure_data = jarFile.getJarEntry("closure_data");
JarEntry closure_idx = jarFile.getJarEntry("closure_idx");
JarEntry codepoints = jarFile.getJarEntry("codepoints");
JarEntry gids = jarFile.getJarEntry("gids");
JarEntry glyph_data = jarFile.getJarEntry("glyph_data");
JarEntry glyph_table = jarFile.getJarEntry("glyph_table");
jarFile.close();
}
}
| package com.github.googlei18n.tachyfont;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class TachyFontServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
String jarFilename = "fonts/noto/sans/NotoSansJP-Thin_subset_smp.TachyFont.jar";
JarFile jarFile = new JarFile("WEB-INF/" + jarFilename);
resp.getWriter().println("Jar entries in " + jarFilename + ":");
Enumeration<JarEntry> enumEntries = jarFile.entries();
resp.getWriter().println("jar file:");
while (enumEntries.hasMoreElements()) {
JarEntry jarEntry = enumEntries.nextElement();
resp.getWriter().println(" " + jarEntry.getName());
}
JarEntry base = jarFile.getJarEntry("base");
JarEntry closure_data = jarFile.getJarEntry("closure_data");
JarEntry closure_idx = jarFile.getJarEntry("closure_idx");
JarEntry codepoints = jarFile.getJarEntry("codepoints");
JarEntry gids = jarFile.getJarEntry("gids");
JarEntry glyph_data = jarFile.getJarEntry("glyph_data");
JarEntry glyph_table = jarFile.getJarEntry("glyph_table");
jarFile.close();
}
}
|
Improve test by removing a hard coded value
Small things make life sweet. | var common = require('../../common');
var connection = common.createConnection();
var assert = require('assert');
common.useTestDb(connection);
var table = 'stream_test';
connection.query([
'CREATE TEMPORARY TABLE `' + table + '` (',
'`id` int(11) unsigned NOT NULL AUTO_INCREMENT,',
'`title` varchar(255),',
'PRIMARY KEY (`id`)',
') ENGINE=InnoDB DEFAULT CHARSET=utf8'
].join('\n'));
var rowCount = 10;
for (var i = 1; i <= rowCount; i++) {
var row = {
id: i,
title: 'Row #' + i,
};
connection.query('INSERT INTO ' + table + ' SET ?', row);
}
var query = connection.query('SELECT * FROM ' + table);
var hadEnd = false;
var rows = [];
var fields = undefined;
query.on('result', function(row) {
connection.pause();
connection.resume();
rows.push(row);
})
.on('end', function() {
hadEnd = true;
});
connection.end();
process.on('exit', function() {
assert.equal(rows.length, rowCount);
assert.equal(hadEnd, true);
});
| var common = require('../../common');
var connection = common.createConnection();
var assert = require('assert');
common.useTestDb(connection);
var table = 'stream_test';
connection.query([
'CREATE TEMPORARY TABLE `' + table + '` (',
'`id` int(11) unsigned NOT NULL AUTO_INCREMENT,',
'`title` varchar(255),',
'PRIMARY KEY (`id`)',
') ENGINE=InnoDB DEFAULT CHARSET=utf8'
].join('\n'));
var rowCount = 10;
for (var i = 1; i <= rowCount; i++) {
var row = {
id: i,
title: 'Row #' + i,
};
connection.query('INSERT INTO ' + table + ' SET ?', row);
}
var query = connection.query('SELECT * FROM ' + table);
var hadEnd = false;
var rows = [];
var fields = undefined;
query.on('result', function(row) {
connection.pause();
connection.resume();
rows.push(row);
})
.on('end', function() {
hadEnd = true;
});
connection.end();
process.on('exit', function() {
assert.equal(rows.length, 10);
assert.equal(hadEnd, true);
});
|
Stop event propagation in form-selector | "use strict";
annotationApp.directive('formSelector', function() {
return {
restrict: 'E',
replace: true,
controller: function($scope, $element, $attrs) {
var id = $scope.id;
var form = $scope.form;
$scope.text = 'Select';
$scope.action = function(event) {
event.stopPropagation();
if ($scope.plugin.isFormSelected(id, form)) {
$scope.text = "Select";
$scope.plugin.unsetState(id);
} else {
$scope.text = "Deselect";
$scope.plugin.setState(id, form);
}
};
},
template: '<span ng-click="action($event)">{{ text }}</span>'
};
});
| "use strict";
annotationApp.directive('formSelector', function() {
return {
restrict: 'E',
replace: true,
controller: function($scope, $element, $attrs) {
var id = $scope.id;
var form = $scope.form;
$scope.text = 'Select';
$scope.action = function() {
if ($scope.plugin.isFormSelected(id, form)) {
$scope.text = "Select";
$scope.plugin.unsetState(id);
} else {
$scope.text = "Deselect";
$scope.plugin.setState(id, form);
}
};
},
template: '<span ng-click="action()">{{ text }}</span>'
};
});
|
Revert "Update CORS provider, again..."
This reverts commit cdd91c9eca4ea4675296e96c8ede6c8f8d7a3236. | $(document).ready(function() {
var menuUrl = "https://www.bin4burgerlounge.com/our-downtown-menu/";
$.ajax({
url: "https://cors-anywhere.herokuapp.com/" + menuUrl,
dataType: "html",
crossDomain: true,
success: writeData
});
function writeData(data, textStatus, jqXHR) {
var root = $($.parseHTML(data));
writeItem(root, "burger");
writeItem(root, "appy");
writeItem(root, "feature cocktail");
writeItem(root, "dessert");
}
function writeItem(root, name) {
var itemElem = root.find(".slide-features .menu-item")
.filter(function(index, elem) {
var text = jQuery(elem).find(".item-label").first().text();
return (text == name);
}).first();
name = name.replace(" ","");
jQuery("#" + name + "_name").text(itemElem.find(".item-title").text());
jQuery("#" + name + "_price").text(itemElem.find(".item-price").text());
jQuery("#" + name + "_description").text(itemElem.find("p").text());
}
});
| $(document).ready(function() {
var menuUrl = "https://www.bin4burgerlounge.com/our-downtown-menu/";
$.ajax({
url: "http://www.corsmirror.com/v1/cors?url=" + menuUrl,
dataType: "html",
crossDomain: true,
success: writeData
});
function writeData(data, textStatus, jqXHR) {
var root = $($.parseHTML(data));
writeItem(root, "burger");
writeItem(root, "appy");
writeItem(root, "feature cocktail");
writeItem(root, "dessert");
}
function writeItem(root, name) {
var itemElem = root.find(".slide-features .menu-item")
.filter(function(index, elem) {
var text = jQuery(elem).find(".item-label").first().text();
return (text == name);
}).first();
name = name.replace(" ","");
jQuery("#" + name + "_name").text(itemElem.find(".item-title").text());
jQuery("#" + name + "_price").text(itemElem.find(".item-price").text());
jQuery("#" + name + "_description").text(itemElem.find("p").text());
}
});
|
Check PHP Version before everything | <?php
// Check for required PHP version
if (version_compare(PHP_VERSION, '5.6.0', '<'))
{
exit(sprintf('This app requires PHP 5.6 or higher. Your PHP version is: %s.', PHP_VERSION));
}
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
// Import external libraries.
if (file_exists('./vendor/autoload.php')) {
require './vendor/autoload.php';
}
// Core class autoload
require_once 'Autoloader.php';
$registry = new Acd\Registry;
$config = new Acd\Configloader('include/config.php');
// Loads configuration into the registry
foreach ($config->loadconfig() as $key => $value) {
$registry->set($key, $value);
}
$database = new Acd\Database($registry->get('database'));
// Connect to database
$database = $database->connect();
foreach ($registry->get('database') as $key => $value) {
echo 'Key = '.$key.' Value = '.$value.'<br>';
}
| <?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
// Check for required PHP version
if (version_compare(PHP_VERSION, '5.6.0', '<'))
{
exit(sprintf('This app requires PHP 5.6 or higher. Your PHP version is: %s.', PHP_VERSION));
}
// Import external libraries.
if (file_exists('./vendor/autoload.php')) {
require './vendor/autoload.php';
}
// Core class autoload
require_once 'Autoloader.php';
$registry = new Acd\Registry;
$config = new Acd\Configloader('include/config.php');
// Loads configuration into the registry
foreach ($config->loadconfig() as $key => $value) {
$registry->set($key, $value);
}
$database = new Acd\Database($registry->get('database'));
// Connect to database
$database = $database->connect();
foreach ($registry->get('database') as $key => $value) {
echo 'Key = '.$key.' Value = '.$value.'<br>';
}
|
Change the rules for infix coordinario | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
# Break the tree
def break_tree(self, tree):
self.has_infix_coordination = False
self.parse_tree(tree)
print "Infix Coordination: " + str(self.has_infix_coordination)
# Parse the tree
def parse_tree(self, tree):
if type(tree) == Tree:
sentence_root = tree[0]
if type(sentence_root) == Tree:
if sentence_root.label() == "S":
print "Valid Tree"
for node in sentence_root:
if type(node) == Tree:
if node.label() == "CC":
self.has_infix_coordination |= True
| __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
self.result_string = ""
# Break the tree
def break_tree(self, tree):
t = Tree.fromstring(str(tree))
self.has_infix_coordination = False
self.result_string = ""
self.parse_tree(t)
print "Infix Coordination: " + str(self.has_infix_coordination)
return self.result_string
# Parse the tree
def parse_tree(self, tree):
if type(tree) == Tree:
self.has_infix_coordination |= tree.label() == "CC"
for node in tree:
self.parse_tree(node) |
Replace solve with solveset in sympy.calculus | from sympy.solvers import solve
from sympy.solvers.solveset import solveset
from sympy.simplify import simplify
def singularities(expr, sym):
"""
Finds singularities for a function.
Currently supported functions are:
- univariate real rational functions
Examples
========
>>> from sympy.calculus.singularities import singularities
>>> from sympy import Symbol
>>> x = Symbol('x', real=True)
>>> singularities(x**2 + x + 1, x)
()
>>> singularities(1/(x + 1), x)
(-1,)
References
==========
.. [1] http://en.wikipedia.org/wiki/Mathematical_singularity
"""
if not expr.is_rational_function(sym):
raise NotImplementedError("Algorithms finding singularities for"
" non rational functions are not yet"
" implemented")
else:
return tuple(sorted(solveset(simplify(1/expr), sym)))
| from sympy.solvers import solve
from sympy.simplify import simplify
def singularities(expr, sym):
"""
Finds singularities for a function.
Currently supported functions are:
- univariate real rational functions
Examples
========
>>> from sympy.calculus.singularities import singularities
>>> from sympy import Symbol
>>> x = Symbol('x', real=True)
>>> singularities(x**2 + x + 1, x)
()
>>> singularities(1/(x + 1), x)
(-1,)
References
==========
.. [1] http://en.wikipedia.org/wiki/Mathematical_singularity
"""
if not expr.is_rational_function(sym):
raise NotImplementedError("Algorithms finding singularities for"
" non rational functions are not yet"
" implemented")
else:
return tuple(sorted(solve(simplify(1/expr), sym)))
|
Allow to run out of browser | import Component from 'substance/ui/Component'
import emojione from 'emojione'
// Consistent with making everying served locally (for offline use etc)...
if (typeof window !== 'undefined') {
emojione.imagePathPNG = (window.stencila.root || '/web') + '/emojione/png/'
}
class EmojiComponent extends Component {
didMount () {
this.props.node.on('name:changed', this.rerender, this)
}
dispose () {
this.props.node.off(this)
}
render ($$) {
var node = this.props.node
var el = $$('span')
.addClass('sc-emoji')
var shortname = ':' + node.name + ':'
var img = emojione.shortnameToImage(shortname)
if (img === shortname) {
// Emoji name is not matched. Indicate this
// but show name to reflect user intent
el.addClass('sm-unknown')
.text(shortname)
} else {
// Emoji found so append `img` tag produced by EmojiOne
el.html(img)
}
return el
}
}
export default EmojiComponent
| import Component from 'substance/ui/Component'
import emojione from 'emojione'
// Consistent with making everying served locally (for offline use etc)...
emojione.imagePathPNG = (window.stencila.root || '/web') + '/emojione/png/'
class EmojiComponent extends Component {
didMount () {
this.props.node.on('name:changed', this.rerender, this)
}
dispose () {
this.props.node.off(this)
}
render ($$) {
var node = this.props.node
var el = $$('span')
.addClass('sc-emoji')
var shortname = ':' + node.name + ':'
var img = emojione.shortnameToImage(shortname)
if (img === shortname) {
// Emoji name is not matched. Indicate this
// but show name to reflect user intent
el.addClass('sm-unknown')
.text(shortname)
} else {
// Emoji found so append `img` tag produced by EmojiOne
el.html(img)
}
return el
}
}
export default EmojiComponent
|
:art: Move tooltip to only show on hovering info-icon | 'use babel'
import {React} from 'react-for-atom'
export default React.createClass({
propTypes: {
readyCount: React.PropTypes.number,
totalCount: React.PropTypes.number
},
render () {
if (isNaN(this.props.readyCount) || isNaN(this.props.totalCount)) {
return <span />
} else {
return (
<div className='tv-loading-progress'>
<span className='inline-block text-smaller text-subtle'>
Reading {this.props.readyCount} of {this.props.totalCount} notes
</span>
<span className='icon icon-info' ref='tooltip' onMouseOver={this._onHover} />
<progress className='inline-block' max={this.props.totalCount} value={this.props.readyCount} />
</div>)
}
},
_onHover () {
atom.notifications.addInfo('Reading files', {
description: 'This is necesary to populate the search index. It is only necessary the first time, the notes will be cached for next session.',
dismissible: true
})
}
})
| 'use babel'
import {React} from 'react-for-atom'
export default React.createClass({
propTypes: {
readyCount: React.PropTypes.number,
totalCount: React.PropTypes.number
},
render () {
if (isNaN(this.props.readyCount) || isNaN(this.props.totalCount)) {
return <span />
} else {
return (
<div className='tv-loading-progress' ref='tooltip' onMouseOver={this._onHover}>
<span className='inline-block text-smaller text-subtle'>
Reading {this.props.readyCount} of {this.props.totalCount} notes
</span>
<span className='icon icon-info' />
<progress className='inline-block' max={this.props.totalCount} value={this.props.readyCount} />
</div>)
}
},
_onHover () {
atom.notifications.addInfo('Reading files', {
description: 'This is necesary to populate the search index. It is only necessary the first time, the notes will be cached for next session.',
dismissible: true
})
}
})
|
Add the option to enable debug mode with Heroku
Don't do this public servers, use it locally with foreman. | #!/usr/bin/env python
from evesrp import create_app
from evesrp.killmail import CRESTMail, ShipURLMixin
import evesrp.auth.testauth
from flask.ext.heroku import Heroku
from os import environ as env
from binascii import unhexlify
skel_url = 'https://wiki.eveonline.com/en/wiki/{name}'
class EOWikiCREST(CRESTMail, ShipURLMixin(skel_url)): pass
app = create_app()
heroku = Heroku(app)
app.config['SECRET_KEY'] = unhexlify(env['SECRET_KEY'])
app.config['USER_AGENT_EMAIL'] = 'paxswill@paxswill.com'
app.config['AUTH_METHODS'] = ['evesrp.auth.testauth.TestAuth']
app.config['CORE_AUTH_PRIVATE_KEY'] = env.get('CORE_PRIVATE_KEY')
app.config['CORE_AUTH_PUBLIC_KEY'] = env.get('CORE_PUBLIC_KEY')
app.config['CORE_AUTH_IDENTIFIER'] = env.get('CORE_IDENTIFIER')
app.config['KILLMAIL_SOURCES'] = [EOWikiCREST]
if env.get('DEBUG') is not None:
app.debug = True
if __name__ == '__main__':
print("Creating databases...")
app.extensions['sqlalchemy'].db.create_all(app=app)
| #!/usr/bin/env python
from evesrp import create_app
from evesrp.killmail import CRESTMail, ShipURLMixin
import evesrp.auth.testauth
from flask.ext.heroku import Heroku
from os import environ as env
from binascii import unhexlify
skel_url = 'https://wiki.eveonline.com/en/wiki/{name}'
class EOWikiCREST(CRESTMail, ShipURLMixin(skel_url)): pass
app = create_app()
heroku = Heroku(app)
app.config['SECRET_KEY'] = unhexlify(env['SECRET_KEY'])
app.config['USER_AGENT_EMAIL'] = 'paxswill@paxswill.com'
app.config['AUTH_METHODS'] = ['evesrp.auth.testauth.TestAuth']
app.config['CORE_AUTH_PRIVATE_KEY'] = env.get('CORE_PRIVATE_KEY')
app.config['CORE_AUTH_PUBLIC_KEY'] = env.get('CORE_PUBLIC_KEY')
app.config['CORE_AUTH_IDENTIFIER'] = env.get('CORE_IDENTIFIER')
app.config['KILLMAIL_SOURCES'] = [EOWikiCREST]
if __name__ == '__main__':
print("Creating databases...")
app.extensions['sqlalchemy'].db.create_all(app=app)
|
Include contrib module in installed package
See https://github.com/yola/yolacom/pull/1775#issuecomment-76513787 | from setuptools import find_packages, setup
import proxyprefix
setup(
name='proxyprefix',
version=proxyprefix.__version__,
description='Prefix SCRIPT_NAME with X-Forwarded-Prefix header',
long_description=proxyprefix.__doc__,
author='Yola',
author_email='engineers@yola.com',
license='MIT (Expat)',
url='https://github.com/yola/proxyprefix',
packages=find_packages(exclude=['tests', 'tests.*']),
test_suite='nose.collector',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
],
extras_require = {
'djproxy': ['djproxy>=2.0.0'],
},
)
| from setuptools import setup
import proxyprefix
setup(
name='proxyprefix',
version=proxyprefix.__version__,
description='Prefix SCRIPT_NAME with X-Forwarded-Prefix header',
long_description=proxyprefix.__doc__,
author='Yola',
author_email='engineers@yola.com',
license='MIT (Expat)',
url='https://github.com/yola/proxyprefix',
packages=['proxyprefix'],
test_suite='nose.collector',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
],
extras_require = {
'djproxy': ['djproxy>=2.0.0'],
},
)
|
Fix reference error due to missing comma | 'use strict';
/**
* Main AngularJS Entry Point.
*
* @author Mohamed Mansour 2015 (http://mohamedmansour.com)
*/
var App = angular
.module('personalDataDashboardApp', [
'ui.router',
'ngAnimate',
'ngMaterial'
])
.run(['$rootScope', '$state', '$stateParams', '$location', function ($rootScope, $state, $stateParams, $location) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
/*// Hookup Google Analytics for sub pages when viewed.
$rootScope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});*/
}])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
});
}]); | 'use strict';
/**
* Main AngularJS Entry Point.
*
* @author Mohamed Mansour 2015 (http://mohamedmansour.com)
*/
var App = angular
.module('personalDataDashboardApp', [
'ui.router',
'ngAnimate'
'ngMaterial'
])
.run(['$rootScope', '$state', '$stateParams', '$location', function ($rootScope, $state, $stateParams, $location) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
/*// Hookup Google Analytics for sub pages when viewed.
$rootScope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});*/
}])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
});
}]); |
Swap out link with unread: 0 on download | $(function () {
var all = $("#select_all");
var none = $("#select_none");
var checkboxes = $(":checkbox");
all.css('cursor', 'pointer');
none.css('cursor', 'pointer');
all.click( function() { checkboxes.prop('checked', true); });
none.click( function() { checkboxes.prop('checked', false); });
$("#delete_collection").submit(function () {
return confirm("Are you sure you want to delete this collection?");
});
$("#delete_collections").submit(function () {
var num_checked = 0;
checkboxes.each(function () {
if (this.checked) num_checked++;
});
if (num_checked > 0) {
return confirm("Are you sure you want to delete the " + num_checked + " selected collection" + (num_checked > 1 ? "s?" : "?"));
}
// Don't submit the form if no collections are selected
return false;
});
$("#unread a").click(function(){
$("#unread").html("unread: 0");
});
});
| $(function () {
var all = $("#select_all");
var none = $("#select_none");
var checkboxes = $(":checkbox");
all.css('cursor', 'pointer');
none.css('cursor', 'pointer');
all.click( function() { checkboxes.prop('checked', true); });
none.click( function() { checkboxes.prop('checked', false); });
$("#delete_collection").submit(function () {
return confirm("Are you sure you want to delete this collection?");
});
$("#delete_collections").submit(function () {
var num_checked = 0;
checkboxes.each(function () {
if (this.checked) num_checked++;
});
if (num_checked > 0) {
return confirm("Are you sure you want to delete the " + num_checked + " selected collection" + (num_checked > 1 ? "s?" : "?"));
}
// Don't submit the form if no collections are selected
return false;
});
});
|
Add fake HTTP_CLIENT_IP for command line use | <?php
// This is global bootstrap for autoloading
namespace Grav;
use Codeception\Util\Fixtures;
use Faker\Factory;
// Ensure vendor libraries exist
$autoload = __DIR__ . '/../vendor/autoload.php';
if (!is_file($autoload)) {
throw new \RuntimeException("Please run: <i>bin/grav install</i>");
}
use Grav\Common\Grav;
// Register the auto-loader.
$loader = require_once $autoload;
if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
throw new \RuntimeException(sprintf('You are running PHP %s, but Grav needs at least <strong>PHP %s</strong> to run.', $ver, $req));
}
// Set timezone to default, falls back to system if php.ini not set
date_default_timezone_set(@date_default_timezone_get());
// Set internal encoding if mbstring loaded
if (!extension_loaded('mbstring')) {
throw new \RuntimeException("'mbstring' extension is not loaded. This is required for Grav to run correctly");
}
mb_internal_encoding('UTF-8');
// Get the Grav instance
$grav = Grav::instance(
array(
'loader' => $loader
)
);
// Set default $_SERVER value used for nonces
empty( $_SERVER['HTTP_CLIENT_IP'] ) && $_SERVER['HTTP_CLIENT_IP'] = '127.0.0.1';
$fake = Factory::create();
Fixtures::add('grav', $grav);
Fixtures::add('fake', $fake); | <?php
// This is global bootstrap for autoloading
namespace Grav;
use Codeception\Util\Fixtures;
use Faker\Factory;
// Ensure vendor libraries exist
$autoload = __DIR__ . '/../vendor/autoload.php';
if (!is_file($autoload)) {
throw new \RuntimeException("Please run: <i>bin/grav install</i>");
}
use Grav\Common\Grav;
// Register the auto-loader.
$loader = require_once $autoload;
if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
throw new \RuntimeException(sprintf('You are running PHP %s, but Grav needs at least <strong>PHP %s</strong> to run.', $ver, $req));
}
// Set timezone to default, falls back to system if php.ini not set
date_default_timezone_set(@date_default_timezone_get());
// Set internal encoding if mbstring loaded
if (!extension_loaded('mbstring')) {
throw new \RuntimeException("'mbstring' extension is not loaded. This is required for Grav to run correctly");
}
mb_internal_encoding('UTF-8');
// Get the Grav instance
$grav = Grav::instance(
array(
'loader' => $loader
)
);
$fake = Factory::create();
Fixtures::add('grav', $grav);
Fixtures::add('fake', $fake); |
tests: Fix typo in mock usage
The error was made evident by a newer mock version that no longer
swallowed the wrong assert as regular use of a spec-less mock. | from __future__ import absolute_import, unicode_literals
from mock import patch
from tests.mpd import protocol
class ConnectionHandlerTest(protocol.BaseTestCase):
def test_close_closes_the_client_connection(self):
with patch.object(self.session, 'close') as close_mock:
self.send_request('close')
close_mock.assert_called_once_with()
self.assertEqualResponse('OK')
def test_empty_request(self):
self.send_request('')
self.assertEqualResponse('ACK [5@0] {} No command given')
self.send_request(' ')
self.assertEqualResponse('ACK [5@0] {} No command given')
def test_kill(self):
self.send_request('kill')
self.assertEqualResponse(
'ACK [4@0] {kill} you don\'t have permission for "kill"')
def test_ping(self):
self.send_request('ping')
self.assertEqualResponse('OK')
| from __future__ import absolute_import, unicode_literals
from mock import patch
from tests.mpd import protocol
class ConnectionHandlerTest(protocol.BaseTestCase):
def test_close_closes_the_client_connection(self):
with patch.object(self.session, 'close') as close_mock:
self.send_request('close')
close_mock.assertEqualResponsecalled_once_with()
self.assertEqualResponse('OK')
def test_empty_request(self):
self.send_request('')
self.assertEqualResponse('ACK [5@0] {} No command given')
self.send_request(' ')
self.assertEqualResponse('ACK [5@0] {} No command given')
def test_kill(self):
self.send_request('kill')
self.assertEqualResponse(
'ACK [4@0] {kill} you don\'t have permission for "kill"')
def test_ping(self):
self.send_request('ping')
self.assertEqualResponse('OK')
|
Revert "Add compile_to_json invocation in Myrial test fixture"
This reverts commit ceb848021d5323b5bad8518ac7ed850a51fc89ca. |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parser = parser.Parser()
self.processor = interpreter.StatementProcessor(self.db)
def execute_query(self, query, test_logical=False):
'''Run a test query against the fake database'''
statements = self.parser.parse(query)
self.processor.evaluate(statements)
if test_logical:
plan = self.processor.get_logical_plan()
else:
plan = self.processor.get_physical_plan()
self.db.evaluate(plan)
return self.db.get_temp_table('__OUTPUT0__')
def run_test(self, query, expected, test_logical=False):
'''Execute a test query with an expected output'''
actual = self.execute_query(query, test_logical)
self.assertEquals(actual, expected)
|
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parser = parser.Parser()
self.processor = interpreter.StatementProcessor(self.db)
def execute_query(self, query, test_logical=False):
'''Run a test query against the fake database'''
statements = self.parser.parse(query)
self.processor.evaluate(statements)
if test_logical:
plan = self.processor.get_logical_plan()
else:
plan = self.processor.get_physical_plan()
json = compile_to_json(query, '', [('A', plan)])
self.db.evaluate(plan)
return self.db.get_temp_table('__OUTPUT0__')
def run_test(self, query, expected, test_logical=False):
'''Execute a test query with an expected output'''
actual = self.execute_query(query, test_logical)
self.assertEquals(actual, expected)
|
Print more statistics on exit | package cz.cuni.mff.d3s.spl.example.newton.checker;
import cz.cuni.mff.d3s.spl.core.data.SerieDataSource;
import cz.cuni.mff.d3s.spl.core.data.Statistics;
import cz.cuni.mff.d3s.spl.core.data.instrumentation.InstrumentingDataSource;
import cz.cuni.mff.d3s.spl.core.formula.Formula;
import cz.cuni.mff.d3s.spl.core.formula.Result;
import cz.cuni.mff.d3s.spl.core.formula.SlaFormula;
public class SlaChecker implements Runnable {
private final static String METHOD = "org.apache.commons.math.analysis.solvers.NewtonSolver#solve";
private final static long SEC_TO_NANOS = 1000 * 1000 * 1000;
SerieDataSource source;
Formula sla;
public SlaChecker() {
source = InstrumentingDataSource.create(METHOD);
sla = SlaFormula.createSimple(source, 1 * SEC_TO_NANOS);
}
@Override
public void run() {
Result result = sla.evaluate();
Statistics stats = source.get();
/* Explicitly flush all previous output to prevent interleaving. */
System.out.flush();
System.err.flush();
System.err.printf(
"NewtonSolver.solve(): mean is %2.1fns, %d samples: %s.\n",
stats.getArithmeticMean(), stats.getSampleCount(), result);
}
}
| package cz.cuni.mff.d3s.spl.example.newton.checker;
import cz.cuni.mff.d3s.spl.core.data.SerieDataSource;
import cz.cuni.mff.d3s.spl.core.data.instrumentation.InstrumentingDataSource;
import cz.cuni.mff.d3s.spl.core.formula.Formula;
import cz.cuni.mff.d3s.spl.core.formula.Result;
import cz.cuni.mff.d3s.spl.core.formula.SlaFormula;
public class SlaChecker implements Runnable {
private final static String METHOD = "org.apache.commons.math.analysis.solvers.NewtonSolver#solve";
//"org.apache.commons.math.analysis.polynomials.PolynomialFunction#value";
private final static long SEC_TO_NANOS = 1000 * 1000 * 1000;
SerieDataSource source;
Formula sla;
public SlaChecker() {
source = InstrumentingDataSource.create(METHOD);
sla = SlaFormula.createSimple(source, 1 * SEC_TO_NANOS);
}
@Override
public void run() {
Result result = sla.evaluate();
System.err.printf("Contract of NewtonSolver.solve(): %s.\n", result);
}
}
|
[binance] Include timestamp in balance requests | package org.knowm.xchange.binance.dto.account;
import java.math.BigDecimal;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public final class BinanceAccountInformation {
public final BigDecimal makerCommission;
public final BigDecimal takerCommission;
public final BigDecimal buyerCommission;
public final BigDecimal sellerCommission;
public final boolean canTrade;
public final boolean canWithdraw;
public final boolean canDeposit;
public final long updateTime;
public List<BinanceBalance> balances;
public BinanceAccountInformation(
@JsonProperty("makerCommission") BigDecimal makerCommission,
@JsonProperty("takerCommission") BigDecimal takerCommission,
@JsonProperty("buyerCommission") BigDecimal buyerCommission,
@JsonProperty("sellerCommission") BigDecimal sellerCommission,
@JsonProperty("canTrade") boolean canTrade,
@JsonProperty("canWithdraw") boolean canWithdraw,
@JsonProperty("canDeposit") boolean canDeposit,
@JsonProperty("updateTime") long updateTime,
@JsonProperty("balances") List<BinanceBalance> balances) {
this.makerCommission = makerCommission;
this.takerCommission = takerCommission;
this.buyerCommission = buyerCommission;
this.sellerCommission = sellerCommission;
this.canTrade = canTrade;
this.canWithdraw = canWithdraw;
this.canDeposit = canDeposit;
this.updateTime = updateTime;
this.balances = balances;
}
}
| package org.knowm.xchange.binance.dto.account;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.List;
public final class BinanceAccountInformation {
public final BigDecimal makerCommission;
public final BigDecimal takerCommission;
public final BigDecimal buyerCommission;
public final BigDecimal sellerCommission;
public final boolean canTrade;
public final boolean canWithdraw;
public final boolean canDeposit;
public List<BinanceBalance> balances;
public BinanceAccountInformation(
@JsonProperty("makerCommission") BigDecimal makerCommission,
@JsonProperty("takerCommission") BigDecimal takerCommission,
@JsonProperty("buyerCommission") BigDecimal buyerCommission,
@JsonProperty("sellerCommission") BigDecimal sellerCommission,
@JsonProperty("canTrade") boolean canTrade,
@JsonProperty("canWithdraw") boolean canWithdraw,
@JsonProperty("canDeposit") boolean canDeposit,
@JsonProperty("balances") List<BinanceBalance> balances) {
this.makerCommission = makerCommission;
this.takerCommission = takerCommission;
this.buyerCommission = buyerCommission;
this.sellerCommission = sellerCommission;
this.canTrade = canTrade;
this.canWithdraw = canWithdraw;
this.canDeposit = canDeposit;
this.balances = balances;
}
}
|
Change the parsing doc comments algorithm to show full method documentation but not just the first string | <?php
/**
* Created by PhpStorm.
* User: alex
* Date: 20/10/2016
* Time: 23:36
*/
namespace vr\api\doc\components;
use yii\base\BaseObject;
/**
* Class DocCommentParser
* @package vr\api\doc\components
* @property string $description
*/
class DocCommentParser extends BaseObject
{
/**
* @var
*/
public $source;
/**
* @var
*/
public $params;
/**
*
*/
public function init()
{
}
/**
* @return string
*/
public function getDescription()
{
$string = explode(PHP_EOL, $this->source);
$values = array_splice($string, 1);
array_walk($values, function (&$item) {
$item = trim($item, "* /\t\r\n");
});
$filtered = array_filter($values, function ($string) {
return !empty($string)
&& strpos($string, '@throws') === false
&& strpos($string, '@return') === false;
});
return implode($filtered, '<br/>');
}
} | <?php
/**
* Created by PhpStorm.
* User: alex
* Date: 20/10/2016
* Time: 23:36
*/
namespace vr\api\doc\components;
use yii\base\BaseObject;
/**
* Class DocCommentParser
* @package vr\api\doc\components
* @property string $description
*/
class DocCommentParser extends BaseObject
{
/**
* @var
*/
public $source;
/**
* @var
*/
public $params;
/**
*
*/
public function init()
{
}
/**
* @return string
*/
public function getDescription()
{
$string = explode(PHP_EOL, $this->source);
$values = array_splice($string, 1);
array_walk($values, function (&$item) {
$item = trim($item, '* /\t\r\n');
});
return implode(array_filter($values), '<br/>');
}
} |
Change default Freenode server URL to recommended one | module.exports = {
public: false,
host: "0.0.0.0",
port: 9000,
bind: undefined,
theme: "themes/{{ shout_theme }}.css",
autoload: true,
prefetch: false,
displayNetwork: true,
logs: {
format: "YYYY-MM-DD HH:mm:ss",
timezone: "UTC+00:00"
},
defaults: {
name: "Freenode",
host: "chat.freenode.net",
port: 6697,
password: "",
tls: true,
nick: "shout-user",
username: "shout-user",
realname: "Shout User",
join: "#foo, #shout-irc"
},
transports: ["polling", "websocket"],
https: {
enable: false,
key: "",
certificate: ""
},
identd: {
enable: false,
port: 113
}
};
| module.exports = {
public: false,
host: "0.0.0.0",
port: 9000,
bind: undefined,
theme: "themes/{{ shout_theme }}.css",
autoload: true,
prefetch: false,
displayNetwork: true,
logs: {
format: "YYYY-MM-DD HH:mm:ss",
timezone: "UTC+00:00"
},
defaults: {
name: "Freenode",
host: "irc.freenode.org",
port: 6697,
password: "",
tls: true,
nick: "shout-user",
username: "shout-user",
realname: "Shout User",
join: "#foo, #shout-irc"
},
transports: ["polling", "websocket"],
https: {
enable: false,
key: "",
certificate: ""
},
identd: {
enable: false,
port: 113
}
};
|
Change Main Response to Json | <?php
namespace App\Http\Controllers\Article;
use App\Article;
use App\Http\Requests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class ArticlesController extends BaseController
{
/**
Article
*/
protected $article;
public function __construct(Article $article){
$this->article = $article;
}
public function getIndex(){
$articles = $this->article->all();
return response()->json($articles);
}
public function getShow($id){
$article = $this->article->find($id);
return response()->json($article);
}
public function getTagIndex($tag_id){
$articles = $this->article->all();
return response()->json($articles);
}
}
| <?php
namespace App\Http\Controllers\Article;
use App\Article;
use App\Http\Requests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class ArticlesController extends BaseController
{
/**
Article
*/
protected $article;
public function __construct(Article $article){
$this->article = $article;
}
public function getIndex(){
$articles = $this->article->all();
return view('articles.index')->with(compact('articles'));
}
public function getShow($id){
$article = $this->article->find($id);
return view('articles.show')->with(compact('article'));
}
public function getTagIndex($tag_id){
$articles = $this->article->all();
return view('articles.index')->with(compact('articles'));
}
}
|
Allow nested routes, and even functions to be passed as routes | Andamio.Router = Backbone.Router.extend({
// Override Backbone.Router._bindRoutes
_bindRoutes: function () {
if (!this.routes) {
return;
}
this.routes = _.result(this, 'routes');
_.each(this.routes, function (route) {
var urls = _.isArray(route.url) ? route.url : [route.url];
var callback;
_.each(urls, function (url) {
// Register the same callback for the same route urls
callback = callback || this._createCallback(url, route.name, route.view);
this.route(url, route.name, callback);
}, this);
}, this);
},
_createCallback: function (url, name, View) {
var router = this;
var callback = function () {
var urlParams = arguments;
var view = new View();
// Execute view's model load method
if (view.model && _.isFunction(view.model.load)) {
view.model.load.apply(view.model, urlParams);
}
router.trigger('navigate', view, url, urlParams);
};
return callback;
}
});
| Andamio.Router = Backbone.Router.extend({
_bindRoutes: function () {
if (!this.routes) {
return;
}
_.each(this.routes, function (route) {
var callback = this._createCallback(route.url, route.name, route.view);
this.route(route.url, route.name, callback);
}, this);
},
_createCallback: function (url, name, View) {
var router = this;
var callback = function () {
var urlParams = arguments;
var view = new View();
if (view.model && _.isFunction(view.model.load)) {
view.model.load.apply(view.model, urlParams);
}
router.trigger('navigate', view, url, urlParams);
};
return callback;
}
});
|
Switch Calc to extend View instead of AbstractView | // Experimental Animated Views
FOAModel({
name: 'ALabel',
extendsModel: 'View',
properties: [
{
name: 'data'
},
{
name: 'className',
defaultValue: 'alabel'
},
{
name: 'left',
postSet: function(_, l) {
this.$.querySelector('.f1').style.left = l;
}
}
],
methods: {
toInnerHTML: function() {
return '<div style="position:absolute;transition: left .3s ease;" class="f1"></div><div style="display:inline;visibility:hidden;" class="f2"></div>';
},
initHTML: function() {
this.data$.addListener(this.onDataChange);
}
},
listeners: [
{
name: 'onDataChange',
isAnimated: true,
code: function() {
if ( ! this.$ ) return;
var f1$ = this.$.querySelector('.f1');
var f2$ = this.$.querySelector('.f2');
f1$.innerHTML = this.data;
f2$.innerHTML = this.data;
f1$.style.top = f2$.offsetTop;
f1$.style.left = f2$.offsetLeft;
}
}
]
});
| // Experimental Animated Views
FOAModel({
name: 'ALabel',
extendsModel: 'AbstractView',
properties: [
{
name: 'data'
},
{
name: 'className',
defaultValue: 'alabel'
},
{
name: 'left',
postSet: function(_, l) {
this.$.querySelector('.f1').style.left = l;
}
}
],
methods: {
toInnerHTML: function() {
return '<div style="position:absolute;transition: left .3s ease;" class="f1"></div><div style="display:inline;visibility:hidden;" class="f2"></div>';
},
initHTML: function() {
this.data$.addListener(this.onDataChange);
}
},
listeners: [
{
name: 'onDataChange',
isAnimated: true,
code: function() {
if ( ! this.$ ) return;
var f1$ = this.$.querySelector('.f1');
var f2$ = this.$.querySelector('.f2');
f1$.innerHTML = this.data;
f2$.innerHTML = this.data;
f1$.style.top = f2$.offsetTop;
f1$.style.left = f2$.offsetLeft;
}
}
]
});
|
Update withId to use the passed parameter | package com.github.davidmoten.rx;
import rx.Scheduler;
public final class Schedulers {
public static Scheduler computation(String id) {
return new SchedulerWithId(rx.schedulers.Schedulers.computation(), id);
}
public static Scheduler computation() {
return withId(rx.schedulers.Schedulers.computation());
}
private static Scheduler withId(Scheduler scheduler) {
return new SchedulerWithId(scheduler, describeCallSite());
}
private static String describeCallSite() {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
StackTraceElement e = elements[3];
return e.getClassName() + ":" + e.getMethodName() + ":" + e.getLineNumber();
}
private static void doIt() {
System.out.println(describeCallSite());
}
public static void main(String[] args) {
doIt();
}
}
| package com.github.davidmoten.rx;
import rx.Scheduler;
public final class Schedulers {
public static Scheduler computation(String id) {
return new SchedulerWithId(rx.schedulers.Schedulers.computation(), id);
}
public static Scheduler computation() {
return withId(rx.schedulers.Schedulers.computation());
}
private static Scheduler withId(Scheduler scheduler) {
return new SchedulerWithId(Schedulers.computation(), describeCallSite());
}
private static String describeCallSite() {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
StackTraceElement e = elements[3];
return e.getClassName() + ":" + e.getMethodName() + ":" + e.getLineNumber();
}
private static void doIt() {
System.out.println(describeCallSite());
}
public static void main(String[] args) {
doIt();
}
}
|
Add setting to optionally enforce PR deadlines | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.core.settings.converters import DatetimeConverter
from indico.modules.events.settings import EventSettingsProxy
paper_reviewing_settings = EventSettingsProxy('paper_reviewing', {
'start_dt': None,
'end_dt': None,
'enforce_deadlines': False,
'content_reviewing_enabled': True,
'layout_reviewing_enabled': False,
'judge_deadline': None,
'layout_reviewer_deadline': None,
'content_reviewer_deadline': None,
}, converters={
'start_dt': DatetimeConverter,
'end_dt': DatetimeConverter,
'judge_deadline': DatetimeConverter,
'layout_reviewer_deadline': DatetimeConverter,
'content_reviewer_deadline': DatetimeConverter,
})
| # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.core.settings.converters import DatetimeConverter
from indico.modules.events.settings import EventSettingsProxy
paper_reviewing_settings = EventSettingsProxy('paper_reviewing', {
'start_dt': None,
'end_dt': None,
'content_reviewing_enabled': True,
'layout_reviewing_enabled': False,
'judge_deadline': None,
'layout_reviewer_deadline': None,
'content_reviewer_deadline': None,
}, converters={
'start_dt': DatetimeConverter,
'end_dt': DatetimeConverter,
'judge_deadline': DatetimeConverter,
'layout_reviewer_deadline': DatetimeConverter,
'content_reviewer_deadline': DatetimeConverter,
})
|
Remove deffered and simplify script. | 'use strict'
// Make callback function
const prepare = function(resolve, reject, withoutErrorAttr) {
// By default start with a second attribute
let base = 2
// But if it's not node style callback switch to the first one
if (withoutErrorAttr)
--base
return function () {
// If node style function return an error
if (arguments[0] && !withoutErrorAttr) {
reject(arguments[0])
}
else if (arguments.length < base) {
resolve()
}
else if (arguments.length === base) {
resolve(arguments[--base])
}
else {
resolve(Array.prototype.slice.call(arguments, --base))
}
}
}
// Transform function with callback to generator
const generatorify = module.exports = function(fn, context, withoutErrorAttr) {
return function() {
let fnArgs = arguments
return new Promise(function(resolve, reject) {
let args = Array.prototype.slice.call(fnArgs)
.concat(prepare(resolve, reject, withoutErrorAttr))
return fn.apply(context, args)
})
}
}
| 'use strict'
// Defer function using native promises
const defer = function() {
let result = {}
result.promise = new Promise(function(resolve, reject) {
result.resolve = resolve
result.reject = reject
})
return result
}
// Make callback function
const prepareCallback = function(deferred, withoutErrorAttr) {
// By default start with a second attribute
let base = 2
// But if it's not node style callback switch to the first one
if (withoutErrorAttr)
--base
return function () {
// If node style function return an error
if (arguments[0] && !withoutErrorAttr) {
deferred.reject(arguments[0])
}
else if (arguments.length < base) {
deferred.resolve()
}
else if (arguments.length === base) {
deferred.resolve(arguments[--base])
}
else {
deferred.resolve(Array.prototype.slice.call(arguments, --base))
}
}
}
// Transform function with callback to generator
const generatorify = module.exports = function(fn, context, withoutErrorAttr) {
return function() {
const deferred = defer(),
callback = prepareCallback(deferred, withoutErrorAttr),
args = Array.prototype.slice.call(arguments).concat(callback)
fn.apply(context, args)
return deferred.promise
};
}
|
Allow enumerable to be specified | module.exports = function (Model) {
Model.on('initialize', function (model) {
Object.keys(Model.attrs).forEach(function (key) {
var options = Model.attrs[key]
// enumerable defaults to false
var enumerable = !!options.enumerable || false
if (Object.hasOwnProperty.call(options, 'value')) {
return Object.defineProperty(model.attrs, key, {
value: options.value,
enumerable: enumerable
})
}
if (typeof options.get === 'function') {
var descriptor = {}
descriptor.enumerable = enumerable
descriptor.get = options.get.bind(model)
if (typeof options.set === 'function') {
descriptor.set = options.set.bind(model)
}
return Object.defineProperty(model.attrs, key, descriptor)
}
})
})
}
| module.exports = function (Model) {
Model.on('initialize', function (model) {
Object.keys(Model.attrs).forEach(function (key) {
var options = Model.attrs[key]
if (Object.hasOwnProperty.call(options, 'value')) {
return Object.defineProperty(model.attrs, key, {
value: options.value,
enumerable: true
})
}
if (typeof options.get === 'function') {
var descriptor = {}
descriptor.get = options.get.bind(model)
if (typeof options.set === 'function') {
descriptor.set = options.set.bind(model)
}
return Object.defineProperty(model.attrs, key, descriptor)
}
})
})
}
|
10: Test all scripts on Windows
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10 | ######
# Create a backup of J2EE Security Roles
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
#
import sys
import os
import ibmcnx.functions
path = raw_input( "Please provide a path for your backup files: " )
ibmcnx.functions.checkBackupPath( path )
apps = AdminApp.list()
appsList = apps.splitlines()
for app in appsList:
filename = path + "/" + app + ".txt"
print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename}
my_file = open( filename, 'w' )
my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) )
my_file.flush
my_file.close()
| ######
# Create a backup of J2EE Security Roles
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
#
import sys
import os
import ibmcnx.functions
# Only load commands if not initialized directly (call from menu)
if __name__ == "__main__":
execfile("ibmcnx/loadCnxApps.py")
path = raw_input( "Please provide a path for your backup files: " )
ibmcnx.functions.checkBackupPath( path )
apps = AdminApp.list()
appsList = apps.splitlines()
for app in appsList:
filename = path + "/" + app + ".txt"
print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename}
my_file = open( filename, 'w' )
my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) )
my_file.flush
my_file.close()
|
Update return docbblock and reorder plainText method | <?php
namespace PhpWatson\Sdk\Language\ToneAnalyser\V3;
use PhpWatson\Sdk\Response;
use PhpWatson\Sdk\Service;
class ToneAnalyserService extends Service
{
/**
* Base url for the service
*
* @var string
*/
protected $url = "https://gateway.watsonplatform.net/tone-analyzer/api";
/**
* API service version
*
* @var string
*/
protected $version = 'v3';
/**
* ToneAnalyserService constructor
*
* @param $username string The service api username
* @param $password string The service api password
*/
public function __construct($username = null, $password = null)
{
parent::__construct($username, $password);
}
/**
* Analyzes the tone of a piece of text
*
* @return Response
*/
public function plainText($textToAnalyse, $version='2016-05-19')
{
return $this->client->request(
'GET',
$this->getMountedUrl().'/tone',
['query' => ['version' => $version, 'text' => $textToAnalyse]]
);
}
} | <?php
namespace PhpWatson\Sdk\Language\ToneAnalyser\V3;
use PhpWatson\Sdk\Service;
class ToneAnalyserService extends Service
{
/**
* Base url for the service
*
* @var string
*/
protected $url = "https://gateway.watsonplatform.net/tone-analyzer/api";
/**
* API service version
*
* @var string
*/
protected $version = 'v3';
/**
* ToneAnalyserService constructor
*
* @param $username string The service api username
* @param $password string The service api password
*/
public function __construct($username = null, $password = null)
{
parent::__construct($username, $password);
}
/**
* Analyzes the tone of a piece of text
*
* @return mixed|\Psr\Http\Message\ResponseInterface
*/
public function plainText($textToAnalyse, $version='2016-05-19')
{
return $this->client->request('GET', $this->getMountedUrl().'/tone', ['query' => ['version' => $version, 'text' => $textToAnalyse]]);
}
} |
Create line break for icons. | import React from 'react';
import icons from '../weather_icons/WeatherIcons';
const SevenHour = ({ hourlyForecast }) => {
if (!hourlyForecast) {
return null;
}
const sevenHourForecast = hourlyForecast.slice(0, 7);
const sevenHourDataLoop = sevenHourForecast.map((hour, i) => {
return (
<div key={i} className="hourly-box">
<h2 className="hourly-forecast hourly-time" tabIndex="0">{hour.FCTTIME.civil}</h2>
<div className={`hourly-icon ${icons[hour.icon]}`} tabIndex="0" alt="hourly weather icon"
aria-label="hourly weather icon"></div>
<h2 className="hourly-forecast hourly-temp" tabIndex="0">{hour.temp.english}°F</h2>
</div>
);
});
return (
<section className="seven-hour-container">
{sevenHourDataLoop}
</section>
);
};
export default SevenHour;
| import React from 'react';
import icons from '../weather_icons/WeatherIcons';
const SevenHour = ({ hourlyForecast }) => {
if (!hourlyForecast) {
return null;
}
const sevenHourForecast = hourlyForecast.slice(0, 7);
const sevenHourDataLoop = sevenHourForecast.map((hour, i) => {
return (
<div key={i} className="hourly-box">
<h2 className="hourly-forecast hourly-time" tabIndex="0">{hour.FCTTIME.civil}</h2>
<div className={`hourly-icon ${icons[hour.icon]}`} tabIndex="0" alt="hourly weather icon" aria-label="hourly weather icon"></div>
<h2 className="hourly-forecast hourly-temp" tabIndex="0">{hour.temp.english}°F</h2>
</div>
);
});
return (
<section className="seven-hour-container">
{sevenHourDataLoop}
</section>
);
};
export default SevenHour;
|
Fix dumb bug in link-props handling | /*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "object")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or objects, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
}) | /*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "function")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or functions, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
}) |
Reset root path config for each test. | package org.rapidoid.test;
/*
* #%L
* rapidoid-commons
* %%
* Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors
* %%
* 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.
* #L%
*/
import org.junit.Before;
import org.rapidoid.config.Conf;
import org.rapidoid.log.Log;
import org.rapidoid.log.LogLevel;
import org.rapidoid.security.Roles;
public abstract class AbstractCommonsTest extends TestCommons {
@Before
public void openContext() {
Conf.setRootPath(Conf.rootPathDefault());
Roles.resetConfig();
Log.setLogLevel(LogLevel.INFO);
}
}
| package org.rapidoid.test;
/*
* #%L
* rapidoid-commons
* %%
* Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors
* %%
* 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.
* #L%
*/
import org.junit.Before;
import org.rapidoid.log.Log;
import org.rapidoid.log.LogLevel;
import org.rapidoid.security.Roles;
public abstract class AbstractCommonsTest extends TestCommons {
@Before
public void openContext() {
Roles.resetConfig();
Log.setLogLevel(LogLevel.INFO);
}
}
|
Improve Inferno example. Thanks Scotty! | import { render } from "inferno";
import { h as hyper } from "inferno-hyperscript";
import { setup } from "../common";
import { sv } from "seview";
const processAttrs = (attrs = {}) => {
Object.keys(attrs).forEach(key => {
if (key === "htmlFor") {
const value = attrs[key];
delete attrs[key];
attrs["for"] = value;
}
})
if (attrs.innerHTML) {
attrs.dangerouslySetInnerHTML = { __html: attrs.innerHTML };
delete attrs.innerHTML;
}
return attrs;
};
const h = sv(node =>
(typeof node === "string")
? node
: hyper(node.tag, processAttrs(node.attrs), node.children || [])
);
export const setupRender = () =>
(view, element) => render(h(view), element);
export const setupApp = () => setup(setupRender());
| import { render } from "inferno";
import { h as hyper } from "inferno-hyperscript";
import { setup } from "../common";
import { sv } from "seview";
const processAttrs = (attrs = {}) => {
Object.keys(attrs).forEach(key => {
if (key === "htmlFor") {
const value = attrs[key];
delete attrs[key];
attrs["for"] = value;
}
else if (attrs.innerHTML) {
attrs.dangerouslySetInnerHTML = { __html: attrs.innerHTML };
delete attrs.innerHTML;
}
})
return attrs;
};
const h = sv(node =>
(typeof node === "string")
? node
: hyper(node.tag, processAttrs(node.attrs), node.children || [])
);
export const setupRender = () =>
(view, element) => render(h(view), element);
export const setupApp = () => setup(setupRender());
|
Fix tag creation with non-ascii chars. (Dammit bottle!) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = request.forms.tags
create = [a.decode("utf-8") for a in request.forms.getall("create")]
ctype = [a.decode("utf-8") for a in request.forms.getall("ctype")]
full = set()
weak = set()
remove = set()
failed = []
for n, t in zip(create, ctype):
if t:
client.add_tag(tag_clean(n), t)
tags += u' ' + n
for t in tags.split():
tag = client.find_tag(tag_clean(t))
if tag:
p = tag_prefix(t)
if p == "~":
weak.add(tag)
elif p == "-":
remove.add(tag)
else:
full.add(tag)
else:
failed.append(t)
tag_post(post, full, weak, remove)
if not failed:
redirect("post/" + m)
data = globaldata()
data.tagtypes = tagtypes()
data.failed = failed
data.m = m
return data
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = request.forms.tags
create = request.forms.getall("create")
ctype = request.forms.getall("ctype")
full = set()
weak = set()
remove = set()
failed = []
for n, t in zip(create, ctype):
if t:
client.add_tag(tag_clean(n), t)
tags += u' ' + n
for t in tags.split():
tag = client.find_tag(tag_clean(t))
if tag:
p = tag_prefix(t)
if p == "~":
weak.add(tag)
elif p == "-":
remove.add(tag)
else:
full.add(tag)
else:
failed.append(t)
tag_post(post, full, weak, remove)
if not failed:
redirect("post/" + m)
data = globaldata()
data.tagtypes = tagtypes()
data.failed = failed
data.m = m
return data
|
Improve performance of jQuery selector | (function () {
'use strict';
$.easing.easeInOutQuint = function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
};
// smooth scroll
$('a[href*="#"]:not([href="#"])').click(function () {
if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, 'easeInOutQuint');
return false;
}
}
});
$('.email').attr('href', 'mailto:' + 'sindre' + 'sorhus' + '@' + 'gmail' + '.' + 'com');
$('.profile a').on('mouseover mouseout', function (e) {
$(this).toggleClass('animated tada', e.type === 'mouseover');
});
setTimeout(function () {
$('.credit').addClass('activate');
}, 1000);
})();
| (function () {
'use strict';
$.easing.easeInOutQuint = function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
};
// smooth scroll
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, 'easeInOutQuint');
return false;
}
}
});
$('.email').attr('href', 'mailto:' + 'sindre' + 'sorhus' + '@' + 'gmail' + '.' + 'com');
$('.profile a').on('mouseover mouseout', function (e) {
$(this).toggleClass('animated tada', e.type === 'mouseover');
});
setTimeout(function () {
$('.credit').addClass('activate');
}, 1000);
})();
|
Disable no-useless-escape of eslint rule on repository regular expression line | 'use strict';
var rRepoURL = /^(?:(?:git|https?|git\+https|git\+ssh):\/\/)?(?:[^@]+@)?([^\/]+?)[\/:](.+?)\.git$/; // eslint-disable-line no-useless-escape
var rGithubPage = /\.github\.(io|com)$/;
function parseRepo(repo) {
var split = repo.split(',');
var url = split.shift();
var branch = split[0];
if (!branch && rRepoURL.test(url)) {
var match = url.match(rRepoURL);
var host = match[1];
var path = match[2];
if (host === 'github.com') {
branch = rGithubPage.test(path) ? 'master' : 'gh-pages';
} else if (host === 'coding.net') {
branch = 'coding-pages';
}
}
return {
url: url,
branch: branch || 'master'
};
}
module.exports = function(args) {
var repo = args.repo || args.repository;
if (!repo) throw new TypeError('repo is required!');
if (typeof repo === 'string') {
var data = parseRepo(repo);
data.branch = args.branch || data.branch;
return [data];
}
var result = [];
var keys = Object.keys(repo);
for (var i = 0, len = keys.length; i < len; i++) {
result.push(parseRepo(repo[keys[i]]));
}
return result;
};
| 'use strict';
var rRepoURL = /^(?:(?:git|https?|git\+https|git\+ssh):\/\/)?(?:[^@]+@)?([^\/]+?)[\/:](.+?)\.git$/;
var rGithubPage = /\.github\.(io|com)$/;
function parseRepo(repo) {
var split = repo.split(',');
var url = split.shift();
var branch = split[0];
if (!branch && rRepoURL.test(url)) {
var match = url.match(rRepoURL);
var host = match[1];
var path = match[2];
if (host === 'github.com') {
branch = rGithubPage.test(path) ? 'master' : 'gh-pages';
} else if (host === 'coding.net') {
branch = 'coding-pages';
}
}
return {
url: url,
branch: branch || 'master'
};
}
module.exports = function(args) {
var repo = args.repo || args.repository;
if (!repo) throw new TypeError('repo is required!');
if (typeof repo === 'string') {
var data = parseRepo(repo);
data.branch = args.branch || data.branch;
return [data];
}
var result = [];
var keys = Object.keys(repo);
for (var i = 0, len = keys.length; i < len; i++) {
result.push(parseRepo(repo[keys[i]]));
}
return result;
};
|
Add error handling to nuget restore task | import gulp from 'gulp';
import nugetRestore from 'gulp-nuget-restore';
export default {
/**
* Task name
* @type {String}
*/
name: 'sitecore:nuget-restore',
/**
* Task description
* @type {String}
*/
description: 'Restore all nuget packages for solution.',
/**
* Task default configuration
* @type {Object}
*/
config: {
deps: [],
},
/**
* Task help options
* @type {Object}
*/
help: {
'solution, -s': 'Solution file path',
},
/**
* Task function
* @param {object} config
* @param {Function} end
* @param {Function} error
*/
fn(config, end, error) {
if (!config.solution) {
error('A solution file path was not set.');
return;
}
gulp.src(config.solution)
.pipe(nugetRestore())
.on('end', end);
},
};
| import gulp from 'gulp';
import nugetRestore from 'gulp-nuget-restore';
export default {
/**
* Task name
* @type {String}
*/
name: 'sitecore:nuget-restore',
/**
* Task description
* @type {String}
*/
description: 'Restore all nuget packages for solution.',
/**
* Task default configuration
* @type {Object}
*/
config: {
deps: [],
},
/**
* Task help options
* @type {Object}
*/
help: {
'solution, -s': 'Solution filepath',
},
/**
* Task function
* @param {object} config
* @param {Function} end
* @param {Function} error
*/
fn(config, end) {
gulp.src(config.solution)
.pipe(nugetRestore())
.on('end', end);
},
};
|
Set order to a low-priority but uncommon value
Without the order, it takes the default value (100), which can
easily collide with another WebConfigurerAdapter in the application
using the library | package org.zalando.problem.spring.web.autoconfigure.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
/**
* Registers exception handling in spring-security
*/
@Configuration
@ConditionalOnClass(WebSecurityConfigurerAdapter.class) //only when spring-security is in classpath
@Import(SecurityProblemSupport.class)
@Order(Ordered.LOWEST_PRECEDENCE - 21)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityProblemSupport problemSupport;
@Override
public void configure(final HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport);
}
}
| package org.zalando.problem.spring.web.autoconfigure.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
/**
* Registers exception handling in spring-security
*/
@Configuration
@ConditionalOnClass(WebSecurityConfigurerAdapter.class) //only when spring-security is in classpath
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityProblemSupport problemSupport;
@Override
public void configure(final HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport);
}
}
|
Include bin/ansible-pull as part of the sdist in distutils. | #!/usr/bin/env python
# NOTE: setup.py does NOT install the contents of the library dir
# for you, you should go through "make install" or "make RPMs"
# for that, or manually copy modules over.
import os
import sys
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
from distutils.core import setup
setup(name='ansible',
version=__version__,
description='Minimal SSH command and control',
author=__author__,
author_email='michael.dehaan@gmail.com',
url='http://ansible.github.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML"],
package_dir={ 'ansible': 'lib/ansible' },
packages=[
'ansible',
'ansible.inventory',
'ansible.playbook',
'ansible.runner',
'ansible.runner.connection',
],
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull'
]
)
| #!/usr/bin/env python
# NOTE: setup.py does NOT install the contents of the library dir
# for you, you should go through "make install" or "make RPMs"
# for that, or manually copy modules over.
import os
import sys
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
from distutils.core import setup
setup(name='ansible',
version=__version__,
description='Minimal SSH command and control',
author=__author__,
author_email='michael.dehaan@gmail.com',
url='http://ansible.github.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML"],
package_dir={ 'ansible': 'lib/ansible' },
packages=[
'ansible',
'ansible.inventory',
'ansible.playbook',
'ansible.runner',
'ansible.runner.connection',
],
scripts=[
'bin/ansible',
'bin/ansible-playbook'
]
)
|
Fix MySQL agent for broken DSN. | package mysql
import (
"database/sql"
"strconv"
"github.com/gansoi/gansoi/plugins"
// We need the MySQL driver for this.
_ "github.com/go-sql-driver/mysql"
)
// MySQL retrieves metrics from a MySQL server.
type MySQL struct {
DSN string `toml:"dsn" json:"dsn" description:"Mysql DSN"`
}
func init() {
plugins.RegisterAgent("mysql", MySQL{})
}
// Check implements plugins.Agent.
func (m *MySQL) Check(result plugins.AgentResult) error {
db, err := sql.Open("mysql", m.DSN)
if err != nil {
return err
}
defer db.Close()
rows, err := db.Query("SHOW GLOBAL STATUS")
if err != nil {
return err
}
defer rows.Close()
var name, value string
for rows.Next() {
e := rows.Scan(&name, &value)
if e == nil {
i, e := strconv.ParseInt(value, 10, 64)
if e != nil {
// Error, value is not integer
result.AddValue(name, value)
} else {
result.AddValue(name, i)
}
}
}
return nil
}
// Ensure compliance
var _ plugins.Agent = (*MySQL)(nil)
| package mysql
import (
"database/sql"
"strconv"
"github.com/gansoi/gansoi/plugins"
// We need the MySQL driver for this.
_ "github.com/go-sql-driver/mysql"
)
// MySQL retrieves metrics from a MySQL server.
type MySQL struct {
DSN string `toml:"dsn" json:"dsn" description:"Mysql DSN"`
}
func init() {
plugins.RegisterAgent("mysql", MySQL{})
}
// Check implements plugins.Agent.
func (m *MySQL) Check(result plugins.AgentResult) error {
// The only thing that will make this fail is if the mysql driver is not
// loaded. We ignore that.
db, _ := sql.Open("mysql", m.DSN)
defer db.Close()
rows, err := db.Query("SHOW GLOBAL STATUS")
if err != nil {
return err
}
defer rows.Close()
var name, value string
for rows.Next() {
e := rows.Scan(&name, &value)
if e == nil {
i, e := strconv.ParseInt(value, 10, 64)
if e != nil {
// Error, value is not integer
result.AddValue(name, value)
} else {
result.AddValue(name, i)
}
}
}
return nil
}
// Ensure compliance
var _ plugins.Agent = (*MySQL)(nil)
|
Fix perspective initialization issue when clicking on top menu navbar | package org.gitcontrib.client.perspectives;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import org.uberfire.client.annotations.Perspective;
import org.uberfire.client.annotations.WorkbenchPerspective;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PanelType;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PartDefinitionImpl;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;
/**
* A Perspective to show File Explorer
*/
@ApplicationScoped
@WorkbenchPerspective(identifier = "MainPerspective", isDefault = true)
public class MainPerspective {
@Perspective
public PerspectiveDefinition buildPerspective() {
PerspectiveDefinition perspective = new PerspectiveDefinitionImpl( PanelType.ROOT_STATIC);
perspective.setTransient(true);
perspective.setName("MainPerspective");
perspective.getRoot().addPart(new PartDefinitionImpl(new DefaultPlaceRequest("KIEDashboardScreen")));
return perspective;
}
}
| package org.gitcontrib.client.perspectives;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import org.uberfire.client.annotations.Perspective;
import org.uberfire.client.annotations.WorkbenchPerspective;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PanelType;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PartDefinitionImpl;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;
/**
* A Perspective to show File Explorer
*/
@ApplicationScoped
@WorkbenchPerspective(identifier = "MainPerspective", isDefault = true)
public class MainPerspective {
private PerspectiveDefinition perspective;
@PostConstruct
public void init() {
buildPerspective();
}
@Perspective
public PerspectiveDefinition getPerspective() {
return this.perspective;
}
public PerspectiveDefinition buildPerspective() {
perspective = new PerspectiveDefinitionImpl( PanelType.ROOT_STATIC);
perspective.setTransient(true);
perspective.setName("MainPerspective");
perspective.getRoot().addPart(new PartDefinitionImpl(new DefaultPlaceRequest("KIEDashboardScreen")));
return perspective;
}
}
|
[sniper_stats] Read metric names on startup for jobid-based stats so self.names is available as expected | import sniper_stats, intelqueue, iqclient
class SniperStatsJobid(sniper_stats.SniperStatsBase):
def __init__(self, jobid):
self.jobid = jobid
self.ic = iqclient.IntelClient()
self.names = self.read_metricnames()
def read_metricnames(self):
return self.ic.graphite_dbresults(self.jobid, 'read_metricnames')
def get_snapshots(self):
return self.ic.graphite_dbresults(self.jobid, 'get_snapshots')
def read_snapshot(self, prefix, metrics = None):
return self.ic.graphite_dbresults(self.jobid, 'read_snapshot', {'prefix': prefix, 'metrics': metrics})
def get_topology(self):
return self.ic.graphite_dbresults(self.jobid, 'get_topology')
def get_markers(self):
return self.ic.graphite_dbresults(self.jobid, 'get_markers')
def get_events(self):
return self.ic.graphite_dbresults(self.jobid, 'get_events')
| import sniper_stats, intelqueue, iqclient
class SniperStatsJobid(sniper_stats.SniperStatsBase):
def __init__(self, jobid):
self.jobid = jobid
self.ic = iqclient.IntelClient()
def read_metricnames(self):
return self.ic.graphite_dbresults(self.jobid, 'read_metricnames')
def get_snapshots(self):
return self.ic.graphite_dbresults(self.jobid, 'get_snapshots')
def read_snapshot(self, prefix, metrics = None):
return self.ic.graphite_dbresults(self.jobid, 'read_snapshot', {'prefix': prefix, 'metrics': metrics})
def get_topology(self):
return self.ic.graphite_dbresults(self.jobid, 'get_topology')
def get_markers(self):
return self.ic.graphite_dbresults(self.jobid, 'get_markers')
def get_events(self):
return self.ic.graphite_dbresults(self.jobid, 'get_events')
|
Add config for client ID for premium g maps users | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-place-autocomplete',
contentFor: function(type, config) {
var content = '';
if (type === 'body-footer') {
var src = "//maps.googleapis.com/maps/api/js",
placeAutocompleteConfig = config['place-autocomplete'] || {},
params = [],
exclude = placeAutocompleteConfig.exclude,
client = placeAutocompleteConfig.client,
key = placeAutocompleteConfig.key;
if (!exclude) {
if (key)
params.push('key=' + encodeURIComponent(key));
if (client)
params.push('client=' + encodeURIComponent(client) + '&v=3.24');
src += '?' + params.join('&') + "&libraries=places";
content = '<script type="text/javascript" src="' + src + '"></script>';
}
}
return content;
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-place-autocomplete',
contentFor: function(type, config) {
var content = '';
if (type === 'body-footer') {
var src = "//maps.googleapis.com/maps/api/js",
placeAutocompleteConfig = config['place-autocomplete'] || {},
params = [],
exclude = placeAutocompleteConfig.exclude,
key = placeAutocompleteConfig.key;
if (!exclude) {
if (key)
params.push('key=' + encodeURIComponent(key));
src += '?' + params.join('&') + "&libraries=places";
content = '<script type="text/javascript" src="' + src + '"></script>';
}
}
return content;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.