text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Bump version for PyPI release | from setuptools import setup
with open('README.rst') as f:
long_desc = f.read()
setup(
name='ttrss-python',
version='0.1.5',
description='A client library for the Tiny Tiny RSS web API',
long_description=long_desc,
url='https://github.com/Vassius/ttrss-python',
author='Markus Wiik',
author_email='markus.wiik@gmail.com',
packages=['ttrss'],
package_data={'': ['README.rst']},
include_package_data=True,
install_requires=['requests>=1.1.0'],
provides=['ttrss'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import setup
with open('README.rst') as f:
long_desc = f.read()
setup(
name='ttrss-python',
version='0.1.4',
description='A client library for the Tiny Tiny RSS web API',
long_description=long_desc,
url='https://github.com/Vassius/ttrss-python',
author='Markus Wiik',
author_email='markus.wiik@gmail.com',
packages=['ttrss'],
package_data={'': ['README.rst']},
include_package_data=True,
install_requires=['requests>=1.1.0'],
provides=['ttrss'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Disable mem leak check, it is to sensitive | package nl.esciencecenter.e3dchem.knime.silicosit;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.workflow.UnsupportedWorkflowVersionException;
import org.knime.core.util.LockFailedException;
import org.knime.testing.core.TestrunConfiguration;
import nl.esciencecenter.e3dchem.knime.testing.TestFlowRunner;
public class PharmacophoreReaderWorkflowTest {
@Rule
public ErrorCollector collector = new ErrorCollector();
private TestFlowRunner runner;
@Before
public void setUp() {
TestrunConfiguration runConfiguration = new TestrunConfiguration();
runConfiguration.setTestDialogs(true);
runConfiguration.setReportDeprecatedNodes(true);
runConfiguration.setCheckMemoryLeaks(false);
runConfiguration.setLoadSaveLoad(false);
runner = new TestFlowRunner(collector, runConfiguration);
}
@Test
public void test_simple() throws IOException, InvalidSettingsException, CanceledExecutionException,
UnsupportedWorkflowVersionException, LockFailedException, InterruptedException {
File workflowDir = new File("src/knime/silicos-it-phar-reader-test");
runner.runTestWorkflow(workflowDir);
}
}
| package nl.esciencecenter.e3dchem.knime.silicosit;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.workflow.UnsupportedWorkflowVersionException;
import org.knime.core.util.LockFailedException;
import org.knime.testing.core.TestrunConfiguration;
import nl.esciencecenter.e3dchem.knime.testing.TestFlowRunner;
public class PharmacophoreReaderWorkflowTest {
@Rule
public ErrorCollector collector = new ErrorCollector();
private TestFlowRunner runner;
@Before
public void setUp() {
TestrunConfiguration runConfiguration = new TestrunConfiguration();
runConfiguration.setTestDialogs(true);
runConfiguration.setReportDeprecatedNodes(true);
runConfiguration.setCheckMemoryLeaks(true);
runConfiguration.setLoadSaveLoad(false);
runner = new TestFlowRunner(collector, runConfiguration);
}
@Test
public void test_simple() throws IOException, InvalidSettingsException, CanceledExecutionException,
UnsupportedWorkflowVersionException, LockFailedException, InterruptedException {
File workflowDir = new File("src/knime/silicos-it-phar-reader-test");
runner.runTestWorkflow(workflowDir);
}
}
|
Add ability to get wireless state of a device |
/**
* Management of a device. Supports quering it for information and changing
* the WiFi settings.
*/
class DeviceManagement {
constructor(device) {
this.device = device;
}
/**
* Get information about this device. Includes model info, token and
* connection information.
*/
info() {
return this.device.call('miIO.info');
}
/**
* Update the wireless settings of this device. Needs `ssid` and `passwd`
* to be set in the options object.
*
* `uid` can be set to associate the device with a Mi Home user id.
*/
updateWireless(options) {
if(typeof options.ssid !== 'string') {
throw new Error('options.ssid must be a string');
}
if(typeof options.passwd !== 'string') {
throw new Error('options.passwd must be a string');
}
return this.device.call('miIO.config_router', options)
.then(result => {
if(! result !== 0) {
throw new Error('Failed updating wireless');
}
return true;
});
}
/**
* Get the wireless state of this device. Includes if the device is
* online and counters for things such as authentication failures and
* connection success and failures.
*/
wirelessState() {
return this.device.call('miIO.wifi_assoc_state');
}
}
module.exports = DeviceManagement;
|
/**
* Management of a device. Supports quering it for information and changing
* the WiFi settings.
*/
class DeviceManagement {
constructor(device) {
this.device = device;
}
/**
* Get information about this device. Includes model info, token and
* connection information.
*/
info() {
return this.device.call('miIO.info');
}
/**
* Update the wireless settings of this device. Needs `ssid` and `passwd`
* to be set in the options object.
*
* `uid` can be set to associate the device with a Mi Home user id.
*/
updateWireless(options) {
if(typeof options.ssid !== 'string') {
throw new Error('options.ssid must be a string');
}
if(typeof options.passwd !== 'string') {
throw new Error('options.passwd must be a string');
}
return this.device.call('miIO.config_router', options)
.then(result => {
if(! result !== 0) {
throw new Error('Failed updating wireless');
}
return true;
});
}
}
module.exports = DeviceManagement;
|
Return proper results for 'test=True' | # -*- coding: utf-8 -*-
'''
Manage RDP Service on Windows servers
'''
def __virtual__():
'''
Load only if network_win is loaded
'''
return 'rdp' if 'rdp.enable' in __salt__ else False
def enabled(name):
'''
Enable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
ret['changes'] = {'enabled rdp': True}
if __opts__['test']:
ret['result'] = stat
return ret
ret['result'] = __salt__['rdp.enable']()
return ret
def disabled(name):
'''
Disable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if stat:
ret['changes'] = {'disable rdp': True}
if __opts__['test']:
ret['result'] = stat
return ret
ret['result'] = __salt__['rdp.disable']()
return ret
| # -*- coding: utf-8 -*-
'''
Manage RDP Service on Windows servers
'''
def __virtual__():
'''
Load only if network_win is loaded
'''
return 'rdp' if 'rdp.enable' in __salt__ else False
def enabled(name):
'''
Enable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
ret['changes'] = {'enabled rdp': True}
if __opts__['test']:
ret['result'] = None
return ret
ret['result'] = __salt__['rdp.enable']()
return ret
def disabled(name):
'''
Disable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if stat:
ret['changes'] = {'disable rdp': True}
if __opts__['test']:
return ret
ret['result'] = __salt__['rdp.disable']()
return ret
|
Send router to projects view | define([
'Backbone',
//Collection
'app/collections/projects',
//Views
'app/views/projectsController',
//Templates
'text!templates/home/loginTemplate.html',
], function(
Backbone,
//Collection
Projects,
//views
projectsController,
//Template
loginTemplate
){
var ProjectsView = Backbone.View.extend({
template: _.template(loginTemplate),
collection: new Projects(),
events: {
'submit #login-form' : 'login'
},
initialize: function(){
this.options.account.bind('change', this.render, this);
this.projectsList = new projectsController({
collection: this.collection,
router: this.options.router
});
},
login: function(event){
event.preventDefault();
this.options.account.clear({silent: true});
var form = this.$(event.currentTarget).serialize();
this.options.account.login(form);
},
render: function(){
var user = this.options.account.get('user');
this.$el.html(this.template({user: user}));
if(user){
this.projectsList.setElement('.projects-list');
this.projectsList.start();
}
}
});
return ProjectsView;
});
| define([
'Backbone',
//Collection
'app/collections/projects',
//Views
'app/views/projectsController',
//Templates
'text!templates/home/loginTemplate.html',
], function(
Backbone,
//Collection
Projects,
//views
projectsController,
//Template
loginTemplate
){
var ProjectsView = Backbone.View.extend({
template: _.template(loginTemplate),
collection: new Projects(),
events: {
'submit #login-form' : 'login'
},
initialize: function(){
this.options.account.bind('change', this.render, this);
this.projectsList = new projectsController({
collection: this.collection
});
},
login: function(event){
event.preventDefault();
this.options.account.clear({silent: true});
var form = this.$(event.currentTarget).serialize();
this.options.account.login(form);
},
render: function(){
var user = this.options.account.get('user');
this.$el.html(this.template({user: user}));
if(user){
this.projectsList.setElement('.projects-list');
this.projectsList.start();
}
}
});
return ProjectsView;
});
|
Fix field name in order to support multiple accounts without usernames. | 'use strict';
const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository');
/**
* @class AccountRepository
*/
class AccountRepository extends BaseRepository {
/**
* @inheritDoc
*/
getSchemaDefinition() {
return {
email: {
type: String,
unique: true,
required: true
},
username: {
type: String,
index: {
unique: true,
partialFilterExpression: {
username: {
$type: 'string'
}
}
}
},
passwordHash: String,
};
}
/**
* @param email
* @param callback
* @returns {AccountRepository}
*/
findOneByEmail(email, callback) {
this.findOne({
email: email,
}, callback);
return this;
}
/**
* Find an account by its username.
*
* @param {string} username
* @param {function} callback
* @return {AccountRepository}
*/
findOneByUsername(username, callback) {
this.findOne({
username: username,
}, callback);
return this;
}
}
module.exports = AccountRepository;
| 'use strict';
const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository');
/**
* @class AccountRepository
*/
class AccountRepository extends BaseRepository {
/**
* @inheritDoc
*/
getSchemaDefinition() {
return {
email: {
type: String,
unique: true,
required: true
},
username: {
type: String,
index: {
unique: true,
partialFilterExpression: {
email: {
$type: 'string'
}
}
}
},
passwordHash: String,
};
}
/**
* @param email
* @param callback
* @returns {AccountRepository}
*/
findOneByEmail(email, callback) {
this.findOne({
email: email,
}, callback);
return this;
}
/**
* Find an account by its username.
*
* @param {string} username
* @param {function} callback
* @return {AccountRepository}
*/
findOneByUsername(username, callback) {
this.findOne({
username: username,
}, callback);
return this;
}
}
module.exports = AccountRepository;
|
DPRO-769: Use wild card for static content controller to support multiple pages | /*
* $HeadURL$
* $Id$
* Copyright (c) 2006-2013 by Public Library of Science http://plos.org http://ambraproject.org
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ambraproject.wombat.controller;
import org.ambraproject.wombat.config.site.Site;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Controller intended to serve static pages
*/
@Controller
public class StaticContentController extends WombatController {
@RequestMapping(value = {"/s/*", "/{site}/s/*"})
public String renderStaticContent(Model model, @SiteParam Site site)
throws IOException {
return site + "/ftl/static/container";
}
}
| /*
* $HeadURL$
* $Id$
* Copyright (c) 2006-2013 by Public Library of Science http://plos.org http://ambraproject.org
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ambraproject.wombat.controller;
import org.ambraproject.wombat.config.site.Site;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Controller intended to serve static pages
*/
@Controller
public class StaticContentController extends WombatController {
@RequestMapping(value = {"/s", "/{site}/s"})
public String renderStaticContent(Model model, @SiteParam Site site)
throws IOException {
return site + "/ftl/static/container";
}
}
|
Fix the issue in SimpleTower with using that by using bind instead | function SimpleTower(coord) {
this.x = coord['x'];
this.y = coord['y'];
this.damage = 10;
this.range = 4;
this.fireRate = 1000;
this.timeSinceLastShot = (new Date().getTime()) - this.fireRate;
}
SimpleTower.prototype.canShoot = function(currentTime) {
let timeElapsed = currentTime - this.timeSinceLastShot;
return timeElapsed >= this.fireRate;
};
SimpleTower.prototype.shoot = function(enemies) {
let currentTime = new Date().getTime();
if (this.canShoot(currentTime)) {
this.selectEnemyToShoot(enemies).hit(this.damage);
this.timeSinceLastShot = currentTime;
}
};
SimpleTower.prototype.selectEnemyToShoot = function(enemies) {
return this.enemiesWithinRange(enemies)[0];
};
SimpleTower.prototype.inRange = function(enemy) {
let dx = enemy.x - this.x;
let dy = enemy.y - this.y;
return Math.pow(dx, 2) + Math.pow(dy, 2) <= Math.pow(this.range, 2);
};
SimpleTower.prototype.enemiesWithinRange = function(enemies) {
return enemies.filter(function(enemy) {
return this.inRange(enemy);
}.bind(this));
};
module.exports = SimpleTower;
| function SimpleTower(coord) {
this.x = coord['x'];
this.y = coord['y'];
this.damage = 10;
this.range = 4;
this.fireRate = 1000;
this.timeSinceLastShot = (new Date().getTime()) - this.fireRate;
}
SimpleTower.prototype.canShoot = function(currentTime) {
let timeElapsed = currentTime - this.timeSinceLastShot;
return timeElapsed >= this.fireRate;
};
SimpleTower.prototype.shoot = function(enemies) {
let currentTime = new Date().getTime();
if (this.canShoot(currentTime)) {
this.selectEnemyToShoot(enemies).hit(this.damage);
this.timeSinceLastShot = currentTime;
}
};
SimpleTower.prototype.selectEnemyToShoot = function(enemies) {
return this.enemiesWithinRange(enemies)[0];
};
SimpleTower.prototype.inRange = function(enemy) {
let dx = enemy.x - this.x;
let dy = enemy.y - this.y;
return Math.pow(dx, 2) + Math.pow(dy, 2) <= Math.pow(this.range, 2);
};
SimpleTower.prototype.enemiesWithinRange = function(enemies) {
var that = this;
return enemies.filter(function(enemy) {
return that.inRange(enemy);
});
};
module.exports = SimpleTower;
|
Make corrections to placement of 'chromato.mix' | (function() {
var Color;
chromato = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.rgb = function(r, g, b, a) {
return new Color(r, g, b, a, 'rgb');
};
chromato.hex = function(x) {
return new Color(x);
};
chromato.interpolate = function(a, b, f, m) {
if ((a == null) || (b == null)) {
return '#000';
}
if (type(a) === 'string') {
a = new Color(a);
}
if (type(b) === 'string') {
b = new Color(b);
}
return a.interpolate(f, b, m);
};
chromato.mix = chromato.interpolate;
}).call(this);
| (function() {
var Color;
chromato = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.rgb = function(r, g, b, a) {
return new Color(r, g, b, a, 'rgb');
};
chromato.hex = function(x) {
return new Color(x);
};
chromato.interpolate = function(a, b, f, m) {
if ((a == null) || (b == null)) {
return '#000';
}
if (type(a) === 'string') {
a = new Color(a);
}
if (type(b) === 'string') {
b = new Color(b);
}
return a.interpolate(f, b, m);
};
}).call(this); chromato.mix = chromato.interpolate;
|
Refactor registering, replacing throw by next | 'use strict';
const Config = require('./config');
exports.register = function (server, options, next) {
if(server.connections.length !== 1) {
return next({
name: 'ValidationError',
details: {
message: 'You cannot register this plugin for two connections at once. \n' +
'Register it for each connection on your server.',
context: server.connections
}
});
}
const results = Config.getConfig(options);
if (results.error) {
return next(results.error);
}
const config = results.value;
// For simplicity
config.meta.page.name = config.query.page.name;
config.meta.limit.name = config.query.limit.name;
// Sets uri for generated link
config.uri = config.meta.baseUri || server.info.uri;
const decorate = require('./decorate')(config);
const ext = require('./ext')(config);
server.decorate('reply', config.reply.paginate, decorate.paginate);
server.ext('onPreHandler', ext.onPreHandler);
server.ext('onPreResponse', ext.onPreResponse);
return next();
};
exports.register.attributes = {
pkg: require('../package.json')
};
| 'use strict';
const Hoek = require('hoek');
const Config = require('./config');
exports.register = function (server, options, next) {
Hoek.assert(server.connections.length === 1,
'You cannot register this plugin for two connections at once. ' +
'Register it for each connection on your server.');
const results = Config.getConfig(options);
if (results.error) {
return next(results.error);
}
const config = results.value;
// For simplicity
config.meta.page.name = config.query.page.name;
config.meta.limit.name = config.query.limit.name;
// Sets uri for generated link
config.uri = config.meta.baseUri || server.info.uri;
const decorate = require('./decorate')(config);
const ext = require('./ext')(config);
server.decorate('reply', config.reply.paginate, decorate.paginate);
server.ext('onPreHandler', ext.onPreHandler);
server.ext('onPreResponse', ext.onPreResponse);
return next();
};
exports.register.attributes = {
pkg: require('../package.json')
};
|
Fix objects options with component label. | import React from 'react';
import {type} from 'ramda';
export const sanitizeOptions = options => {
if (type(options) === 'Object') {
return Object.entries(options).map(([value, label]) => ({
label: React.isValidElement(label) ? label : String(label),
value,
}));
}
if (type(options) === 'Array') {
if (
options.length > 0 &&
['String', 'Number', 'Bool'].includes(type(options[0]))
) {
return options.map(option => ({
label: String(option),
value: option,
}));
}
return options;
}
return options;
};
| import {type} from 'ramda';
export const sanitizeOptions = options => {
if (type(options) === 'Object') {
return Object.entries(options).map(([value, label]) => ({
label: String(label),
value,
}));
}
if (type(options) === 'Array') {
if (
options.length > 0 &&
['String', 'Number', 'Bool'].includes(type(options[0]))
) {
return options.map(option => ({
label: String(option),
value: option,
}));
}
return options;
}
return options;
};
|
Allow renderEvery to be passed a DOM node | 'use strict';
var h = require('virtual-hyperscript');
var VDOM = {
diff: require('virtual-dom/diff'),
patch: require('virtual-dom/patch')
};
var DOMDelegator = require('dom-delegator');
function renderEvery(vtree$, container) {
// Find and prepare the container
var container = typeof container === 'string' ? document.querySelector(container) : container;
if (container === null) {
throw new Error('Couldn\'t render into unknown \'' + container + '\'');
}
container.innerHTML = '';
// Make the DOM node bound to the VDOM node
var rootNode = document.createElement('div');
container.appendChild(rootNode);
return vtree$.startWith(h())
.bufferWithCount(2, 1)
.subscribe(function (buffer) {
try {
var oldVTree = buffer[0];
var newVTree = buffer[1];
rootNode = VDOM.patch(rootNode, VDOM.diff(oldVTree, newVTree));
} catch (err) {
console.error(err);
}
});
}
var delegator = new DOMDelegator();
module.exports = {
renderEvery: renderEvery,
delegator: delegator
};
| 'use strict';
var h = require('virtual-hyperscript');
var VDOM = {
diff: require('virtual-dom/diff'),
patch: require('virtual-dom/patch')
};
var DOMDelegator = require('dom-delegator');
function renderEvery(vtree$, containerSelector) {
// Find and prepare the container
var container = document.querySelector(containerSelector);
if (container === null) {
throw new Error('Couldn\'t render into unknown \'' + containerSelector + '\'');
}
container.innerHTML = '';
// Make the DOM node bound to the VDOM node
var rootNode = document.createElement('div');
container.appendChild(rootNode);
return vtree$.startWith(h())
.bufferWithCount(2, 1)
.subscribe(function (buffer) {
try {
var oldVTree = buffer[0];
var newVTree = buffer[1];
rootNode = VDOM.patch(rootNode, VDOM.diff(oldVTree, newVTree));
} catch (err) {
console.error(err);
}
});
}
var delegator = new DOMDelegator();
module.exports = {
renderEvery: renderEvery,
delegator: delegator
};
|
Revert 5505 - introduced numerous regressions into the test suite | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use application named Hyperbola',
benefactorClass = hyperbola_model.HyperbolaBenefactor)
plugin = offering.Offering(
name = u"Hyperbola",
description = u"""
This is the wonderful Hyperbola application. Click me to install.
""",
siteRequirements = (
(userbase.IRealm, userbase.LoginSystem),
(None, website.WebSite)),
appPowerups = (
),
benefactorFactories = (hyperbolaer,),
themes = (HyperbolaTheme('base', 0),)
)
| from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use application named Hyperbola',
benefactorClass = hyperbola_model.HyperbolaBenefactor)
plugin = offering.Offering(
name = u"Hyperbola",
description = u"""
This is the wonderful Hyperbola application. Click me to install.
""",
siteRequirements = (
(userbase.IRealm, userbase.LoginSystem),
(None, website.WebSite)),
appPowerups = (
),
benefactorFactories = (hyperbolaer,),
loginInterfaces = (),
themes = (HyperbolaTheme('base', 0),)
)
|
Set public org access when using public repos | var _ = require('underscore');
var Backbone = require('backbone');
var Org = require('../models/org');
var config = require('../config');
var cookie = require('../cookie');
module.exports = Backbone.Collection.extend({
model: Org,
initialize: function(models, options) {
options = _.clone(options) || {};
_.bindAll(this);
this.user = options.user;
},
url: function() {
var token = cookie.get('oauth-token');
var scope = cookie.get('scope');
// If not authenticated, show public repos for user in path.
// https://developer.github.com/v3/orgs/#list-user-organizations
if (!token || scope !== 'repo') {
return config.api + '/users/' + this.user.get('login') + '/orgs';
}
// Authenticated users see all repos they have access to.
// https://developer.github.com/v3/orgs/#list-your-organizations
else {
return config.api + '/user/orgs';
}
}
});
| var _ = require('underscore');
var Backbone = require('backbone');
var Org = require('../models/org');
var config = require('../config');
var cookie = require('../cookie');
module.exports = Backbone.Collection.extend({
model: Org,
initialize: function(models, options) {
options = _.clone(options) || {};
_.bindAll(this);
this.user = options.user;
},
url: function() {
var token = cookie.get('oauth-token');
// If not authenticated, show public repos for user in path.
// https://developer.github.com/v3/orgs/#list-user-organizations
if (!token) {
return config.api + '/users/' + this.user.get('login') + '/orgs';
}
// Authenticated users see all repos they have access to.
// https://developer.github.com/v3/orgs/#list-your-organizations
else {
return config.api + '/user/orgs';
}
}
});
|
Add square brackets around tags in logs in FabricUIManager
Summary:
See title.
Changelog: [Internal]
Differential Revision: D23257809
fbshipit-source-id: b8e519971603506e8ae2b327582d3e3e7d65fddf | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.fabric.mounting.mountitems;
import androidx.annotation.NonNull;
import com.facebook.react.fabric.mounting.MountingManager;
public class InsertMountItem implements MountItem {
private int mReactTag;
private int mParentReactTag;
private int mIndex;
public InsertMountItem(int reactTag, int parentReactTag, int index) {
mReactTag = reactTag;
mParentReactTag = parentReactTag;
mIndex = index;
}
@Override
public void execute(@NonNull MountingManager mountingManager) {
mountingManager.addViewAt(mParentReactTag, mReactTag, mIndex);
}
public int getParentReactTag() {
return mParentReactTag;
}
public int getIndex() {
return mIndex;
}
@Override
public String toString() {
return "InsertMountItem ["
+ mReactTag
+ "] - parentTag: ["
+ mParentReactTag
+ "] - index: "
+ mIndex;
}
}
| /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.fabric.mounting.mountitems;
import androidx.annotation.NonNull;
import com.facebook.react.fabric.mounting.MountingManager;
public class InsertMountItem implements MountItem {
private int mReactTag;
private int mParentReactTag;
private int mIndex;
public InsertMountItem(int reactTag, int parentReactTag, int index) {
mReactTag = reactTag;
mParentReactTag = parentReactTag;
mIndex = index;
}
@Override
public void execute(@NonNull MountingManager mountingManager) {
mountingManager.addViewAt(mParentReactTag, mReactTag, mIndex);
}
public int getParentReactTag() {
return mParentReactTag;
}
public int getIndex() {
return mIndex;
}
@Override
public String toString() {
return "InsertMountItem ["
+ mReactTag
+ "] - parentTag: "
+ mParentReactTag
+ " - index: "
+ mIndex;
}
}
|
Adjust ServiceWorker for polyfill demo | importScripts('/streaming-dot.min.js');
const ASSETS = [
'/header.partial.html',
'/footer.partial.html',
'/index.dot.html'
];
self.oninstall = event => event.waitUntil(
caches.open('static')
.then(cache => cache.addAll(ASSETS))
.then(_ => self.skipWaiting())
);
self.onactivate = event => event.waitUntil(self.clients.claim());
function timeoutPromise(t) {
return new Promise(resolve =>
setTimeout(resolve, t)
);
}
self.onfetch = event => {
event.parsedUrl = new URL(event.request.url);
if (event.parsedUrl.pathname !== '/') return event.respondWith(fetch(event.request));
event.respondWith(
caches.match('/index.dot.html')
.then(response => response.text())
.then(body => {
const template = doT.compile(body);
const response = template({
header: caches.match('/header.partial.html').then(r => r.body),
footer: caches.match('/footer.partial.html').then(r => r.body),
location: timeoutPromise(2000).then(_ => 'in a service worker'),
version: doT.version
});
return new Response(response, {headers: {'Content-Type': 'text/html'}});
})
);
};
| importScripts('/streaming-dot.min.js');
const ASSETS = [
'/header.partial.html',
'/footer.partial.html',
'/index.dot.html'
];
self.oninstall = event => event.waitUntil(
caches.open('static')
.then(cache => cache.addAll(ASSETS))
.then(_ => self.skipWaiting())
);
self.onactivate = event => event.waitUntil(self.clients.claim());
function timeoutPromise(t) {
return new Promise(resolve =>
setTimeout(resolve, t)
);
}
self.onfetch = event => event.respondWith(
caches.match('/index.dot.html')
.then(response => response.text())
.then(body => {
const template = doT.compile(body);
const response = template({
header: caches.match('/header.partial.html').then(r => r.body),
footer: caches.match('/footer.partial.html').then(r => r.body),
location: timeoutPromise(2000).then(_ => 'in a service worker'),
version: doT.version
});
return new Response(response, {headers: {'Content-Type': 'text/html'}});
})
);
|
Add identicon icon_url to sendToSlack | var _ = require('lodash');
var logger = require('winston');
var request = require('superagent');
function SlackGateway(incomingURL, channelMapping) {
this.incomingURL = incomingURL;
this.invertedMapping = _.invert(channelMapping);
}
SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) {
var payload = {
username: author,
icon_url: 'https://github.com/identicons/' + author + '.png',
channel: this.invertedMapping[ircChannel],
text: message
};
request
.post(this.incomingURL)
.send(payload)
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) return logger.error('Couldn\'t post message to Slack', err);
logger.debug('Posted message to Slack', res.body, res.statusCode);
});
};
module.exports = SlackGateway;
| var _ = require('lodash');
var logger = require('winston');
var request = require('superagent');
function SlackGateway(incomingURL, channelMapping) {
this.incomingURL = incomingURL;
this.invertedMapping = _.invert(channelMapping);
}
SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) {
var payload = {
username: author,
channel: this.invertedMapping[ircChannel],
text: message
};
request
.post(this.incomingURL)
.send(payload)
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) return logger.error('Couldn\'t post message to Slack', err);
logger.debug('Posted message to Slack', res.body, res.statusCode);
});
};
module.exports = SlackGateway;
|
Return a proper relative path | #!/usr/bin/env node
exports.command = {
description: 'resolve a path to a project',
arguments: '<path>'
};
if (require.main !== module) {
return;
}
var path = require('path');
var storage = require('../lib/storage.js');
var utilities = require('../lib/utilities.js');
var program = utilities.programDefaults('resolve', '<path>');
program.option('-r, --relative', 'display the relative path');
program.parse(process.argv);
program.handleColor();
if (!program.args[0]) {
console.error('Please specify a path.');
process.exit(1);
}
storage.setup(function () {
var project = storage.getProjectByDirectory(program.args[0]);
if (project) {
if (program.relative) {
var relativePath = path.relative(process.cwd(), project.directory);
// Return '.' if we're at the root of the project
console.log(relativePath === '' ? '.' : relativePath);
} else {
console.log(project.directory);
}
process.exit(0);
}
process.exit(1);
});
| #!/usr/bin/env node
exports.command = {
description: 'resolve a path to a project',
arguments: '<path>'
};
if (require.main !== module) {
return;
}
var path = require('path');
var storage = require('../lib/storage.js');
var utilities = require('../lib/utilities.js');
var program = utilities.programDefaults('resolve', '<path>');
program.option('-r, --relative', 'display the relative path');
program.parse(process.argv);
program.handleColor();
if (!program.args[0]) {
console.error('Please specify a path.');
process.exit(1);
}
storage.setup(function () {
var project = storage.getProjectByDirectory(program.args[0]);
if (project) {
if (program.relative) {
console.log(path.relative(process.cwd(), project.directory));
} else {
console.log(project.directory);
}
process.exit(0);
}
process.exit(1);
});
|
Set first tab as active by default, fix undefined error | /**
* Toolkit JavaScript
*/
// Tabs
function Tabs (tab) {
this.tabsItem = tab;
this.displayTabs = function (active) {
var tabsContent = this.tabsItem.querySelectorAll('[data-tabs-content]');
tabsContent.forEach(function (t) {
t.style.display = t.getAttribute('id') !== active.dataset.tab ? 'none': '';
});
}.bind(this);
this.showTab = function (e) {
e.preventDefault();
var siblings = Array.prototype.filter.call(e.target.parentNode.children, function(child) {
return child !== e.target;
});
// Hide other tabs
siblings.forEach(function (i) {
i.classList.remove('active')
});
e.target.classList.add('active');
this.displayTabs(e.target);
}.bind(this);
var links = this.tabsItem.querySelectorAll('a');
var active = this.tabsItem.querySelector('.active') || this.tabsItem.querySelector('.tabs-header-link')[0];
active.classList.add('active');
// Run first time
this.displayTabs(active);
// Bind links
for(var link of links) {
link.addEventListener('click', this.showTab);
}
}
// Initialize Tabs
var tabs = document.querySelectorAll('[data-tabs]');
for (var tab of tabs) {
new Tabs(tab);
}
| /**
* Toolkit JavaScript
*/
// Tabs
function Tabs (tab) {
this.tabsItem = tab;
this.displayTabs = function (active) {
var tabsContent = this.tabsItem.querySelectorAll('[data-tabs-content]');
tabsContent.forEach(function (t) {
t.style.display = t.getAttribute('id') !== active.dataset.tab ? 'none': '';
});
}.bind(this);
this.showTab = function (e) {
e.preventDefault();
var siblings = Array.prototype.filter.call(e.target.parentNode.children, function(child) {
return child !== e.target;
});
// Hide other tabs
siblings.forEach(function (i) {
i.classList.remove('active')
});
e.target.classList.add('active');
this.displayTabs(e.target);
}.bind(this);
var links = this.tabsItem.querySelectorAll('a');
var active = this.tabsItem.querySelector('.active');
// Run first time
this.displayTabs(active);
// Bind links
for(var link of links) {
link.addEventListener('click', this.showTab);
}
}
// Initialize Tabs
var tabs = document.querySelectorAll('[data-tabs]');
for (var tab of tabs) {
new Tabs(tab);
}
|
Replace depreciated AudioElement with MediaElement in zoom example | 'use strict';
// Create an instance
var wavesurfer = Object.create(WaveSurfer);
// Init & load audio file
document.addEventListener('DOMContentLoaded', function () {
// Init
wavesurfer.init({
container: document.querySelector('#waveform'),
waveColor: '#A8DBA8',
progressColor: '#3B8686',
backend: 'MediaElement'
});
// Load audio from URL
wavesurfer.load('../media/demo.wav');
// Zoom slider
var slider = document.querySelector('[data-action="zoom"]');
slider.value = wavesurfer.params.minPxPerSec;
slider.min = wavesurfer.params.minPxPerSec;
slider.addEventListener('input', function () {
wavesurfer.zoom(Number(this.value));
});
// Play button
var button = document.querySelector('[data-action="play"]');
button.addEventListener('click', wavesurfer.playPause.bind(wavesurfer));
});
| 'use strict';
// Create an instance
var wavesurfer = Object.create(WaveSurfer);
// Init & load audio file
document.addEventListener('DOMContentLoaded', function () {
// Init
wavesurfer.init({
container: document.querySelector('#waveform'),
waveColor: '#A8DBA8',
progressColor: '#3B8686',
backend: 'AudioElement'
});
// Load audio from URL
wavesurfer.load('../media/demo.wav');
// Zoom slider
var slider = document.querySelector('[data-action="zoom"]');
slider.value = wavesurfer.params.minPxPerSec;
slider.min = wavesurfer.params.minPxPerSec;
slider.addEventListener('input', function () {
wavesurfer.zoom(Number(this.value));
});
// Play button
var button = document.querySelector('[data-action="play"]');
button.addEventListener('click', wavesurfer.playPause.bind(wavesurfer));
});
|
Update sample to reflect final destination in wiki documentation. | #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Translate.
Command-line application that translates
some text.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import pprint
import sys
from apiclient.discovery import build
from apiclient.model import LoggingJsonModel
FLAGS = gflags.FLAGS
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
service = build('translate', 'v2',
developerKey='AIzaSyAQIKv_gwnob-YNrXV2stnY86GSGY81Zr0',
model=LoggingJsonModel())
print service.translations().list(
source='en',
target='fr',
q=['flower', 'car']
).execute()
if __name__ == '__main__':
main(sys.argv)
| #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Translate.
Command-line application that translates
some text.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import pprint
import sys
from apiclient.discovery import build
from apiclient.model import LoggingJsonModel
FLAGS = gflags.FLAGS
FLAGS.dump_request_response = True
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def main(argv):
service = build('translate', 'v2',
developerKey='AIzaSyAQIKv_gwnob-YNrXV2stnY86GSGY81Zr0',
model=LoggingJsonModel())
print service.translations().list(
source='en',
target='fr',
q=['flower', 'car']
).execute()
if __name__ == '__main__':
main(sys.argv)
|
Revert "Mark backcompat on some Handlebars functions"
This reverts commit b777b04a66e98b90f8541e19a7e8106d3e90b1d1. | // XXX this file no longer makes sense in isolation. take it apart as
// part file reorg on the 'ui' package
var globalHelpers = {};
UI.registerHelper = function (name, func) {
globalHelpers[name] = func;
};
UI._globalHelper = function (name) {
return globalHelpers[name];
};
Handlebars = {};
Handlebars.registerHelper = UI.registerHelper;
// Utility to HTML-escape a string.
UI._escape = Handlebars._escape = (function() {
var escape_map = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`", /* IE allows backtick-delimited attributes?? */
"&": "&"
};
var escape_one = function(c) {
return escape_map[c];
};
return function (x) {
return x.replace(/[&<>"'`]/g, escape_one);
};
})();
// Return these from {{...}} helpers to achieve the same as returning
// strings from {{{...}}} helpers
Handlebars.SafeString = function(string) {
this.string = string;
};
Handlebars.SafeString.prototype.toString = function() {
return this.string.toString();
};
| // XXX this file no longer makes sense in isolation. take it apart as
// part file reorg on the 'ui' package
var globalHelpers = {};
UI.registerHelper = function (name, func) {
globalHelpers[name] = func;
};
UI._globalHelper = function (name) {
return globalHelpers[name];
};
// Utility to HTML-escape a string.
UI._escape = (function() {
var escape_map = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`", /* IE allows backtick-delimited attributes?? */
"&": "&"
};
var escape_one = function(c) {
return escape_map[c];
};
return function (x) {
return x.replace(/[&<>"'`]/g, escape_one);
};
})();
// Return these from {{...}} helpers to achieve the same as returning
// strings from {{{...}}} helpers
Handlebars.SafeString = function(string) {
this.string = string;
};
Handlebars.SafeString.prototype.toString = function() {
return this.string.toString();
};
// XXX COMPAT WITH 0.7.2
Handlebars = {};
Handlebars._escape = UI._escape;
Handlebars.registerHelper = UI.registerHelper;
|
Use $onChanges to react to updated content | import markdown from "markdown-it";
const md = markdown({
xhtmlOut: true,
breaks: true
});
export default class ExpandablePanelController {
constructor($sce) {
"ngInject";
Object.assign(this, {
$sce,
expandable: false,
expanded: false,
parsed: ""
});
}
$onChanges(changes) {
if (changes.content && changes.content.currentValue) {
let content = changes.content.currentValue;
// more then 10 lines?
if (content.match(/\n/mg).length > 9) {
this.expandable = true;
}
if (this.markdown) {
this.parsed = this.$sce.trustAsHtml(md.render(content));
}
}
}
toggle() {
this.expanded = !this.expanded;
}
}
| import markdown from "markdown-it";
const md = markdown({
xhtmlOut: true,
breaks: true
});
export default class ExpandablePanelController {
constructor($timeout, $sce) {
"ngInject";
Object.assign(this, {
expandable: false,
expanded: false,
parsed: ""
});
$timeout( () => {
// more then 10 lines?
if (this.content.match(/\n/mg).length > 9) {
this.expandable = true;
}
if (this.markdown) {
this.parsed = $sce.trustAsHtml(md.render(this.content));
}
});
}
toggle() {
this.expanded = !this.expanded;
}
}
|
Add redirect after successful login | /**
*
* Meet-Up Event Planner
* Copyright 2015 Justin Varghese John All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*/
/* eslint-env browser */
'use strict';
var firebase = new Firebase("https://meet-up-event-planner.firebaseio.com");
let emailInput = document.querySelector('input[name="email"]');
let passwordInput = document.querySelector('input[name="password"]');
let submit = document.querySelector('button[type="submit"]');
submit.onclick = function() {
event.preventDefault();
firebase.authWithPassword({
email : emailInput.value,
password : passwordInput.value
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
window.location.href = '/create-event.html';
}
});
};
| /**
*
* Meet-Up Event Planner
* Copyright 2015 Justin Varghese John All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*/
/* eslint-env browser */
'use strict';
var firebase = new Firebase("https://meet-up-event-planner.firebaseio.com");
let emailInput = document.querySelector('input[name="email"]');
let passwordInput = document.querySelector('input[name="password"]');
let submit = document.querySelector('button[type="submit"]');
submit.onclick = function() {
event.preventDefault();
firebase.authWithPassword({
email : emailInput.value,
password : passwordInput.value
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
};
|
Add style to domain list output | var api = require('digio-api')
, print = require('../print')
, tools = require('../tools')
var domains = function (cmd, _config) {
api = new api(tools.get_active_key(_config))
cmd.register(
'domains',
'list',
[],
'List all domains',
function () {
api.domains.list(function (err, data) {
if (err) return print.error(err.message)
print.list(JSON.parse(data).domains.map(
function (e) {
return e.name
})
)
})
}
)
cmd.register(
'domains',
'create',
['<domain>', '<ip>'],
'Create a new domain',
function (domain, ip_address) {
api.domains.create(domain, ip_address, function (err, data) {
if (err) return print.error(err.message)
console.log(data)
})
}
)
}
module.exports = domains
| var api = require('digio-api')
, print = require('../print')
, tools = require('../tools')
var domains = function (cmd, _config) {
api = new api(tools.get_active_key(_config))
cmd.register(
'domains',
'list',
[],
'List all domains',
function () {
api.domains.list(function (err, data) {
if (err) return print.error(err.message)
console.log(data)
})
}
)
cmd.register(
'domains',
'create',
['<domain>', '<ip>'],
'Create a new domain',
function (domain, ip_address) {
api.domains.create(domain, ip_address, function (err, data) {
if (err) return print.error(err.message)
console.log(data)
})
}
)
}
module.exports = domains
|
Fix missing word in sum up numbers problem | #!/usr/local/bin/python
# Code Fights Sum Up Numbers Problem
import re
def sumUpNumbers(inputString):
return sum([int(n) for n in re.findall(r'\d+', inputString)])
def main():
tests = [
["2 apples, 12 oranges", 14],
["123450", 123450],
["Your payment method is invalid", 0]
]
for t in tests:
res = sumUpNumbers(t[0])
ans = t[1]
if ans == res:
print("PASSED: sumUpNumbers({}) returned {}"
.format(t[0], res))
else:
print("FAILED: sumUpNumbers({}) returned {}, answer: {}"
.format(t[0], res, ans))
if __name__ == '__main__':
main()
| #!/usr/local/bin/python
# Code Fights Sum Up Problem
import re
def sumUpNumbers(inputString):
return sum([int(n) for n in re.findall(r'\d+', inputString)])
def main():
tests = [
["2 apples, 12 oranges", 14],
["123450", 123450],
["Your payment method is invalid", 0]
]
for t in tests:
res = sumUpNumbers(t[0])
ans = t[1]
if ans == res:
print("PASSED: sumUpNumbers({}) returned {}"
.format(t[0], res))
else:
print("FAILED: sumUpNumbers({}) returned {}, answer: {}"
.format(t[0], res, ans))
if __name__ == '__main__':
main()
|
Return rejected promise instead of throwing if an error occurs in Request | import { request as baseRequest, sanitize } from 'js-utility-belt/es6';
import ApiUrls from '../constants/api_urls';
const DEFAULT_REQUEST_CONFIG = {
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
/**
* Small wrapper around js-utility-belt's request that provides url resolving, default settings, and
* response handling.
*/
export default function request(url, config = {}) {
// Load default fetch configuration and remove any falsy query parameters
const requestConfig = Object.assign({}, DEFAULT_REQUEST_CONFIG, config, {
query: config.query && sanitize(config.query)
});
let apiUrl = url;
if (!url) {
return Promise.reject(new Error('Request was not given a url.'));
} else if (!url.match(/^http/)) {
apiUrl = ApiUrls[url];
if (!apiUrl) {
return Promise.reject(new Error(`Request could not find a url mapping for "${url}"`));
}
}
return baseRequest(apiUrl, requestConfig)
.then((res) => res.json())
.catch((err) => {
console.error(err);
throw err;
});
}
| import { request as baseRequest, sanitize } from 'js-utility-belt/es6';
import ApiUrls from '../constants/api_urls';
const DEFAULT_REQUEST_CONFIG = {
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
/**
* Small wrapper around js-utility-belt's request that provides default settings and response
* handling
*/
export default function request(url, config) {
// Load default fetch configuration and remove any falsey query parameters
const requestConfig = Object.assign({}, DEFAULT_REQUEST_CONFIG, config, {
query: config.query && sanitize(config.query)
});
let apiUrl = url;
if (!apiUrl.match(/^http/)) {
apiUrl = ApiUrls[url];
if (!url) {
throw new Error(`Cannot find a url mapping for "${name}"`);
}
}
return baseRequest(apiUrl, requestConfig)
.then((res) => res.json())
.catch((err) => {
console.error(err);
throw err;
});
}
|
Establish basic JSON API capability. | from flask import Flask, redirect, render_template, request
import json
import six
from badgecheck.verifier import verify
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024 # 4mb file upload limit
def request_wants_json():
best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/html']
@app.route("/")
def home():
return render_template('index.html')
@app.route("/results", methods=['GET'])
def resultGetRedirect():
return redirect('/')
@app.route("/results", methods=['POST'])
def results():
if isinstance(request.form['data'], six.string_types) or request.files:
user_input = request.form['data']
if 'image' in request.files and len(request.files['image'].filename):
user_input = request.files['image']
verification_results = verify(user_input)
if request_wants_json():
return (json.dumps(verification_results, indent=4), 200, {'Content-Type': 'application/json'},)
return render_template(
'results.html', results=json.dumps(verification_results, indent=4))
return redirect('/')
if __name__ == "__main__":
app.run()
| from flask import Flask, redirect, render_template, request
import json
import six
from badgecheck.verifier import verify
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024 # 4mb file upload limit
@app.route("/")
def home():
return render_template('index.html')
@app.route("/results", methods=['POST'])
def results():
if isinstance(request.form['data'], six.string_types) or request.files:
user_input = request.form['data']
if 'image' in request.files and len(request.files['image'].filename):
user_input = request.files['image']
verification_results = verify(user_input)
return render_template(
'results.html', results=json.dumps(verification_results, indent=4))
return redirect('/')
if __name__ == "__main__":
app.run()
|
Use courses query to load a users courses | import Ember from 'ember';
import DS from 'ember-data';
const { Component, computed, inject, RSVP } = Ember;
const { service }= inject;
export default Component.extend({
store: service(),
currentUser: service(),
tagName: 'div',
classNames: ['dashboard-block'],
courseSorting: ['startDate:desc'],
sortedListOfCourses: computed.sort('listOfCourses', 'courseSorting'),
listOfCourses: computed('currentUser.model', function(){
let defer = RSVP.defer();
this.get('currentUser').get('model').then( user => {
this.get('store').query('course', {
filters: {
users: [user.get('id')],
locked: false,
archived: false
}
}).then(filteredCourses => {
defer.resolve(filteredCourses);
});
});
return DS.PromiseArray.create({
promise: defer.promise
});
}),
});
| import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Component.extend({
currentUser: Ember.inject.service(),
tagName: 'div',
classNames: ['dashboard-block'],
courseSorting: ['startDate:desc'],
sortedListOfCourses: Ember.computed.sort('listOfCourses', 'courseSorting'),
listOfCourses: Ember.computed('currentUser.model.allRelatedCourses.[]', function(){
let defer = Ember.RSVP.defer();
this.get('currentUser').get('model').then( user => {
user.get('allRelatedCourses').then( courses => {
let filteredCourses = courses.filter(course => {
return (!course.get('locked') && !course.get('archived'));
});
defer.resolve(filteredCourses);
});
});
return DS.PromiseArray.create({
promise: defer.promise
});
}),
});
|
Refactor header to comply to Foundation Sites structure | <div id="adminNav" class="top-bar">
<div class="top-bar-left">
<ul class="dropdown menu" data-dropdown-menu>
<li class="menu-text">
Angel Admin
</li>
<li{!! Request::is('admin/pages*') ? ' class="active"' : '' !!}>
<a href="{{ url('admin/pages') }}">
Pages
</a>
</li>
<li{!! Request::is('admin/blogs*') ? ' class="active"' : '' !!}>
<a href="{{ url('admin/blogs') }}">
Blogs
</a>
</li>
<li{!! Request::is('admin/users*') ? ' class="active"' : '' !!}>
<a href="{{ url('admin/users') }}">
Users
</a>
</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>
<a href="{{ url('admin/logout') }}">
Sign Out
</a>
</li>
</ul>
</div>
</div> | <nav id="adminNav" class="top-bar" data-topbar role="navigation">
<ul class="title-area">
<li class="name">
<h1><a href="{{ url('admin') }}">Angel Admin</a></h1>
</li>
<!-- Remove the class "menu-icon" to get rid of menu icon. Take out "Menu" to just have icon alone -->
<li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a></li>
</ul>
<section class="top-bar-section">
<!-- Right Nav Section -->
<ul class="right">
<li>
<a href="{{ url('admin/logout') }}">
Sign Out
</a>
</li>
</ul>
<!-- Left Nav Section -->
<ul class="left">
<li{!! Request::is('admin/pages*') ? ' class="active"' : '' !!}>
<a href="{{ url('admin/pages') }}">
Pages
</a>
</li>
<li{!! Request::is('admin/blogs*') ? ' class="active"' : '' !!}>
<a href="{{ url('admin/blogs') }}">
Blogs
</a>
</li>
<li{!! Request::is('admin/users*') ? ' class="active"' : '' !!}>
<a href="{{ url('admin/users') }}">
Users
</a>
</li>
</ul>
</section>
</nav> |
Make link from category thumbnail | <?
/**
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
?>
<? foreach($categories as $category) : ?>
<article>
<div class="page-header">
<h1>
<a href="<?= @helper('route.category', array('row' => $category)) ?>">
<?= @escape($category->title);?>
</a>
</h1>
</div>
<div class="clearfix">
<? if($category->thumbnail) : ?>
<a href="<?= @helper('route.category', array('row' => $category)) ?>">
<img class="article__thumbnail" src="<?= $category->thumbnail ?>" />
</a>
<? endif ?>
<? if ($category->description) : ?>
<p><?= $category->description; ?></p>
<? endif; ?>
</div>
<a href="<?= @helper('route.category', array('row' => $category)) ?>"><?= @text('Read more') ?></a>
</article>
<? endforeach; ?>
| <?
/**
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
?>
<? foreach($categories as $category) : ?>
<article>
<div class="page-header">
<h1>
<a href="<?= @helper('route.category', array('row' => $category)) ?>">
<?= @escape($category->title);?>
</a>
</h1>
</div>
<div class="clearfix">
<?= @helper('com:attachments.image.thumbnail', array('row' => $category)) ?>
<? if ($category->description) : ?>
<p><?= $category->description; ?></p>
<? endif; ?>
</div>
<a href="<?= @helper('route.category', array('row' => $category)) ?>"><?= @text('Read more') ?></a>
</article>
<? endforeach; ?>
|
Fix typo in Alg00 that prevents CIEUtils from loading |
'use strict';
var CIEStrategy = require('./cie_strategy.js').CIEStrategy;
var CIEUtils = require('./cie_utils.js').CIEUtils;
var cieUtils = new CIEUtils();
var Alg00 = function() {};
Alg00.prototype = new CIEStrategy();
Alg00.prototype = {
execute: function(input) {
var validationRules = {
reference: {length: {min: 1,max: 19}}
};
if (!cieUtils.validateInput(input, validationRules)) {
var error = new Error('Longitud invalida');
error.status = '422';
throw error;
}
var acc = 0;
var tmpInput = input.reference.split("").reverse().join("")
for(var i = 0; i < input.reference.length; i++) {
acc += cieUtils.sequentialAdd( parseInt(tmpInput[i],10) * ( ( (i+1)%2 !== 0 ) ? 2 : 1) );
}
return input.reference + (cieUtils.nearestMultipleOf(acc,10) - acc)%10;
}
};
module.exports.Alg00 = Alg00;
|
'use strict';
var CIEStrategy = require('./cie_strategy.js').CIEStrategy;
var CIEUtils = require('./cie_utils.js').CIEUtils;
var cieUtils = new CIEUtil();
var Alg00 = function() {};
Alg00.prototype = new CIEStrategy();
Alg00.prototype = {
execute: function(input) {
var validationRules = {
reference: {length: {min: 1,max: 19}}
};
if (!cieUtils.validateInput(input, validationRules)) {
var error = new Error('Longitud invalida');
error.status = '422';
throw error;
}
var acc = 0;
var tmpInput = input.reference.split("").reverse().join("")
for(var i = 0; i < input.reference.length; i++) {
acc += cieUtils.sequentialAdd( parseInt(tmpInput[i],10) * ( ( (i+1)%2 !== 0 ) ? 2 : 1) );
}
return input.reference + (cieUtils.nearestMultipleOf(acc,10) - acc)%10;
}
};
module.exports.Alg00 = Alg00;
|
Change version number to 0.1dev | """
Flask-FlatPages
---------------
Provides flat static pages to a Flask application, based on text files
as opposed to a relationnal database.
"""
from setuptools import setup
setup(
name='Flask-FlatPages',
version='0.1dev',
url='http://exyr.org/Flask-FlatPages/',
license='BSD',
author='Simon Sapin',
author_email='simon.sapin@exyr.org',
description='Provides flat static pages to a Flask application',
long_description=__doc__,
packages=['flaskext'],
namespace_packages=['flaskext'],
test_suite='test_flatpages',
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'PyYAML',
'Markdown',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| """
Flask-FlatPages
---------------
Provides flat static pages to a Flask application, based on text files
as opposed to a relationnal database.
"""
from setuptools import setup
setup(
name='Flask-FlatPages',
version='0.1',
url='http://exyr.org/Flask-FlatPages/',
license='BSD',
author='Simon Sapin',
author_email='simon.sapin@exyr.org',
description='Provides flat static pages to a Flask application',
long_description=__doc__,
packages=['flaskext'],
namespace_packages=['flaskext'],
test_suite='test_flatpages',
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'PyYAML',
'Markdown',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Hide secret channels from /NAMES users | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "p" in chan.mode and chan.name not in user.channels:
user.sendMessage(irc.ERR_NOSUCHNICK, chan, ":No such nick/channel")
remove.append(chan)
for chan in remove:
data["targetchan"].remove(chan)
return data
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_s = None
def spawn(self):
self.mode_s = SecretMode()
return {
"modes": {
"cns": self.mode_s
},
"actions": {
"commandextra": [self.mode_s.listOutput]
}
}
def cleanup(self):
self.ircd.removeMode("cns")
self.ircd.actions["commandextra"].remove(self.mode_s.listOutput) | from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_s = None
def spawn(self):
self.mode_s = SecretMode()
return {
"modes": {
"cns": self.mode_s
},
"actions": {
"commandextra": [self.mode_s.listOutput]
}
}
def cleanup(self):
self.ircd.removeMode("cns")
self.ircd.actions["commandextra"].remove(self.mode_s.listOutput) |
Use __init__ for factory imports. | from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device.__init__')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage.__init__')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
r('DigitalGateStage', module='moa.stage.gate')
r('AnalogGateStage', module='moa.stage.gate')
| from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
r('DigitalGateStage', module='moa.stage.gate')
r('AnalogGateStage', module='moa.stage.gate')
|
Use PotionMeta instead of ThrownPotion | package com.github.rmsy.bukkitpotdebug;
import org.bukkit.Bukkit;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import java.util.Collection;
public class PotDebugPlugin extends JavaPlugin implements Listener {
@Override
public void onDisable() {
HandlerList.unregisterAll((JavaPlugin) this);
}
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPotionSplash(final PotionSplashEvent event) {
ThrownPotion potion = event.getPotion();
Collection<PotionEffect> effects = ((PotionMeta) potion.getItem().getItemMeta()).getCustomEffects();
Bukkit.broadcastMessage("A " + event.getEntity().getType().getName() + " splashed a potion with " + effects.size() + " effects attached:");
for (PotionEffect effect : effects) {
Bukkit.broadcastMessage("Type: " + effect.getType().getName() + ", Level: " + (effect.getAmplifier() + 1) + ", Duration: " + effect.getDuration());
}
}
}
| package com.github.rmsy.bukkitpotdebug;
import org.bukkit.Bukkit;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import java.util.Collection;
public class PotDebugPlugin extends JavaPlugin implements Listener {
@Override
public void onDisable() {
HandlerList.unregisterAll((JavaPlugin) this);
}
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPotionSplash(final PotionSplashEvent event) {
ThrownPotion potion = event.getPotion();
Collection<PotionEffect> effects = potion.getEffects();
Bukkit.broadcastMessage("A " + event.getEntity().getType().getName() + " splashed a potion with " + effects.size() + " effects attached:");
for (PotionEffect effect : effects) {
Bukkit.broadcastMessage("Type: " + effect.getType().getName() + ", Level: " + (effect.getAmplifier() + 1) + ", Duration: " + effect.getDuration());
}
}
}
|
Make the example test less erratic | var _ = require('lodash')
var helper = require('./support/helper')
var assert = require('assert')
var result = helper.run('example/test/lib/**/*.js')
assert.equal(result, false)
helper.assertLog(
"TAP version 13",
"1..3",
"I'll run once before both tests",
"I'll run twice - once before each test",
"ok 1 - \"adds\" - test #1 in `example/test/lib/exporting-an-object.js`",
"I'll run twice - once after each test",
"I'll run twice - once before each test",
"ok 2 - \"subtracts\" - test #2 in `example/test/lib/exporting-an-object.js`",
"I'll run twice - once after each test",
"I'll run once after both tests",
"not ok 3 - \"blueIsRed\" - test #1 in `example/test/lib/single-function.js`",
" ---",
" message: 'blue' == 'red'",
/ stacktrace: AssertionError: 'blue' == 'red'/,
" ..."
)
| var _ = require('lodash')
var helper = require('./support/helper')
var assert = require('assert')
ogConsoleLog = console.log
var result = helper.run('example/test/lib/**/*.js'),
log = helper.log()
assert.equal(result, false)
helper.assertLog(
"TAP version 13",
"1..3",
"I'll run once before both tests",
"I'll run twice - once before each test",
"ok 1 - \"adds\" - test #1 in `example/test/lib/exporting-an-object.js`",
"I'll run twice - once after each test",
"I'll run twice - once before each test",
"ok 2 - \"subtracts\" - test #2 in `example/test/lib/exporting-an-object.js`",
"I'll run twice - once after each test",
"I'll run once after both tests",
"not ok 3 - \"blueIsRed\" - test #1 in `example/test/lib/single-function.js`",
" ---",
" message: 'blue' == 'red'",
/ stacktrace: AssertionError: \'blue\' == \'red\'\n at blueIsRed /,
" ..."
)
|
Format API grep return to state ready | function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
}
function parseJSON(response) {
return response.json();
}
function formatState(dataset) {
let result = {};
for (const [key, subdata] of Object.entries(dataset.data)) {
result[key] = subdata.value;
}
return result;
}
/**
* grep values from recalbox.conf
*/
export function grep(keys) {
return fetch(`/grep?keys=${keys.join('|')}`)
.then(checkStatus)
.then(parseJSON)
.then(formatState);
}
/**
* get values from config file
*/
export function conf(keys) {
return fetch(`/conf?keys=${keys.join(',')}`)
.then(checkStatus)
.then(parseJSON);
}
/**
* save values to recalbox.conf
*/
export function save(values) {
return fetch('/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values)
})
.then(checkStatus)
.then(parseJSON);
}
| function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
}
function parseJSON(response) {
return response.json();
}
/**
* grep values from recalbox.conf
*/
export function grep(keys) {
return fetch(`/grep?keys=${keys.join('|')}`)
.then(checkStatus)
.then(parseJSON);
}
/**
* get values from config file
*/
export function conf(keys) {
return fetch(`/conf?keys=${keys.join(',')}`)
.then(checkStatus)
.then(parseJSON);
}
/**
* save values to recalbox.conf
*/
export function save(values) {
return fetch('/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values)
})
.then(checkStatus)
.then(parseJSON);
}
|
Use divs to avoid inheriting paragraph styles. | /**
* Admin Bar Zero Data component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
const AdminBarZeroData = () => {
return (
<div>
<div className="googlesitekit-adminbar__subtitle googlesitekit-font-weight-bold">
{ __( 'No data available yet', 'google-site-kit' ) }
</div>
<div className="googlesitekit-adminbar__subtitle">
{ __( 'There is no data available for this content yet. This could be because it was recently created or because nobody has accessed it so far.', 'google-site-kit' ) }
</div>
</div>
);
};
export default AdminBarZeroData;
| /**
* Admin Bar Zero Data component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
const AdminBarZeroData = () => {
return (
<div>
<p className="googlesitekit-adminbar__subtitle googlesitekit-font-weight-bold">
{ __( 'No data available yet', 'google-site-kit' ) }
</p>
<p className="googlesitekit-adminbar__subtitle">
{ __( 'There is no data available for this content yet. This could be because it was recently created or because nobody has accessed it so far.', 'google-site-kit' ) }
</p>
</div>
);
};
export default AdminBarZeroData;
|
Improve unicode method. Whitespace cleanup | from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
public = models.BooleanField(default=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True, auto_now=True)
type = models.CharField(max_length=20,
choices=[("segment", "Segment"), ("binarize", "Binarize")])
data = fields.PickledObjectField()
def __unicode__(self):
"""
String representation.
"""
return "<%s: %s>" % (self.__class__.__name__, self.name)
| from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
public = models.BooleanField(default=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True, auto_now=True)
type = models.CharField(max_length=20,
choices=[("segment", "Segment"), ("binarize", "Binarize")])
data = fields.PickledObjectField()
def __unicode__(self):
"""
String representation.
"""
return self.name
|
Use a regexp for the initial string search
Previously, we were using multiple String.indexOf() checks to determine
if the URL contained any query string parameters we might need to strip.
String.indexOf() is case-sensitive while our replacement pattern is not,
so there were rare times when we wouldn't match an expected parameter.
While I'm here, add a little commentary about these two patterns. | /*
* Pattern matching the prefix of at least one stripped query string
* parameter. We'll search the query string portion of the URL for this
* pattern to determine if there's any stripping work to do.
*/
var searchPattern = new RegExp('utm_|clid|mkt_tok', 'i');
/*
* Pattern matching the query string parameters (key=value) that will be
* stripped from the final URL.
*/
var replacePattern = new RegExp('([?&](mkt_tok|(g|fb)clid|utm_(source|medium|term|campaign|content|cid|reader|referrer|name))=[^&#]*)', 'ig');
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var url = details.url;
var queryStringIndex = url.indexOf('?');
if (url.search(searchPattern) > queryStringIndex) {
var stripped = url.replace(replacePattern, '');
if (stripped.charAt(queryStringIndex) === '&') {
stripped = stripped.substr(0, queryStringIndex) + '?' +
stripped.substr(queryStringIndex + 1)
}
if (stripped != url) {
return {redirectUrl: stripped};
}
}
},
{urls: ['https://*/*?*', 'http://*/*?*'], types: ['main_frame']}, ['blocking']);
| var re = new RegExp('([?&](mkt_tok|(g|fb)clid|utm_(source|medium|term|campaign|content|cid|reader|referrer|name))=[^&#]*)', 'ig');
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var url = details.url;
var queryStringIndex = url.indexOf('?');
if (url.indexOf('utm_') > queryStringIndex ||
url.indexOf('clid') > queryStringIndex ||
url.indexOf('mkt_tok') > queryStringIndex) {
var stripped = url.replace(re, '');
if (stripped.charAt(queryStringIndex) === '&') {
stripped = stripped.substr(0, queryStringIndex) + '?' +
stripped.substr(queryStringIndex + 1)
}
if (stripped != url) {
return {redirectUrl: stripped};
}
}
},
{urls: ['https://*/*?*', 'http://*/*?*'], types: ['main_frame']}, ['blocking']);
|
Remove unnecessary code and add comment | // ==UserScript==
// @name SFcomic Viewer
// @namespace
// @version 0.2.1
// @description Auto load comic picture.
// @author AntonioTsai
// @match http://comic.sfacg.com/*
// @include http://comic.sfacg.com/*
// @grant none
// @downloadURL https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js
// ==/UserScript==
/**
* picAy: The array store all image's url of the volume
* hosts: The array store possible host
* getHost(): Get the current host index
*/
(() => {
var imgTable = document.querySelector("table tbody");
var tempTr = document.createElement("tr");
// remove original image & social media icon
var tr = document.querySelector("tr");
tr.parentElement.removeChild(tr);
// generate all images
for (var i = 0; i < picCount; i++) {
var imgTr = tempTr.cloneNode(true);
imgTr.appendChild(document.createElement("img"));
imgTr.children[0].children[0].src = picAy[i];
imgTable.appendChild(imgTr);
}
})();
| // ==UserScript==
// @name SFcomic Viewer
// @namespace
// @version 0.2.1
// @description Auto load comic picture.
// @author AntonioTsai
// @match http://comic.sfacg.com/*
// @include http://comic.sfacg.com/*
// @grant none
// @downloadURL https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js
// ==/UserScript==
/**
* picAy: The array store all image's url of the volume
* hosts: The array store possible host
* getHost(): Get the current host index
*/
(() => {
var imgTable = document.querySelector("table tbody");
var tempTr = document.createElement("tr");
var imgs = document.createElement("img");
tempTr.appendChild(document.createElement("td"));
tempTr.children[0].appendChild(imgs);
// remove original image
var tr = document.querySelector("tr");
tr.parentElement.removeChild(tr);
// generate all images
for (var i = 0; i < picCount; i++) {
var imgTr = tempTr.cloneNode(true);
imgTr.appendChild(document.createElement("img"));
imgTr.children[0].children[0].src = picAy[i];
imgTable.appendChild(imgTr);
}
})();
|
Fix hound code style issues | 'use strict';
import chai from 'chai';
import {ObjectVector} from '../../lib.compiled/Generic/ObjectVector';
suite('Generic/ObjectVector', function() {
var TestProto = () => {
return 'test';
};
let firstItemToAdd = new TestProto();
firstItemToAdd.testData = 'firstItemToAdd';
let secondItemToAdd = new TestProto();
secondItemToAdd.testData = 'secondItemToAdd';
let thirdItemToAdd = {testData: 'thirdItemToAdd'};
let objectVector = null;
test('Class ObjectVector exists in Generic/ObjectVector', function() {
chai.expect(typeof ObjectVector).to.equal('function');
});
test('Check constructor throws exception for invalid input', function() {
let error = null;
try {
new ObjectVector(testProto, firstItemToAdd, secondItemToAdd, thirdItemToAdd);
} catch (e) {
error = e;
}
chai.assert.instanceOf(error, Error, 'error is an instance of Error');
});
test('Check constructor for valid input', function() {
objectVector = new ObjectVector(testProto, firstItemToAdd, secondItemToAdd);
chai.expect(objectVector.collection).to.be.eql([firstItemToAdd, secondItemToAdd]);
});
}); | 'use strict';
import chai from 'chai';
import {ObjectVector} from '../../lib.compiled/Generic/ObjectVector';
suite('Generic/ObjectVector', function() {
var testProto = () => {
return 'test';
};
let firstItemToAdd = new testProto();
firstItemToAdd.testData = 'firstItemToAdd';
let secondItemToAdd = new testProto();
secondItemToAdd.testData = 'secondItemToAdd';
let thirdItemToAdd = {testData: 'thirdItemToAdd'};
let objectVector = null;
test('Class ObjectVector exists in Generic/ObjectVector', function() {
chai.expect(typeof ObjectVector).to.equal('function');
});
test('Check constructor throws exception for invalid input', function() {
let error = null;
try {
new ObjectVector(testProto, firstItemToAdd, secondItemToAdd, thirdItemToAdd);
} catch (e) {
error = e;
}
chai.assert.instanceOf(error, Error, 'error is an instance of Error');
});
test('Check constructor for valid input', function() {
objectVector = new ObjectVector(testProto, firstItemToAdd, secondItemToAdd);
chai.expect(objectVector.collection).to.be.eql([firstItemToAdd, secondItemToAdd]);
});
}); |
Remove deprecated fast_suite and check list for unit tests | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_session
from . import test_event
from . import test_job
from . import test_queue
from . import test_worker
from . import test_backend
from . import test_producer
from . import test_connector
from . import test_mapper
from . import test_related_action
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_session
from . import test_event
from . import test_job
from . import test_queue
from . import test_worker
from . import test_backend
from . import test_producer
from . import test_connector
from . import test_mapper
from . import test_related_action
fast_suite = [
]
checks = [
test_session,
test_event,
test_job,
test_queue,
test_worker,
test_backend,
test_producer,
test_connector,
test_mapper,
test_related_action,
]
|
Use location.key for storing scroll position when available | import React from 'react';
import assign from 'object-assign';
import History from './History';
import Location from './Location';
import { getWindowScrollPosition } from './DOMUtils';
/**
* A history interface that assumes a DOM environment.
*/
class DOMHistory extends History {
static propTypes = assign({
getScrollPosition: React.PropTypes.func.isRequired
}, History.propTypes);
static defaultProps = assign({
getScrollPosition: getWindowScrollPosition
}, History.defaultProps);
static childContextTypes = assign({}, History.childContextTypes);
constructor(props, context) {
super(props, context);
this.scrollHistory = {};
}
getScrollKey(path, query, key) {
return key || this.makePath(path, query);
}
createLocation(path, query, navigationType, key) {
var scrollKey = this.getScrollKey(path, query, key);
var scrollPosition = this.scrollHistory[scrollKey];
return new Location(path, query, navigationType, key, scrollPosition);
}
go(n) {
if (n === 0)
return;
window.history.go(n);
}
recordScrollPosition() {
var location = this.state.location;
var scrollKey = this.getScrollKey(location.path, location.query, location.key);
this.scrollHistory[scrollKey] = this.props.getScrollPosition();
}
}
export default DOMHistory;
| import React from 'react';
import assign from 'object-assign';
import History from './History';
import Location from './Location';
import { getWindowScrollPosition } from './DOMUtils';
/**
* A history interface that assumes a DOM environment.
*/
class DOMHistory extends History {
static propTypes = assign({
getScrollPosition: React.PropTypes.func.isRequired
}, History.propTypes);
static defaultProps = assign({
getScrollPosition: getWindowScrollPosition
}, History.defaultProps);
static childContextTypes = assign({}, History.childContextTypes);
constructor(props, context) {
super(props, context);
this.scrollHistory = {};
}
createLocation(path, query, navigationType, key) {
var fullPath = this.makePath(path, query);
var scrollPosition = this.scrollHistory[fullPath];
return new Location(path, query, navigationType, key, scrollPosition);
}
go(n) {
if (n === 0)
return;
window.history.go(n);
}
recordScrollPosition() {
var renderedLocation = this.state.location;
var renderedFullPath = this.makePath(renderedLocation.path, renderedLocation.query);
this.scrollHistory[renderedFullPath] = this.props.getScrollPosition();
}
}
export default DOMHistory;
|
Update markdown-to-html converter missing message
The `league/html-to-markdown` library does not support Markdown to HTML conversion (anymore?). The `league/commonmark` library is suitable for that. | <?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extra\Markdown;
use League\CommonMark\CommonMarkConverter;
use Michelf\MarkdownExtra;
use Parsedown;
class DefaultMarkdown implements MarkdownInterface
{
private $converter;
public function __construct()
{
if (class_exists(CommonMarkConverter::class)) {
$this->converter = new LeagueMarkdown();
} elseif (class_exists(MarkdownExtra::class)) {
$this->converter = new MichelfMarkdown();
} elseif (class_exists(Parsedown::class)) {
$this->converter = new ErusevMarkdown();
} else {
throw new \LogicException('You cannot use the "markdown_to_html" filter as no Markdown library is available; try running "composer require league/commonmark".');
}
}
public function convert(string $body): string
{
return $this->converter->convert($body);
}
}
| <?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extra\Markdown;
use League\CommonMark\CommonMarkConverter;
use Michelf\MarkdownExtra;
use Parsedown;
class DefaultMarkdown implements MarkdownInterface
{
private $converter;
public function __construct()
{
if (class_exists(CommonMarkConverter::class)) {
$this->converter = new LeagueMarkdown();
} elseif (class_exists(MarkdownExtra::class)) {
$this->converter = new MichelfMarkdown();
} elseif (class_exists(Parsedown::class)) {
$this->converter = new ErusevMarkdown();
} else {
throw new \LogicException('You cannot use the "markdown_to_html" filter as no Markdown library is available; try running "composer require league/html-to-markdown".');
}
}
public function convert(string $body): string
{
return $this->converter->convert($body);
}
}
|
Make global-bind plugin safe in node envs, part 2
Follow on from #465, which missed the ReferenceError from trying to use the Mousetrap global at the end of the file. | /**
* adds a bindGlobal method to Mousetrap that allows you to
* bind specific keyboard shortcuts that will still work
* inside a text input field
*
* usage:
* Mousetrap.bindGlobal('ctrl+s', _saveChanges);
*/
/* global Mousetrap:true */
(function(Mousetrap) {
if (! Mousetrap) {
return;
}
var _globalCallbacks = {};
var _originalStopCallback = Mousetrap.prototype.stopCallback;
Mousetrap.prototype.stopCallback = function(e, element, combo, sequence) {
var self = this;
if (self.paused) {
return true;
}
if (_globalCallbacks[combo] || _globalCallbacks[sequence]) {
return false;
}
return _originalStopCallback.call(self, e, element, combo);
};
Mousetrap.prototype.bindGlobal = function(keys, callback, action) {
var self = this;
self.bind(keys, callback, action);
if (keys instanceof Array) {
for (var i = 0; i < keys.length; i++) {
_globalCallbacks[keys[i]] = true;
}
return;
}
_globalCallbacks[keys] = true;
};
Mousetrap.init();
}) (typeof Mousetrap !== "undefined" ? Mousetrap : undefined);
| /**
* adds a bindGlobal method to Mousetrap that allows you to
* bind specific keyboard shortcuts that will still work
* inside a text input field
*
* usage:
* Mousetrap.bindGlobal('ctrl+s', _saveChanges);
*/
/* global Mousetrap:true */
(function(Mousetrap) {
if (! Mousetrap) {
return;
}
var _globalCallbacks = {};
var _originalStopCallback = Mousetrap.prototype.stopCallback;
Mousetrap.prototype.stopCallback = function(e, element, combo, sequence) {
var self = this;
if (self.paused) {
return true;
}
if (_globalCallbacks[combo] || _globalCallbacks[sequence]) {
return false;
}
return _originalStopCallback.call(self, e, element, combo);
};
Mousetrap.prototype.bindGlobal = function(keys, callback, action) {
var self = this;
self.bind(keys, callback, action);
if (keys instanceof Array) {
for (var i = 0; i < keys.length; i++) {
_globalCallbacks[keys[i]] = true;
}
return;
}
_globalCallbacks[keys] = true;
};
Mousetrap.init();
}) (Mousetrap);
|
Add auto JS building on source change | 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var config = {
js: ['src/**/*.js']
};
gulp.task('js', function () {
// set up the browserify instance on a task basis
var b = browserify({
entries: './public/js/app.js',
debug: true
});
return b.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});
gulp.task('develop', function() {
gulp.watch(config.js, ['js']);
});
| 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
gulp.task('js', function () {
// set up the browserify instance on a task basis
var b = browserify({
entries: './public/js/app.js',
debug: true
});
return b.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});
|
Correct the url for the rating instance resource | from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home', name='home'),
# url(r'^project/', include('project.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^$',
views.TemplateView.as_view(template_name='index.html'),
name='home'),
url(r'^ratings/$',
resources.RatingListView.as_view(),
name='rating_list'),
url(r'^ratings/(?P<id>\d+)$',
resources.RatingInstanceView.as_view(),
name='rating_instance'),
url(r'^survey_session',
resources.SurveySessionView.as_view(),
name='survey_session_instance')
)
| from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home', name='home'),
# url(r'^project/', include('project.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^$',
views.TemplateView.as_view(template_name='index.html'),
name='home'),
url(r'^ratings/$',
resources.RatingListView.as_view(),
name='rating_list'),
url(r'^ratings/(P<id>\d+)$',
resources.RatingInstanceView.as_view(),
name='rating_instance'),
url(r'^survey_session',
resources.SurveySessionView.as_view(),
name='survey_session_instance')
)
|
Enforce endianess when converting IPs to long.
git-svn-id: 21715c51dd601a1fb57681abbfe4e8ed6f4259bf@205 4c10cf09-d433-0410-9a0a-09c53010615a | import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l << n) != 0:
return n + 1
return 0
def _highest_bit(number):
if number == 0:
return 0
number -= 1
number |= number >> 1
number |= number >> 2
number |= number >> 4
number |= number >> 8
number |= number >> 16
number += 1
return math.sqrt(number)
def ip2int(ip):
if ip == '255.255.255.255':
return 0xFFFFFFFFl
return struct.unpack('!L', socket.inet_aton(ip))[0]
def int2ip(number):
return socket.inet_ntoa(struct.pack('!L', number))
def pfxlen2mask(pfxlen):
return 0xFFFFFFFFl << (32 - int(pfxlen))
def mask2pfxlen(mask):
mask_int = ip2int(mask)
return 33 - _least_bit(mask_int)
def parse_prefix(prefix, default_mask = 24):
if '/' in prefix:
(network, pfxlen) = prefix.split('/')
else:
network = prefix
pfxlen = default_mask
return (ip2int(network), int(pfxlen))
| import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l << n) != 0:
return n + 1
return 0
def _highest_bit(number):
if number == 0:
return 0
number -= 1
number |= number >> 1
number |= number >> 2
number |= number >> 4
number |= number >> 8
number |= number >> 16
number += 1
return math.sqrt(number)
def ip2int(ip):
if ip == '255.255.255.255':
return 0xFFFFFFFFl
return struct.unpack('L', socket.inet_aton(ip))[0]
def int2ip(number):
return socket.inet_ntoa(struct.pack('L', number))
def pfxlen2mask(pfxlen):
return 0xFFFFFFFFl << (32 - int(pfxlen))
def mask2pfxlen(mask):
mask_int = ip2int(mask)
return 33 - _least_bit(mask_int)
def parse_prefix(prefix, default_mask = 24):
if '/' in prefix:
(network, pfxlen) = prefix.split('/')
else:
network = prefix
pfxlen = default_mask
return (ip2int(network), int(pfxlen))
|
Allow app to be flushed during teardown.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Testbench;
use Orchestra\Testbench\Traits\ApplicationClientTrait;
use Orchestra\Testbench\Traits\ApplicationTrait;
use Orchestra\Testbench\Traits\PHPUnitAssertionsTrait;
abstract class TestCase extends \PHPUnit_Framework_TestCase implements TestCaseInterface
{
use ApplicationClientTrait, ApplicationTrait, PHPUnitAssertionsTrait;
/**
* Setup the test environment.
*
* @return void
*/
public function setUp()
{
if (! $this->app) {
$this->refreshApplication();
}
}
/**
* Clean up the testing environment before the next test.
*/
public function tearDown()
{
$this->app->flush();
}
/**
* Define environment setup.
*
* @param \Illuminate\Foundation\Application $app
* @return void
*/
protected function getEnvironmentSetUp($app)
{
// Define your environment setup.
}
}
| <?php namespace Orchestra\Testbench;
use Orchestra\Testbench\Traits\ApplicationClientTrait;
use Orchestra\Testbench\Traits\ApplicationTrait;
use Orchestra\Testbench\Traits\PHPUnitAssertionsTrait;
abstract class TestCase extends \PHPUnit_Framework_TestCase implements TestCaseInterface
{
use ApplicationClientTrait, ApplicationTrait, PHPUnitAssertionsTrait;
/**
* Setup the test environment.
*
* @return void
*/
public function setUp()
{
if (! $this->app) {
$this->refreshApplication();
}
}
/**
* Define environment setup.
*
* @param \Illuminate\Foundation\Application $app
* @return void
*/
protected function getEnvironmentSetUp($app)
{
// Define your environment setup.
}
}
|
Add initialization before get url | #!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
parser = OptionParser()
parser.add_option('-u', '--url', dest='startUrl', help='Target URL (e.g. \'http://www.site.com/\')')
parser.add_option('-d', '--depth', dest='depth', help='The depth you want to scan (default: 2)')
(options, args) = parser.parse_args()
if options.startUrl:
url = initialize(options.startUrl)
rootLink = Link(url, url)
if options.depth:
getPage(rootLink, int(options.depth))
else:
getPage(rootLink, 2)
getScript()
xssScanner()
pass
if __name__ == '__main__':
main()
| #!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
parser = OptionParser()
parser.add_option('-u', '--url', dest='startUrl', help='Target URL (e.g. \'http://www.site.com/\')')
parser.add_option('-d', '--depth', dest='depth', help='The depth you want to scan (default: 2)')
(options, args) = parser.parse_args()
if options.startUrl:
rootLink = Link(options.startUrl, options.startUrl)
if options.depth:
getPage(rootLink, int(options.depth))
else:
getPage(rootLink, 2)
getScript()
xssScanner()
pass
if __name__ == '__main__':
main()
|
Make what reader can handle what clearer | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
|
Fix typo in feedback model | 'use strict';
module.exports = function(sequelize, DataTypes) {
var feedbacks = sequelize.define('feedbacks', {
msg: DataTypes.STRING,
region_code: DataTypes.STRING
}, {
timestamps: true,
underscored: true,
classMethods: {
associate: function(models) {
// associations can be defined here
feedbacks.belongsTo(models.User, {
onDelete: 'CASCADE',
foreignKey: 'user_id',
});
}
}
});
return feedbacks;
};
| 'use strict';
module.exports = function(sequelize, DataTypes) {
var notifications = sequelize.define('notifications', {
msg: DataTypes.STRING,
region_code: DataTypes.STRING
}, {
timestamps: true,
underscored: true,
classMethods: {
associate: function(models) {
// associations can be defined here
notifications.belongsTo(models.User, {
onDelete: 'CASCADE',
foreignKey: 'user_id',
});
}
}
});
return notifications;
};
|
Add support for mixed "plain color string" and "color map" background defintitions
Lets you do this:
```
backgroundColors: [
'blue',
'purple',
'pink',
{
primary: 'white',
secondary: 'orange',
},
]
``` | const postcss = require('postcss')
const _ = require('lodash')
function findColor(colors, color) {
const colorsNormalized = _.mapKeys(colors, (value, key) => {
return _.camelCase(key)
})
return _.get(colorsNormalized, _.camelCase(color), color)
}
module.exports = function ({ colors, backgroundColors }) {
if (_.isArray(backgroundColors)) {
backgroundColors = _(backgroundColors).flatMap(color => {
if (_.isString(color)) {
return [[color, color]]
}
return _.toPairs(color)
}).fromPairs()
}
return _(backgroundColors).toPairs().map(([className, colorName]) => {
const kebabClass = _.kebabCase(className)
return postcss.rule({
selector: `.bg-${kebabClass}`
}).append({
prop: 'background-color',
value: findColor(colors, colorName)
})
}).value()
}
| const postcss = require('postcss')
const _ = require('lodash')
function findColor(colors, color) {
const colorsNormalized = _.mapKeys(colors, (value, key) => {
return _.camelCase(key)
})
return _.get(colorsNormalized, _.camelCase(color), color)
}
module.exports = function ({ colors, backgroundColors }) {
if (_.isArray(backgroundColors)) {
backgroundColors = _(backgroundColors).map(color => [color, color]).fromPairs()
}
return _(backgroundColors).toPairs().map(([className, colorName]) => {
const kebabClass = _.kebabCase(className)
return postcss.rule({
selector: `.bg-${kebabClass}`
}).append({
prop: 'background-color',
value: findColor(colors, colorName)
})
}).value()
}
|
Add support for single files | <?php
declare(strict_types=1);
namespace Mihaeu\PhpDependencies\OS;
class PhpFileFinder
{
public function find(\SplFileInfo $file) : PhpFileSet
{
return $file->isDir()
? $this->findInDir($file)
: (new PhpFileSet())->add(new PhpFile($file));
}
private function findInDir(\SplFileInfo $dir) : PhpFileSet
{
$collection = new PhpFileSet();
$regexIterator = new \RegexIterator(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir->getPathname())
), '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH
);
foreach ($regexIterator as $fileName) {
$collection = $collection->add(new PhpFile(new \SplFileInfo($fileName[0])));
}
return $collection;
}
}
| <?php
declare(strict_types=1);
namespace Mihaeu\PhpDependencies\OS;
class PhpFileFinder
{
public function find(\SplFileInfo $file) : PhpFileSet
{
return $file->isDir()
? $this->findInDir($file)
: new PhpFileSet();
}
private function findInDir(\SplFileInfo $dir) : PhpFileSet
{
$collection = new PhpFileSet();
$regexIterator = new \RegexIterator(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir->getPathname())
), '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH
);
foreach ($regexIterator as $fileName) {
$collection = $collection->add(new PhpFile(new \SplFileInfo($fileName[0])));
}
return $collection;
}
}
|
Increase size of test docs | """Test helpers specific to LDA
"""
import numpy as np
import itertools as it
from microscopes.common.testutil import permutation_iter
def toy_dataset(defn):
"""Generate a toy variadic dataset for HDP-LDA
"""
lengths = 1 + np.random.poisson(lam=10, size=defn.n)
def mkrow(nwords):
return np.random.choice(range(defn.v), size=nwords)
return map(mkrow, lengths)
def permutations(doclengths):
"""Generate a permutation of XXX
WARNING: very quickly becomes intractable
"""
perms = [permutation_iter(length) for length in doclengths]
for prod in it.product(*perms):
dishes = sum([max(x) + 1 for x in prod])
for p in permutation_iter(dishes):
idx = 0
ret = []
for d in prod:
ntables = max(d) + 1
ret.append(tuple(p[idx:idx+ntables]))
idx += ntables
yield prod, tuple(ret) | """Test helpers specific to LDA
"""
import numpy as np
import itertools as it
from microscopes.common.testutil import permutation_iter
def toy_dataset(defn):
"""Generate a toy variadic dataset for HDP-LDA
"""
lengths = 1 + np.random.poisson(lam=1.0, size=defn.n)
def mkrow(nwords):
return np.random.choice(range(defn.v), size=nwords)
return map(mkrow, lengths)
def permutations(doclengths):
"""Generate a permutation of XXX
WARNING: very quickly becomes intractable
"""
perms = [permutation_iter(length) for length in doclengths]
for prod in it.product(*perms):
dishes = sum([max(x) + 1 for x in prod])
for p in permutation_iter(dishes):
idx = 0
ret = []
for d in prod:
ntables = max(d) + 1
ret.append(tuple(p[idx:idx+ntables]))
idx += ntables
yield prod, tuple(ret) |
Add apache headers to interceptor
git-svn-id: 2c5eef89e506a7ff64d405e714ba3c778b83051b@1506125 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.rave.rest.interceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.rave.rest.model.JsonResponseWrapper;
/**
* Created with IntelliJ IDEA.
* User: erinnp
* Date: 7/22/13
* Time: 4:56 PM
* To change this template use File | Settings | File Templates.
*/
public class JsonResponseWrapperInterceptor extends AbstractPhaseInterceptor<Message> {
public JsonResponseWrapperInterceptor() {
super(Phase.WRITE);
}
@Override
public void handleMessage(Message message) throws Fault {
Object o = message.getContent(Object.class);
JsonResponseWrapper wrapper = new JsonResponseWrapper(o);
message.setContent(JsonResponseWrapper.class, wrapper);
}
}
| package org.apache.rave.rest.interceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.rave.rest.model.JsonResponseWrapper;
/**
* Created with IntelliJ IDEA.
* User: erinnp
* Date: 7/22/13
* Time: 4:56 PM
* To change this template use File | Settings | File Templates.
*/
public class JsonResponseWrapperInterceptor extends AbstractPhaseInterceptor<Message> {
public JsonResponseWrapperInterceptor() {
super(Phase.WRITE);
}
@Override
public void handleMessage(Message message) throws Fault {
Object o = message.getContent(Object.class);
JsonResponseWrapper wrapper = new JsonResponseWrapper(o);
message.setContent(JsonResponseWrapper.class, wrapper);
}
}
|
Add Python version trove classifiers | from setuptools import setup
setup(
name='django-easymoney',
version='0.5',
author='Alexander Schepanovski',
author_email='suor.web@gmail.com',
description='An easy MoneyField for Django.',
long_description=open('README.rst').read(),
url='http://github.com/Suor/django-easymoney',
license='BSD',
py_modules=['easymoney'],
install_requires=[
'django>=1.6',
'babel',
'six',
],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| from setuptools import setup
setup(
name='django-easymoney',
version='0.5',
author='Alexander Schepanovski',
author_email='suor.web@gmail.com',
description='An easy MoneyField for Django.',
long_description=open('README.rst').read(),
url='http://github.com/Suor/django-easymoney',
license='BSD',
py_modules=['easymoney'],
install_requires=[
'django>=1.6',
'babel',
'six',
],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
[IMP] project: Enable `Timesheets` option if `Time Billing` is enabled | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ProjectConfiguration(models.TransientModel):
_name = 'project.config.settings'
_inherit = 'res.config.settings'
company_id = fields.Many2one('res.company', string='Company', required=True,
default=lambda self: self.env.user.company_id)
module_pad = fields.Boolean("Collaborative Pads")
module_hr_timesheet = fields.Boolean("Timesheets")
module_project_timesheet_synchro = fields.Boolean("Awesome Timesheet")
module_rating_project = fields.Boolean(string="Rating on Tasks")
module_project_forecast = fields.Boolean(string="Forecasts")
module_hr_holidays = fields.Boolean("Leave Management")
module_hr_timesheet_attendance = fields.Boolean("Attendances")
module_sale_timesheet = fields.Boolean("Time Billing")
module_hr_expense = fields.Boolean("Expenses")
group_subtask_project = fields.Boolean("Sub-tasks", implied_group="project.group_subtask_project")
@api.onchange('module_sale_timesheet')
def _onchange_module_sale_timesheet(self):
if self.module_sale_timesheet:
self.module_hr_timesheet = True
| # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ProjectConfiguration(models.TransientModel):
_name = 'project.config.settings'
_inherit = 'res.config.settings'
company_id = fields.Many2one('res.company', string='Company', required=True,
default=lambda self: self.env.user.company_id)
module_pad = fields.Boolean("Collaborative Pads")
module_hr_timesheet = fields.Boolean("Timesheets")
module_project_timesheet_synchro = fields.Boolean("Awesome Timesheet")
module_rating_project = fields.Boolean(string="Rating on Tasks")
module_project_forecast = fields.Boolean(string="Forecasts")
module_hr_holidays = fields.Boolean("Leave Management")
module_hr_timesheet_attendance = fields.Boolean("Attendances")
module_sale_timesheet = fields.Boolean("Time Billing")
module_hr_expense = fields.Boolean("Expenses")
group_subtask_project = fields.Boolean("Sub-tasks", implied_group="project.group_subtask_project")
|
Reduce undoings of multi-prefix on users | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class MultiPrefix(ModuleData):
implements(IPlugin, IModuleData)
name = "MultiPrefix"
def actions(self):
return [ ("channelstatuses", 2, self.allStatuses),
("capabilitylist", 10, self.addCapability) ]
def load(self):
if "unloading-multi-prefix" in self.ircd.dataCache:
del self.ircd.dataCache["unloading-multi-prefix"]
return
if "cap-add" in self.ircd.functionCache:
self.ircd.functionCache["cap-add"]("multi-prefix")
def unload(self):
self.ircd.dataCache["unloading-multi-prefix"] = True
def fullUnload(self):
del self.ircd.dataCache["unloading-multi-prefix"]
if "cap-del" in self.ircd.functionCache:
self.ircd.functionCache["cap-del"]("multi-prefix")
def addCapability(self, capList):
capList.append("multi-prefix")
def allStatuses(self, channel, user, requestingUser):
if "capabilities" not in requestingUser.cache or "multi-prefix" not in requestingUser.cache["capabilities"]:
return None
if user not in channel.users:
return ""
statusList = []
for status in channel.users[user]["status"]:
statusList.append(self.ircd.channelStatuses[status][0])
return "".join(statusList)
multiPrefix = MultiPrefix() | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class MultiPrefix(ModuleData):
implements(IPlugin, IModuleData)
name = "MultiPrefix"
def actions(self):
return [ ("channelstatuses", 2, self.allStatuses),
("capabilitylist", 10, self.addCapability) ]
def load(self):
if "cap-add" in self.ircd.moduleFunctionCache:
self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
def unload(self):
if "cap-add" in self.ircd.moduleFunctionCache:
self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
def addCapability(self, capList):
capList.append("multi-prefix")
def allStatuses(self, channel, user, requestingUser):
if "capabilities" not in requestingUser.cache or "multi-prefix" not in requestingUser.cache["capabilities"]:
return None
if user not in channel.users:
return ""
statusList = []
for status in channel.users[user]["status"]:
statusList.append(self.ircd.channelStatuses[status][0])
return "".join(statusList)
multiPrefix = MultiPrefix() |
Add basic settings-change request error handling
Need to integrate this with some sort of notification system e.g.
toasts, modals, etc... | import axios from 'axios';
import { SETTINGS_CHANGE_RECEIVE, SETTINGS_CHANGE_REQUEST } from '../constants/actionTypes';
import { API_SETTINGS_ENDPOINT } from '../constants/endpoints';
export function requestChangeSettings() {
return {
type: SETTINGS_CHANGE_REQUEST
};
}
export function receiveChangeSettings(status) {
return {
type: SETTINGS_CHANGE_RECEIVE,
payload: {
status
}
};
}
export function changeSettings(newSettings) {
return function (dispatch) {
dispatch(requestChangeSettings());
axios.post(API_SETTINGS_ENDPOINT, newSettings)
.then(() => {
dispatch(receiveChangeSettings('success'))
// error /success handling
})
.catch(() => {
dispatch(receiveChangeSettings('error updating settings'));
})
;
};
}
| import axios from 'axios';
import { SETTINGS_CHANGE_RECEIVE, SETTINGS_CHANGE_REQUEST } from '../constants/actionTypes';
import { API_SETTINGS_ENDPOINT } from '../constants/endpoints';
export function requestChangeSettings() {
return {
type: SETTINGS_CHANGE_REQUEST
};
}
export function receiveChangeSettings(status) {
return {
type: SETTINGS_CHANGE_RECEIVE,
payload: {
status
}
};
}
export function changeSettings(newSettings) {
return function (dispatch) {
dispatch(requestChangeSettings());
axios.post(API_SETTINGS_ENDPOINT, newSettings)
.then(() => {
dispatch(receiveChangeSettings('success'))
// error /success handling
});
};
}
|
Allow trailing slash in URL | import importlib
from flask import render_template
from werkzeug.exceptions import NotFound
from . import main
DATA_QUALITY_ROUTE = '/data-quality/'
@main.route('/')
def index():
return render_template('index.html')
@main.route('/data-quality/<path:page>')
def data_quality_page(page):
"""Serve a data quality page.
page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package.
Params:
-------
page: str
Path of the directory containing the page content.
"""
page = page.strip('/')
page = page.replace('/', '.') # turn directory path into package name
try:
dq = importlib.import_module('app.main.pages.' + page, __package__)
except ImportError:
raise NotFound
return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
| import importlib
from flask import render_template
from werkzeug.exceptions import NotFound
from . import main
DATA_QUALITY_ROUTE = '/data-quality/'
@main.route('/')
def index():
return render_template('index.html')
@main.route('/data-quality/<path:page>')
def data_quality_page(page):
"""Serve a data quality page.
page must be a directory path relative to /app/main/pages, and the corresponding directory must be a package.
Params:
-------
page: str
Path of the directory containing the page content.
"""
page = page.replace('/', '.') # turn directory path into package name
try:
dq = importlib.import_module('app.main.pages.' + page, __package__)
except ImportError:
raise NotFound
return render_template('data_quality/data_quality_page.html', title=dq.title(), content=dq.content())
|
Update the comment spelling :-p | package org.jsmpp.session;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;
/**
* This listener will listen to every incoming short message, recognized by
* deliver_sm command. The logic on this listener should be accomplish in a
* short time, because the deliver_sm_resp will be processed after the logic
* executed. Normal logic will be return the deliver_sm_resp with zero valued
* command_status, or throw {@link ProcessMessageException} that gave non-zero
* valued command_status (in means negative response) depends on the given error
* code specified on the {@link ProcessMessageException}.
*
* @author uudashr
* @version 1.0
* @since 2.0
*
*/
public interface MessageReceiverListener {
/**
* Event that called when an short message accepted.
*
* @param deliverSm is the deliver_sm command.
* @throws ProcessMessageException throw if there should be return Non-OK
* command_status for the response.
*/
public void onAcceptDeliverSm(DeliverSm deliverSm)
throws ProcessMessageException;
}
| package org.jsmpp.session;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;
/**
* This listener will listen to every incomming short message, recognized by
* deliver_sm command. The logic on this listener should be accomplish in a
* short time, because the deliver_sm_resp will be processed after the logic
* executed. Normal logic will be return the deliver_sm_resp with zero valued
* command_status, or throw {@link ProcessMessageException} that gave non-zero
* valued command_status (in means negative response) depends on the given error
* code specified on the {@link ProcessMessageException}.
*
* @author uudashr
* @version 1.0
* @since 2.0
*
*/
public interface MessageReceiverListener {
/**
* Event that called when an short message accepted.
*
* @param deliverSm is the deliver_sm command.
* @throws ProcessMessageException throw if there should be return Non-OK
* command_status for the response.
*/
public void onAcceptDeliverSm(DeliverSm deliverSm)
throws ProcessMessageException;
}
|
Update type to updated namespace | /*browser:true*/
/*global define*/
define(
[
'uiComponent',
'Magento_Checkout/js/model/payment/renderer-list'
],
function (
Component,
rendererList
) {
'use strict';
rendererList.push(
{
type: 'pstk_paystack',
component: 'Pstk_Paystack/js/view/payment/method-renderer/pstk_paystack'
}
);
/** Add view logic here if needed */
return Component.extend({});
}
);
| /*browser:true*/
/*global define*/
define(
[
'uiComponent',
'Magento_Checkout/js/model/payment/renderer-list'
],
function (
Component,
rendererList
) {
'use strict';
rendererList.push(
{
type: 'paystack',
component: 'Pstk_Paystack/js/view/payment/method-renderer/pstk_paystack'
}
);
/** Add view logic here if needed */
return Component.extend({});
}
);
|
Use plot_report._available instead of available() | import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
available = False
with warnings.catch_warnings(record=True) as w:
self.assertEqual(extensions.PlotReport.available(), available)
# It shows warning only when matplotlib is not available
if available:
self.assertEqual(len(w), 0)
else:
self.assertEqual(len(w), 1)
# In Python 2 the above test does not raise UserWarning,
# so we use plot_report._available instead of PlotReport.available()
@unittest.skipUnless(
extensions.plot_report._available, 'matplotlib is not installed')
def test_lazy_import(self):
# To support python2, we do not use self.assertWarns()
with warnings.catch_warnings(record=True) as w:
import matplotlib
matplotlib.use('Agg')
self.assertEqual(len(w), 0)
testing.run_module(__name__, __file__)
| import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
available = False
with warnings.catch_warnings(record=True) as w:
self.assertEqual(extensions.PlotReport.available(), available)
# It shows warning only when matplotlib.pyplot is not available
if available:
self.assertEqual(len(w), 0)
else:
self.assertEqual(len(w), 1)
@unittest.skipUnless(
extensions.PlotReport.available(), 'matplotlib is not installed')
def test_lazy_import(self):
# To support python2, we do not use self.assertWarns()
with warnings.catch_warnings(record=True) as w:
import matplotlib
matplotlib.use('Agg')
self.assertEqual(len(w), 0)
testing.run_module(__name__, __file__)
|
Disable coverage test on python3.2 | import os.path
import platform
from nose2.compat import unittest
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
@unittest.skipIf(
platform.python_version_tuple()[:2] == ('3', '2'),
'coverage package does not support python 3.2')
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 5 38%'
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
self.assertTestRunOutputMatches(
proc,
stderr='TOTAL ' + STATS)
| import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 5 38%'
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
self.assertTestRunOutputMatches(
proc,
stderr='TOTAL ' + STATS)
|
Fix formatting of invitation e-mail slightly. | <?php
require_once("database.php");
require_once("templating.php");
if(!$logged_in) {
$smarty->display("login.tpl");
die();
}
if(isset($_POST['invite'])) {
$errors = "";
$email = $_POST['email'];
if(empty($email)) {
$errors .= "You must enter an e-mail address.<br />";
}
if(empty($errors)) {
$code = md5(md5($username) . time());
$mdb2->query("INSERT INTO Invitations (inviter, code) VALUES ("
. $mdb2->quote($username, "text") . ", "
. $mdb2->quote($code, "text") . ")");
$url = $base_url . "/register.php?authcode=" . $code;
$headers = "From: Libre.fm Invitations <invitations@libre.fm>";
mail($email, "Libre.fm Invitation", "Hi!\n\nClearly " . $username . " really likes you, because they've sent you an inivitation to join http://libre.fm\n\nJust visit " . $url . " to sign up, all the cool kids are doing it.\n", $headers);
$smarty->assign("sent", true);
} else {
$smarty->assign("errors", $errors);
}
}
$smarty->display("invite.tpl");
?>
| <?php
require_once("database.php");
require_once("templating.php");
if(!$logged_in) {
$smarty->display("login.tpl");
die();
}
if(isset($_POST['invite'])) {
$errors = "";
$email = $_POST['email'];
if(empty($email)) {
$errors .= "You must enter an e-mail address.<br />";
}
if(empty($errors)) {
$code = md5(md5($username) . time());
$mdb2->query("INSERT INTO Invitations (inviter, code) VALUES ("
. $mdb2->quote($username, "text") . ", "
. $mdb2->quote($code, "text") . ")");
$url = $base_url . "/register.php?authcode=" . $code;
$headers = "From: Libre.fm Invitations <invitations@libre.fm>";
mail($email, "Libre.fm Invitation", "Hi!\n\nClearly " . $username . " really likes you, because they've sent you an inivitation to join http://libre.fm\n Just visit " . $url . " to sign up, all the cool kids are doing it.\n", $headers);
$smarty->assign("sent", true);
} else {
$smarty->assign("errors", $errors);
}
}
$smarty->display("invite.tpl");
?>
|
Remove vestigial reference to console() | #!/usr/bin/env python
import re
from setuptools import setup, find_packages
import sys
import warnings
dynamic_requires = []
version = 0.9
setup(
name='anthemav',
version=0.9,
author='David McNett',
author_email='nugget@macnugget.org',
url='https://github.com/nugget/python-anthemav',
packages=find_packages(),
scripts=[],
install_requires=['asyncio'],
description='Python API for controlling Anthem Receivers',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
include_package_data=True,
zip_safe=True,
)
| #!/usr/bin/env python
import re
from setuptools import setup, find_packages
import sys
import warnings
dynamic_requires = []
version = 0.9
setup(
name='anthemav',
version=0.9,
author='David McNett',
author_email='nugget@macnugget.org',
url='https://github.com/nugget/python-anthemav',
packages=find_packages(),
scripts=[],
install_requires=['asyncio'],
description='Python API for controlling Anthem Receivers',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
include_package_data=True,
zip_safe=True,
entry_points = {
'console_scripts': ['anthemav_console=anthemav.__main__:console']
},
)
|
Complete javadoc and don't throw NPE | package com.alexrnl.commons.error;
import java.util.logging.Logger;
/**
* Utility methods for exception handling.<br />
* @author Alex
*/
public final class ExceptionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(ExceptionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private ExceptionUtils () {
super();
}
/**
* Print a nice message with the {@link Class} and the {@link Throwable#getMessage() message}
* of the exception.<br />
* @param e
* the throwable object to display.
* @return a {@link String} containing the class and the message of the exception.
*/
public static String displayClassAndMessage (final Throwable e) {
if (e == null) {
lg.warning("Cannot display null exception.");
return "null exception caught";
}
return e.getClass() + "; " + e.getMessage();
}
}
| package com.alexrnl.commons.error;
import java.util.Objects;
import java.util.logging.Logger;
/**
* TODO
* @author Alex
*/
public final class ExceptionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(ExceptionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private ExceptionUtils () {
super();
}
/**
*
* @param e
* the throwable object to display.
* @return a {@link String} containing the class and the message of the exception.
* @throws NullPointerException
* if the {@link Throwable} is <code>null</code>.
*/
public static String displayClassAndMessage (final Throwable e) throws NullPointerException {
Objects.requireNonNull(e);
return e.getClass() + "; " + e.getMessage();
}
}
|
Set prefix to static url patterm call | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += mediafiles_urlpatterns()
|
Remove obsolete -h shorthand check | #!/usr/bin/env node
/*
* Copyright (c) Maximilian Antoni <max@javascript.studio>
*
* @license MIT
*/
'use strict';
const editor = require('editor');
const changes = require('..');
const argv = require('minimist')(process.argv.slice(2), {
alias: {
file: 'f',
help: 'h'
}
});
/* eslint-disable max-len */
const HELP_TEXT = `usage: changes [--file] [--help]
Options are ...
-f, --file [FILENAME] Specify the name of the changelog file. Defaults to CHANGES.md.
-h, --help Display this help message.
`;
/* eslint-enable */
if (argv.help) {
console.log(HELP_TEXT);
process.exit();
}
let file = argv.file;
if (file) {
changes.setFile(file);
} else {
file = changes.getFile();
}
// Write the commit history to the changes file
const previous = changes.write();
// Let the user edit the changes
editor(file, (code) => {
if (code === 0) {
// Add the changes file to git
changes.add(previous);
} else {
// Roll back
changes.abort(previous);
}
});
| #!/usr/bin/env node
/*
* Copyright (c) Maximilian Antoni <max@javascript.studio>
*
* @license MIT
*/
'use strict';
const editor = require('editor');
const changes = require('..');
const argv = require('minimist')(process.argv.slice(2), {
alias: {
file: 'f',
help: 'h'
}
});
/* eslint-disable max-len */
const HELP_TEXT = `usage: changes [--file] [--help]
Options are ...
-f, --file [FILENAME] Specify the name of the changelog file. Defaults to CHANGES.md.
-h, --help Display this help message.
`;
/* eslint-enable */
if (argv.h || argv.help) {
console.log(HELP_TEXT);
process.exit();
}
let file = argv.file;
if (file) {
changes.setFile(file);
} else {
file = changes.getFile();
}
// Write the commit history to the changes file
const previous = changes.write();
// Let the user edit the changes
editor(file, (code) => {
if (code === 0) {
// Add the changes file to git
changes.add(previous);
} else {
// Roll back
changes.abort(previous);
}
});
|
Add init to WordPress theme file | <?php
/*
Plugin Name: Timber
Description: The WordPress Timber Library allows you to write themes using the power Twig templates.
Plugin URI: http://timber.upstatement.com
Author: Jared Novack + Upstatement
Version: 1.0.3
Author URI: http://upstatement.com/
*/
// we look for Composer files first in the plugins dir.
// then in the wp-content dir (site install).
// and finally in the current themes directories.
if ( file_exists( $composer_autoload = __DIR__ . '/vendor/autoload.php' ) /* check in self */
|| file_exists( $composer_autoload = WP_CONTENT_DIR.'/vendor/autoload.php') /* check in wp-content */
|| file_exists( $composer_autoload = plugin_dir_path( __FILE__ ).'vendor/autoload.php') /* check in plugin directory */
|| file_exists( $composer_autoload = get_stylesheet_directory().'/vendor/autoload.php') /* check in child theme */
|| file_exists( $composer_autoload = get_template_directory().'/vendor/autoload.php') /* check in parent theme */
) {
require_once $composer_autoload;
}
new \Timber\Timber;
| <?php
/*
Plugin Name: Timber
Description: The WordPress Timber Library allows you to write themes using the power Twig templates.
Plugin URI: http://timber.upstatement.com
Author: Jared Novack + Upstatement
Version: 1.0.3
Author URI: http://upstatement.com/
*/
// we look for Composer files first in the plugins dir.
// then in the wp-content dir (site install).
// and finally in the current themes directories.
if ( file_exists( $composer_autoload = __DIR__ . '/vendor/autoload.php' ) /* check in self */
|| file_exists( $composer_autoload = WP_CONTENT_DIR.'/vendor/autoload.php') /* check in wp-content */
|| file_exists( $composer_autoload = plugin_dir_path( __FILE__ ).'vendor/autoload.php') /* check in plugin directory */
|| file_exists( $composer_autoload = get_stylesheet_directory().'/vendor/autoload.php') /* check in child theme */
|| file_exists( $composer_autoload = get_template_directory().'/vendor/autoload.php') /* check in parent theme */
) {
require_once $composer_autoload;
}
|
Fix chapter sorting on homepage | import { Link } from 'react-router';
import HomepageTile from './homepage-tile.js';
import chaptersData from './chapter-data.js';
import sortBy from 'lodash/sortBy';
// Clone the chapters since sort mutates the array
const chapters = sortBy(
[...chaptersData].filter(chapter => !chapter.hidden),
chapter => parseInt(chapter.id, 10)
);
const HomePage = React.createClass({
render: function() {
return (
<div className="container homepage">
<div className="pure-g row-gap-small">
<div className="pure-u-1">
<h2>Grade 6 Science</h2>
</div>
</div>
<div className="pure-g">
{chapters.map((chapter, index) => (
<HomepageTile key={index} imagePath={chapter.thumbnailImagePath} chapterId={chapter.id} title={chapter.title} />
))}
</div>
{this.props.children}
</div>
);
}
});
export default HomePage; | import { Link } from 'react-router';
import HomepageTile from './homepage-tile.js';
import chaptersData from './chapter-data.js';
import sortBy from 'lodash/sortBy';
// Clone the chapters since sort mutates the array
const chapters = sortBy(
[...chaptersData].filter(chapter => !chapter.hidden),
'id'
);
const HomePage = React.createClass({
render: function() {
return (
<div className="container homepage">
<div className="pure-g row-gap-small">
<div className="pure-u-1">
<h2>Grade 6 Science</h2>
</div>
</div>
<div className="pure-g">
{chapters.map((chapter, index) => (
<HomepageTile key={index} imagePath={chapter.thumbnailImagePath} chapterId={chapter.id} title={chapter.title} />
))}
</div>
{this.props.children}
</div>
);
}
});
export default HomePage; |
Change adapter; fix filter func | from requests.adapters import HTTPAdapter
RetryAdapter = HTTPAdapter(max_retries=5,
pool_connections=100,
pool_maxsize=50)
def create_db_url(username, passwd, host, port):
if username and passwd:
cr = '{}:{}@'.format(username, passwd)
else:
cr = ''
return 'http://{}{}:{}/'.format(
cr, host, port
)
def save_or_update(db, doc):
if doc['id'] not in db:
doc['_id'] = doc['id']
db.save(doc)
else:
old = db.get(doc['id'])
old = doc
db.save(old)
def check_doc(db, feed_item):
if feed_item['id'] not in db:
return True
if db.get_doc(feed_item['id'])['dateModified'] < feed_item['dateModified']:
return True
return False
| from requests.adapters import HTTPAdapter
RetryAdapter = HTTPAdapter(max_retries=5)
def create_db_url(username, passwd, host, port):
if username and passwd:
cr = '{}:{}@'.format(username, passwd)
else:
cr = ''
return 'http://{}{}:{}/'.format(
cr, host, port
)
def save_or_update(db, doc):
if doc['id'] not in db:
doc['_id'] = doc['id']
db.save(doc)
else:
old = db.get(doc['id'])
old = doc
db.save(old)
def check_doc(db, feed_item):
if feed_item['id'] not in db:
return True
if db.get(feed_item['id'])['dateModified'] < feed_item['dateModified']:
return True
return False
|
Remove unused imports from MyActivity | package com.example.mwismer.mobproto_finalproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by mwismer on 10/23/14.
*/
public class MyFragment extends Fragment {
private String TAG = "MyFragment";
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
new BLEScanner(getActivity()).scanBLE();
return rootView;
}
} | package com.example.mwismer.mobproto_finalproject;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by mwismer on 10/23/14.
*/
public class MyFragment extends Fragment {
private String TAG = "MyFragment";
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
new BLEScanner(getActivity()).scanBLE();
return rootView;
}
} |
Set default encoding of diff file to utf-8 according of issue reported by @yqt: diff file gets wrong encoding | package rb;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
/**
* Created by IntelliJ IDEA.
* User: Gong Zeng
* Date: 5/16/11
* Time: 12:12 PM
*/
public class MemoryFile {
String name;
String content;
public MemoryFile(String name, String diff) {
this.name = name;
this.content = diff;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public InputStream getInputStream() throws UnsupportedEncodingException {
return new ByteArrayInputStream(content.getBytes("utf-8"));
}
}
| package rb;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* Created by IntelliJ IDEA.
* User: Gong Zeng
* Date: 5/16/11
* Time: 12:12 PM
*/
public class MemoryFile {
String name;
String content;
public MemoryFile(String name, String diff) {
this.name = name;
this.content = diff;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public InputStream getInputStream() {
return new ByteArrayInputStream(content.getBytes());
}
}
|
Use encryption available for Laravel 5.0 and 5.1 in tests | <?php
class AimeosTestAbstract extends Orchestra\Testbench\TestCase
{
protected function getEnvironmentSetUp($app)
{
$app['config']->set('database.default', 'mysql');
$app['config']->set('database.connections.mysql', [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
]);
$app['config']->set('app.key', 'SomeRandomStringWith32Characters');
$app['config']->set('app.cipher', MCRYPT_RIJNDAEL_128);
$app['config']->set('shop.routes.account', ['prefix' => '{site}']);
$app['config']->set('shop.routes.default', ['prefix' => '{site}']);
}
protected function getPackageProviders($app)
{
return ['Aimeos\Shop\ShopServiceProvider'];
}
} | <?php
class AimeosTestAbstract extends Orchestra\Testbench\TestCase
{
protected function getEnvironmentSetUp($app)
{
$app['config']->set('database.default', 'mysql');
$app['config']->set('database.connections.mysql', [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
]);
$app['config']->set('app.key', 'SomeRandomStringWith32Characters');
$app['config']->set('app.cipher', 'AES-256-CBC');
$app['config']->set('shop.routes.account', ['prefix' => '{site}']);
$app['config']->set('shop.routes.default', ['prefix' => '{site}']);
}
protected function getPackageProviders($app)
{
return ['Aimeos\Shop\ShopServiceProvider'];
}
} |
Fix same rule parameter validation | (function() {
var num = parseInt(request.param.num, 10).toString(10);
var rule = data.rules[num] || null;
if (rule === null) return response.error(404);
switch (request.method) {
case 'PUT':
var cmd = '';
switch (request.param.action) {
case 'enable':
cmd = 'node app-cli.js -mode rule --enable -n ' + num;
break;
case 'disable':
cmd = 'node app-cli.js -mode rule --disable -n ' + num;
break;
}
child_process.exec(cmd, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
return;
}
})();
| (function() {
var rule = data.rules[parseInt(request.param.num, 10)] || null;
if (rule === null) return response.error(404);
switch (request.method) {
case 'PUT':
var cmd = '';
switch (request.param.action) {
case 'enable':
cmd = 'node app-cli.js -mode rule --enable -n ' + request.param.num;
break;
case 'disable':
cmd = 'node app-cli.js -mode rule --disable -n ' + request.param.num;
break;
}
child_process.exec(cmd, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
return;
}
})(); |
Add empty tests to the build doesn't complain | package org.opennms.netmgt.threshd;
import org.opennms.netmgt.config.DatabaseConnectionFactory;
import org.opennms.netmgt.mock.MockDatabase;
import org.opennms.netmgt.mock.MockUtil;
import junit.framework.TestCase;
public class ThreshdTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(ThreshdTest.class);
}
protected void setUp() throws Exception {
super.setUp();
MockUtil.setupLogging();
MockDatabase db = new MockDatabase();
DatabaseConnectionFactory.setInstance(db);
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void xtestthreshd() {
Threshd threshd = new Threshd();
threshd.init();
threshd.start();
threshd.stop();
}
public void testDoNothing() {
}
}
| package org.opennms.netmgt.threshd;
import org.opennms.netmgt.config.DatabaseConnectionFactory;
import org.opennms.netmgt.mock.MockDatabase;
import org.opennms.netmgt.mock.MockUtil;
import junit.framework.TestCase;
public class ThreshdTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(ThreshdTest.class);
}
protected void setUp() throws Exception {
super.setUp();
MockUtil.setupLogging();
MockDatabase db = new MockDatabase();
DatabaseConnectionFactory.setInstance(db);
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void xtestthreshd() {
Threshd threshd = new Threshd();
threshd.init();
threshd.start();
threshd.stop();
}
}
|
Add changes to the js file | // window.checkAdLoad = function(){
// var checkAdLoadfunction = function(){
// var msg = "Ad unit is not present";
// if($("._teraAdContainer")){
// console.log("Ad unit is present")
// msg = "Ad unit is present";
// }
// return msg;
// }
// checkAdLoadfunction()
// console.log(checkAdLoadfunction);
// var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
// window.dispatchEvent(validateAd);
// }
t$(document).ready(function(){
console.log("Checking the AdInstances.");
var checkAdLoadfunction = function(){
if(t$("._abmMainAdContainer")){
console.log("Ad unit is present");
t$('._teraAdContainer').mouseover(function(){
t$(this).find('._abmAdContainer').text("Mouse over tera ad unit")
console.log('Hoverred mouse over tera ad unit')
});
}
}
checkAdLoadfunction();
});
| // window.checkAdLoad = function(){
// var checkAdLoadfunction = function(){
// var msg = "Ad unit is not present";
// if($("._teraAdContainer")){
// console.log("Ad unit is present")
// msg = "Ad unit is present";
// }
// return msg;
// }
// checkAdLoadfunction()
// console.log(checkAdLoadfunction);
// var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
// window.dispatchEvent(validateAd);
// }
t$(document).ready(function(){
console.log("Checking the AdInstances.");
var checkAdLoadfunction = function(){
if(t$("._teraAdContainer")){
console.log("Ad unit is present");
t$('._teraAdContainer').mouseover(function(){
t$(this).focus();
console.log('Hoverred mouseover tera ad unit')
});
}
}
checkAdLoadfunction();
});
|
Update utils color string with basic sprintf support | 'use strict';
// Load requirements
const clk = require('chalk'),
chalk = new clk.constructor({level: 1, enabled: true});
// Formats a string with ANSI styling
module.exports = function(str) {
// Variables
const regex = /\{([a-z,]+)\:([\s\S]*?)\}/gmi;
let m = null, args = Array.prototype.slice.call(arguments, 1);
// Check for a non-string
if ( typeof str !== 'string' ) {
return '';
}
// Add basic sprintf-esque support
args.forEach((arg) => {
str = str.replace('%s', arg);
});
// Loop through matches
while ( ( m = regex.exec(str) ) !== null ) {
// Allow for multiple formatting options
let split = m[1].split(','),
partial = m[2];
// Wrap the replacement area
for ( let i in split ) {
if ( chalk[split[i]] !== undefined ) {
partial = chalk[split[i]](partial);
}
}
// Make the replacement in the original string
str = str.replace(m[0], partial);
}
// Still matches to be made
return ( str.match(regex) !== null ? this.colorString(str, args) : str.replace(/\{([a-z,]+)\:/gi, '') );
};
| 'use strict';
// Load requirements
const clk = require('chalk'),
chalk = new clk.constructor({level: 1, enabled: true});
// Formats a string with ANSI styling
module.exports = function(str) {
// Variables
const regex = /\{([a-z,]+)\:([\s\S]*?)\}/gmi;
let m;
// Check for a non-string
if ( typeof str !== 'string' ) {
return '';
}
// Loop through matches
while ( ( m = regex.exec(str) ) !== null ) {
// Allow for multiple formatting options
let split = m[1].split(','),
partial = m[2];
// Wrap the replacement area
for ( let i in split ) {
if ( chalk[split[i]] !== undefined ) {
partial = chalk[split[i]](partial);
}
}
// Make the replacement in the original string
str = str.replace(m[0], partial);
}
// Still matches to be made
return ( str.match(regex) !== null ? this.colorString(str) : str.replace(/\{([a-z,]+)\:/gi, '') );
};
|
Throw when we don't know the answer. | 'use strict';
function defaultPort(protocol) {
if (typeof protocol !== 'number') {
if (Object.prototype.hasOwnProperty.call(defaultPort, protocol)) {
return defaultPort[protocol];
}
throw new Error('Unknown protocol.');
}
for (const key in defaultPort) {
if (Object.prototype.hasOwnProperty.call(defaultPort, key)) {
if (defaultPort[key] === protocol) {
return key;
}
}
}
throw new Error('Unknown port number.');
}
// Hypertext Transfer Protocol
defaultPort.http = 80;
// HTTP Secure
defaultPort.https = 443;
// WebSocket
defaultPort.ws = 80;
// WebSocket Secure
defaultPort.wss = 443;
// File Transfer Protocol
defaultPort.ftp = 21;
// Secure Shell
defaultPort.ssh = 22;
// SSH File Transfer Protocol
defaultPort.sftp = 22;
// Remote Framebuffer
defaultPort.rfb = 5900;
module.exports = defaultPort;
| 'use strict';
function defaultPort(protocol) {
if (typeof protocol !== 'number') {
return defaultPort[protocol];
}
for (const key in defaultPort) {
if (Object.prototype.hasOwnProperty.call(defaultPort, key)) {
if (defaultPort[key] === protocol) {
return key;
}
}
}
}
// Hypertext Transfer Protocol
defaultPort.http = 80;
// HTTP Secure
defaultPort.https = 443;
// WebSocket
defaultPort.ws = 80;
// WebSocket Secure
defaultPort.wss = 443;
// File Transfer Protocol
defaultPort.ftp = 21;
// Secure Shell
defaultPort.ssh = 22;
// SSH File Transfer Protocol
defaultPort.sftp = 22;
// Remote Framebuffer
defaultPort.rfb = 5900;
module.exports = defaultPort;
|
Update acc-provision version to 1.9.7 | from setuptools import setup, find_packages
setup(
name='acc_provision',
version='1.9.7',
description='Tool to provision ACI for ACI Containers Controller',
author="Cisco Systems, Inc.",
author_email="apicapi@noironetworks.com",
url='http://github.com/noironetworks/aci-containers/',
license="http://www.apache.org/licenses/LICENSE-2.0",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'acc-provision=acc_provision.acc_provision:main',
]
},
install_requires=[
'requests',
'pyyaml',
'jinja2',
'pyopenssl',
],
)
| from setuptools import setup, find_packages
setup(
name='acc_provision',
version='1.9.6',
description='Tool to provision ACI for ACI Containers Controller',
author="Cisco Systems, Inc.",
author_email="apicapi@noironetworks.com",
url='http://github.com/noironetworks/aci-containers/',
license="http://www.apache.org/licenses/LICENSE-2.0",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'acc-provision=acc_provision.acc_provision:main',
]
},
install_requires=[
'requests',
'pyyaml',
'jinja2',
'pyopenssl',
],
)
|
Add "localhost" in the allowed hosts for testing purposes | """GeoKey settings."""
from geokey.core.settings.dev import *
DEFAULT_FROM_EMAIL = 'no-reply@travis-ci.org'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'geokey',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
ALLOWED_HOSTS = ['localhost']
INSTALLED_APPS += (
'geokey_epicollect',
)
STATIC_URL = '/static/'
MEDIA_ROOT = normpath(join(dirname(dirname(abspath(__file__))), 'assets'))
MEDIA_URL = '/assets/'
WSGI_APPLICATION = 'wsgi.application'
| """GeoKey settings."""
from geokey.core.settings.dev import *
DEFAULT_FROM_EMAIL = 'no-reply@travis-ci.org'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'geokey',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
INSTALLED_APPS += (
'geokey_epicollect',
)
STATIC_URL = '/static/'
MEDIA_ROOT = normpath(join(dirname(dirname(abspath(__file__))), 'assets'))
MEDIA_URL = '/assets/'
WSGI_APPLICATION = 'wsgi.application'
|
Mark the socket client as skipped | <?php
namespace CouchDB\Tests\Http;
use CouchDB\Tests\TestCase;
use CouchDB\Http\SocketClient;
/**
* @author Markus Bachmann <markus.bachmann@bachi.biz>
*/
class SocketClientTest extends TestCase
{
protected function setUp()
{
$this->markTestSkipped('Performance to low');
$this->client = $this->getTestClient();
}
public function testConnect()
{
$this->assertFalse($this->client->isConnected());
$this->client->connect();
$this->assertTrue($this->client->isConnected());
}
public function testPutRequest()
{
$this->client->connect();
$response = $this->client->request('/test', 'PUT');
$this->assertTrue($response->isSuccessful());
}
public function testPostRequest()
{
$this->client->connect();
$response = $this->client->request('/_all_dbs', 'GET');
$this->assertInstanceOf('\\CouchDB\\Http\\Response\ResponseInterface', $response);
$this->assertTrue($response->isSuccessful());
$this->assertInternalType('string', $response->getContent());
}
protected function getTestClient()
{
static $c;
if (null === $c) {
$c = new SocketClient();
}
return $c;
}
}
| <?php
namespace CouchDB\Tests\Http;
use CouchDB\Tests\TestCase;
use CouchDB\Http\SocketClient;
/**
* @author Markus Bachmann <markus.bachmann@bachi.biz>
*/
class SocketClientTest extends TestCase
{
protected function setUp()
{
$this->client = $this->getTestClient();
}
public function testConnect()
{
$this->assertFalse($this->client->isConnected());
$this->client->connect();
$this->assertTrue($this->client->isConnected());
}
public function testPutRequest()
{
$this->client->connect();
$response = $this->client->request('/test', 'PUT');
$this->assertTrue($response->isSuccessful());
}
public function testPostRequest()
{
$this->client->connect();
$response = $this->client->request('/_all_dbs', 'GET');
$this->assertInstanceOf('\\CouchDB\\Http\\Response\ResponseInterface', $response);
$this->assertTrue($response->isSuccessful());
$this->assertInternalType('string', $response->getContent());
}
protected function getTestClient()
{
static $c;
if (null === $c) {
$c = new SocketClient();
}
return $c;
}
}
|
Clarify that it's a-okay to use possibly_qualify_id to determine
whether to declare an actor local. | import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""If this actor doesn't already have a hive id assigned to it, assign it
Note that you can specify a hive_id here, and if there is already
a hive_id on the actor_id, it simply won't assign something. This
is useful if you want to declare an actor as local if it's not
assigned, but let it stay remote if it is.
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
| import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""
If this actor doesn't already have a hive id assigned to it, assign it
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
|
Install `ember-auto-import` to Ember App during `ember install` | /*jshint node:true*/
var pkg = require('../../package.json');
function getDependencyVersion(packageJson, name) {
var dependencies = packageJson.dependencies;
var devDependencies = packageJson.devDependencies;
return dependencies[name] || devDependencies[name];
}
function getPeerDependencyVersion(packageJson, name) {
var peerDependencies = packageJson.peerDependencies;
return peerDependencies[name];
}
module.exports = {
description: 'Install ember-cli-react dependencies into your app.',
normalizeEntityName: function() {},
// Install react into host app
afterInstall: function() {
const packages = [
{
name: 'ember-auto-import',
target: getDependencyVersion(pkg, 'ember-auto-import'),
},
{
name: 'react',
target: getPeerDependencyVersion(pkg, 'react'),
},
{
name: 'react-dom',
target: getPeerDependencyVersion(pkg, 'react-dom'),
},
];
return this.addPackagesToProject(packages);
},
};
| /*jshint node:true*/
var pkg = require('../../package.json');
function getPeerDependencyVersion(packageJson, name) {
var peerDependencies = packageJson.peerDependencies;
return peerDependencies[name];
}
module.exports = {
description: 'Install ember-cli-react dependencies into your app.',
normalizeEntityName: function() {},
// Install react into host app
afterInstall: function() {
const packages = [
{
name: 'react',
target: getPeerDependencyVersion(pkg, 'react'),
},
{
name: 'react-dom',
target: getPeerDependencyVersion(pkg, 'react-dom'),
},
];
return this.addPackagesToProject(packages);
},
};
|
Revert change in endpoint configuration | /*
* AET
*
* Copyright (C) 2013 Cognifide Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(['angularAMD'], function (angularAMD) {
'use strict';
angularAMD.factory('endpointConfiguration', function () {
return {
getEndpoint: function () {
var config = {
'getUrl': '/api/'
//'getUrl': 'http://aet-vagrant/api/'
};
return config;
}
};
});
});
| /*
* AET
*
* Copyright (C) 2013 Cognifide Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(['angularAMD'], function (angularAMD) {
'use strict';
angularAMD.factory('endpointConfiguration', function () {
return {
getEndpoint: function () {
var config = {
// 'getUrl': '/api/'
//'getUrl': 'http://aet-vagrant/api/'
'getUrl': 'http://localhost:8181/api/'
};
return config;
}
};
});
});
|
Remove alias from service provider.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Widget;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class WidgetServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.widget', function ($app) {
return new WidgetManager($app);
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../');
$this->package('orchestra/widget', 'orchestra/widget', $path);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.widget');
}
}
| <?php namespace Orchestra\Widget;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class WidgetServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.widget', function ($app) {
return new WidgetManager($app);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Widget', 'Orchestra\Support\Facades\Widget');
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../');
$this->package('orchestra/widget', 'orchestra/widget', $path);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.widget');
}
}
|
Initialize database if it does not exist | from heutagogy import app
import heutagogy.persistence
import os
from datetime import timedelta
app.config.from_object(__name__)
app.config.update(dict(
USERS={
'myuser': {'password': 'mypassword'},
'user2': {'password': 'pass2'},
},
JWT_AUTH_URL_RULE='/api/v1/login',
JWT_EXPIRATION_DELTA=timedelta(seconds=2592000), # 1 month
DATABASE=os.path.join(app.root_path, 'heutagogy.sqlite3'),
DEBUG=True))
app.config.from_envvar('HEUTAGOGY_SETTINGS', silent=True)
if not app.config['SECRET_KEY']:
app.config['SECRET_KEY'] = 'super-secret'
@app.cli.command('initdb')
def initdb_command():
"""Creates the database tables."""
heutagogy.persistence.initialize()
with app.app_context():
if not os.path.isfile(app.config['DATABASE']):
heutagogy.persistence.initialize()
| from heutagogy import app
import heutagogy.persistence
import os
from datetime import timedelta
app.config.from_object(__name__)
app.config.update(dict(
USERS={
'myuser': {'password': 'mypassword'},
'user2': {'password': 'pass2'},
},
JWT_AUTH_URL_RULE='/api/v1/login',
JWT_EXPIRATION_DELTA=timedelta(seconds=2592000), # 1 month
DATABASE=os.path.join(app.root_path, 'heutagogy.sqlite3'),
DEBUG=True))
app.config.from_envvar('HEUTAGOGY_SETTINGS', silent=True)
if not app.config['SECRET_KEY']:
app.config['SECRET_KEY'] = 'super-secret'
@app.cli.command('initdb')
def initdb_command():
"""Creates the database tables."""
heutagogy.persistence.initialize()
|
Update infrastructure for single node run | package dgcj;
public class TemplateDgcjMain {
static final Object PROBLEM = new TemplateDgcjProblem(); // PROBLEM NAME goes here
public String run() {
// long n = ;
// long from = 1L * n * ID / NODES;
// long to = 1L * n * (ID + 1) / NODES;
return null;
}
static int NODES;
static int ID;
/**
* Arguments:
* "" = as for submit
* "0" = run multi node infrastructure
* "1" = run single node
*/
public static void main(String[] args) {
PROBLEM.equals(args); // Local testing framework invocation
boolean single = args.length == 1 && args[0].equals("1");
NODES = single ? 1 : message.NumberOfNodes();
ID = single ? 0 : message.MyNodeId();
String ans = new TemplateDgcjMain().run();
if (ans != null) {
System.out.println(ans);
}
}
public void log(String msg) {
PROBLEM.equals(ID + ": " + msg); // Local testing framework log
}
}
| package dgcj;
public class TemplateDgcjMain {
static final Object PROBLEM = new TemplateDgcjProblem(); // PROBLEM NAME goes here
public String run() {
// long n = ;
// long from = 1L * n * ID / NODES;
// long to = 1L * n * (ID + 1) / NODES;
return null;
}
final static boolean SINGLE = false;
final int NODES = SINGLE ? 1 : message.NumberOfNodes();
final int ID = SINGLE ? 0 : message.MyNodeId();
// EXECUTE with non-empty args
public static void main(String[] args) {
if (!SINGLE) {
PROBLEM.equals(args); // Local testing framework invocation
}
String ans = new TemplateDgcjMain().run();
if (ans != null) {
System.out.println(ans);
}
}
public void log(String msg) {
PROBLEM.equals(ID + ": " + msg); // Local testing framework log
}
}
|
Fix test case class name.
git-svn-id: b6e219894c353fb1d215c78b2075057d8daadfba@1040 44c647ce-9c0f-0410-b52a-842ac1e357ba | <?php
if (!defined('PHPUnit2_MAIN_METHOD')) {
define('PHPUnit2_MAIN_METHOD', 'Zend_HttpClient_AllTests::main');
}
require_once 'PHPUnit2/Framework/TestSuite.php';
require_once 'PHPUnit2/TextUI/TestRunner.php';
require_once 'Zend/Http/ResponseTest.php';
require_once 'Zend/Http/ClientTest.php';
class Zend_Http_AllTests
{
public static function main()
{
PHPUnit2_TextUI_TestRunner::run(self::suite());
}
public static function suite()
{
$suite = new PHPUnit2_Framework_TestSuite('Zend Framework - Zend_HttpClient');
$suite->addTestSuite('Zend_Http_ClientTest');
$suite->addTestSuite('Zend_Http_Client_ResponseTest');
return $suite;
}
}
if (PHPUnit2_MAIN_METHOD == 'Zend_Http_AllTests::main') {
Zend_HttpClient_AllTests::main();
}
| <?php
if (!defined('PHPUnit2_MAIN_METHOD')) {
define('PHPUnit2_MAIN_METHOD', 'Zend_HttpClient_AllTests::main');
}
require_once 'PHPUnit2/Framework/TestSuite.php';
require_once 'PHPUnit2/TextUI/TestRunner.php';
require_once 'Zend/Http/ResponseTest.php';
require_once 'Zend/Http/ClientTest.php';
class Zend_Http_AllTests
{
public static function main()
{
PHPUnit2_TextUI_TestRunner::run(self::suite());
}
public static function suite()
{
$suite = new PHPUnit2_Framework_TestSuite('Zend Framework - Zend_HttpClient');
$suite->addTestSuite('Zend_Http_ClientTest');
$suite->addTestSuite('Zend_Http_ResponseTest');
return $suite;
}
}
if (PHPUnit2_MAIN_METHOD == 'Zend_Http_AllTests::main') {
Zend_HttpClient_AllTests::main();
}
|
Allow testing with ip for dev | var CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var debug = '&debug=true'
module.exports = {
entry: './src/index.js',
output: {
path: 'dist',
filename: 'index.js'
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js', '.elm']
},
module: {
loaders: [
{
test: /\.html$/,
exclude: /node_modules/,
loader: 'file?name=[name].[ext]'
},
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
loader: 'elm-hot!elm-webpack?verbose=true&warn=true&debug=true'
}
],
noParse: /\.elm$/
},
plugins: [
new CleanWebpackPlugin(['dist'], {
root: __dirname,
verbose: true,
dry: false
}),
new CopyWebpackPlugin([
{ from: 'src/assets', to: 'assets'}
])
],
devServer: {
stats: 'errors-only',
host: '0.0.0.0',
historyApiFallback: true
}
};
| var CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var debug = '&debug=true'
module.exports = {
entry: './src/index.js',
output: {
path: 'dist',
filename: 'index.js'
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js', '.elm']
},
module: {
loaders: [
{
test: /\.html$/,
exclude: /node_modules/,
loader: 'file?name=[name].[ext]'
},
{
test: /\.elm$/,
exclude: [/elm-stuff/, /node_modules/],
loader: 'elm-hot!elm-webpack?verbose=true&warn=true&debug=true'
}
],
noParse: /\.elm$/
},
plugins: [
new CleanWebpackPlugin(['dist'], {
root: __dirname,
verbose: true,
dry: false
}),
new CopyWebpackPlugin([
{ from: 'src/assets', to: 'assets'}
])
],
devServer: {
stats: 'errors-only',
historyApiFallback: true
}
};
|
[MF] Solve static analysis issues for f3cf071 commit. | /**
* Created by alnedorezov on 5/26/17.
*/
function initZoomIn() {
Tool.zoomIn = function () {
return fromPrototype(Tool, {
onClick: function (isButtonPressed) {
/*global zoomCount*/
/*eslint no-undef: "error"*/
/*global maxZoomCount*/
/*eslint no-undef: "error"*/
if (zoomCount === maxZoomCount) {
return;
}
/*global zoomCount*/
/*eslint no-undef: "error"*/
zoomCount++;
zoomPlus();
/*global svgScale*/
/*eslint no-undef: "error"*/
svgScale(2);
},
isProlonged: false,
buttonId: "btn_zoom_in"
});
};
} | /**
* Created by alnedorezov on 5/26/17.
*/
function initZoomIn() {
Tool.zoomIn = function () {
return fromPrototype(Tool, {
onClick: function (isButtonPressed) {
/*global zoomCount*/
/*eslint no-undef: "error"*/
if (zoomCount === maxZoomCount) {
return;
}
/*global zoomCount*/
/*eslint no-undef: "error"*/
zoomCount++;
zoomPlus();
/*global svgScale*/
/*eslint no-undef: "error"*/
svgScale(2);
},
isProlonged: false,
buttonId: "btn_zoom_in"
});
};
} |
Fix playground CSP for demo if deployed under proxied domain | from django.conf import settings
from django.shortcuts import render
from ..graphql.views import GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and validation errors highlighted within the text.
#
# Here is an example query to fetch a list of products:
#
{
products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
name
description
}
}
}
}
""" % {
"channel_slug": settings.DEFAULT_CHANNEL_SLUG
}
class DemoGraphQLView(GraphQLView):
def render_playground(self, request):
pwa_origin = settings.PWA_ORIGINS[0]
ctx = {
"query": EXAMPLE_QUERY,
"api_url": f"https://{pwa_origin}/graphql/",
}
return render(request, "graphql/playground.html", ctx)
| from django.conf import settings
from django.shortcuts import render
from ..graphql.views import API_PATH, GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and validation errors highlighted within the text.
#
# Here is an example query to fetch a list of products:
#
{
products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
name
description
}
}
}
}
""" % {
"channel_slug": settings.DEFAULT_CHANNEL_SLUG
}
class DemoGraphQLView(GraphQLView):
def render_playground(self, request):
ctx = {
"query": EXAMPLE_QUERY,
"api_url": request.build_absolute_uri(str(API_PATH)),
}
return render(request, "graphql/playground.html", ctx)
|
Change 'patron' to 'customer' in BarterAccount | from django.db import models
# Create your models here.
class BarterEvent(models.Model):
barter_account = models.ForeignKey(
'BarterAccount',
#on_delete=models.CASCADE,
)
ADD = 'Add'
SUBTRACT = 'Subtract'
NOTE = 'Note'
EVENT_TYPE_CHOICES = (
(ADD, 'Add'),
(SUBTRACT, 'Subtract'),
(NOTE, 'Note'),
)
event_type = models.CharField(
max_length=20,
choices = EVENT_TYPE_CHOICES,
default = SUBTRACT,
)
event_time = models.DateTimeField(auto_now_add=True)
#staff_id = models.ForeignKey()
class BarterAccount(models.Model):
customer_name = models.CharField(max_length=100)
balance = models.DecimalField(max_digits=5, decimal_places=2)
| from django.db import models
# Create your models here.
class BarterEvent(models.Model):
barter_account = models.ForeignKey(
'BarterAccount',
#on_delete=models.CASCADE,
)
ADD = 'Add'
SUBTRACT = 'Subtract'
NOTE = 'Note'
EVENT_TYPE_CHOICES = (
(ADD, 'Add'),
(SUBTRACT, 'Subtract'),
(NOTE, 'Note'),
)
event_type = models.CharField(
max_length=20,
choices = EVENT_TYPE_CHOICES,
default = SUBTRACT,
)
event_time = models.DateTimeField(auto_now_add=True)
#staff_id = models.ForeignKey()
class BarterAccount(models.Model):
patron_name = models.CharField(max_length=100)
balance = models.DecimalField(max_digits=5, decimal_places=2)
|
Change beat to fractional values | var five = require("../lib/johnny-five.js"),
board = new five.Board();
board.on("ready", function() {
// Creates a piezo object and defines the pin to be used for the signal
var piezo = new five.Piezo(3);
// Injects the piezo into the repl
board.repl.inject({
piezo: piezo
});
// Plays a song
piezo.play({
// song is composed by an array of pairs of notes and beats
// The first argument is the note (null means "no note")
// The second argument is the length of time (beat) of the note (or non-note)
song: [
["C4", 1/4],
["D4", 1/4],
["F4", 1/4],
["D4", 1/4],
["A4", 1/4],
[null, 1/4],
["A4", 1],
["G4", 1],
[null, 1/2],
["C4", 1/4],
["D4", 1/4],
["F4", 1/4],
["D4", 1/4],
["G4", 1/4],
[null, 1/4],
["G4", 1],
["F4", 1],
[null, 1/2]
],
tempo: 100
});
});
| var five = require("../lib/johnny-five.js"),
board = new five.Board();
board.on("ready", function() {
// Creates a piezo object and defines the pin to be used for the signal
var piezo = new five.Piezo(3);
// Injects the piezo into the repl
board.repl.inject({
piezo: piezo
});
// Plays a song
piezo.play({
// song is composed by an array of pairs of notes and beats
// The first argument is the note (null means "no note")
// The second argument is the length of time (beat) of the note (or non-note)
song: [
["C4", 1],
["D4", 1],
["F4", 1],
["D4", 1],
["A4", 1],
[null, 1],
["A4", 4],
["G4", 4],
[null, 2],
["C4", 1],
["D4", 1],
["F4", 1],
["D4", 1],
["G4", 1],
[null, 1],
["G4", 4],
["F4", 4],
[null, 2]
],
tempo: 250
});
});
|
Add missing data to the projects table. | 'use strict';
const Sequelize = require('sequelize');
// projects-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
module.exports = function(sequelize) {
const Projects = sequelize.define('Projects', {
name: {
type: Sequelize.STRING,
allowNull: false
},
description:{
type: Sequelize.STRING,
allowNull: false
},
bounty: {
type: Sequelize.INTEGER,
allowNull: false,
},
videoUrl: {
type: Sequelize.STRING,
allowNull: true
},
awarded:{
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
image: {
type: Sequelize.BLOB('long'),
allowNull: true
}
}, {
image: {
type: Sequelize.BLOB('long'),
allowNull: true
}
}, {
/* Feathers adds additional level of complexity when creating database tables.
the class Method associate is used to add the table relations before the database is synced. The actual creation of ll the tables happens in the services/index.js file */
classMethods: {
associate() {
Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'});
}
}
});
return Projects;
};
| 'use strict';
const Sequelize = require('sequelize');
// projects-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
module.exports = function(sequelize) {
const Projects = sequelize.define('Projects', {
name: {
type: Sequelize.STRING,
allowNull: false
},
description:{
type: Sequelize.STRING,
allowNull: false
},
bounty: {
type: Sequelize.INTEGER,
allowNull: false,
},
videoUrl: {
type: Sequelize.STRING,
allowNull: true
},
awarded:{
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
image: {
type: Sequelize.BLOB('long'),
allowNull: true
}
}, {
/* Feathers adds additional level of complexity when creating database tables.
the class Method associate is used to add the table relations before the database is synced. The actual creation of ll the tables happens in the services/index.js file */
classMethods: {
associate() {
Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'});
}
}
});
return Projects;
};
|
Add the newly created NameServers to the DNS Get Response | package dns
import "github.com/jen20/riviera/azure"
type GetDNSZoneResponse struct {
ID *string `mapstructure:"id"`
Name *string `mapstructure:"name"`
Location *string `mapstructure:"location"`
Tags *map[string]*string `mapstructure:"tags"`
NumberOfRecordSets *string `mapstructure:"numberOfRecordSets"`
MaxNumberOfRecordSets *string `mapstructure:"maxNumberOfRecordSets"`
NameServers *[]string `mapstructure:"nameServers"`
}
type GetDNSZone struct {
Name string `json:"-"`
ResourceGroupName string `json:"-"`
}
func (s GetDNSZone) APIInfo() azure.APIInfo {
return azure.APIInfo{
APIVersion: apiVersion,
Method: "GET",
URLPathFunc: dnsZoneDefaultURLPathFunc(s.ResourceGroupName, s.Name),
ResponseTypeFunc: func() interface{} {
return &GetDNSZoneResponse{}
},
}
}
| package dns
import "github.com/jen20/riviera/azure"
type GetDNSZoneResponse struct {
ID *string `mapstructure:"id"`
Name *string `mapstructure:"name"`
Location *string `mapstructure:"location"`
Tags *map[string]*string `mapstructure:"tags"`
NumberOfRecordSets *string `mapstructure:"numberOfRecordSets"`
MaxNumberOfRecordSets *string `mapstructure:"maxNumberOfRecordSets"`
}
type GetDNSZone struct {
Name string `json:"-"`
ResourceGroupName string `json:"-"`
}
func (s GetDNSZone) APIInfo() azure.APIInfo {
return azure.APIInfo{
APIVersion: apiVersion,
Method: "GET",
URLPathFunc: dnsZoneDefaultURLPathFunc(s.ResourceGroupName, s.Name),
ResponseTypeFunc: func() interface{} {
return &GetDNSZoneResponse{}
},
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.