text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Return Response instances for fakeFetch
import queryString from 'query-string'; import pathMatch from 'path-match'; import parseUrl from 'parse-url'; const nativeFetch = window.fetch; //TODO: Handle response headers let fakeResponse = function(response = {}) { const responseStr = JSON.stringify(response); return new Response(responseStr); }; export const fakeFetch = (serverRoutes) => { return (url, options = {}) => { const body = options.body || ''; const method = options.method || 'GET'; const handlers = serverRoutes[method]; const pathname = parseUrl(url).pathname; const matchesPathname = path => pathMatch()(path)(pathname); const route = Object.keys(handlers).find(matchesPathname); if (!route) { return nativeFetch(url, options); } const handler = handlers[route]; const query = queryString.parse(parseUrl(url).search); const params = matchesPathname(route); return Promise.resolve(fakeResponse(handler({params, query, body}))); }; }; export const reset = () => { window.fetch = nativeFetch; };
import queryString from 'query-string'; import pathMatch from 'path-match'; import parseUrl from 'parse-url'; const nativeFetch = window.fetch; export const fakeFetch = (serverRoutes) => { return (url, options = {}) => { const body = options.body || ''; const method = options.method || 'GET'; const handlers = serverRoutes[method]; const pathname = parseUrl(url).pathname; const matchesPathname = path => pathMatch()(path)(pathname); const route = Object.keys(handlers).find(matchesPathname); if (!route) { return nativeFetch(url, options); } const handler = handlers[route]; const query = queryString.parse(parseUrl(url).search); const params = matchesPathname(route); // @TODO: Wrap 'resolve' result into a Response instance, // check https://github.com/devlucky/Kakapo.js/issues/16 return Promise.resolve(handler({params, query, body})); }; }; export const reset = () => { window.fetch = nativeFetch; };
ListCommand: Remove options, the command does not take options.
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.core.template import TemplateManager class ListCommand(BaseCommand): def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Template command help entry' parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS]'.format(name) ) aliases = ('tmp',) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) def run(self, *args, **options): manger = TemplateManager() manger.list() def get_default_option(self): return []
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.core.template import TemplateManager class TemplateCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", default='default', help='Database router id.', metavar="DATABASE" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Template command help entry' parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS] FILE...'.format(name) ) aliases = ('tmp',) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) def run(self, *args, **options): url = options.get('url') debug = options.get('debug') manger = TemplateManager() manger.list() print "Execute template {0}, {1}".format(url, debug)
Insert data into Images collection
Template.createBetForm.helpers({ photo: function(){ return Session.get("photo"); } }) Template.createBetForm.events({ "submit .create-bet" : function(event){ event.preventDefault(); var title = event.target.betTitle.value, wager = event.target.betWager.value, user = Meteor.user(), username = user.username, defender = event.target.defender.value, type = "new"; if (Meteor.users.find({username: defender}).count() === 0){ throw new Meteor.Error( alert( "Sorry the Username you are trying to challenge is not valid!" ) ); } if (defender === username) { throw new Meteor.Error( alert( "You can't bet yourself!" ) ); } Meteor.call("createBet", username, defender, title, wager); Meteor.call("createBetNotification", username, defender, type); Router.go('/bets'); }, "click .take-photo" : function(event){ event.preventDefault(); var cameraOptions = { width: 700, height: 500 }; MeteorCamera.getPicture(cameraOptions, function(error, data){ Images.insert(data); Session.set("photo", data); }); } });
Template.createBetForm.helpers({ photo: function(){ return Session.get("photo"); } }) Template.createBetForm.events({ "submit .create-bet" : function(event){ event.preventDefault(); var title = event.target.betTitle.value, wager = event.target.betWager.value, user = Meteor.user(), username = user.username, defender = event.target.defender.value, type = "new"; if (Meteor.users.find({username: defender}).count() === 0){ throw new Meteor.Error( alert( "Sorry the Username you are trying to challenge is not valid!" ) ); } if (defender === username) { throw new Meteor.Error( alert( "You can't bet yourself!" ) ); } Meteor.call("createBet", username, defender, title, wager); Meteor.call("createBetNotification", username, defender, type); Router.go('/bets'); }, "click .take-photo" : function(event){ event.preventDefault(); var cameraOptions = { width: 700, height: 500 }; MeteorCamera.getPicture(cameraOptions, function(error, data){ Session.set("photo", data); }); } });
Access code lower-cased on submit.
/** * Emerging Citizens * Developed by Engagement Lab, 2015 * ============== * Game player view controller. * * Help: http://keystonejs.com/docs/getting-started/#routesviews-firstview * * @class game * @static * @author Johnny Richardson * * ========== */ var keystone = require('keystone'); var _ = require('underscore'); var Tweet = keystone.list('Tweet'); var _twitter = keystone.get('twitter'); var GameSession = keystone.list('GameSession'); exports = module.exports = function(req, res) { var view = new keystone.View(req, res); var locals = res.locals; locals.game_not_found = false; // locals.section is used to set the currently selected // item in the header navigation. locals.section = 'player'; view.on('init', function(next) { GameSession.model.findOne({ accessCode: req.params.accesscode.toLowerCase() }, function (err, game) { if(game === null) locals.game_not_found = true; else locals.game = game; next(err); }); }); // Render the view view.render('game/player'); };
/** * Emerging Citizens * Developed by Engagement Lab, 2015 * ============== * Game player view controller. * * Help: http://keystonejs.com/docs/getting-started/#routesviews-firstview * * @class game * @static * @author Johnny Richardson * * ========== */ var keystone = require('keystone'); var _ = require('underscore'); var Tweet = keystone.list('Tweet'); var _twitter = keystone.get('twitter'); var GameSession = keystone.list('GameSession'); exports = module.exports = function(req, res) { var view = new keystone.View(req, res); var locals = res.locals; locals.game_not_found = false; // locals.section is used to set the currently selected // item in the header navigation. locals.section = 'player'; view.on('init', function(next) { GameSession.model.findOne({accessCode: req.params.accesscode}, function (err, game) { if(game === null) locals.game_not_found = true; else locals.game = game; next(err); }); }); // Render the view view.render('game/player'); };
[test] Use new API in `simple/use-load` test
/* * use-test.js: Basic tests for the carapace module * * (C) 2011 Nodejitsu Inc * MIT LICENCE * */ var assert = require('assert'), vows = require('vows'), helper = require('../helper/macros.js'), carapace = require('../../lib/carapace'); vows.describe('carapace/simple/use-plugins').addBatch({ "When using haibu-carapace": { "load up chdir, chroot, heartbeat plugins" : helper.assertUse(['chdir', 'chroot', 'heartbeat'], { "and running the heartbeat plugin" : { topic : function () { carapace.on('heartbeat', this.callback.bind(carapace, null)); carapace.heartbeat(); }, "should see a heartbeat event" : function (_, event, data) { assert.isString(carapace.event); assert.equal(carapace.event, 'heartbeat'); } } }) } }).export(module);
/* * use-test.js: Basic tests for the carapace module * * (C) 2011 Nodejitsu Inc * MIT LICENCE * */ var assert = require('assert'), vows = require('vows'), helper = require('../helper/macros.js'), carapace = require('../../lib/carapace'); var PORT = 5050; vows.describe('carapace/simple/use-plugins').addBatch({ "When using haibu-carapace": helper.assertListen(PORT, { "load up chdir, chroot, heartbeat plugins" : helper.assertUse(['chdir', 'chroot', 'heartbeat'], { "and running the heartbeat plugin" : { topic : function () { carapace.on('carapace::heartbeat', this.callback.bind(carapace, null)); carapace.heartbeat(); }, "should see a carapace::heartbeat event" : function (_, event, data) { assert.isString(carapace.event); assert.equal(carapace.event, 'carapace::heartbeat'); } } }) }) }).export(module);
Fix iDEAL test in demo app
package com.braintreepayments.demo.test; import android.support.test.filters.SdkSuppress; import android.support.test.runner.AndroidJUnit4; import com.braintreepayments.demo.test.utilities.TestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static com.lukekorth.deviceautomator.AutomatorAction.click; import static com.lukekorth.deviceautomator.AutomatorAssertion.text; import static com.lukekorth.deviceautomator.DeviceAutomator.onDevice; import static com.lukekorth.deviceautomator.UiObjectMatcher.withText; import static org.hamcrest.Matchers.containsString; @RunWith(AndroidJUnit4.class) @SdkSuppress(minSdkVersion = 21) public class IdealBrowserSwitchTest extends TestHelper { @Before public void setup() { super.setup(); setMerchantAccountId("ideal_eur"); } @Test(timeout = 60000) public void browserSwitch_createsAnIdealNonce() { onDevice(withText("iDEAL")).waitForEnabled().perform(click()); onDevice(withText("iDEAL")).waitForEnabled().perform(click()); onDevice(withText("bunq")).perform(click()); onDevice(withText("Continue")).perform(click()); getNonceDetails().check(text(containsString("COMPLETE"))); } }
package com.braintreepayments.demo.test; import android.support.test.filters.SdkSuppress; import android.support.test.runner.AndroidJUnit4; import com.braintreepayments.demo.test.utilities.TestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static com.lukekorth.deviceautomator.AutomatorAction.click; import static com.lukekorth.deviceautomator.AutomatorAssertion.text; import static com.lukekorth.deviceautomator.DeviceAutomator.onDevice; import static com.lukekorth.deviceautomator.UiObjectMatcher.withContentDescription; import static com.lukekorth.deviceautomator.UiObjectMatcher.withText; import static org.hamcrest.Matchers.containsString; @RunWith(AndroidJUnit4.class) @SdkSuppress(minSdkVersion = 21) public class IdealBrowserSwitchTest extends TestHelper { @Before public void setup() { super.setup(); setMerchantAccountId("ideal_eur"); } @Test(timeout = 60000) public void browserSwitch_createsAnIdealNonce() { onDevice(withText("iDEAL")).waitForEnabled().perform(click()); onDevice(withText("iDEAL")).waitForEnabled().perform(click()); onDevice(withText("bunq")).perform(click()); onDevice(withContentDescription("Continue")).perform(click()); getNonceDetails().check(text(containsString("COMPLETE"))); } }
Allow to properly disable verification of SSL
"""Python library to enable Axis devices to integrate with Home Assistant.""" import requests from requests.auth import HTTPDigestAuth class Configuration(object): """Device configuration.""" def __init__(self, *, loop, host, username, password, port=80, web_proto='http', verify_ssl=False, event_types=None, signal=None): """All config params available to the device.""" self.loop = loop self.web_proto = web_proto self.host = host self.port = port self.username = username self.password = password self.session = requests.Session() self.session.auth = HTTPDigestAuth(self.username, self.password) self.session.verify = verify_ssl self.event_types = event_types self.signal = signal
"""Python library to enable Axis devices to integrate with Home Assistant.""" import requests from requests.auth import HTTPDigestAuth class Configuration(object): """Device configuration.""" def __init__(self, *, loop, host, username, password, port=80, web_proto='http', verify_ssl=False, event_types=None, signal=None): """All config params available to the device.""" self.loop = loop self.web_proto = web_proto self.host = host self.port = port self.username = username self.password = password self.session = requests.Session() self.session.auth = HTTPDigestAuth( self.username, self.password) if self.web_proto == 'https': self.session.verify_ssl = verify_ssl self.event_types = event_types self.signal = signal
Fix nick search missing from new standardised search function
'use strict' class API { static createQueryFromRequest (request) { let limit = parseInt(request.limit) || 25 delete request.limit let offset = parseInt(request.offset) || 0 delete request.offset let order = parseInt(request.order) || 'createdAt' delete request.order let direction = request.direction || 'ASC' delete request.direction if (request.data) { let dataQuery = request.data delete request.data request.data = { $contains: JSON.parse(dataQuery) } } if (query.nicknames) { query.nicknames = { $contains: [query.nicknames] } } let query = { where: request, limit: limit, offset: offset, order: [ [order, direction] ] } return query } } module.exports = API
'use strict' class API { static createQueryFromRequest (request) { let limit = parseInt(request.limit) || 25 delete request.limit let offset = parseInt(request.offset) || 0 delete request.offset let order = parseInt(request.order) || 'createdAt' delete request.order let direction = request.direction || 'ASC' delete request.direction if (request.data) { let dataQuery = request.data delete request.data request.data = { $contains: JSON.parse(dataQuery) } } let query = { where: request, limit: limit, offset: offset, order: [ [order, direction] ] } return query } } module.exports = API
Emphasize that events fire just once
'use strict'; const EventEmitter = require('events'); const devtools = require('./lib/devtools'); const Chrome = require('./lib/chrome'); module.exports = function (options, callback) { if (typeof options === 'function') { callback = options; options = undefined; } const notifier = new EventEmitter(); if (typeof callback === 'function') { // allow to register the error callback later process.nextTick(function () { new Chrome(options, notifier); }); return notifier.once('connect', callback); } else { return new Promise(function (fulfill, reject) { notifier.once('connect', fulfill); notifier.once('error', reject); new Chrome(options, notifier); }); } }; // for backward compatibility module.exports.listTabs = devtools.List; module.exports.spawnTab = devtools.New; module.exports.closeTab = devtools.Close; module.exports.Protocol = devtools.Protocol; module.exports.List = devtools.List; module.exports.New = devtools.New; module.exports.Activate = devtools.Activate; module.exports.Close = devtools.Close; module.exports.Version = devtools.Version;
'use strict'; const EventEmitter = require('events'); const devtools = require('./lib/devtools'); const Chrome = require('./lib/chrome'); module.exports = function (options, callback) { if (typeof options === 'function') { callback = options; options = undefined; } const notifier = new EventEmitter(); if (typeof callback === 'function') { // allow to register the error callback later process.nextTick(function () { new Chrome(options, notifier); }); return notifier.on('connect', callback); } else { return new Promise(function (fulfill, reject) { notifier.on('connect', fulfill); notifier.on('error', reject); new Chrome(options, notifier); }); } }; // for backward compatibility module.exports.listTabs = devtools.List; module.exports.spawnTab = devtools.New; module.exports.closeTab = devtools.Close; module.exports.Protocol = devtools.Protocol; module.exports.List = devtools.List; module.exports.New = devtools.New; module.exports.Activate = devtools.Activate; module.exports.Close = devtools.Close; module.exports.Version = devtools.Version;
Add a trailing separator to all sents
__author__ = 's7a' # All imports from parser import Parser from breaker import Breaker import re # The Syntactic simplification class class SyntacticSimplifier: # Constructor for the Syntactic Simplifier def __init__(self): self.parser = Parser() self.breaker = Breaker() # Simplify content def simplify(self, content, plot_tree=False): results = [] sentences = re.split('\.|!|\?', content) for sentence in sentences: sentence += "." if sentence == ".": continue parse_trees = self.parser.parse(sentence, plot_tree) for parse_tree in parse_trees: broken_string = self.breaker.break_tree(parse_tree) results.append({ "tree": str(parse_tree), "broken_string": broken_string }) return results
__author__ = 's7a' # All imports from parser import Parser from breaker import Breaker import re # The Syntactic simplification class class SyntacticSimplifier: # Constructor for the Syntactic Simplifier def __init__(self): self.parser = Parser() self.breaker = Breaker() # Simplify content def simplify(self, content, plot_tree=False): results = [] sentences = re.split('\.|!|\?', content) for sentence in sentences: parse_trees = self.parser.parse(sentence, plot_tree) for parse_tree in parse_trees: broken_string = self.breaker.break_tree(parse_tree) results.append({ "tree": str(parse_tree), "broken_string": broken_string }) return results
Add search special status property
<?php namespace MssPhp\Schema\Request; use JMS\Serializer\Annotation\Type; use JMS\Serializer\Annotation\XmlList; class SearchSpecial { /** * @Type("array<integer>") * @XmlList(inline = true, entry="offer_id") */ public $offer_id; /** * @Type("DateTime<'Y-m-d'>") */ public $date_from; /** * @Type("DateTime<'Y-m-d'>") */ public $date_to; /** * @Type("array<integer>") * @XmlList(inline = true, entry="theme") */ public $theme; /** * @Type("array<integer>") * @XmlList(inline = true, entry="poi_id") */ public $poi_id; /** * @Type("array<integer>") * @XmlList(inline = true, entry="poi_cat") */ public $poi_cat; /** * @Type("MssPhp\Schema\Request\Validity") */ public $validity; /** * @Type("integer") */ public $typ; /** * @Type("integer") */ public $premium; /** * @Type("integer") */ public $status; }
<?php namespace MssPhp\Schema\Request; use JMS\Serializer\Annotation\Type; use JMS\Serializer\Annotation\XmlList; class SearchSpecial { /** * @Type("array<integer>") * @XmlList(inline = true, entry="offer_id") */ public $offer_id; /** * @Type("DateTime<'Y-m-d'>") */ public $date_from; /** * @Type("DateTime<'Y-m-d'>") */ public $date_to; /** * @Type("array<integer>") * @XmlList(inline = true, entry="theme") */ public $theme; /** * @Type("array<integer>") * @XmlList(inline = true, entry="poi_id") */ public $poi_id; /** * @Type("array<integer>") * @XmlList(inline = true, entry="poi_cat") */ public $poi_cat; /** * @Type("MssPhp\Schema\Request\Validity") */ public $validity; /** * @Type("integer") */ public $typ; /** * @Type("integer") */ public $premium; }
Update is public access logic
var loopback = require('loopback'), debug = require('debug')('openframe:isPublicOrOwner'); /** * This mixin requires a model to have 'is_public: true' or the current user * to be the object's owner in order to provide access. */ module.exports = function(Model, options) { Model.observe('access', function(reqCtx, next) { var appCtx = loopback.getCurrentContext(), currentUser = appCtx && appCtx.get('currentUser'); debug('currentUser', currentUser); reqCtx.query.where = reqCtx.query.where || {}; if (currentUser && !reqCtx.query.where.is_public) { reqCtx.query.where.or = [ {is_public: true}, {ownerId: currentUser.id} ]; } else { reqCtx.query.where.is_public = true; } next(); }); };
var loopback = require('loopback'), debug = require('debug')('openframe:isPublicOrOwner'); /** * This mixin requires a model to have 'is_public: true' or the current user * to be the object's owner in order to provide access. */ module.exports = function(Model, options) { Model.observe('access', function(reqCtx, next) { var appCtx = loopback.getCurrentContext(), currentUser = appCtx && appCtx.get('currentUser'); debug('currentUser', currentUser); reqCtx.query.where = reqCtx.query.where || {}; if (currentUser) { reqCtx.query.where.or = [ {is_public: true}, {ownerId: currentUser.id} ]; } else { reqCtx.query.where.is_public = true; } next(); }); };
Make sure react-helmet styles are rendered
import React, { Component, PropTypes } from "react"; import Helmet from "react-helmet"; import { BodyAttributes } from "gluestick-shared"; import "assets/css/normalize.css"; /** * The index html will be generated from this file. You can customize things as * you see fit. `body` and `head` will be generated by the server and you * should not remove those or the application will likely stop working. */ export default class Index extends Component { static propTypes = { head: PropTypes.any, body: PropTypes.any }; render () { const { head, body } = this.props; const helmet = Helmet.rewind(); const bodyAttributes = BodyAttributes.rewind(); return ( <html lang="en-us"> <head> {helmet.base.toComponent()} {helmet.title.toComponent()} {helmet.meta.toComponent()} {helmet.link.toComponent()} {helmet.script.toComponent()} {helmet.style.toComponent()} {head /* DO NOT REMOVE */} </head> <body {...bodyAttributes}> {body /* DO NOT REMOVE */} </body> </html> ); } }
import React, { Component, PropTypes } from "react"; import Helmet from "react-helmet"; import { BodyAttributes } from "gluestick-shared"; import "assets/css/normalize.css"; /** * The index html will be generated from this file. You can customize things as * you see fit. `body` and `head` will be generated by the server and you * should not remove those or the application will likely stop working. */ export default class Index extends Component { static propTypes = { head: PropTypes.any, body: PropTypes.any }; render () { const { head, body } = this.props; const helmet = Helmet.rewind(); const bodyAttributes = BodyAttributes.rewind(); return ( <html lang="en-us"> <head> {helmet.base.toComponent()} {helmet.title.toComponent()} {helmet.meta.toComponent()} {helmet.link.toComponent()} {helmet.script.toComponent()} {head /* DO NOT REMOVE */} </head> <body {...bodyAttributes}> {body /* DO NOT REMOVE */} </body> </html> ); } }
Split up Flexbox guide into two parts to avoid running out of WebGL contexts in Chrome (max of 8 per page).
/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others. 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.*/ //Pure JS based composition define.class(function($server$, composition, $ui$, screen, view, label, require){ this.render = function(){ var dynviews = []; for (var digit=0; digit<10; digit++) { for (var w=100; w<=200; w+= 25) { var v1 = view({ size: vec2(w, w) ,bgimage: define.classPath(this) + 'assets/' + digit + '.png' ,bgimagemode:"stretch" }) dynviews.push(v1); } } var views = [ screen({name:'default', clearcolor:'#484230'} ,dynviews) ]; return views } })
/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others. 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.*/ //Pure JS based composition define.class(function($server$, composition, $ui$, screen, view, label, require){ this.render = function(){ var dynviews = []; for (var digit=0; digit<10; digit++) { for (var w=100; w<=200; w+= 25) { var v1 = view({ size: vec2(w, w) ,bgimage: require('./assets/' + digit + '.png') }) dynviews.push(v1); } } var views = [ screen({name:'default', clearcolor:'#484230'} ,dynviews) ]; return views } })
Handle localStorage not being available on page load You won't be able to log in, but you'll at least be able to browse the site! Closes #47
import Ember from 'ember'; export default Ember.Object.extend({ savedTransition: null, isLoggedIn: false, currentUser: null, init: function() { var isLoggedIn; try { isLoggedIn = localStorage.getItem('isLoggedIn') === '1'; } catch (e) { isLoggedIn = false; } this.set('isLoggedIn', isLoggedIn); this.set('currentUser', null); }, loginUser: function(user) { this.set('isLoggedIn', true); this.set('currentUser', user); try { localStorage.setItem('isLoggedIn', '1'); } catch (e) {} }, logoutUser: function() { this.set('savedTransition', null); this.set('isLoggedIn', null); this.set('currentUser', null); try { localStorage.removeItem('isLoggedIn'); } catch (e) {} }, });
import Ember from 'ember'; export default Ember.Object.extend({ savedTransition: null, isLoggedIn: false, currentUser: null, init: function() { this.set('isLoggedIn', localStorage.getItem('isLoggedIn') === '1'); this.set('currentUser', null); }, loginUser: function(user) { this.set('isLoggedIn', true); this.set('currentUser', user); localStorage.setItem('isLoggedIn', '1'); }, logoutUser: function() { this.set('savedTransition', null); this.set('isLoggedIn', null); this.set('currentUser', null); localStorage.removeItem('isLoggedIn'); }, });
Fix value should be given formatted
package de.retest.recheck.ui.descriptors; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; import de.retest.recheck.util.StringSimilarity; @XmlRootElement public class TextAttribute extends StringAttribute { private static final long serialVersionUID = 1L; // Used by JaxB protected TextAttribute() {} public TextAttribute( final String key, final String value ) { this( key, value, null ); } public TextAttribute( final String key, final String value, final String variableName ) { super( key, value, variableName ); } @Override public double match( final Attribute other ) { if ( !(other instanceof TextAttribute) ) { return NO_MATCH; } assert other.getKey().equals( getKey() ); return StringSimilarity.textSimilarity( getValue(), ((StringAttribute) other).getValue() ); } @Override public Attribute applyChanges( final Serializable actual ) { return new TextAttribute( getKey(), (String) actual, getVariableName() ); } @Override public ParameterizedAttribute applyVariableChange( final String variableName ) { return new TextAttribute( getKey(), getValue(), variableName ); } }
package de.retest.recheck.ui.descriptors; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; import de.retest.recheck.util.StringSimilarity; @XmlRootElement public class TextAttribute extends StringAttribute { private static final long serialVersionUID = 1L; // Used by JaxB protected TextAttribute() {} public TextAttribute( final String key, final String value ) { this( key, value, null ); } public TextAttribute( final String key, final String value, final String variableName ) { super( key, value != null ? value.trim() : null, variableName ); } @Override public double match( final Attribute other ) { if ( !(other instanceof TextAttribute) ) { return NO_MATCH; } assert other.getKey().equals( getKey() ); return StringSimilarity.textSimilarity( getValue(), ((StringAttribute) other).getValue() ); } @Override public Attribute applyChanges( final Serializable actual ) { return new TextAttribute( getKey(), (String) actual, getVariableName() ); } @Override public ParameterizedAttribute applyVariableChange( final String variableName ) { return new TextAttribute( getKey(), getValue(), variableName ); } }
site: Copy site into releases folder
const gulp = require('gulp') const runSequence = require('run-sequence') const harp = require('harp') const webpackStream = require('webpack-stream') const del = require('del') const config = require('./config') gulp.task('clean', () => { return del(['./www']) }) gulp.task('webpack:prod', () => { return gulp.src('./site/public/_js/script.js') .pipe(webpackStream(config.webpack.prod)) .pipe(gulp.dest('site/')) }) gulp.task('harp:compile', done => { harp.compile('./site', '../www', done) }) gulp.task('copy:site', done => { return gulp.src(['./www/**/*']) .pipe(gulp.dest('./releases')) }) gulp.task('build', done => { runSequence( ['clean', 'dist'], 'webpack:prod', 'harp:compile', 'copy:site', 'clean', done ) })
const gulp = require('gulp') const runSequence = require('run-sequence') const harp = require('harp') const webpackStream = require('webpack-stream') const del = require('del') const config = require('./config') gulp.task('clean', () => { return del(['./www']) }) gulp.task('webpack:prod', () => { return gulp.src('./site/public/_js/script.js') .pipe(webpackStream(config.webpack.prod)) .pipe(gulp.dest('site/')) }) gulp.task('harp:compile', done => { harp.compile('./site', '../www', done) }) gulp.task('build', done => { runSequence( ['clean', 'dist'], 'webpack:prod', 'harp:compile', done ) })
Fix the CoffeeScript and TOML dependency injection
/** * Gray Matter * Copyright (c) 2014 Jon Schlinkert, Brian Woodward, contributors. * Licensed under the MIT license. */ 'use strict'; // node_modules var YAML = require('js-yaml'), coffee, toml; // The module to export var parse = module.exports = {}; parse.yaml = function(src) { return YAML.load(src); }; parse.json = function(src) { return JSON.parse(src); }; parse.coffee = function(src, options) { options = options || {}; if (!coffee) { coffee = require('coffee-script'); } try { return coffee['eval'](src, options); } catch (e) { console.warn('Could not parse coffee-script:', e); } }; parse.toml = function(src) { if (!toml) { toml = require('toml'); } try { return toml.parse(src.trim()); } catch (e) { console.warn('Count not parse toml:' + src, e); } };
/** * Gray Matter * Copyright (c) 2014 Jon Schlinkert, Brian Woodward, contributors. * Licensed under the MIT license. */ 'use strict'; // node_modules var YAML = require('js-yaml'); var coffee = require('coffee-script'); var toml = require('toml'); // The module to export var parse = module.exports = {}; parse.yaml = function(src) { return YAML.load(src); }; parse.json = function(src) { return JSON.parse(src); }; parse.coffee = function(src, options) { options = options || {}; try { return coffee['eval'](src, options); } catch (e) { console.warn('Could not parse coffee-script:', e); } }; parse.toml = function(src) { try { return toml.parse(src.trim()); } catch (e) { console.warn('Count not parse toml:' + src, e); } };
Change particle restart test to check for output on stderr rather than checking the return status.
#!/usr/bin/env python import os from subprocess import Popen, STDOUT, PIPE pwd = os.path.dirname(__file__) def setup(): os.putenv('PWD', pwd) os.chdir(pwd) def test_run(): proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE) stdout, stderr = proc.communicate() assert stderr != '' def test_created_restart(): assert os.path.exists(pwd + '/particle_0.binary') def test_run_restart(): proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'], stderr=PIPE, stdout=PIPE, shell=True) stdout, stderr = proc.communicate() assert stderr != '' def teardown(): output = [pwd + '/particle_0.binary'] for f in output: if os.path.exists(f): os.remove(f)
#!/usr/bin/env python import os from subprocess import Popen, STDOUT, PIPE pwd = os.path.dirname(__file__) def setup(): os.putenv('PWD', pwd) os.chdir(pwd) def test_run(): proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE) returncode = proc.wait() print(proc.communicate()[0]) assert returncode != 0 def test_run_restart(): proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'], stderr=STDOUT, stdout=PIPE) returncode = proc.wait() print(proc.communicate()[0]) assert returncode != 0 def test_created_restart(): assert os.path.exists(pwd + '/particle_0.binary') def teardown(): output = [pwd + '/particle_0.binary'] for f in output: if os.path.exists(f): os.remove(f)
Fix problems to update image of publication
<?php require_once __DIR__ . "/../class/autoload.php"; use \html\Page as Page; use \html\AdministratorMenu as AdministratorMenu; use \html\Forms as Forms; use \configuration\Globals as Globals; use \utilities\Session as Session; Page::startHeader("Editar Página"); Page::styleSheet("user"); Page::styleSheet("form"); echo "<script src=\"../css/ckeditor/ckeditor.js\"></script>"; Page::closeHeader(); $session = new Session(); $session->verifyIfSessionIsStarted(); $menu = new AdministratorMenu(); $menu->construct(); ?> <!--Conteúdo da página--> <div id="update"></div> <main style="text-align: left;"> <h1>Edição de Página </h1> <form action="<?php echo PROJECT_ROOT;?>controller/updatePage.php" method="POST" enctype="multipart/form-data"> <fieldset> <?php Forms::updatePageForm($_GET['pages']); ?> </fieldset> <input type="hidden" value="<?php echo $_GET['pages']?>" id="page_code"> <input type="submit" value="Atualizar"> </form> </main> <?php Page::footer(); Page::closeBody(); ?>
<?php require_once __DIR__ . "/../class/autoload.php"; use \html\Page as Page; use \html\AdministratorMenu as AdministratorMenu; use \html\Forms as Forms; use \configuration\Globals as Globals; use \utilities\Session as Session; Page::startHeader("Editar Página"); Page::styleSheet("user"); Page::styleSheet("form"); echo "<script src=\"../css/ckeditor/ckeditor.js\"></script>"; Page::closeHeader(); $session = new Session(); $session->verifyIfSessionIsStarted(); $menu = new AdministratorMenu(); $menu->construct(); ?> <!--Conteúdo da página--> <div id="update"></div> <main style="text-align: left;"> <h1>Edição de Página </h1> <form action="<?php echo PROJECT_ROOT;?>controller/updatePage.php" method="POST"> <fieldset> <?php Forms::updatePageForm($_GET['pages']); ?> </fieldset> <input type="hidden" value="<?php echo $_GET['pages']?>" id="page_code"> <input type="submit" value="Atualizar"> </form> </main> <?php Page::footer(); Page::closeBody(); ?>
Fix detection of QUnit version in QUnitAdapter.
import { inspect } from 'ember-utils'; import Adapter from './adapter'; /** This class implements the methods defined by Ember.Test.Adapter for the QUnit testing framework. @class QUnitAdapter @namespace Ember.Test @extends Ember.Test.Adapter @public */ export default Adapter.extend({ init() { this.doneCallbacks = []; }, asyncStart() { if (typeof QUnit.stop === 'function') { // very old QUnit version QUnit.stop(); } else { this.doneCallbacks.push(QUnit.config.current ? QUnit.config.current.assert.async() : null); } }, asyncEnd() { // checking for QUnit.stop here (even though we _need_ QUnit.start) because // QUnit.start() still exists in QUnit 2.x (it just throws an error when calling // inside a test context) if (typeof QUnit.stop === 'function') { QUnit.start(); } else { let done = this.doneCallbacks.pop(); // This can be null if asyncStart() was called outside of a test if (done) { done(); } } }, exception(error) { QUnit.config.current.assert.ok(false, inspect(error)); } });
import { inspect } from 'ember-utils'; import Adapter from './adapter'; /** This class implements the methods defined by Ember.Test.Adapter for the QUnit testing framework. @class QUnitAdapter @namespace Ember.Test @extends Ember.Test.Adapter @public */ export default Adapter.extend({ init() { this.doneCallbacks = []; }, asyncStart() { if (typeof QUnit.stop === 'function') { // very old QUnit version QUnit.stop(); } else { this.doneCallbacks.push(QUnit.config.current ? QUnit.config.current.assert.async() : null); } }, asyncEnd() { if (typeof QUnit.start === 'function') { QUnit.start(); } else { let done = this.doneCallbacks.pop(); // This can be null if asyncStart() was called outside of a test if (done) { done(); } } }, exception(error) { QUnit.config.current.assert.ok(false, inspect(error)); } });
fix: Add missing Cost Center filter in cash flow statement
// Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.require("assets/erpnext/js/financial_statements.js", function() { frappe.query_reports["Cash Flow"] = $.extend({}, erpnext.financial_statements); // The last item in the array is the definition for Presentation Currency // filter. It won't be used in cash flow for now so we pop it. Please take // of this if you are working here. frappe.query_reports["Cash Flow"]["filters"].splice(5, 1); frappe.query_reports["Cash Flow"]["filters"].push( { "fieldname": "accumulated_values", "label": __("Accumulated Values"), "fieldtype": "Check" }, { "fieldname": "include_default_book_entries", "label": __("Include Default Book Entries"), "fieldtype": "Check" } ); });
// Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.require("assets/erpnext/js/financial_statements.js", function() { frappe.query_reports["Cash Flow"] = $.extend({}, erpnext.financial_statements); // The last item in the array is the definition for Presentation Currency // filter. It won't be used in cash flow for now so we pop it. Please take // of this if you are working here. frappe.query_reports["Cash Flow"]["filters"].pop(); frappe.query_reports["Cash Flow"]["filters"].push({ "fieldname": "accumulated_values", "label": __("Accumulated Values"), "fieldtype": "Check" }); frappe.query_reports["Cash Flow"]["filters"].push({ "fieldname": "include_default_book_entries", "label": __("Include Default Book Entries"), "fieldtype": "Check" }); });
Update e2e tests in relation to latest ui changes
var utils = require('./utils.js'); describe('admin add users', function() { it('should add new users', function(done) { browser.setLocation('admin/users'); var add_user = function(role, roleSelector, name, address) { return protractor.promise.controlFlow().execute(function() { var deferred = protractor.promise.defer(); element(by.model('new_user.name')).sendKeys(name); element(by.model('new_user.email')).sendKeys(address); element(by.model('new_user.role')).element(by.xpath(".//*[text()='" + roleSelector + "']")).click(); element(by.css('[data-ng-click="add_user()"]')).click().then(function() { utils.waitUntilReady(element(by.xpath(".//*[text()='" + name + "']"))); deferred.fulfill(); }); return deferred.promise; }); }; add_user("receiver", "Recipient", "Recipient 2", "globaleaks-receiver2@mailinator.com"); add_user("receiver", "Recipient", "Recipient 3", "globaleaks-receiver3@mailinator.com"); add_user("custodian", "Custodian", "Custodian 1", "globaleaks-custodian1@mailinator.com"); done(); }); });
var utils = require('./utils.js'); describe('admin add users', function() { it('should add new users', function(done) { browser.setLocation('admin/users'); var add_user = function(username, role, roleSelector, name, address) { return protractor.promise.controlFlow().execute(function() { var deferred = protractor.promise.defer(); element(by.model('new_user.username')).sendKeys(username); element(by.model('new_user.name')).sendKeys(name); element(by.model('new_user.email')).sendKeys(address); element(by.model('new_user.role')).element(by.xpath(".//*[text()='" + roleSelector + "']")).click(); element(by.css('[data-ng-click="add_user()"]')).click().then(function() { utils.waitUntilReady(element(by.xpath(".//*[text()='" + name + "']"))); deferred.fulfill(); }); return deferred.promise; }); }; add_user("receiver2", "receiver", "Recipient", "Recipient 2", "globaleaks-receiver2@mailinator.com"); add_user("receiver3", "receiver", "Recipient", "Recipient 3", "globaleaks-receiver3@mailinator.com"); add_user("custodian1", "custodian", "Custodian", "Custodian 1", "globaleaks-custodian1@mailinator.com"); done(); }); });
Send a hostkeys-00@openssh.com request if the client is an OpenSSH version and we're pretenting to be one too
package main import ( "log" "net" "strings" "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" ) func handleConnection(conn net.Conn, sshServerConfig *ssh.ServerConfig) { defer conn.Close() defer logrus.WithField("remote_address", conn.RemoteAddr().String()).Infoln("Connection closed") serverConn, newChannels, requests, err := ssh.NewServerConn(conn, sshServerConfig) if err != nil { log.Println("Failed to establish SSH connection:", err) return } getLogEntry(serverConn).Infoln("SSH connection established") defer getLogEntry(serverConn).Infoln("SSH connection closed") if strings.HasPrefix(string(serverConn.ClientVersion()), "SSH-2.0-OpenSSH") && strings.HasPrefix(string(serverConn.ServerVersion()), "SSH-2.0-OpenSSH") { serverConn.SendRequest("hostkeys-00@openssh.com", false, ssh.Marshal(struct{ hostKeys []string }{})) } go handleGlobalRequests(requests, serverConn) channelID := 0 for newChannel := range newChannels { go handleNewChannel(newChannel, channelMetadata{conn: serverConn, channelID: channelID}) channelID++ } }
package main import ( "log" "net" "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" ) func handleConnection(conn net.Conn, sshServerConfig *ssh.ServerConfig) { defer conn.Close() defer logrus.WithField("remote_address", conn.RemoteAddr().String()).Infoln("Connection closed") serverConn, newChannels, requests, err := ssh.NewServerConn(conn, sshServerConfig) if err != nil { log.Println("Failed to establish SSH connection:", err) return } getLogEntry(serverConn).Infoln("SSH connection established") defer getLogEntry(serverConn).Infoln("SSH connection closed") go handleGlobalRequests(requests, serverConn) channelID := 0 for newChannel := range newChannels { go handleNewChannel(newChannel, channelMetadata{conn: serverConn, channelID: channelID}) channelID++ } }
Rename findByDomainId's parameter to match new function name
<?php namespace Nord\Lumen\Core\Infrastructure; use Doctrine\ORM\EntityRepository as BaseRepository; use Nord\Lumen\Core\Domain\Model\Entity; class EntityRepository extends BaseRepository { /** * @param string $domainId * * @return Entity|null */ public function findByDomainId($domainId) { return $this->findOneBy(['domainId' => $domainId]); } /** * @param $domainId * * @return int */ public function domainIdExists($domainId) { return (int) $this->createQueryBuilder('t') ->select('COUNT(t.domainId)') ->where('t.domainId = :domainId') ->setParameter('domainId', $domainId) ->getQuery() ->getSingleScalarResult(); } }
<?php namespace Nord\Lumen\Core\Infrastructure; use Doctrine\ORM\EntityRepository as BaseRepository; use Nord\Lumen\Core\Domain\Model\Entity; class EntityRepository extends BaseRepository { /** * @param string $objectId * * @return Entity|null */ public function findByDomainId($objectId) { return $this->findOneBy(['objectId' => $objectId]); } /** * @param $domainId * * @return int */ public function domainIdExists($domainId) { return (int) $this->createQueryBuilder('t') ->select('COUNT(t.domainId)') ->where('t.domainId = :domainId') ->setParameter('domainId', $domainId) ->getQuery() ->getSingleScalarResult(); } }
Create new method object generate get riak bucket and generate tuple or list
#!/usr/bin/env python # -*- coding: utf-8 -*- import riak from wtforms.fields import TextField, TextAreaField, SelectField from wtforms.validators import Required from wtforms_tornado import Form def ObjGenerate(bucket, key, value=None, _type=tuple): myClient = riak.RiakClient(protocol='http', http_port=8098, host='127.0.0.1') myBucket = myClient.bucket('openmining-admin') bconnection = myBucket.get(bucket).data try: if _type is tuple: return _type([(c[key], c[value]) for c in bconnection]) return _type(c[key] for c in bconnection) except: return _type() class ConnectionForm(Form): name = TextField(validators=[Required()]) conection = TextField(validators=[Required()]) class CubeForm(Form): name = TextField(validators=[Required()]) conection = SelectField(choices=ObjGenerate('connection', 'slug', 'name'), validators=[Required()]) sql = TextAreaField(validators=[Required()])
#!/usr/bin/env python # -*- coding: utf-8 -*- import riak from wtforms.fields import TextField, TextAreaField, SelectField from wtforms.validators import Required from wtforms_tornado import Form class ConnectionForm(Form): name = TextField(validators=[Required()]) conection = TextField(validators=[Required()]) class CubeForm(Form): myClient = riak.RiakClient(protocol='http', http_port=8098, host='127.0.0.1') myBucket = myClient.bucket('openmining-admin') bconnection = myBucket.get('connection').data try: CONNECTION = tuple([(c['slug'], c['name']) for c in bconnection]) except: CONNECTION = tuple() name = TextField(validators=[Required()]) conection = SelectField(choices=CONNECTION, validators=[Required()]) sql = TextAreaField(validators=[Required()])
Check to see if user already exists for email
<?php require_once('../includes/config.php'); $errors = array(); $data = array(); if(isset($_POST['_csrf']) && session_csrf_check($_POST['_csrf'])) { $recaptcha = new \ReCaptcha\ReCaptcha($config['captcha']['priv'], new \ReCaptcha\RequestMethod\CurlPost()); $resp = $recaptcha->verify($_POST['g-recaptcha-response']); if ($resp->isSuccess()) { if((isset($_POST['email']) && !empty($_POST['email']) && get_user_id($_POST['email']) == FALSE) && (isset($_POST['password']) && !empty($_POST['password']))) { global $pdo; $email = $_POST['email']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); reset_user_password($email, $password); $data['success'] = true; $data['message'] = 'Success!'; } else { $errors['name'] = 'Email or password is invalid.'; } } else { $errors['captcha'] = 'Captcha is invalid.'; } } else { $errors['req'] = 'Request is invalid.'; } if(!empty($errors)) { $data['success'] = false; $data['errors'] = $errors; } echo json_encode($data);
<?php require_once('../includes/config.php'); $errors = array(); $data = array(); if(isset($_POST['_csrf']) && session_csrf_check($_POST['_csrf'])) { $recaptcha = new \ReCaptcha\ReCaptcha($config['captcha']['priv'], new \ReCaptcha\RequestMethod\CurlPost()); $resp = $recaptcha->verify($_POST['g-recaptcha-response']); if ($resp->isSuccess()) { if((isset($_POST['email']) && !empty($_POST['email'])) && (isset($_POST['password']) && !empty($_POST['password']))) { global $pdo; $email = $_POST['email']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); reset_user_password($email, $password); $data['success'] = true; $data['message'] = 'Success!'; } else { $errors['name'] = 'Email or password is invalid.'; } } else { $errors['captcha'] = 'Captcha is invalid.'; } } else { $errors['req'] = 'Request is invalid.'; } if(!empty($errors)) { $data['success'] = false; $data['errors'] = $errors; } echo json_encode($data);
Fix bug when resizing terminal
// +build !windows package gottyclient import ( "encoding/json" "fmt" "golang.org/x/sys/unix" "os" "os/signal" "syscall" ) func notifySignalSIGWINCH(c chan<- os.Signal) { signal.Notify(c, syscall.SIGWINCH) } func resetSignalSIGWINCH() { signal.Reset(syscall.SIGWINCH) } func syscallTIOCGWINSZ() ([]byte, error) { ws, err := unix.IoctlGetWinsize(0, 0) if err != nil { return nil, fmt.Errorf("ioctl error: %v", err) } tws := winsize{Rows: ws.Row, Columns: ws.Col} b, err := json.Marshal(tws) if err != nil { return nil, fmt.Errorf("json.Marshal error: %v", err) } return b, err }
// +build !windows package gottyclient import ( "encoding/json" "fmt" "golang.org/x/sys/unix" "os" "os/signal" "syscall" ) func notifySignalSIGWINCH(c chan<- os.Signal) { signal.Notify(c, syscall.SIGWINCH) } func resetSignalSIGWINCH() { signal.Reset(syscall.SIGWINCH) } func syscallTIOCGWINSZ() ([]byte, error) { ws, err := unix.IoctlGetWinsize(0, 0) if err != nil { return nil, fmt.Errorf("ioctl error: %v", err) } b, err := json.Marshal(ws) if err != nil { return nil, fmt.Errorf("json.Marshal error: %v", err) } return b, err }
Update store to use new Vuex plugins. Overall this feels like a much cleaner approach.
import Vue from 'vue'; import Vuex from 'vuex'; import undoRedo from '../plugins/undo-redo'; import shareMutations from '../plugins/share-mutations'; import shareDevTools from '../plugins/share-devtools'; import page from './modules/page'; import definition from './modules/definition'; import Config from 'classes/Config'; /* global process */ Vue.use(Vuex); let store = new Vuex.Store({ state: { over: { x: 0, y: 0 }, preview: { visible: false, url: '' }, wrapperStyles: {}, showIframeOverlay: false }, getters: {}, mutations: { updateOver(state, position) { state.over = position; }, changePreview(state, value) { state.preview = value; }, updateWrapperStyle(state, { prop, value }) { state.wrapperStyles = { ...state.wrapperStyles, [prop]: value }; }, showIframeOverlay(state, yes) { state.showIframeOverlay = yes; } }, actions: {}, modules: { page, definition }, plugins: [ shareMutations, undoRedo, ...(Config.get('debug', false) ? [shareDevTools] : []) ], strict: process.env.NODE_ENV !== 'production' }); export default store;
import Vue from 'vue'; import Vuex from 'vuex'; import undoRedo from '../plugins/undo-redo'; import page from './modules/page'; import definition from './modules/definition'; /* global window */ Vue.use(Vuex); const store = ( window.self === window.top ? { state: { over: { x: 0, y: 0 }, preview: { visible: false, url: '' }, wrapperStyles: {}, showIframeOverlay: false }, getters: {}, mutations: { updateOver(state, position) { state.over = position; }, changePreview(state, value) { state.preview = value; }, updateWrapperStyle(state, { prop, value }) { state.wrapperStyles = { ...state.wrapperStyles, [prop]: value }; }, showIframeOverlay(state, yes) { state.showIframeOverlay = yes; } }, actions: {}, modules: { page, definition }, plugins: [undoRedo] } : window.top.store ); window.store = store; export default new Vuex.Store(store);
Rebuild the query every time it's needed so that preseeded results display
var environment = require('../environment'), offload = require('../../graphworker/standalone'); module.exports.search = function (options, recordcb, facetcb) { if (typeof options.query !== 'undefined') { options.query.plan = environment.querybuilder.build(options.query.ast); options.query.offset = options.offset; options.query.size = options.perpage; } offload('search', options, function (results) { recordcb(results.search); }); if (typeof facetcb === 'function') { offload('facet', options, function (results) { facetcb(results.facet); }); } }; module.exports.facet = function (options, facetcb) { if (typeof options.query !== 'undefined') { options.query.plan = environment.querybuilder.build(options.query.ast); } offload('facet', options, function (results) { facetcb(results.facet); }); };
var environment = require('../environment'), offload = require('../../graphworker/standalone'); module.exports.search = function (options, recordcb, facetcb) { if (typeof options.query !== 'undefined') { if (typeof options.query.plan === 'undefined') { options.query.plan = environment.querybuilder.build(options.query.ast); } options.query.offset = options.offset; options.query.size = options.perpage; } offload('search', options, function (results) { recordcb(results.search); }); if (typeof facetcb === 'function') { offload('facet', options, function (results) { facetcb(results.facet); }); } }; module.exports.facet = function (options, facetcb) { if (typeof options.query !== 'undefined' && typeof options.query.plan === 'undefined') { options.query.plan = environment.querybuilder.build(options.query.ast); } offload('facet', options, function (results) { facetcb(results.facet); }); };
Add test for Brazilian states count
<?php use Galahad\LaravelAddressing\AdministrativeAreaCollection; use Galahad\LaravelAddressing\Country; /** * Class AdministrativeAreaCollectionTest * * @author Junior Grossi <juniorgro@gmail.com> */ class AdministrativeAreaCollectionTest extends PHPUnit_Framework_TestCase { public function testCollectionClass() { $country = new Country; $brazil = $country->getByCode('BR'); $states = $brazil->getAdministrativeAreas(); $this->assertInstanceOf(AdministrativeAreaCollection::class, $states); } public function testUSStatesCount() { $country = new Country; $us = $country->getByCode('US'); $states = $us->getAdministrativeAreas(); $this->assertEquals($states->count(), 62); } public function testBrazilianStatesCount() { $country = new Country; $brazil = $country->getByName('Brazil'); $states = $brazil->getAdministrativeAreas(); $this->assertEquals($states->count(), 27); } }
<?php use Galahad\LaravelAddressing\AdministrativeAreaCollection; use Galahad\LaravelAddressing\Country; /** * Class AdministrativeAreaCollectionTest * * @author Junior Grossi <juniorgro@gmail.com> */ class AdministrativeAreaCollectionTest extends PHPUnit_Framework_TestCase { public function testCollectionClass() { $country = new Country; $brazil = $country->getByCode('BR'); $states = $brazil->getAdministrativeAreas(); $this->assertInstanceOf(AdministrativeAreaCollection::class, $states); } public function testUSStatesCount() { $country = new Country; $us = $country->getByCode('US'); $states = $us->getAdministrativeAreas(); $this->assertEquals($states->count(), 62); } }
Add dataset upload_to attribute. Fix DateTimeField name.
from django.db import models from django.contrib.auth.models import User class DatasetLicence(models.Model): title = models.CharField(max_length=255) short_title = models.CharField(max_length=30) url = models.URLField() summary = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class FileFormat(models.Model): extension = models.CharField(max_length=10) description = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def get_dataset_upload_path(self, instance, filename): return '/%s/' % instance.author.username class Dataset(models.Model): title = models.CharField(max_length=255) licence = models.ForeignKey('DatasetLicence') file = models.FileField(upload_to=get_dataset_upload_path) file_format = models.ForeignKey('FileFormat') description = models.TextField() author = models.ForeignKey(User) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True)
from django.db import models from django.contrib.auth.models import User class DatasetLicence(models.Model): title = models.CharField(max_length=255) short_title = models.CharField(max_length=30) url = models.URLField() summary = models.TextField() updated = models.DatetimeField(auto_now=True) created = models.DatetimeField(auto_now_add=True) class FileFormat(models.Model): extension = models.CharField(max_length=10) description = models.TextField() updated = models.DatetimeField(auto_now=True) created = models.DatetimeField(auto_now_add=True) class Dataset(models.Model): title = models.CharField(max_length=255) licence = models.ForeignKey('DatasetLicence') file = models.FileField() file_format = models.ForeignKey('FileFormat') description = models.TextField() author = models.ForeignKey(User) updated = models.DatetimeField(auto_now=True) created = models.DatetimeField(auto_now_add=True)
Add route for getting books
import React, { Component } from 'react'; import { Router, Route, Switch } from 'react-router-dom'; import { hot } from 'react-hot-loader'; import SignUpPage from './SignUp/SignUpPage'; import LoginPage from './Login/LoginPage'; import IndexPage from './Index'; import Books from './Books'; class App extends Component { render() { return ( <Router history = { this.props.history }> <Switch> <Route exact path = '/signup' component = { SignUpPage } /> <Route exact path = '/login' component = { LoginPage } /> <Route exact path = '/' component = { IndexPage } /> <Route path = '/books' component = { Books } /> </Switch> </Router> ); } } export default hot(module)(App);
import React, { Component } from 'react'; import { Router, Route, Switch } from 'react-router-dom'; import { hot } from 'react-hot-loader'; import SignUpPage from './SignUp/SignUpPage'; import LoginPage from './Login/LoginPage'; import IndexPage from './Index'; class App extends Component { render() { return ( <Router history = { this.props.history }> <Switch> <Route path = '/signup' component = { SignUpPage } /> <Route path = '/login' component = { LoginPage } /> <Route path = '/' component = { IndexPage } /> </Switch> </Router> ); } } export default hot(module)(App);
karma-mocha: Increase the timeout to 10s in an attempt to avoid random failures
module.exports = function(config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/es5-shim.js', 'vendor/es5-sham.js', 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js' ], browsers: ['ChromeHeadlessNoSandbox', 'ie11'], client: { mocha: { reporter: 'html', timeout: 10000 } }, browserStack: { video: false, project: 'unexpected' }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] }, ie11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7' } }, reporters: ['dots', 'BrowserStack'] }); };
module.exports = function(config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/es5-shim.js', 'vendor/es5-sham.js', 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js' ], browsers: ['ChromeHeadlessNoSandbox', 'ie11'], client: { mocha: { reporter: 'html' } }, browserStack: { video: false, project: 'unexpected' }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] }, ie11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7' } }, reporters: ['dots', 'BrowserStack'] }); };
Allow Curve25519DH import to fail in crypto package With the refactoring to avoid pylint warnings, a problem was introduced in importing the crypto module when the curve25519 dependencies were unavailable. This commit fixes that problem.
# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Ron Frederick - initial implementation, API, and documentation """A shim for accessing cryptographic primitives needed by asyncssh""" import importlib from .cipher import register_cipher, lookup_cipher try: from .curve25519 import Curve25519DH except ImportError: pass from . import chacha pyca_available = importlib.find_loader('cryptography') pycrypto_available = importlib.find_loader('Crypto') if pyca_available: from . import pyca if pycrypto_available: from . import pycrypto if pyca_available: from .pyca.dsa import DSAPrivateKey, DSAPublicKey from .pyca.rsa import RSAPrivateKey, RSAPublicKey elif pycrypto_available: from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey else: raise ImportError('No suitable crypto library found.')
# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Ron Frederick - initial implementation, API, and documentation """A shim for accessing cryptographic primitives needed by asyncssh""" import importlib from .cipher import register_cipher, lookup_cipher from .curve25519 import Curve25519DH from . import chacha pyca_available = importlib.find_loader('cryptography') pycrypto_available = importlib.find_loader('Crypto') if pyca_available: from . import pyca if pycrypto_available: from . import pycrypto if pyca_available: from .pyca.dsa import DSAPrivateKey, DSAPublicKey from .pyca.rsa import RSAPrivateKey, RSAPublicKey elif pycrypto_available: from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey else: raise ImportError('No suitable crypto library found.')
Use a private RNG for guids. Avoids potential for trouble w/ the global instance.
""" Utility functions """ import random import time from . import constants guid_rng = random.Random() # Uses urandom seed def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://' return ''.join([protocol, host, ':', str(port), '/_rpc/v1/reports/binary']) def _generate_guid(): """ Construct a guid - random 64 bit integer converted to a string. """ return str(guid_rng.getrandbits(64)) def _now_micros(): """ Get the current time in microseconds since the epoch. """ return _time_to_micros(time.time()) def _time_to_micros(t): """ Convert a time.time()-style timestamp to microseconds. """ return long(round(t * constants.SECONDS_TO_MICRO)) def _merge_dicts(*dict_args): """Destructively merges dictionaries, returns None instead of an empty dictionary. Elements of dict_args can be None. Keys in latter dicts override those in earlier ones. """ result = {} for dictionary in dict_args: if dictionary: result.update(dictionary) return result if result else None
""" Utility functions """ import random import time from . import constants def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://' return ''.join([protocol, host, ':', str(port), '/_rpc/v1/reports/binary']) def _generate_guid(): """ Construct a guid - random 64 bit integer converted to a string. """ return str(random.getrandbits(64)) def _now_micros(): """ Get the current time in microseconds since the epoch. """ return _time_to_micros(time.time()) def _time_to_micros(t): """ Convert a time.time()-style timestamp to microseconds. """ return long(round(t * constants.SECONDS_TO_MICRO)) def _merge_dicts(*dict_args): """Destructively merges dictionaries, returns None instead of an empty dictionary. Elements of dict_args can be None. Keys in latter dicts override those in earlier ones. """ result = {} for dictionary in dict_args: if dictionary: result.update(dictionary) return result if result else None
Fix 'Do not access attributes directly.' error on Activity
var SharedModelMethods = require('mixins/shared_model_methods'); var Activity = module.exports = Backbone.Model.extend({ name: 'activity', i18nScope: 'activerecord.attributes.', timestampFormat: 'd mmm yyyy', initialize: function(args) { var data = args.activity; this.i18nScope += data.subject_type.toLowerCase(); this.set({ date: new Date(data.updated_at).format(this.timestampFormat), action: this.humanActionName(data.action), subject_changes: this.parseChanges(data.subject_changes) }); }, humanActionName: function(action) { return I18n.t(action, {scope: 'activity.actions'}); }, parseChanges: function(changes) { return _.map(changes, function(value, key) { if (key == 'documents_attributes') key = 'documents'; return { attribute: this.humanAttributeName(key), oldValue: value[0], newValue: value[1] } }, this); } }); _.defaults(Activity.prototype, SharedModelMethods);
var SharedModelMethods = require('mixins/shared_model_methods'); var Activity = module.exports = Backbone.Model.extend({ name: 'activity', i18nScope: 'activerecord.attributes.', timestampFormat: 'd mmm yyyy', initialize: function(args) { var attributes = this.attributes; var data = args.activity; this.i18nScope += data.subject_type.toLowerCase(); attributes.date = new Date(data.updated_at).format(this.timestampFormat); attributes.action = this.humanActionName(data.action); attributes.subject_changes = this.parseChanges(data.subject_changes); }, humanActionName: function(action) { return I18n.t(action, {scope: 'activity.actions'}); }, parseChanges: function(changes) { return _.map(changes, function(value, key) { if (key == 'documents_attributes') key = 'documents'; return { attribute: this.humanAttributeName(key), oldValue: value[0], newValue: value[1] } }, this); } }); _.defaults(Activity.prototype, SharedModelMethods);
Test arities of 0 properly.
/* global describe it */ /* * Ensure that storage providers are complete and consistent. */ var chai = require('chai'); var dirtyChai = require('dirty-chai'); chai.use(dirtyChai); var expect = chai.expect; var delegates = require('../src/storage').delegates; var MemoryStorage = require('../src/storage/memory').MemoryStorage; var RemoteStorage = require('../src/storage/remote').RemoteStorage; var arities = {}; function ensureComplete (backend) { return function () { var instance = new backend(); var makeDelegateTester = function (delegate) { return function () { expect(instance[delegate]).to.be.an.instanceOf(Function); if (arities[delegate] !== undefined) { expect(instance[delegate].length).to.equal(arities[delegate]); } else { arities[delegate] = instance[delegate].length; } }; }; delegates.forEach(function (delegate) { it("implements the " + delegate + " method", makeDelegateTester(delegate)); }); }; } describe('the Memory storage backend', ensureComplete(MemoryStorage)); describe('the Remote storage backend', ensureComplete(RemoteStorage));
/* global describe it */ /* * Ensure that storage providers are complete and consistent. */ var chai = require('chai'); var dirtyChai = require('dirty-chai'); chai.use(dirtyChai); var expect = chai.expect; var delegates = require('../src/storage').delegates; var MemoryStorage = require('../src/storage/memory').MemoryStorage; var RemoteStorage = require('../src/storage/remote').RemoteStorage; var arities = {}; function ensureComplete (backend) { return function () { var instance = new backend(); var makeDelegateTester = function (delegate) { return function () { expect(instance[delegate]).to.be.an.instanceOf(Function); if (arities[delegate]) { expect(instance[delegate].length).to.equal(arities[delegate]); } else { arities[delegate] = instance[delegate].length; } }; }; delegates.forEach(function (delegate) { it("implements the " + delegate + " method", makeDelegateTester(delegate)); }); }; } describe('the Memory storage backend', ensureComplete(MemoryStorage)); describe('the Remote storage backend', ensureComplete(RemoteStorage));
Stop using the undocumented get_all_related_objects_with_model API
from django.db import models from tournamentcontrol.competition.signals.custom import match_forfeit # noqa from tournamentcontrol.competition.signals.ladders import ( # noqa changed_points_formula, scale_ladder_entry, team_ladder_entry_aggregation, ) from tournamentcontrol.competition.signals.matches import ( # noqa match_saved_handler, notify_match_forfeit_email, ) from tournamentcontrol.competition.signals.places import ( # noqa set_ground_latlng, set_ground_timezone, ) from tournamentcontrol.competition.signals.teams import delete_team # noqa def delete_related(sender, instance, *args, **kwargs): for ro, __ in [ (f, f.model) for f in instance._meta.get_fields() if (f.one_to_many or f.one_to_one) and f.auto_created and not f.concrete]: name = ro.get_accessor_name() if isinstance(ro.field, models.ManyToManyField): continue if isinstance(instance, ro.model): continue manager = getattr(instance, name) for obj in manager.all(): obj.delete()
from django.db import models from tournamentcontrol.competition.signals.custom import match_forfeit # noqa from tournamentcontrol.competition.signals.ladders import ( # noqa changed_points_formula, scale_ladder_entry, team_ladder_entry_aggregation, ) from tournamentcontrol.competition.signals.matches import ( # noqa match_saved_handler, notify_match_forfeit_email, ) from tournamentcontrol.competition.signals.places import ( # noqa set_ground_latlng, set_ground_timezone, ) from tournamentcontrol.competition.signals.teams import delete_team # noqa def delete_related(sender, instance, *args, **kwargs): for ro, __ in instance._meta.get_all_related_objects_with_model(): name = ro.get_accessor_name() if isinstance(ro.field, models.ManyToManyField): continue if isinstance(instance, ro.model): continue manager = getattr(instance, name) for obj in manager.all(): obj.delete()
Set default content type to text/html for WebAgents.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.http; import foam.core.*; import foam.dao.*; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; @SuppressWarnings("serial") public class WebAgentServlet extends HttpServlet implements ContextAware { protected WebAgent agent_; protected X x_; public WebAgentServlet(WebAgent agent) { agent_ = agent; } public X getX() { return x_; } public void setX(X x) { x_ = x; } @Override public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); agent_.execute(getX().put(req.getClass(), req).put(resp.getClass(), resp).put(PrintWriter.class, resp.getWriter())); } }
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.http; import foam.core.*; import foam.dao.*; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; @SuppressWarnings("serial") public class WebAgentServlet extends HttpServlet implements ContextAware { protected WebAgent agent_; protected X x_; public WebAgentServlet(WebAgent agent) { agent_ = agent; } public X getX() { return x_; } public void setX(X x) { x_ = x; } @Override public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { agent_.execute(getX().put(req.getClass(), req).put(resp.getClass(), resp).put(PrintWriter.class, resp.getWriter())); } }
Add support for single quoted multi-line strings in Python
Prism.languages.python= { 'comment': { pattern: /(^|[^\\])#.*?(\r?\n|$)/g, lookbehind: true }, 'string': /"""[\s\S]+?"""|'''[\s\S]+?'''|("|')(\\?.)*?\1/g, 'keyword' : /\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g, 'boolean' : /\b(True|False)\b/g, 'number' : /\b-?(0x)?\d*\.?[\da-f]+\b/g, 'operator' : /[-+]{1,2}|=?&lt;|=?&gt;|!|={1,2}|(&){1,2}|(&amp;){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g, 'ignore' : /&(lt|gt|amp);/gi, 'punctuation' : /[{}[\];(),.:]/g };
Prism.languages.python= { 'comment': { pattern: /(^|[^\\])#.*?(\r?\n|$)/g, lookbehind: true }, 'string': /"""[\s\S]+?"""|("|')(\\?.)*?\1/g, 'keyword' : /\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g, 'boolean' : /\b(True|False)\b/g, 'number' : /\b-?(0x)?\d*\.?[\da-f]+\b/g, 'operator' : /[-+]{1,2}|=?&lt;|=?&gt;|!|={1,2}|(&){1,2}|(&amp;){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g, 'ignore' : /&(lt|gt|amp);/gi, 'punctuation' : /[{}[\];(),.:]/g };
Add pytest-cov to test extras
from codecs import open as codecs_open from setuptools import setup, find_packages # Get the long description from the relevant file with codecs_open('README.rst', encoding='utf-8') as f: long_description = f.read() setup(name='tile-stitcher', version='0.0.1', description=u"Stitch image tiles into composite TIFs", long_description=long_description, classifiers=[], keywords='', author=u"Damon Burgett", author_email='damon@mapbox.com', url='https://github.com/mapbox/tile-stitcher', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'click' ], extras_require={ 'test': ['pytest', 'pytest-cov'], }, entry_points=""" [console_scripts] tile-stitch=tile_stitcher.scripts.cli:cli """ )
from codecs import open as codecs_open from setuptools import setup, find_packages # Get the long description from the relevant file with codecs_open('README.rst', encoding='utf-8') as f: long_description = f.read() setup(name='tile-stitcher', version='0.0.1', description=u"Stitch image tiles into composite TIFs", long_description=long_description, classifiers=[], keywords='', author=u"Damon Burgett", author_email='damon@mapbox.com', url='https://github.com/mapbox/tile-stitcher', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'click' ], extras_require={ 'test': ['pytest'], }, entry_points=""" [console_scripts] tile-stitch=tile_stitcher.scripts.cli:cli """ )
Increment `retries` variable in a way that pleases `jshint`.
'use strict'; var net = require('net'), utils = require('radiodan-client').utils, logger = utils.logger(__filename); function create(port, socket) { var deferred = utils.promise.defer(), retries = 0, timeout = 1000; socket = socket || new net.Socket(); socket.setTimeout(2500); function addHandlers() { socket.on('connect', handleConnect); socket.on('error', handleError); } function handleConnect() { logger.debug('Connected to', port); deferred.resolve(port); } function handleError() { retries++; logger.warn('Cannot connect, attempt #' + retries); setTimeout(function () { socket.connect(port); }, timeout); } function connect() { logger.debug('Connecting to port', port); addHandlers(); socket.connect(port); return deferred.promise; } return { _addHandlers: addHandlers, connect: connect }; } module.exports = { create: create };
'use strict'; var net = require('net'), utils = require('radiodan-client').utils, logger = utils.logger(__filename); function create(port, socket) { var deferred = utils.promise.defer(), retries = 0, timeout = 1000; socket = socket || new net.Socket(); socket.setTimeout(2500); function addHandlers() { socket.on('connect', handleConnect); socket.on('error', handleError); } function handleConnect() { logger.debug('Connected to', port); deferred.resolve(port); } function handleError() { logger.warn('Cannot connect, attempt #' + ++retries); setTimeout(function () { socket.connect(port); }, timeout); } function connect() { logger.debug('Connecting to port', port); addHandlers(); socket.connect(port); return deferred.promise; } return { _addHandlers: addHandlers, connect: connect }; } module.exports = { create: create };
Add with back to dial, docstring
"""Demonstration of setting up a conference call in Flask with Twilio.""" from flask import Flask, request from twilio.twiml.voice_response import VoiceResponse, Dial app = Flask(__name__) # Update with your own phone number in E.164 format MODERATOR = '+18005551212' @app.route("/voice", methods=['GET', 'POST']) def call(): """Return TwiML for a moderated conference call.""" # Start our TwiML response response = VoiceResponse() # Start with a <Dial> verb with Dial() as dial: # If the caller is our MODERATOR, then start the conference when they # join and end the conference when they leave if request.values.get('From') == MODERATOR: dial.conference( 'My conference', startConferenceOnEnter=True, endConferenceOnExit=True) else: # Otherwise have the caller join as a regular participant dial.conference('My conference', startConferenceOnEnter=False) response.append(dial) return str(response) if __name__ == "__main__": app.run(debug=True)
from flask import Flask, request from twilio.twiml.voice_response import VoiceResponse, Dial app = Flask(__name__) # Update with your own phone number in E.164 format MODERATOR = '+15558675309' @app.route("/voice", methods=['GET', 'POST']) def call(): """Returns TwiML for a moderated conference call""" # Start our TwiML response response = VoiceResponse() # Start with a <Dial> verb dial = Dial() # If the caller is our MODERATOR, then start the conference when they # join and end the conference when they leave if request.values.get('From') == MODERATOR: dial.conference( 'My conference', start_conference_on_enter=True, end_conference_on_exit=True) else: # Otherwise have the caller join as a regular participant dial.conference('My conference', start_conference_on_enter=False) return str(response.append(dial)) if __name__ == "__main__": app.run(debug=True)
Fix a typo in the Django ConfigPropertyModel class.
# coding: utf-8 # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Models relating to configuration properties.""" __author__ = 'Sean Lip' from core import django_utils import core.storage.base_model.models as base_models class ConfigPropertyModel(base_models.BaseModel): """A class that represents a named configuration property. The id is the name of the property. """ # The property value. value = django_utils.JSONField(default={})
# coding: utf-8 # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Models relating to configuration properties.""" __author__ = 'Sean Lip' from core import django_utils import core.storage.base_model.models as base_models class ConfigPropertyModel(base_models.BaseModel): """A class that represents a named configuration property. The id is the name of the property. """ # The property value. value = django_utils.JsonField(default={})
PLAT-8479: Add accessibility option to make accessibility feature enable on garnet sample Add accessibility option, which is set to true. https://jira2.lgsvl.com/browse/PLAT-8479 Enyo-DCO-1.1-Signed-off-by: Bongsub Kim <bongsub.kim@lgepartner.com> Change-Id: I6017abad0e08c1796b615e2e4776c380dded92bb
require('enyo/options').accessibility = true; var ready = require('enyo/ready'), kind = require('enyo/kind'); var SampleList = require('../src/strawman/SampleList'); var samples = { Enyo: require('../src/enyo-samples'), Garnet: require('./src'), Layout: require('../src/layout-samples'), Spotlight: require('../src/spotlight-samples'), iLib: require('../src/enyo-ilib-samples'), Onyx: require('../src/onyx-samples'), Canvas: require('../src/canvas-samples'), Svg: require('../src/svg-samples') }; var List = kind({ kind: SampleList, title: 'Enyo Strawman - Samples Gallery', classes: 'home', listType: 'grid', samples: samples }); ready(function () { var names = window.document.location.search.substring(1).split('&'), name = names[0], Sample = samples[name] || List; new Sample().renderInto(document.body); }); module.exports = { samples: samples, List: List };
var ready = require('enyo/ready'), kind = require('enyo/kind'); var SampleList = require('../src/strawman/SampleList'); var samples = { Enyo: require('../src/enyo-samples'), Garnet: require('./src'), Layout: require('../src/layout-samples'), Spotlight: require('../src/spotlight-samples'), iLib: require('../src/enyo-ilib-samples'), Onyx: require('../src/onyx-samples'), Canvas: require('../src/canvas-samples'), Svg: require('../src/svg-samples') }; var List = kind({ kind: SampleList, title: 'Enyo Strawman - Samples Gallery', classes: 'home', listType: 'grid', samples: samples }); ready(function () { var names = window.document.location.search.substring(1).split('&'), name = names[0], Sample = samples[name] || List; new Sample().renderInto(document.body); }); module.exports = { samples: samples, List: List };
Increase 503 retry strategy from 200ms to 2000ms, Nike+ was occasionally returning "429 Too Many Requests".
package com.awsmithson.tcx2nikeplus.http; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.HttpClientBuilder; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class HttpClients { private static final @Nonnull RequestConfig REQUEST_CONFIG_DEFAULT = RequestConfig.custom() .setConnectTimeout(5_000) .setConnectionRequestTimeout(5_000) .setSocketTimeout(8_000) .build(); // The "URL_DATA_SYNC" nike+ service seems to intermittently return 503, HttpComponents can deal with that nicely. private static final @Nonnull HttpStatusCodeRetryStrategy DEFAULT_RETRY_STRATEGY = new HttpStatusCodeRetryStrategy(10, 2000, new Predicate<HttpResponse>() { @Override public boolean apply(@Nullable HttpResponse httpResponse) { return (httpResponse == null) || (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE); } }); public static HttpClientBuilder createDefaultHttpClientBuilder() { return HttpClientBuilder .create() .setDefaultRequestConfig(REQUEST_CONFIG_DEFAULT) .setRetryHandler(new HttpTimeoutRetryHandler(10)) .setServiceUnavailableRetryStrategy(DEFAULT_RETRY_STRATEGY); } }
package com.awsmithson.tcx2nikeplus.http; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.HttpClientBuilder; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class HttpClients { private static final @Nonnull RequestConfig REQUEST_CONFIG_DEFAULT = RequestConfig.custom() .setConnectTimeout(5_000) .setConnectionRequestTimeout(5_000) .setSocketTimeout(8_000) .build(); // The "URL_DATA_SYNC" nike+ service seems to intermittently return 503, HttpComponents can deal with that nicely. private static final @Nonnull HttpStatusCodeRetryStrategy DEFAULT_RETRY_STRATEGY = new HttpStatusCodeRetryStrategy(10, 200, new Predicate<HttpResponse>() { @Override public boolean apply(@Nullable HttpResponse httpResponse) { return (httpResponse == null) || (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE); } }); public static HttpClientBuilder createDefaultHttpClientBuilder() { return HttpClientBuilder .create() .setDefaultRequestConfig(REQUEST_CONFIG_DEFAULT) .setRetryHandler(new HttpTimeoutRetryHandler(10)) .setServiceUnavailableRetryStrategy(DEFAULT_RETRY_STRATEGY); } }
Support provide a URI Object
'use strict' var parseURI = require('parse-uri') var encode = require('punycode2/encode') // Illegal characters (anything which is not in between the square brackets): var ILLEGALS = /[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i // Incomplete HEX escapes: var HEX1 = /%[^0-9a-f]/i var HEX2 = /%[0-9a-f](:?[^0-9a-f]|$)/i // Scheme must begin with a letter, then consist of letters, digits, '+', '.', or '-' => e.g., 'http', 'https', 'ftp' var PROTOCOL = /^[a-z][a-z0-9\+\-\.]*$/ // If authority is not present, path must not begin with '//' var PATH = /^\/\// module.exports = function isURI (uri, opts) { if (!uri) return false if (typeof uri !== 'object') { uri = encode(uri) if (ILLEGALS.test(uri)) return false if (HEX1.test(uri) || HEX2.test(uri)) return false uri = parseURI(uri, opts) } if (!uri.protocol || !PROTOCOL.test(uri.protocol.toLowerCase())) return false if (!uri.authority && PATH.test(uri.path)) return false return true }
'use strict' var parseURI = require('parse-uri') var encode = require('punycode2/encode') // Illegal characters (anything which is not in between the square brackets): var ILLEGALS = /[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i // Incomplete HEX escapes: var HEX1 = /%[^0-9a-f]/i var HEX2 = /%[0-9a-f](:?[^0-9a-f]|$)/i // Scheme must begin with a letter, then consist of letters, digits, '+', '.', or '-' => e.g., 'http', 'https', 'ftp' var PROTOCOL = /^[a-z][a-z0-9\+\-\.]*$/ // If authority is not present, path must not begin with '//' var PATH = /^\/\// module.exports = function isURI (str, opts) { if (!str) return false str = encode(str) if (ILLEGALS.test(str)) return false if (HEX1.test(str) || HEX2.test(str)) return false var uri = parseURI(str, opts) if (!Boolean(uri.protocol) || !PROTOCOL.test(uri.protocol.toLowerCase())) return false if (!Boolean(uri.authority) && PATH.test(uri.path)) return false return true }
Store player name as owner by default. Should further help singleplayer ownership issues.
package com.carpentersblocks.util.protection; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; public class ProtectedObject { public EntityPlayer entityPlayer; public ProtectedObject(EntityPlayer entityPlayer) { this.entityPlayer = entityPlayer; } @Override public String toString() { if (FMLCommonHandler.instance().getSide() == Side.SERVER) { boolean onlineMode = ((EntityPlayerMP)entityPlayer).mcServer.isServerInOnlineMode(); if (onlineMode) { return entityPlayer.getUniqueID().toString(); } else { return entityPlayer.getDisplayName(); } } else { return entityPlayer.getDisplayName(); } } }
package com.carpentersblocks.util.protection; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; public class ProtectedObject { public EntityPlayer entityPlayer; public ProtectedObject(EntityPlayer entityPlayer) { this.entityPlayer = entityPlayer; } @Override public String toString() { if (FMLCommonHandler.instance().getSide() == Side.SERVER) { boolean onlineMode = ((EntityPlayerMP)entityPlayer).mcServer.isServerInOnlineMode(); if (onlineMode) { return entityPlayer.getUniqueID().toString(); } else { return entityPlayer.getDisplayName(); } } else { return ""; } } }
Allow more zvals to be passed as ref
<?php namespace PHPPHP\Engine\OpLines; use PHPPHP\Engine\Zval; class Send extends \PHPPHP\Engine\OpLine { public function execute(\PHPPHP\Engine\ExecuteData $data) { $ptr = null; if($data->executor->executorGlobals->call->getFunction()->isArgByRef($this->op2)) { if ($this->op1->isVariable() || $this->op1->isRef() || $this->op1->isObject()) { $op = $this->op1->getPtr(); $op->makeRef(); $op->addRef(); $ptr = Zval::ptrFactory($op->getZval()); } else { throw new \RuntimeException("Can't pass parameter {$this->op2} by reference"); } } else { $ptr = Zval::ptrFactory($this->op1->getValue()); } $data->executor->getStack()->push($ptr); $data->nextOp(); } }
<?php namespace PHPPHP\Engine\OpLines; use PHPPHP\Engine\Zval; class Send extends \PHPPHP\Engine\OpLine { public function execute(\PHPPHP\Engine\ExecuteData $data) { $ptr = null; if($data->executor->executorGlobals->call->getFunction()->isArgByRef($this->op2)) { if ($this->op1->isVariable()) { $op = $this->op1->getPtr(); $op->makeRef(); $op->addRef(); $ptr = Zval::ptrFactory($op->getZval()); } else { throw new \RuntimeException("Can't pass parameter {$this->op2} by reference"); } } else { $ptr = Zval::ptrFactory($this->op1->getValue()); } $data->executor->getStack()->push($ptr); $data->nextOp(); } }
Resolve an unassigned variable error.
<?php if(!Utility::isBot()) { if(!isset($sidebar)) { $sidebar = false; } if($article) { $advert = \FelixOnline\Core\Advert::randomPick('articles', $sidebar, $article->getCategory()); } elseif($category) { $advert = \FelixOnline\Core\Advert::randomPick('categories', $sidebar, $category); } else { $advert = \FelixOnline\Core\Advert::randomPick('frontpage', $sidebar, null); } if($advert) { if(!$sidebar) { $class = 'external-img-top advert-area'; } else { $class = 'external-img-side'; } $advert->viewAdvert(); ?> <div class="text-center external-img"> <div class="<?php echo $class; ?>"> <a href="<?php echo $advert->getUrl(); ?>" target="_blank"><img src="<?php echo $advert->getImage()->getUrl(); ?>"></a> </div> </div> <?php } } ?>
<?php if(!Utility::isBot()) { if(!$sidebar) { $sidebar = false; } if($article) { $advert = \FelixOnline\Core\Advert::randomPick('articles', $sidebar, $article->getCategory()); } elseif($category) { $advert = \FelixOnline\Core\Advert::randomPick('categories', $sidebar, $category); } else { $advert = \FelixOnline\Core\Advert::randomPick('frontpage', $sidebar, null); } if($advert) { if(!$sidebar) { $class = 'external-img-top advert-area'; } else { $class = 'external-img-side'; } $advert->viewAdvert(); ?> <div class="text-center external-img"> <div class="<?php echo $class; ?>"> <a href="<?php echo $advert->getUrl(); ?>" target="_blank"><img src="<?php echo $advert->getImage()->getUrl(); ?>"></a> </div> </div> <?php } } ?>
Disable info if both pagination and filter is disabled
<?php $fields = json_decode(json_encode(get_fields($module->ID))); $classes = ''; if (isset($fields->mod_table_classes) && is_array($fields->mod_table_classes)) { $classes = implode(' ', $fields->mod_table_classes); } ?> <div class="box box-panel"> <h4 class="box-title"><?php echo $module->post_title; ?></h4> <?php echo str_replace( '<table class="', sprintf( '<table data-paging="%2$s" data-page-length="%3$s" data-searching="%4$s" data-info="%5$s" class="datatable %1$s ', $classes, $fields->mod_table_pagination, $fields->mod_table_pagination_count, $fields->mod_table_search, $fields->mod_table_pagination || $fields->mod_table_search ), $fields->mod_table ); ?> </div>
<?php $fields = json_decode(json_encode(get_fields($module->ID))); $classes = ''; if (isset($fields->mod_table_classes) && is_array($fields->mod_table_classes)) { $classes = implode(' ', $fields->mod_table_classes); } ?> <div class="box box-panel"> <h4 class="box-title"><?php echo $module->post_title; ?></h4> <?php echo str_replace( '<table class="', sprintf( '<table data-paging="%2$s" data-page-length="%3$s" data-searching="%4$s" class="datatable %1$s ', $classes, $fields->mod_table_pagination, $fields->mod_table_pagination_count, $fields->mod_table_search ), $fields->mod_table ); ?> </div>
Make random IDs start with a letter
import string import random from django.conf import settings def validate_settings(): assert settings.AWS, \ "No AWS settings found" assert settings.AWS.get('ACCESS_KEY'), \ "AWS access key is not set in settings" assert settings.AWS.get('SECRET_KEY'), \ "AWS secret key is not set in settings" assert settings.AWS.get('BUCKET'), \ "AWS bucket name is not set in settings" ID_FIELD_LENGTH = 24 alphabet = string.ascii_lowercase + string.digits alphabet0 = string.ascii_lowercase + string.ascii_lowercase for loser in 'l1o0': i = alphabet.index(loser) alphabet = alphabet[:i] + alphabet[i + 1:] for loser in 'lo': i = alphabet0.index(loser) alphabet0 = alphabet0[:i] + alphabet0[i + 1:] def byte_to_base32_chr(byte): return alphabet[byte & 31] def byte_to_letter(byte): return alphabet0[byte & 31] def random_id(): rand_id = [random.randint(0, 0xFF) for i in range(ID_FIELD_LENGTH)] return (byte_to_letter(rand_id[0]) + ''.join(map(byte_to_base32_chr, rand_id[1:])))
import string import random from django.conf import settings def validate_settings(): assert settings.AWS, \ "No AWS settings found" assert settings.AWS.get('ACCESS_KEY'), \ "AWS access key is not set in settings" assert settings.AWS.get('SECRET_KEY'), \ "AWS secret key is not set in settings" assert settings.AWS.get('BUCKET'), \ "AWS bucket name is not set in settings" ID_FIELD_LENGTH = 24 alphabet = string.ascii_lowercase + string.digits for loser in 'l1o0': i = alphabet.index(loser) alphabet = alphabet[:i] + alphabet[i + 1:] def byte_to_base32_chr(byte): return alphabet[byte & 31] def random_id(): rand_id = [random.randint(0, 0xFF) for i in range(ID_FIELD_LENGTH)] return ''.join(map(byte_to_base32_chr, rand_id))
Fix incorrect import for FxOS nav tests.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.firefox.family_navigation import FirefoxPage @pytest.mark.nondestructive @pytest.mark.parametrize('slug', [ pytest.mark.smoke(('os')), pytest.mark.smoke(('os/devices')), pytest.mark.smoke(('os/devices/tv'))]) def test_fxos_navigation_active_nav(slug, base_url, selenium): page = FirefoxPage(base_url, selenium, slug=slug).open() assert page.fxos_navigation.active_primary_nav_id == slug.replace('/', '-') @pytest.mark.nondestructive @pytest.mark.parametrize('slug', [ pytest.mark.smoke(('os')), pytest.mark.smoke(('os/devices')), pytest.mark.smoke(('os/devices/tv'))]) def test_fxos_navigation_adjunct_menu(slug, base_url, selenium): page = FirefoxPage(base_url, selenium, slug=slug).open() page.fxos_navigation.open_adjunct_menu() assert page.fxos_navigation.is_adjunct_menu_displayed
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.firefox.fxos_navigation import FirefoxPage @pytest.mark.nondestructive @pytest.mark.parametrize('slug', [ pytest.mark.smoke(('os')), pytest.mark.smoke(('os/devices')), pytest.mark.smoke(('os/devices/tv'))]) def test_fxos_navigation_active_nav(slug, base_url, selenium): page = FirefoxPage(base_url, selenium, slug=slug).open() assert page.fxos_navigation.active_primary_nav_id == slug.replace('/', '-') @pytest.mark.nondestructive @pytest.mark.parametrize('slug', [ pytest.mark.smoke(('os')), pytest.mark.smoke(('os/devices')), pytest.mark.smoke(('os/devices/tv'))]) def test_fxos_navigation_adjunct_menu(slug, base_url, selenium): page = FirefoxPage(base_url, selenium, slug=slug).open() page.fxos_navigation.open_adjunct_menu() assert page.fxos_navigation.is_adjunct_menu_displayed
Replace index_to_column_id with iterative fx The recursive one was neat but a bit too clever.
# -*- coding: utf-8 -*- # Part of the masterfile package: https://github.com/njvack/masterfile # Copyright (c) 2017 Board of Regents of the University of Wisconsin System # Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds # at the University of Wisconsin-Madison. # Released under MIT licence; see LICENSE at the package root. """ This package contains functions for pretty-printing data — for example, converting column numbers into Excel-like column identifier strings. """ import string def index_to_column_id(number): """ Takes a zero-based index and converts it to a column identifier string such as used in Excel. Examples: 0 => A 25 => Z 26 => AA """ if number < 0 or not isinstance(number, int): raise AttributeError("index_to_column_id requires a non-negative int") digits = string.ascii_uppercase parts = [] number += 1 # The algorithm works on 1-based input while number > 0: number, mod = divmod(number - 1, len(digits)) parts.insert(0, digits[mod]) return ''.join(parts)
# -*- coding: utf-8 -*- # Part of the masterfile package: https://github.com/njvack/masterfile # Copyright (c) 2017 Board of Regents of the University of Wisconsin System # Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds # at the University of Wisconsin-Madison. # Released under MIT licence; see LICENSE at the package root. """ This package contains functions for pretty-printing data — for example, converting column numbers into Excel-like column identifier strings. """ import string def index_to_column_id(number): """ Takes a zero-based index and converts it to a column identifier string such as used in Excel. Examples: 0 => A 25 => Z 26 => AA """ if number < 0 or not isinstance(number, int): raise AttributeError("index_to_column_id requires a non-negative int") digits = string.ascii_uppercase if number == 0: return digits[0] return __rec_int_to_colid(number, digits) def __rec_int_to_colid(number, digits): base = len(digits) if number < 0: return '' return ( __rec_int_to_colid((number // base) - 1, digits) + digits[number % base])
Modify not to create message unless joining the thread.
define([ 'underscore', 'controllers/ApplicationController', 'models/Thread', 'models/Message', 'utils/Utils' ], function(_, ApplicationController, Thread, Message, Utils) { var MessageController = Utils.inherit(ApplicationController, function(networkAgent) { ApplicationController.call(this, networkAgent); }); MessageController.prototype.create = function(args, format) { var self = this; if (!_.contains(this._networkAgent.getJoiningThreadIds(), args.threadId)) { throw new Error("Unknown thread ID: " + args.threadId); } Message.new(args).exists(function(exists) { Message.create(args, function(message, error) { if (error) { throw new Error("Failed to create message:", error); } Utils.debug("Created or updated message:", message.id); if (!exists) { Utils.debug("Spreading message:", message.id); self._networkAgent.spreadMessage(message.toJson()); } self._response(format, { html: function() { WebRtcBbs.context.routing.to('/thread/show', {threadId: args.threadId}, true); } }); }); }); }; return MessageController; });
define([ 'underscore', 'controllers/ApplicationController', 'models/Thread', 'models/Message', 'utils/Utils' ], function(_, ApplicationController, Thread, Message, Utils) { var MessageController = Utils.inherit(ApplicationController, function(networkAgent) { ApplicationController.call(this, networkAgent); }); MessageController.prototype.create = function(args, format) { var self = this; Message.new(args).exists(function(exists) { Message.create(args, function(message, error) { if (error) { throw new Error("Failed to create message:", error); } Utils.debug("Created or updated message:", message.id); if (!exists) { Utils.debug("Spreading message:", message.id); self._networkAgent.spreadMessage(message.toJson()); } self._response(format, { html: function() { WebRtcBbs.context.routing.to('/thread/show', {threadId: args.threadId}, true); } }); }); }); }; return MessageController; });
Check if file exists before reading.
<?php require __DIR__ . '/../vendor/autoload.php'; $configfile = __DIR__.'/config.json'; $config = false; if (file_exists($configfile)) { $config = json_decode(file_get_contents(__DIR__.'/config.json'), true); } if ($config == false) { $user = getenv('CP_USER'); $pass = getenv('CP_PASSWORD'); } else { $user = $config['CP_USER']; $pass = $config['CP_PASSWORD']; } define('CP_USER', $user); define('CP_PASSWORD', $pass); define('CP_SANDBOX_ENDPOINT', "https://ct.soa-gw.canadapost.ca"); define('LOOKUP_CODE', 'H3G2A9'); define('LOOKUP_CITY', 'Montreal'); define('LOOKUP_PROVINCE', 'QC'); define('LOOKUP_LONG', '-73.63908'); define('LOOKUP_LAT', "45.54545");
<?php require __DIR__ . '/../vendor/autoload.php'; $config = json_decode(file_get_contents(__DIR__.'/config.json'), true); if ($config == false) { $user = getenv('CP_USER'); $pass = getenv('CP_PASSWORD'); } else { $user = $config['CP_USER']; $pass = $config['CP_PASSWORD']; } define('CP_USER', $user); define('CP_PASSWORD', $pass); define('CP_SANDBOX_ENDPOINT', "https://ct.soa-gw.canadapost.ca"); define('LOOKUP_CODE', 'H3G2A9'); define('LOOKUP_CITY', 'Montreal'); define('LOOKUP_PROVINCE', 'QC'); define('LOOKUP_LONG', '-73.63908'); define('LOOKUP_LAT', "45.54545");
Set max_workers the same as max_size.
# -*- coding: utf-8 -*- from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} def register_pool(self, group_key, max_size=10, max_workers=10): executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers) IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key]
# -*- coding: utf-8 -*- from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} def register_pool(self, group_key, max_size=1): executor = QueueExecutor(pool_key=group_key, max_size=max_size) IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key]
Add value for parameter "fiat" in method fetch_coin
import notify2 import Rates def notify(): icon_path = "/home/dushyant/Desktop/Github/Crypto-Notifier/logo.jpg" cryptocurrencies = ["bitcoin", "ethereum", "litecoin", "monero", "ripple", "dash"] result = "" for coin in cryptocurrencies: rate = Rates.fetch_coin(coin, "INR") result += "{} - {}\n".format(rate[0], rate[2].encode('utf-8')) print result notify2.init("Cryptocurrency rates notifier") n = notify2.Notification("Crypto Notifier", icon=icon_path) n.set_urgency(notify2.URGENCY_NORMAL) n.set_timeout(1000) n.update("Current Rates", result) n.show() if __name__ == "__main__": notify()
import notify2 import Rates def notify(): icon_path = "/home/dushyant/Desktop/Github/Crypto-Notifier/logo.jpg" cryptocurrencies = ["bitcoin", "ethereum", "litecoin", "monero", "ripple", "dash"] result = "" for coin in cryptocurrencies: rate = Rates.fetch_coin(coin) result += "{} - {}\n".format(rate[0], rate[2].encode('utf-8')) print result notify2.init("Cryptocurrency rates notifier") n = notify2.Notification("Crypto Notifier", icon=icon_path) n.set_urgency(notify2.URGENCY_NORMAL) n.set_timeout(1000) n.update("Current Rates", result) n.show() if __name__ == "__main__": notify()
Fix license MIT to BSD
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='Graphistry', version='1.1.0.dev1', description='This is established as a Data Loader for Graphistry', long_description=long_description, url='https://github.com/graphistry/pygraphistry', author='Graphistry', author_email='xin@graphistry.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Graphistry User', 'Topic :: Data Visualization Development :: Load Tools', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='Python Data Loader', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), )
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='Graphistry', version='1.1.0.dev1', description='This is established as a Data Loader for Graphistry', long_description=long_description, url='https://github.com/graphistry/pygraphistry', author='Graphistry', author_email='xin@graphistry.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Graphistry User', 'Topic :: Data Visualization Development :: Load Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='Python Data Loader', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), )
Format go to the new design
from genes import apt, brew, pacman, http_downloader, checksum, msiexec import platform opsys = platform.system() dist = platform.linux_distribution() if platform == 'Linux' and dist == 'Arch': pacman.update() pacman.sync('go') if platform == 'Linux' and (dist == 'Debian' or dist == 'Ubuntu'): apt.update() apt.install('golang') # TODO: make this a runner and require a switch to enable this apt.install('golang-go-darwin-amd64', 'golang-go-freebsd-amd64', 'golang-go-netbsd-amd64', 'golang-go-windows-amd64') if platform == 'Darwin': brew.update() brew.install('go') if platform == 'Windows': installer = http_downloader.get('https://storage.googleapis.com/golang/go1.5.1.windows-amd64.msi') checksum.check(installer, 'sha1', '0a439f49b546b82f85adf84a79bbf40de2b3d5ba') install_flags = ('/qn' '/norestart') msiexec.run(installer, install_flags)
from evolution_master.runners import pkg, download # Install for Arch with pkg.pacman() as pkg_man: pkg_man.install('go') # Install for Debian & Ubuntu with pkg.apt() as pkg_man: pkg_man.install('golang') # TODO: make this a runner and require a switch to enable this pkg_man.install('golang-go-darwin-amd64', 'golang-go-freebsd-amd64', 'golang-go-netbsd-amd64', 'golang-go-windows-amd64') # Install for OSX with pkg.brew() as pkg_man: pkg_man.install('go') # Install for Windows with download.https() as downloader, pkg.msiexec() as installer: downloader.get('https://storage.googleapis.com/golang/go1.5.1.windows-amd64.msi') downloader.checksum('sha1', '0a439f49b546b82f85adf84a79bbf40de2b3d5ba') installer.install_flags('/qn' '/norestart') installer.await(downloader.finished())
Add parenthesis around lambda arg
package com.bpedman.lambdas; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; /** * @author Brandon Pedersen &lt;bpedersen@getjive.com&gt; */ public class Example_03 { /** * Less lines of code but you still need to read the predicate lambda to understand what is * happening... */ private static boolean isPrime(final int number) { return number > 1 && IntStream .range(2, number - 1) .noneMatch((value) -> number % value == 0); } /** * Our goal...turn this set of calculations into something that is as readable as the method name * itself and more succinct than it is * * @param numbers * potentially unordered, non-unique set of numbers */ public static int findDoubleOfFirstPrimeNumberGreaterThan5(List<Integer> numbers) { int result = 0; for (final Integer number : numbers) { // first check if prime if (isPrime(number)) { if (number > 5) { result = number * 2; } } } return result; } public static void main(String[] args) { System.out.println(findDoubleOfFirstPrimeNumberGreaterThan5( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); } }
package com.bpedman.lambdas; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; /** * @author Brandon Pedersen &lt;bpedersen@getjive.com&gt; */ public class Example_03 { /** * Less lines of code but you still need to read the predicate lambda to understand what is * happening... */ private static boolean isPrime(final int number) { return number > 1 && IntStream .range(2, number - 1) .noneMatch(value -> number % value == 0); } /** * Our goal...turn this set of calculations into something that is as readable as the method name * itself and more succinct than it is * * @param numbers * potentially unordered, non-unique set of numbers */ public static int findDoubleOfFirstPrimeNumberGreaterThan5(List<Integer> numbers) { int result = 0; for (final Integer number : numbers) { // first check if prime if (isPrime(number)) { if (number > 5) { result = number * 2; } } } return result; } public static void main(String[] args) { System.out.println(findDoubleOfFirstPrimeNumberGreaterThan5( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); } }
Make default options map unmodifiable
package me.coley.recaf.decompile; import me.coley.recaf.workspace.Workspace; import java.util.*; /** * Decompiler base. * * @author Matt. */ public abstract class Decompiler<OptionType> { private final Map<String, OptionType> defaultOptions = Collections.unmodifiableMap(generateDefaultOptions()); private Map<String, OptionType> options = new HashMap<>(defaultOptions); /** * @return Map of the current options. */ public Map<String, OptionType> getOptions() { return options; } /** * @param options * Map of the options to use. */ public void setOptions(Map<String, OptionType> options) { this.options = options; } /** * @return Map of the default decompiler options. */ public Map<String, OptionType> getDefaultOptions() { return defaultOptions; } /** * @return Map of the default decompiler options. */ protected abstract Map<String, OptionType> generateDefaultOptions(); /** * @param workspace * Workspace to pull classes from. * @param name * Name of the class to decompile. * * @return Decompiled text of the class. */ public abstract String decompile(Workspace workspace, String name); }
package me.coley.recaf.decompile; import me.coley.recaf.workspace.Workspace; import java.util.Map; /** * Decompiler base. * * @author Matt. */ public abstract class Decompiler<OptionType> { private final Map<String, OptionType> defaultOptions = generateDefaultOptions(); private Map<String, OptionType> options = defaultOptions; /** * @return Map of the current options. */ public Map<String, OptionType> getOptions() { return options; } /** * @param options * Map of the options to use. */ public void setOptions(Map<String, OptionType> options) { this.options = options; } /** * @return Map of the default decompiler options. */ public Map<String, OptionType> getDefaultOptions() { return defaultOptions; } /** * @return Map of the default decompiler options. */ protected abstract Map<String, OptionType> generateDefaultOptions(); /** * @param workspace * Workspace to pull classes from. * @param name * Name of the class to decompile. * * @return Decompiled text of the class. */ public abstract String decompile(Workspace workspace, String name); }
Clean up analytics index action test
<?php namespace Backend\Modules\Analytics\Tests\Action; use Backend\Core\Tests\BackendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; class IndexTest extends BackendWebTestCase { public function testAuthenticationIsNeeded(Client $client): void { $this->assertAuthenticationIsNeeded($client, '/private/en/analytics/index'); } public function testRedirectToSettingsActionWhenTheAnalyticsModuleIsNotConfigured(Client $client): void { $this->login($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/analytics/index'); // we should have been redirected to the settings page because the module isn't configured self::assertContains( '/private/en/analytics/settings', $client->getHistory()->current()->getUri() ); } }
<?php namespace Backend\Modules\Analytics\Tests\Action; use Backend\Core\Tests\BackendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; class IndexTest extends BackendWebTestCase { public function testAuthenticationIsNeeded(Client $client): void { $this->assertAuthenticationIsNeeded($client, '/private/en/analytics/index'); } public function testRedirectToSettingsActionWhenTheAnalyticsModuleIsNotConfigured(): void { $client = static::createClient(); $this->login($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/analytics/reset'); // we should have been redirected to the settings page after the reset self::assertContains( '/private/en/analytics/settings', $client->getHistory()->current()->getUri() ); } }
Fix db migration merge conflicts
"""empty message Revision ID: 0074_update_sms_rate Revises: 0073_add_international_sms_flag Create Date: 2017-04-24 12:10:02.116278 """ import uuid revision = '0074_update_sms_rate' down_revision = '0073_add_international_sms_flag' from alembic import op def upgrade(): op.get_bind() op.execute("INSERT INTO provider_rates (id, valid_from, rate, provider_id) " "VALUES ('{}', '2017-04-01 00:00:00', 1.58, " "(SELECT id FROM provider_details WHERE identifier = 'mmg'))".format(uuid.uuid4()) ) def downgrade(): op.get_bind() op.execute("DELETE FROM provider_rates where valid_from = '2017-04-01 00:00:00' " "and provider_id = (SELECT id FROM provider_details WHERE identifier = 'mmg')")
"""empty message Revision ID: 0074_update_sms_rate Revises: 0072_add_dvla_orgs Create Date: 2017-04-24 12:10:02.116278 """ import uuid revision = '0074_update_sms_rate' down_revision = '0072_add_dvla_orgs' from alembic import op def upgrade(): op.get_bind() op.execute("INSERT INTO provider_rates (id, valid_from, rate, provider_id) " "VALUES ('{}', '2017-04-01 00:00:00', 1.58, " "(SELECT id FROM provider_details WHERE identifier = 'mmg'))".format(uuid.uuid4()) ) def downgrade(): op.get_bind() op.execute("DELETE FROM provider_rates where valid_from = '2017-04-01 00:00:00' " "and provider_id = (SELECT id FROM provider_details WHERE identifier = 'mmg')")
Use config file in import script
import MySQLdb import json # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" data = open(filename, 'r') guests = [] # Config Setup config_file = open('config.json', 'r') config = json.load(config_file) for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) db = MySQLdb.connect(config['db_host'], config['db_user'], config['db_password'], config['db_name']) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close()
import MySQLdb # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" data = open(filename, 'r'); guests = []; db_host = "" # Add your host db_user = "" # Add your user db_password = "" # Add your password db_name = "" # Add your database name db_table = "" # Add your table name for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) db = MySQLdb.connect(db_host, db_user, db_password, db_name) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close()
Fix and ungodly number of linter errors
var jwt = require('jwt-simple'); module.exports = { // Getus user from db, returns a promise of that user applyToUser: function (user) { if ((typeof user) === 'string') { user = {username: user}; } return findUser({username: username}) .then(function (user) { if (!user) { next(new Error('User does not exist')); } else { return user; } }); }, errorLogger: function (error, req, res, next) { console.error(error.stack); next(error); }, errorHandler: function (error, req, res, next) { res.send(500, {error: error.message}); }, decode: function (req, res, next) { var token = req.headers['x-access-token']; var user; if (!token) { return res.send(403); // send forbidden if a token is not provided } try { user = jwt.decode(token, 'secret'); req.user = user; next(); } catch (error) { return next(error); } } };
var jwt = require('jwt-simple'); module.exports = { // Getus user from db, returns a promise of that user applyToUser: function(user) { if (typeof(user) === 'string') { user = {username: user}; } return findUser({username: username}) .then(function (user) { if (!user) { next(new Error('User does not exist')); } else { return user; } }); }, errorLogger: function (error, req, res, next) { console.error(error.stack); next(error); }, errorHandler: function (error, req, res, next) { res.send(500, {error: error.message}); }, decode: function (req, res, next) { var token = req.headers['x-access-token']; var user; if (!token) { return res.send(403); // send forbidden if a token is not provided } try { user = jwt.decode(token, 'secret'); req.user = user; next(); } catch (error) { return next(error); } } };
Use project for monkey patch, instead of assuming NPM structure.
/* jshint node: true */ 'use strict'; var VersionChecker = require('ember-cli-version-checker'); module.exports = { name: 'ember-resolver', init: function() { var checker = new VersionChecker(this); var dep = checker.for('ember-cli', 'npm'); if (!dep.satisfies('>= 2.0.0')) { this.monkeyPatchVendorFiles(); } }, monkeyPatchVendorFiles: function() { var EmberApp = this.project.require('ember-cli/lib/broccoli/ember-app'); var originalPopulateLegacyFiles = EmberApp.prototype.populateLegacyFiles; EmberApp.prototype.populateLegacyFiles = function () { delete this.vendorFiles['ember-resolver.js']; originalPopulateLegacyFiles.apply(this, arguments); }; } };
/* jshint node: true */ 'use strict'; var VersionChecker = require('ember-cli-version-checker'); module.exports = { name: 'ember-resolver', init: function() { var checker = new VersionChecker(this); var dep = checker.for('ember-cli', 'npm'); if (!dep.satisfies('>= 2.0.0')) { this.monkeyPatchVendorFiles(); } }, monkeyPatchVendorFiles: function() { var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var originalPopulateLegacyFiles = EmberApp.prototype.populateLegacyFiles; EmberApp.prototype.populateLegacyFiles = function () { delete this.vendorFiles['ember-resolver.js']; originalPopulateLegacyFiles.apply(this, arguments); }; } };
Remove reference to old, bad migration that was in my local tree.
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-07-24 22:43 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0089_auto_20180706_2242'), ] operations = [ migrations.AlterField( model_name='channel', name='content_defaults', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.AlterField( model_name='user', name='content_defaults', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-07-24 22:43 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0090_auto_20180724_1625'), ] operations = [ migrations.AlterField( model_name='channel', name='content_defaults', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.AlterField( model_name='user', name='content_defaults', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), ]
Add null check for cancelled attempt too select profile file
package fortiss.gui.listeners.button; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import fortiss.components.Demand; import fortiss.gui.Designer; import fortiss.gui.listeners.helper.Chooser; public class DBrowseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { int building = Designer.currentBuilding; int component = Designer.currentComponent; Demand d = Designer.buildings.get(building).getDemand().get(component); // Update selection in text field Chooser c = new Chooser(); String path = c.choosePath(); if (path != null) { Designer.demandPanel.txtDConsumption.setText(path); d.setConsumptionProfile(path); } // null check necessary to account for a cancelled attempt to change path if (!d.getConsumptionProfile().isEmpty() && path != null) { Designer.demandPanel.setData(path); } } }
package fortiss.gui.listeners.button; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import fortiss.components.Demand; import fortiss.gui.Designer; import fortiss.gui.listeners.helper.Chooser; public class DBrowseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { int building = Designer.currentBuilding; int component = Designer.currentComponent; Demand d = Designer.buildings.get(building).getDemand().get(component); // Update selection in text field Chooser c = new Chooser(); String path = c.choosePath(); if (path != null) { Designer.demandPanel.txtDConsumption.setText(path); d.setConsumptionProfile(path); } if (!d.getConsumptionProfile().isEmpty()) { Designer.demandPanel.setData(path); } } }
Remove user from connections upon disconnect
var models = require('../db/models.js'); var io; var connections = {}; var events = { //input: {userToken: string} init: function(data) { connections[data.userToken] = this; this.emit('init'); }, //input: {userToken: string, messageId: string} upvote: function(data) { models.createVote(data) .then(function(success) { return models.retrieveUserScore(data.userToken); }).then(function(user) { exports.sendUserScore(user[0]); }); }, disconnect: function() { for (var u in connections) { if (connections[u] === this) { delete connections[u]; } } } }; exports.initialize = function(server) { io = server; io.on('connection', function(socket) { for (var e in events) { socket.on(e, events[e]); } }); }; exports.sendUserScore = function(user) { if (connections.hasOwnProperty(user.token)) { connections[user.token].emit('score', {score: user.total_votes}); } };
var models = require('../db/models.js'); var io; var connections = {}; var events = { //input: {userToken: string} init: function(data) { connections[data.userToken] = this; this.emit('init'); }, //input: {userToken: string, messageId: string} upvote: function(data) { models.createVote(data) .then(function(success) { return models.retrieveUserScore(data.userToken); }).then(function(user) { exports.sendUserScore(user[0]); }); }, disconnect: function() { console.log('user disconnected'); } }; exports.initialize = function(server) { io = server; io.on('connection', function(socket) { for (var e in events) { socket.on(e, events[e]); } }); }; exports.sendUserScore = function(user) { connections[user.token].emit('score', {score: user.total_votes}); };
Update the API URL to filter non-article contributions.
<?php //language if(!paramExists("lang")) {respond("missing parameter!");} $language=$_REQUEST["lang"]; //username if(!paramExists("user")) {respond("missing parameter!");} $username=$_REQUEST["user"]; //create the request url $apiUrl="http://$language.wikipedia.org/w/api.php?action=feedcontributions&namespace=0&format=xml&feedformat=rss&user=$username"; //fetch the data $apiResponse=file_get_contents($apiUrl); //echo the data echo $apiResponse; function paramExists($param, $empty=false) { if(isset($_REQUEST[$param])) { if(!$empty&&empty($_REQUEST[$param])) {return false;} return true; } return false; } function respond($message) { echo "<?xml version='1.0'?>\n"; echo "<proxy>\n"; echo "\t<message>\n"; echo "\t\t".$message."\n"; echo "\t</message>\n"; echo "</proxy>\n"; exit(); } ?>
<?php //language if(!paramExists("lang")) {respond("missing parameter!");} $language=$_REQUEST["lang"]; //username if(!paramExists("user")) {respond("missing parameter!");} $username=$_REQUEST["user"]; //create the request url $apiUrl="http://$language.wikipedia.org/w/api.php?action=feedcontributions&format=xml&feedformat=rss&user=$username"; //fetch the data $apiResponse=file_get_contents($apiUrl); //echo the data echo $apiResponse; function paramExists($param, $empty=false) { if(isset($_REQUEST[$param])) { if(!$empty&&empty($_REQUEST[$param])) {return false;} return true; } return false; } function respond($message) { echo "<?xml version='1.0'?>\n"; echo "<proxy>\n"; echo "\t<message>\n"; echo "\t\t".$message."\n"; echo "\t</message>\n"; echo "</proxy>\n"; exit(); } ?>
Move return to inside try It is easy to understand if 'return' statement is moved inside try clause and there is no need to initialize a value. Follow-up minor fixes for review 276086 Change-Id: I3968e1702c0129ae02517e817da189ca137e7ab4
# Copyright 2015-2016 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy.orm import exc as sa_exc from neutron.db import l3_db from oslo_log import log as logging LOG = logging.getLogger(__name__) def get_tenant_id_by_router(session, router_id): with session.begin(subtransactions=True): try: router = session.query(l3_db.Router).filter_by(id=router_id).one() rt_tid = router.tenant_id LOG.debug("rt_tid=%s", rt_tid) return rt_tid except sa_exc.NoResultFound: LOG.debug("router not found %s", router_id)
# Copyright 2015-2016 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy.orm import exc as sa_exc from neutron.db import l3_db from oslo_log import log as logging LOG = logging.getLogger(__name__) def get_tenant_id_by_router(session, router_id): rt_tid = None with session.begin(subtransactions=True): try: router = session.query(l3_db.Router).filter_by(id=router_id).one() rt_tid = router.tenant_id except sa_exc.NoResultFound: LOG.debug("router not found %s", router_id) LOG.debug("rt_tid=%s", rt_tid) return rt_tid
Add dependencies, update for module name change
#! /usr/bin/env python import os, glob from distutils.core import setup NAME = 'bacula_configuration' VERSION = '0.1' WEBSITE = 'http://gallew.org/bacula_configuration' LICENSE = 'GPLv3 or later' DESCRIPTION = 'Bacula configuration management tool' LONG_DESCRIPTION = 'Bacula is a great backup tool, but ships with no way to manage the configuration. This suite will help you solve the management problem' AUTHOR = 'Brian Gallew' EMAIL = 'bacula_configuration@gallew.org' setup(name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=EMAIL, url=WEBSITE, install_requires = ['mysql-python'], extras_require = { 'parsing': ['pyparsing']}, scripts = glob.glob('bin/*'), package_data = {'bacula_tools': ['data/*']}, packages=['bacula_tools',], classifiers=['Development Status :: 5 - Alpha', 'Environment :: Console', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Programming Language :: Python', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Topic :: Utilities'], )
#! /usr/bin/env python import os, glob from distutils.core import setup NAME = 'bacula_configuration' VERSION = '0.1' WEBSITE = 'http://gallew.org/bacula_configuration' LICENSE = 'GPLv3 or later' DESCRIPTION = 'Bacula configuration management tool' LONG_DESCRIPTION = 'Bacula is a great backup tool, but ships with no way to manage the configuration. This suite will help you solve the management problem' AUTHOR = 'Brian Gallew' EMAIL = 'bacula_configuration@gallew.org' setup(name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=EMAIL, url=WEBSITE, scripts = glob.glob('bin/*'), package_data = {'bacula_configuration': ['data/*']}, packages=['bacula_configuration',], classifiers=['Development Status :: 5 - Alpha', 'Environment :: Console', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Programming Language :: Python', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Topic :: Utilities'], )
Fix config path difference (W vs w)
<?php namespace Hyperized\WeFact; use Illuminate\Support\ServiceProvider; class WefactServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool $defer */ protected $defer = false; /** * Bootstrap the application services. * * @return void */ public function boot() { // Configuration file $configPath = __DIR__.'/config/wefact.php'; $this->mergeConfigFrom($configPath, 'Wefact'); $this->publishes([ $configPath => config_path('Wefact.php'), ]); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['Hyperized\WeFact']; } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('Wefact', function($app) { return new Hyperized\WeFact; }); } }
<?php namespace Hyperized\WeFact; use Illuminate\Support\ServiceProvider; class WefactServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool $defer */ protected $defer = false; /** * Bootstrap the application services. * * @return void */ public function boot() { // Configuration file $configPath = __DIR__.'/config/wefact.php'; $this->mergeConfigFrom($configPath, 'Wefact'); $this->publishes([ $configPath => config_path('wefact.php'), ]); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['Hyperized\WeFact']; } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('Wefact', function($app) { return new Hyperized\WeFact; }); } }
Add an explanation detailing behavior of doneCountBuilder.
window.respokeTestConfig = { baseURL: 'http://testing.digiumlabs.com:3001' }; respoke.log.setLevel('silent'); window.doneOnceBuilder = function (done) { var called = false; return function (err) { if (!called) { called = true; done(err); } }; }; // build a function which calls the done callback according to the following rules: // 1. immediately if there is an error passed to it // 2. when the function has been called $num times. window.doneCountBuilder = function (num, done) { return (function () { var called = false; var count = 0; if (!num || num < 0) { throw new Error('First argument must be a positive integer.'); } return function (err) { if (called === true) { return; } count += 1; if (count === num || err) { called = true; done(err); } }; })(); };
window.respokeTestConfig = { baseURL: 'http://testing.digiumlabs.com:3001' }; respoke.log.setLevel('silent'); window.doneOnceBuilder = function (done) { var called = false; return function (err) { if (!called) { called = true; done(err); } }; }; window.doneCountBuilder = function (num, done) { return (function () { var called = false; var count = 0; if (!num || num < 0) { throw new Error('First argument must be a positive integer.'); } return function (err) { if (called === true) { return; } count += 1; if (count === num || err) { called = true; done(err); } }; })(); };
Fix imports for Django 1.6 and above
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Use the CAPI_DEVICE_PATH property in blockmap tests
/* IBM_PROLOG_BEGIN_TAG * This is an automatically generated prolog. * * $Source: src/java/test/blockmap/com/ibm/research/blockmap/CapiTestSupport.java $ * * IBM Data Engine for NoSQL - Power Systems Edition User Library Project * * Contributors Listed Below - COPYRIGHT 2015,2016,2017 * [+] International Business Machines Corp. * * * 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. * * IBM_PROLOG_END_TAG */ package com.ibm.research.blockmap; import org.junit.Ignore; @Ignore class CapiTestSupport { static final String DEVICE_PATH = "amd64".equals(System.getProperty("os.arch")) ? null : System.getProperty("CAPI_DEVICE_PATH", "/dev/sdf"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //static final String DEVICE_PATH="/dev/hdisk0"; }
/* IBM_PROLOG_BEGIN_TAG * This is an automatically generated prolog. * * $Source: src/java/test/blockmap/com/ibm/research/blockmap/CapiTestSupport.java $ * * IBM Data Engine for NoSQL - Power Systems Edition User Library Project * * Contributors Listed Below - COPYRIGHT 2015,2016,2017 * [+] International Business Machines Corp. * * * 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. * * IBM_PROLOG_END_TAG */ package com.ibm.research.blockmap; import org.junit.Ignore; @Ignore class CapiTestSupport { static final String DEVICE_PATH = "amd64".equals(System.getProperty("os.arch")) ? null : "/dev/sdf"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //static final String DEVICE_PATH="/dev/hdisk0"; }
CC-5781: Upgrade script for new storage quota implementation
<?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library') ))); set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library/propel/runtime/lib') ))); //Propel classes. set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path()); class StorageQuotaUpgrade { public static function startUpgrade() { echo "* Updating storage usage for new quota tracking".PHP_EOL; self::setStorageUsage(); } private static function setStorageUsage() { $musicDir = CcMusicDirsQuery::create() ->filterByDbType('stor') ->filterByDbExists(true) ->findOne(); $storPath = $musicDir->getDbDirectory(); $freeSpace = disk_free_space($storPath); $totalSpace = disk_total_space($storPath); Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace); } }
<?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library') ))); set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library/propel/runtime/lib') ))); class StorageQuotaUpgrade { public static function startUpgrade() { echo "* Updating storage usage for new quota tracking".PHP_EOL; self::setStorageUsage(); } private static function setStorageUsage() { $musicDir = CcMusicDirsQuery::create() ->filterByDbType('stor') ->filterByDbExists(true) ->findOne(); $storPath = $musicDir->getDbDirectory(); $freeSpace = disk_free_space($storPath); $totalSpace = disk_total_space($storPath); Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace); } }
Handle now returning Promise function
import {_string, _comment, p, pp} from '../universal/base'; import {_formatError} from './error'; window.console = window.console || {}; const _fnOrig = {}; function _interceptNativeConsoleFn(name) { _fnOrig[name] = window.console[name]; const {map} = Array.prototype; window.console[name] = function () { let str = map.call(arguments, arg => _string(arg)).join(' '); p(str, _comment('', '', `intercepted console.${name}`), {level: name}); try { _fnOrig[name] && _fnOrig[name].apply(window.console, arguments); } catch (err) { _formatError(err).then(str => { p(str, _comment('', err, `native console.${name}`), {level: 'error'}); }); } }; } function _restoreNativeConsoleFns() { Object.keys(_fnOrig).forEach(name => { window.console[name] = _fnOrig[name]; }); } export { _interceptNativeConsoleFn, _restoreNativeConsoleFns };
import {_string, _comment, p, pp} from '../universal/base'; import {_formatError} from './error'; window.console = window.console || {}; const _fnOrig = {}; function _interceptNativeConsoleFn(name) { _fnOrig[name] = window.console[name]; const {map} = Array.prototype; window.console[name] = function () { let str = map.call(arguments, arg => _string(arg)).join(' '); p(str, _comment('', '', `intercepted console.${name}`), {level: name}); try { _fnOrig[name] && _fnOrig[name].apply(window.console, arguments); } catch (err) { p(_formatError(err), _comment('', err, `native console.${name}`), {level: 'error'}); } }; } function _restoreNativeConsoleFns() { Object.keys(_fnOrig).forEach(name => { window.console[name] = _fnOrig[name]; }); } export { _interceptNativeConsoleFn, _restoreNativeConsoleFns };
Revert "[mh-14] "This import is ultimately just from django.contrib.auth.models import User - using that directly would probably address whatever circular import required that this import get put here, and make it clearer which model User is."-Dane" This reverts commit 7350c56339acaef416d03b6d7ae0e818ab8db182.
import re from django.core.exceptions import ValidationError from django.core.validators import EmailValidator, RegexValidator # First Name, Last Name: At least one alphanumeric character. name_validator = RegexValidator( regex=r'\w', flags=re.U, message='Please enter your name' ) # Email: valid email address email_validator = EmailValidator() # Email is not already taken def email_not_taken_validator(email): from myhpom.models import User if len(User.objects.filter(email=email)) > 0: raise ValidationError(u'Email already in use.') # Password: At least 8 chars total, 1 uppercase, lowercase, digit, special char. def password_validator(password): errors = [] if len(password) < 8: errors.append(u'8 characters total') if re.search(r"[a-z]", password) is None: errors.append(u'1 lowercase letter (a-z)') if re.search(r"[A-Z]", password) is None: errors.append(u'1 uppercase letter (A-Z)') if re.search(r"\d", password) is None: errors.append(u'1 number (0-9)') if re.search(r"[!\@\#\$\%\^\*\(\)\_\+\-\=]", password) is None: errors.append(u'1 special character (! @ # $ % ^ * ( ) _ + - =)') if len(errors) > 0: raise ValidationError(u'Please enter a password with at least ' + u', '.join(errors))
import re from django.core.exceptions import ValidationError from django.core.validators import EmailValidator, RegexValidator from django.contrib.auth.models import User # First Name, Last Name: At least one alphanumeric character. name_validator = RegexValidator( regex=r'\w', flags=re.U, message='Please enter your name' ) # Email: valid email address email_validator = EmailValidator() # Email is not already taken def email_not_taken_validator(email): if len(User.objects.filter(email=email)) > 0: raise ValidationError(u'Email already in use.') # Password: At least 8 chars total, 1 uppercase, lowercase, digit, special char. def password_validator(password): errors = [] if len(password) < 8: errors.append(u'8 characters total') if re.search(r"[a-z]", password) is None: errors.append(u'1 lowercase letter (a-z)') if re.search(r"[A-Z]", password) is None: errors.append(u'1 uppercase letter (A-Z)') if re.search(r"\d", password) is None: errors.append(u'1 number (0-9)') if re.search(r"[!\@\#\$\%\^\*\(\)\_\+\-\=]", password) is None: errors.append(u'1 special character (! @ # $ % ^ * ( ) _ + - =)') if len(errors) > 0: raise ValidationError(u'Please enter a password with at least ' + u', '.join(errors))
bug: Remove description from Restaurant class
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) description = Column(String(250)) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
Add Window functions to attempt partial sum
# Knapsack 0-1 function wieights, values and size n. import sys import pyspark.sql.functions as func from pyspark.sql.window import Window from pyspark.sql import Row from pyspark.sql.functions import lit from pyspark.sql.functions import col # Greedy implementation of 0-1 Knapsack algorithm. def knapsack(knapsackDF, W): ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights)) ratioDF.sort(col("ratio").desc()) partialSumsDF = (ratioDF .map(lambda x: x) ) return partialSumsDF knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)] knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values']) k = knapsack(knapsackData, 5) print k.take(3)
# Knapsack 0-1 function wieights, values and size n. from pyspark.sql import Row from pyspark.sql.functions import lit from pyspark.sql.functions import col # Greedy implementation of 0-1 Knapsack algorithm. def knapsack(knapsackDF, W): ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights)) ratioDF.sort(col("ratio").desc()) partialSumsDF = (ratioDF .map(lambda x: x) ) return partialSumsDF knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)] knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values']) k = knapsack(knapsackData, 5) print k.take(3)
Fix compression tests for legacy IE; make compression tests test for size rather than exact value stored
var { deepEqual } = require('../tests/util') module.exports = { plugin: require('./compression'), setup: setup, } function setup(store) { test('string compression size', function() { var str = 'foo' var serialized = store._serialize(str) store.set('foo', str) assert(store.raw.get('foo').length < serialized.length, 'compressed string should be smaller than uncompressed') assert(deepEqual(store.get('foo'), str), 'value should be equal') }) test('object compression', function () { var obj = { one: { two: 3 }} var serialized = store._serialize(obj) store.set('foo', obj) assert(store.raw.get('foo').length < serialized.length, 'compressed object should be smaller than uncompressed') assert(deepEqual(store.get('foo'), obj), 'should deep equal original object') store.remove('foo') }) test('decompress uncopmressed data', function () { store.raw.set('foo', 'baz') assert(store.get('foo') == 'baz', 'value should be baz') store.remove('foo') }) test('decompress non-existing data', function () { assert(store.get('bar') == undefined, 'value should be undefined') store.remove('bar') }) }
var { deepEqual } = require('../tests/util') module.exports = { plugin: require('./compression'), setup: setup, } function setup(store) { test('string compression', function() { store.set('foo', 'baz') assert(store.raw.get('foo') == 'ᄂゆ׬䀀', 'string should be lz compressed') assert(store.get('foo') == 'baz', 'value should be baz') }) test('object compression', function () { var obj = { one: { two: 3 }} store.set('foo', obj) assert(store.raw.get('foo') == '㞂⃶ݠ꘠岠ᜃ릎٠⾆耀', 'object should be lz compressed') assert(deepEqual(store.get('foo'), obj), 'should deep equal original object') store.remove('foo') }) test('decompress uncopmressed data', function () { store.raw.set('foo', 'baz') assert(store.get('foo') == 'baz', 'value should be baz') store.remove('foo') }) test('decompress non-existing data', function () { assert(store.get('bar') == undefined, 'value should be undefined') store.remove('bar') }) }
Add an entry in URLs configuration for image support.
from django.conf.urls import include, url from django.conf import settings from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtailimages import urls as wagtailimages_urls urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', 'search.views.search', name='search'), url(r'', include(wagtail_urls)), url(r'^images/', include(wagtailimages_urls)), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf.urls import include, url from django.conf import settings from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailcore import urls as wagtail_urls urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', 'search.views.search', name='search'), url(r'', include(wagtail_urls)), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
FIX disable product supplier pricelist
# -*- coding: utf-8 -*- { 'name': 'Product Supplier Pricelist', 'version': '1.0', 'category': 'Product', 'sequence': 14, 'summary': '', 'description': """ Product Supplier Pricelist ========================== Add sql constraint to restrict: 1. That you can only add one supplier to a product per company 2. That you can add olny one record of same quantity for a supplier pricelist It also adds to more menus (and add some related fields) on purchase/product. """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'purchase', ], 'data': [ 'product_view.xml', ], 'demo': [ ], 'test': [ ], # TODO fix this module and make installable 'installable': False, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- { 'name': 'Product Supplier Pricelist', 'version': '1.0', 'category': 'Product', 'sequence': 14, 'summary': '', 'description': """ Product Supplier Pricelist ========================== Add sql constraint to restrict: 1. That you can only add one supplier to a product per company 2. That you can add olny one record of same quantity for a supplier pricelist It also adds to more menus (and add some related fields) on purchase/product. """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'purchase', ], 'data': [ 'product_view.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Include detail in "The listed user cannot be searched" message
let index = 0; const logEntries = []; for (let i = 0; i < 500; i++) { logEntries.push(null); } export function getLog() { return logEntries; } export function log(name, message) { logEntries.shift(); logEntries.push({ index: index++, date: (new Date()).toISOString(), level: 'log', name, message, }); } export function warn(message) { logEntries.shift(); logEntries.push({ index: index++, date: (new Date()).toISOString(), level: 'warn', message, }); } export function error(context, stack = '') { if ( /The listed users and repositories cannot be searched/.test(stack) ) { stack = 'The listed user cannot be searched'; } logEntries.shift(); logEntries.push({ index: index++, date: (new Date()).toISOString(), level: 'error', context, stack, }); console.error(context + '\n' + stack); }
let index = 0; const logEntries = []; for (let i = 0; i < 500; i++) { logEntries.push(null); } export function getLog() { return logEntries; } export function log(name, message) { logEntries.shift(); logEntries.push({ index: index++, date: (new Date()).toISOString(), level: 'log', name, message, }); } export function warn(message) { logEntries.shift(); logEntries.push({ index: index++, date: (new Date()).toISOString(), level: 'warn', message, }); } export function error(context, stack = '') { if ( /The listed users and repositories cannot be searched/.test(stack) ) { warn('The listed user cannot be searched'); } else { logEntries.shift(); logEntries.push({ index: index++, date: (new Date()).toISOString(), level: 'error', context, stack, }); console.error(context + '\n' + stack); } }
Remove unused keys from manifest.
# -*- coding: utf-8 -*- # © 2015 Antiun Ingeniería S.L. - Jairo Llopis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Set Snippet's Anchor", "summary": "Allow to reach a concrete section in the page", "version": "8.0.1.0.0", "category": "Website", "website": "http://www.antiun.com", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": [ "website", ], "data": [ "views/assets.xml", "views/snippets.xml", ], }
# -*- coding: utf-8 -*- # © 2015 Antiun Ingeniería S.L. - Jairo Llopis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Set Snippet's Anchor", "summary": "Allow to reach a concrete section in the page", "version": "8.0.1.0.0", "category": "Website", "website": "http://www.antiun.com", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "website", ], "data": [ "views/assets.xml", "views/snippets.xml", ], }
Verify that type 4 fields are parsed correctly See #13
var assert = require("assert"); var parseApk = require(".."); describe("APK V24", function () { var output = null; before(function (done) { parseApk(__dirname + "/samples/test_v24.apk", function (err, out) { if (err) { return done(err); } output = out; done(); }); }); it("Parses correctly", function () { assert.notEqual(null, output); }); it("Starts with a manifest tag", function () { assert.equal(output.manifest.length, 1); }); it("Has a package name", function () { assert.equal(output.manifest[0]["@package"], "com.idotools.bookstore"); }); it("Has a package version", function () { assert.equal(output.manifest[0]["@platformBuildVersionCode"], "24"); }); it("Parses platformBuildVersionName", function () { assert.equal(output.manifest[0]["@platformBuildVersionName"], "7.0"); }); it("Has an application tag", function () { var manifest = output.manifest[0]; assert.equal(manifest.application.length, 1); }); });
var assert = require("assert"); var parseApk = require(".."); describe("APK V24", function () { var output = null; before(function (done) { parseApk(__dirname + "/samples/test_v24.apk", function (err, out) { if (err) { return done(err); } output = out; done(); }); }); it("Parses correctly", function () { assert.notEqual(null, output); }); it("Starts with a manifest tag", function () { assert.equal(output.manifest.length, 1); }); it("Has a package name", function () { assert.equal(output.manifest[0]["@package"], "com.idotools.bookstore"); }); it("Has a package version", function () { assert.equal(output.manifest[0]["@platformBuildVersionCode"], "24"); }); it("Has an application tag", function () { var manifest = output.manifest[0]; assert.equal(manifest.application.length, 1); }); });
Remove oversampling; use 20 percent instead
#!/usr/bin/env python import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 0.2) def generate_data(numx, numy): stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) return stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): stimulus = generate_data(gridDim[0], gridDim[1]) print('%d %d' % stimulus) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
#!/usr/bin/env python import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) return stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): stimulus = generate_data(gridDim[0], gridDim[1]) print('%d %d' % stimulus) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
Set example logLevel to 'info'
const iris = require('../index'); const dock = require('./docks/http'); const handler = require('./handlers/handler1'); const inputHook = require('./hooks/hook1'); const outputHook = require('./hooks/hook2'); iris.config = { threads: 4, logLevel: 'info', events: { dispatcher: true, docks: true }, vantage: { enabled: false, port: 1337 } }; dock.config = { port: 5000, parser: { subtagSeparator: '|', dataSeparator: ',' }, encoder: { subtagSeparator: '|', dataSeparator: ',' }, maxMessageLength: 100 }; iris.flow('Flow 1', { tag: 'tag1', docks: [dock], handler: handler, inputHooks: [inputHook], outputHooks: [outputHook] }); iris.flow('Flow 2', { tag: 'tag2', docks: [dock], handler: handler, inputHooks: [inputHook], outputHooks: [outputHook] });
const iris = require('../index'); const dock = require('./docks/http'); const handler = require('./handlers/handler1'); const inputHook = require('./hooks/hook1'); const outputHook = require('./hooks/hook2'); iris.config = { threads: 4, logLevel: 'silly', events: { dispatcher: true, docks: true }, vantage: { enabled: false, port: 1337 } }; dock.config = { port: 5000, parser: { subtagSeparator: '|', dataSeparator: ',' }, encoder: { subtagSeparator: '|', dataSeparator: ',' }, maxMessageLength: 100 }; iris.flow('Flow 1', { tag: 'tag1', docks: [dock], handler: handler, inputHooks: [inputHook], outputHooks: [outputHook] }); iris.flow('Flow 2', { tag: 'tag2', docks: [dock], handler: handler, inputHooks: [inputHook], outputHooks: [outputHook] });
Add .urban as Urban Dictionary alias.
from plumeria.command import commands, CommandError from plumeria.util import http from plumeria.util.ratelimit import rate_limit @commands.register("urban", "urb", category="Search") @rate_limit() async def urban_dictionary(message): """ Search Urban Dictionary for a word. """ q = message.content.strip() if not q: raise CommandError("Search term required!") r = await http.get("http://api.urbandictionary.com/v0/define", params=[ ('term', q), ]) data = r.json() if len(data['list']): return "**{word}** - {definition}".format( word=data['list'][0]['word'], definition=data['list'][0]['definition']) else: raise CommandError("no results found")
from plumeria.command import commands, CommandError from plumeria.util import http from plumeria.util.ratelimit import rate_limit @commands.register("urbandict", "urb", category="Search") @rate_limit() async def urban_dictionary(message): """ Search Urban Dictionary for a word. """ q = message.content.strip() if not q: raise CommandError("Search term required!") r = await http.get("http://api.urbandictionary.com/v0/define", params=[ ('term', q), ]) data = r.json() if len(data['list']): return "**{word}** - {definition}".format( word=data['list'][0]['word'], definition=data['list'][0]['definition']) else: raise CommandError("no results found")
EST-495: Add Electrical Substation and Land as unit type
/* * * Copyright 2012-2014 Eurocommercial Properties NV * * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.estatio.dom.asset; import org.estatio.dom.TitledEnum; import org.estatio.dom.utils.StringUtils; public enum UnitType implements TitledEnum { BOUTIQUE, CINEMA, DEHOR, EXTERNAL, HYPERMARKET, MEDIUM, OFFICE, SERVICES, STORAGE, TECHNICAL_ROOM, VIRTUAL, LAND, ELECTRICAL_SUBSTATION; public String title() { return StringUtils.enumTitle(this.name()); } }
/* * * Copyright 2012-2014 Eurocommercial Properties NV * * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.estatio.dom.asset; import org.estatio.dom.TitledEnum; import org.estatio.dom.utils.StringUtils; public enum UnitType implements TitledEnum { BOUTIQUE, CINEMA, DEHOR, EXTERNAL, HYPERMARKET, MEDIUM, OFFICE, SERVICES, STORAGE, TECHNICAL_ROOM, VIRTUAL; public String title() { return StringUtils.enumTitle(name()); } }
Fix enter key on Collaborative Room selection.
var mapSketcherClient; jQuery(function() { jQuery.getJSON('/config.json', function(config) { config.hostname = window.location.hostname mapSketcherClient = new MapSketcherClient(config); mapSketcherClient.launch(); }); $("a[rel]").overlay({ mask: { color: '#ebecff' , loadSpeed: 200 , opacity: 0.9 } }); $('#collaborativeRoomSelection form .cancel').click(function(e) { $('.close').click(); return e.preventDefault(); }); $('#collaborativeRoomSelection form').submit(function(e) { $('.close').click(); mapSketcherClient.joinColaborativeRoom(this.name.value); return e.preventDefault(); }); $(function() { $("#collaborativeRoomSelection form input").keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $('#collaborativeRoomSelection form').submit(); return false; } else { return true; } }); }); $('#feedback').githubVoice('sagmor', 'mapsketcher'); $('#personal').touchScrollable(); });
var mapSketcherClient; jQuery(function() { jQuery.getJSON('/config.json', function(config) { config.hostname = window.location.hostname mapSketcherClient = new MapSketcherClient(config); mapSketcherClient.launch(); }); $("a[rel]").overlay({ mask: { color: '#ebecff' , loadSpeed: 200 , opacity: 0.9 } }); $('#collaborativeRoomSelection form .cancel').click(function(e) { $('.close').click(); return e.preventDefault(); }); $('#collaborativeRoomSelection form').submit(function(e) { $('.close').click(); mapSketcherClient.joinColaborativeRoom(this.name.value); return e.preventDefault(); }); $('#feedback').githubVoice('sagmor', 'mapsketcher'); $('#personal').touchScrollable(); });
refactor(createUserReducer): Add initial user redux state.
import update from 'immutability-helper' // TODO: port user-specific code from the otp reducer. function createUserReducer () { const initialState = { accessToken: null, loggedInUser: null, loggedInUserMonitoredTrips: null, pathBeforeSignIn: null } return (state = initialState, action) => { switch (action.type) { case 'SET_CURRENT_USER': { return update(state, { accessToken: { $set: action.payload.accessToken }, loggedInUser: { $set: action.payload.user } }) } case 'SET_CURRENT_USER_MONITORED_TRIPS': { return update(state, { loggedInUserMonitoredTrips: { $set: action.payload } }) } case 'SET_PATH_BEFORE_SIGNIN': { return update(state, { pathBeforeSignIn: { $set: action.payload } }) } default: return state } } } export default createUserReducer
import update from 'immutability-helper' // TODO: port user-specific code from the otp reducer. function createUserReducer () { const initialState = {} return (state = initialState, action) => { switch (action.type) { case 'SET_CURRENT_USER': { return update(state, { accessToken: { $set: action.payload.accessToken }, loggedInUser: { $set: action.payload.user } }) } case 'SET_CURRENT_USER_MONITORED_TRIPS': { return update(state, { loggedInUserMonitoredTrips: { $set: action.payload } }) } case 'SET_PATH_BEFORE_SIGNIN': { return update(state, { pathBeforeSignIn: { $set: action.payload } }) } default: return state } } } export default createUserReducer
Fix paths to data files
package config import ( "flag" "github.com/vharitonsky/iniflags" ) var ( Name = flag.String("name", "tad", "Nick to use in IRC") Server = flag.String("server", "127.0.0.1:6668", "Host:Port to connect to") Channels = flag.String("chan", "#tad", "Channels to join") Ssl = flag.Bool("ssl", false, "Use SSL/TLS") Listen = flag.Bool("listenChannel", false, "Listen for command on public channels") HostInfo = flag.String("hostInfo", "./data/va_host_info_report.json", "Path to host info report") Promises = flag.String("promises", "./data/promises_outcome.log", "Path to promises report") Classes = flag.String("classes", "./data/classes.log", "Path to classes report") ) func init() { iniflags.Parse() }
package config import ( "flag" "github.com/vharitonsky/iniflags" ) var ( Name = flag.String("name", "tad", "Nick to use in IRC") Server = flag.String("server", "127.0.0.1:6668", "Host:Port to connect to") Channels = flag.String("chan", "#tad", "Channels to join") Ssl = flag.Bool("ssl", false, "Use SSL/TLS") Listen = flag.Bool("listenChannel", false, "Listen for command on public channels") HostInfo = flag.String("hostInfo", "./data/va_host_info_report.json", "Path to host info report") Promises = flag.String("promises", "./data/promises.csv", "Path to promises report") Classes = flag.String("classes", "./data/classes.txt", "Path to classes report") ) func init() { iniflags.Parse() }
Check if dir exists before calling listdir Changes along the way to how we clean up and detach after copying an image to a volume exposed a problem in the cleanup of the brick/initiator routines. The clean up in the initiator detach was doing a blind listdir of /dev/disk/by-path, however due to detach and cleanup being called upon completion of the image download to the volume if there are no other devices mapped in this directory the directory is removed. The result was that even though the create and copy of the image was succesful, the HostDriver code called os.lisdir on a directory that doesn't exist any longer and raises an unhandled exception that cause the taskflow mechanism to mark the volume as failed. Change-Id: I488755c1a49a77f42efbb58a7a4eb6f4f084df07 Closes-bug: #1243980
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os class HostDriver(object): def get_all_block_devices(self): """Get the list of all block devices seen in /dev/disk/by-path/.""" files = [] dir = "/dev/disk/by-path/" if os.path.isdir(dir): files = os.listdir(dir) devices = [] for file in files: devices.append(dir + file) return devices
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os class HostDriver(object): def get_all_block_devices(self): """Get the list of all block devices seen in /dev/disk/by-path/.""" dir = "/dev/disk/by-path/" files = os.listdir(dir) devices = [] for file in files: devices.append(dir + file) return devices
Fix get_backend doesn't actually return a backend
from armstrong.utils.backends import GenericBackend def get_template_names(blast, recipient_list, recipient): return [ 'tt_dailyemailblast/%s/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug, recipient.slug), 'tt_dailyemailblast/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug), 'tt_dailyemailblast/%s.html' % blast.blast_type.slug, ] def dispatch_to_backend(backend, default, *args): """Configure a GenericBackend and call it with `*args`. :param backend: Django setting name for the backend. :param default: Module path to the default backend. """ GenericBackend(backend, defaults=[default, ]).get_backend(*args)
from armstrong.utils.backends import GenericBackend def get_template_names(blast, recipient_list, recipient): return [ 'tt_dailyemailblast/%s/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug, recipient.slug), 'tt_dailyemailblast/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug), 'tt_dailyemailblast/%s.html' % blast.blast_type.slug, ] def dispatch_to_backend(backend, default, *args): """Configure a GenericBackend and call it with `*args`. :param backend: Django setting name for the backend. :param default: Module path to the default backend. """ GenericBackend(backend, defaults=[default, ]).get_backend()(*args)
Enable source maps in demo
module.exports = { entry: './docs/App.jsx', output: { filename: './docs/bundle.js' }, devServer: { inline: true }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'react', 'es2015' ], plugins: [ 'transform-class-properties', 'transform-object-rest-spread', 'transform-function-bind' ] } } ] }, devtool: 'source-map' };
module.exports = { entry: './docs/App.jsx', output: { filename: './docs/bundle.js' }, devServer: { inline: true }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'react', 'es2015' ], plugins: [ 'transform-class-properties', 'transform-object-rest-spread', 'transform-function-bind' ] } } ] } };
Check that init is a function
var i = (function() { 'use strict'; return { c: function(obj, args) { if (arguments.length > 0) { var newObj = Object.create(arguments[0]); if ('init' in newObj && typeof newObj.init === 'function') { if (arguments.length > 1) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } newObj.init.apply(newObj, args); } } return newObj; } } }; })();
var i = (function() { 'use strict'; return { c: function(obj, args) { if (arguments.length > 0) { var newObj = Object.create(arguments[0]); if ('init' in newObj) { if (arguments.length > 1) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } newObj.init.apply(newObj, args); } } return newObj; } } }; })();