text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Print only the message, not the whole tuple.
# vim: fileencoding=utf-8 from __future__ import print_function, absolute_import, unicode_literals import sys class VersionError (ValueError): pass def check_ex (): v = sys.version_info if v.major == 3: if v.minor < 3 or (v.minor == 3 and v.micro < 4): raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(v.minor, v.micro)) elif v.major == 2: if v.minor < 7: raise VersionError("Error: this is Python 2.{}, not 2.7".format(v.minor)) else: raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(v.major)) def check (): try: check_ex() except VersionError as e: print(e.args[0], file=sys.stderr) print("Python 2.7 or 3.3+ is required.", file=sys.stderr) sys.exit(2)
# vim: fileencoding=utf-8 from __future__ import print_function, absolute_import, unicode_literals import sys class VersionError (ValueError): pass def check_ex (): v = sys.version_info if v.major == 3: if v.minor < 3 or (v.minor == 3 and v.micro < 4): raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(v.minor, v.micro)) elif v.major == 2: if v.minor < 7: raise VersionError("Error: this is Python 2.{}, not 2.7".format(v.minor)) else: raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(v.major)) def check (): try: check_ex() except VersionError as e: print(e.args, file=sys.stderr) print("Python 2.7 or 3.3+ is required.", file=sys.stderr) sys.exit(2)
Use PHPUnit_Framework_Assert::assertSame() to check if the variables refer to the same ClassLoader instances
<?php namespace Spark\Test\Util; use PHPUnit_Framework_TestCase, Spark\Util; class ClassLoaderTest extends PHPUnit_Framework_TestCase { function setUp() { $this->classLoader = Util\ClassLoader(); } function testClassLoaderActsAsSingleton() { $instance1 = Util\ClassLoader(); $instance2 = Util\ClassLoader(); $this->assertSame($instance1, $instance2); } function testClassLoaderRegistersOnSplAutoloadStack() { $classLoader = $this->classLoader; $this->assertTrue(in_array($classLoader, spl_autoload_functions(), true)); } function testClassLoaderCanBeUnregisteredFromSplAutoloadStack() { $classLoader = $this->classLoader; $classLoader->unregister(); $this->assertFalse(in_array($classLoader, spl_autoload_functions(), true)); $classLoader->register(); } function testAutoloadFunction() { autoload("Spark\Test\SampleClass", TESTS . "/Spark/_data/SampleClass.php"); $this->assertTrue(class_exists("Spark\Test\SampleClass"), "Sample Class is not loadable"); } }
<?php namespace Spark\Test\Util; use PHPUnit_Framework_TestCase, Spark\Util; class ClassLoaderTest extends PHPUnit_Framework_TestCase { function setUp() { $this->classLoader = Util\ClassLoader(); } function testClassLoaderActsAsSingleton() { $instance1 = Util\ClassLoader(); $instance2 = Util\ClassLoader(); $this->assertEquals($instance1, $instance2); } function testClassLoaderRegistersOnSplAutoloadStack() { $classLoader = $this->classLoader; $this->assertTrue(in_array($classLoader, spl_autoload_functions(), true)); } function testClassLoaderCanBeUnregisteredFromSplAutoloadStack() { $classLoader = $this->classLoader; $classLoader->unregister(); $this->assertFalse(in_array($classLoader, spl_autoload_functions(), true)); $classLoader->register(); } function testAutoloadFunction() { autoload("Spark\Test\SampleClass", TESTS . "/Spark/_data/SampleClass.php"); $this->assertTrue(class_exists("Spark\Test\SampleClass"), "Sample Class is not loadable"); } }
Add descriptive name to each node type
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.provision; /** * The possible types of nodes in the node repository * * @author bratseth */ public enum NodeType { /** A node to be assigned to a tenant to run application workloads */ tenant(false, "Tenant node"), /** A host of a set of (docker) tenant nodes */ host(true, "Tenant docker host"), /** Nodes running the shared proxy layer */ proxy(false, "Proxy node"), /** A host of a (docker) proxy node */ proxyhost(true, "Proxy docker host"), /** A config server */ config(false, "Config server"), /** A host of a (docker) config server node */ confighost(true, "Config docker host"); private final boolean isDockerHost; private final String description; NodeType(boolean isDockerHost, String description) { this.isDockerHost = isDockerHost; this.description = description; } public boolean isDockerHost() { return isDockerHost; } public String description() { return description; } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.provision; /** * The possible types of nodes in the node repository * * @author bratseth */ public enum NodeType { /** A host of a set of (docker) tenant nodes */ host(true), /** Nodes running the shared proxy layer */ proxy(false), /** A host of a (docker) proxy node */ proxyhost(true), /** A node to be assigned to a tenant to run application workloads */ tenant(false), /** A config server */ config(false), /** A host of a (docker) config server node */ confighost(true); private boolean isDockerHost; NodeType(boolean isDockerHost) { this.isDockerHost = isDockerHost; } public boolean isDockerHost() { return isDockerHost; } }
UPDATE - Started work. Debugging atm
<?php //A PHP script to fetch, return and possibly store the latest headlines from the /r/onion and /r/notonion subreddits. function getTitles() { $feed = implode(file('http://reddit.com/r/nottheonion.rss?limit=100')); $xml = simplexml_load_string($feed); $json = json_encode($xml); $array = json_decode($json,TRUE); $feed = implode(file('http://reddit.com/r/theonion.rss?limit=100')); $xml = simplexml_load_string($feed); $json = json_encode($xml); $array2 = json_decode($json,TRUE); for ($i = 1; $i < count(array2['channel']['item']); $i++) { array_push($array['channel']['item'], $array2['channel']['item'][$i]); } return $array; } function getArticle() { //Fetch article, display to user. $conn = new mysqli("127.0.0.1", "database", "Password1234567890", "articles"); $query = "SELECT column FROM `allowed` ORDER BY RAND() LIMIT 1"; $result = $conn->query($query); print_r($result); } ?>
<?php //A PHP script to fetch, return and possibly store the latest headlines from the /r/onion and /r/notonion subreddits. function getTitles() { $feed = implode(file('http://reddit.com/r/nottheonion.rss?limit=100')); $xml = simplexml_load_string($feed); $json = json_encode($xml); $array = json_decode($json,TRUE); $feed = implode(file('http://reddit.com/r/theonion.rss?limit=100')); $xml = simplexml_load_string($feed); $json = json_encode($xml); $array2 = json_decode($json,TRUE); for ($i = 1; $i < count(array2['channel']['item']); $i++) { array_push($array['channel']['item'], $array2['channel']['item'][$i]); } return $array; } function getArticle() { } ?>
Print usage when invoking help or when too few arguments have been passed
package main import ( "flag" "fmt" "github.com/jbowtie/ratago/xslt" "github.com/moovweb/gokogiri" "github.com/moovweb/gokogiri/xml" "io/ioutil" "os" ) func xmlReadFile(filename string) (doc *xml.XmlDocument, err error) { data, err := ioutil.ReadFile(filename) if err != nil { return } doc, err = gokogiri.ParseXml(data) return } func usage() { fmt.Fprintf(os.Stderr, "Usage: %s [options] STYLESHEET INPUT\n", os.Args[0]) flag.PrintDefaults() } func main() { flag.Usage = usage flag.Parse() if flag.NArg() < 2 { usage() return } //set some prefs based on flags xslfile := flag.Arg(0) inxml := flag.Arg(1) style, err := xmlReadFile(xslfile) if err != nil { fmt.Println(err) return } doc, err := xmlReadFile(inxml) if err != nil { fmt.Println(err) return } //TODO: register some extensions (EXSLT, testing, debug) //TODO: process XInclude if enabled stylesheet := xslt.ParseStylesheet(style, xslfile) output := stylesheet.Process(doc) fmt.Println(output) }
package main import ( "flag" "fmt" "github.com/jbowtie/ratago/xslt" "github.com/moovweb/gokogiri" "github.com/moovweb/gokogiri/xml" "io/ioutil" ) func xmlReadFile(filename string) (doc *xml.XmlDocument, err error) { data, err := ioutil.ReadFile(filename) if err != nil { return } doc, err = gokogiri.ParseXml(data) return } func main() { flag.Parse() //set some prefs based on flags xslfile := flag.Arg(0) inxml := flag.Arg(1) style, err := xmlReadFile(xslfile) if err != nil { fmt.Println(err) return } doc, err := xmlReadFile(inxml) if err != nil { fmt.Println(err) return } //TODO: register some extensions (EXSLT, testing, debug) //TODO: process XInclude if enabled stylesheet := xslt.ParseStylesheet(style, xslfile) output := stylesheet.Process(doc) fmt.Println(output) }
test: Change test to reflect that arrayOf needs a validator
// @flow /* eslint-env jest */ import arrayOf from '../arrayOf'; import { validator } from '../../'; describe('rules.arrayOf', () => { it('should return array of validation errors', () => { expect(arrayOf('elements', [{}], { name: { required: true } }, validator)).toEqual( [{ name: { rule: 'required', value: undefined, field: 'name', config: { required: true } } }] ); }); it('should return correct with nested arrayOf', () => { const options = { name: { length: { max: 10 } }, nestedValues: { arrayOf: { key: { numeric: { min: 0 } }, value: { length: { min: 3 } } }, }, }; const output = arrayOf( 'fields', [{ name: 'Test 1', nestedValues: [{ key: 'NaN', value: 'Value' }] }], options, validator ); const expectedOutput = [{ 'nestedValues[0].key': { field: 'nestedValues[0].key', rule: 'numeric', value: 'NaN', config: { numeric: { min: 0 } }, }, }]; expect(output).toEqual(expectedOutput); }); });
// @flow /* eslint-env jest */ import arrayOf from '../arrayOf'; describe('rules.arrayOf', () => { it('should return array of validation errors', () => { expect(arrayOf('elements', [{}], { name: { required: true } })).toEqual( [{ name: { rule: 'required', value: undefined, field: 'name', config: { required: true } } }] ); }); it('should return correct with nested arrayOf', () => { const options = { name: { length: { max: 10 } }, nestedValues: { arrayOf: { key: { numeric: { min: 0 } }, value: { length: { min: 3 } } }, }, }; const output = arrayOf( 'fields', [{ name: 'Test 1', nestedValues: [{ key: 'NaN', value: 'Value' }] }], options ); const expectedOutput = [{ 'nestedValues[0].key': { field: 'nestedValues[0].key', rule: 'numeric', value: 'NaN', config: { numeric: { min: 0 } }, }, }]; expect(output).toEqual(expectedOutput); }); });
[build-script] Make --show-sdks fail if calling `xcodebuild` failed
# swift_build_support/debug.py - Print information on the build -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ---------------------------------------------------------------------------- # # Convenient functions for printing out information on the build process. # # ---------------------------------------------------------------------------- from __future__ import absolute_import from __future__ import print_function import sys from . import shell def print_xcodebuild_versions(file=sys.stdout): """ Print the host machine's `xcodebuild` version, as well as version information for all available SDKs. """ version = shell.capture( ['xcodebuild', '-version'], dry_run=False, echo=False).rstrip() sdks = shell.capture( ['xcodebuild', '-version', '-sdk'], dry_run=False, echo=False).rstrip() fmt = """\ {version} --- SDK versions --- {sdks} """ print(fmt.format(version=version, sdks=sdks), file=file) file.flush()
# swift_build_support/debug.py - Print information on the build -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ---------------------------------------------------------------------------- # # Convenient functions for printing out information on the build process. # # ---------------------------------------------------------------------------- from __future__ import absolute_import from __future__ import print_function import sys from . import shell def print_xcodebuild_versions(file=sys.stdout): """ Print the host machine's `xcodebuild` version, as well as version information for all available SDKs. """ version = shell.capture( ['xcodebuild', '-version'], dry_run=False, echo=False, optional=True).rstrip() sdks = shell.capture( ['xcodebuild', '-version', '-sdk'], dry_run=False, echo=False, optional=True).rstrip() fmt = """\ {version} --- SDK versions --- {sdks} """ print(fmt.format(version=version, sdks=sdks), file=file) file.flush()
Add updateItem test for field Boolean.
var demand = require('must'); var keystone = require('../').init(), Types = keystone.Field.Types; /** Test List and Fields */ var Test = keystone.List('Test'); var item; before(function() { Test.add({ date: Types.Date, datetime: Types.Datetime, bool: Types.Boolean }); Test.register(); /** Test Item */ item = new Test.model(); }); /** FieldType: Date */ describe("Fields", function() { describe("Date", function() { it('should parse without error via underscore date', function() { item._.date.parse('20131204', 'YYYYMMDD'); }); it('should be the date we expect', function() { demand(item._.date.format()).to.equal('4th Dec 2013'); demand(item._.date.format('YYYYMMDD')).to.equal('20131204'); }); it('should be a moment object', function() { demand(item._.date.moment()._isAMomentObject); }); }); describe("Boolean", function() { it('should update it\'s model if data passed is boolean true', function() { Test.fields.bool.updateItem(item, { 'bool': true }); demand(item.bool).to.be.true(); }); it('should update it\'s model if data passed is string \'true\'', function() { Test.fields.bool.updateItem(item, { 'bool': 'true' }); demand(item.bool).to.be.true(); }); }); });
var demand = require('must'); var keystone = require('../').init(), Types = keystone.Field.Types; /** Test List and Fields */ var Test = keystone.List('Test'); Test.add({ date: Types.Date, datetime: Types.Datetime }); Test.register(); /** Test Item */ var item = new Test.model(); /** FieldType: Date */ describe("Fields", function() { describe("Date", function() { it('should parse without error via underscore date', function() { item._.date.parse('20131204', 'YYYYMMDD'); }); it('should be the date we expect', function() { demand(item._.date.format()).to.equal('4th Dec 2013'); demand(item._.date.format('YYYYMMDD')).to.equal('20131204'); }); it('should be a moment object', function() { demand(item._.date.moment()._isAMomentObject); }); }); });
Allow inspection of Delegate's handlers and clean up.
var util = require('./util'); // Returns a callable object that, when called with a function, subscribes // to the delegate. Call invoke on this object to invoke each handler. function Delegate() { var handlers = []; function callable(handler) { if (arguments.length !== 1) { throw new Error('Delegate takes exactly 1 argument (' + arguments.length + ' given)'); } else if (typeof handler !== 'function') { throw new Error('Delegate argument must be a Function object (got ' + typeof handler + ')'); } handlers.push(handler); return function unsubscribe() { return util.removeLast(handlers, handler); }; } callable.invoke = function invoke() { var args = arguments; util.forEach(handlers, function (handler) { handler.apply(null, args); }); }; // Expose handlers for inspection callable.handlers = handlers; return callable; } module.exports = Delegate;
var util = require('./util'); // Returns a callable object that, when called with a function, subscribes // to the delegate. Call invoke on this object to invoke each handler. function Delegate() { var self = this; self.handlers = []; function callable(handler) { if (arguments.length !== 1) { throw new Error('Delegate takes exactly 1 argument (' + arguments.length + ' given)'); } else if (typeof handler !== 'function') { throw new Error('Delegate argument must be a Function object (got ' + typeof handler + ')'); } self.handlers.push(handler); return function unsubscribe() { return util.removeLast(self.handlers, handler); }; } callable.invoke = function invoke() { var args = arguments; util.forEach(self.handlers, function (handler) { handler.apply(null, args); }); }; return callable; } module.exports = Delegate;
Correct the layouts directory path in docblock. Changed "/app/Template/Layout" to "/src/Template/Layout".
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.4 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace App\View; use Cake\Event\EventManager; use Cake\Network\Request; use Cake\Network\Response; /** * A view class that is used for AJAX responses. * Currently only switches the default layout and sets the response type - * which just maps to text/html by default. */ class AjaxView extends AppView { /** * The name of the layout file to render the view inside of. The name * specified is the filename of the layout in /src/Template/Layout without * the .ctp extension. * * @var string */ public $layout = 'ajax'; /** * Initialization hook method. * * @return void */ public function initialize() { parent::initialize(); $this->response->type('ajax'); } }
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.4 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace App\View; use Cake\Event\EventManager; use Cake\Network\Request; use Cake\Network\Response; /** * A view class that is used for AJAX responses. * Currently only switches the default layout and sets the response type - * which just maps to text/html by default. */ class AjaxView extends AppView { /** * The name of the layout file to render the view inside of. The name * specified is the filename of the layout in /app/Template/Layout without * the .ctp extension. * * @var string */ public $layout = 'ajax'; /** * Initialization hook method. * * @return void */ public function initialize() { parent::initialize(); $this->response->type('ajax'); } }
Remove duplicate route for /
var pg = require('pg'); var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 3000 }); server.start(function () { console.log('Server running at:', server.info.uri); }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Hello from SpotScore API!'); } }); server.route({ method: 'GET', path: '/objects', handler: function (request, reply) { var location = request.params.location; var address = request.params.address; var categories = request.params.categories; var bbox = request.params.bbox; var radius = request.params.radius; var nearest = request.params.nearest; // Make actual request to database // Compile the JSON response reply(); } });
var pg = require('pg'); var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 3000 }); server.start(function () { console.log('Server running at:', server.info.uri); }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Hello from SpotScore API!'); } }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Hello from SpotScore API!'); } }); server.route({ method: 'GET', path: '/objects', handler: function (request, reply) { var location = request.params.location; var address = request.params.address; var categories = request.params.categories; var bbox = request.params.bbox; var radius = request.params.radius; var nearest = request.params.nearest; // Make actual request to database // Compile the JSON response reply(); } });
Change example test function name to comply with go vet
/* * Copyright (c) 2015 Kurt Jung (Gmail: kurt.w.jung) * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package example_test import ( "errors" "github.com/jung-kurt/gofpdf/internal/example" ) // Test the Filename() and Summary() functions. func ExampleFilename() { fileStr := example.Filename("example") example.Summary(errors.New("printer on fire"), fileStr) // Output: // printer on fire }
/* * Copyright (c) 2015 Kurt Jung (Gmail: kurt.w.jung) * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package example_test import ( "errors" "github.com/jung-kurt/gofpdf/internal/example" ) // Test the Filename() and Summary() functions. func ExampleExample_Filename() { fileStr := example.Filename("example") example.Summary(errors.New("printer on fire"), fileStr) // Output: // printer on fire }
Remove unnecessary code to init the game
describe('Satellite game', function () { it('should exists', function () { expect(s).to.be.an('object'); expect(s).to.have.property('config'); expect(s).to.have.property('init'); }); it('should contains ship properties', function () { expect(s.config.ship).to.be.an('object'); expect(s).to.have.deep.property('config.ship.hull'); expect(s).to.have.deep.property('config.ship.shields'); expect(s).to.have.deep.property('config.ship.maxSpeed'); }); it('should init game variables', function () { expect(s).to.have.property('projector').and.to.be.an('object'); expect(s).to.have.property('loader').and.to.be.an('object'); expect(s).to.have.property('game').and.to.be.an('object'); }); });
describe('Satellite game', function () { it('should exists', function () { expect(s).to.be.an('object'); expect(s).to.have.property('config'); expect(s).to.have.property('init'); }); it('should contains ship properties', function () { expect(s.config.ship).to.be.an('object'); expect(s).to.have.deep.property('config.ship.hull'); expect(s).to.have.deep.property('config.ship.shields'); expect(s).to.have.deep.property('config.ship.maxSpeed'); }); it('should init the game', function () { var spy = sinon.spy(s, 'init'); s.init(); expect(spy.called).to.equal(true); expect(s).to.have.property('projector').and.to.be.an('object'); expect(s).to.have.property('loader').and.to.be.an('object'); expect(s).to.have.property('game').and.to.be.an('object'); }); });
Update module name and summary
# -*- coding: utf-8 -*- # © 2017 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Bank Reconciliation Report', 'version': '10.0.1.0.0', 'license': 'AGPL-3', 'author': "Akretion,Odoo Community Association (OCA)", 'website': 'http://www.akretion.com', 'summary': 'Adds an XLSX report to help on bank reconciliation', 'depends': ['account', 'report_xlsx'], 'data': [ 'report/report.xml', 'views/account_bank_statement_view.xml', ], 'installable': True, }
# -*- coding: utf-8 -*- # © 2017 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Account Bank Statement Reconciliation Summary', 'version': '10.0.1.0.0', 'license': 'AGPL-3', 'author': "Akretion,Odoo Community Association (OCA)", 'website': 'http://www.akretion.com', 'summary': 'Adds an XLSX report to help on bank statement reconciliation', 'depends': ['account', 'report_xlsx'], 'data': [ 'report/report.xml', 'views/account_bank_statement_view.xml', ], 'installable': True, }
Use lists for the JOIN command and parse them before sending
class OutputHandler(object): def __init__(self, connection): self.connection = connection def cmdJOIN(self, channels, keys=[]): for i in range(len(channels)): if channels[i][0] not in self.connection.supportHelper.chanTypes: channels[i] = "#{}".format(channels[i]) self.connection.sendMessage("JOIN", ",".join(channels), ",".join(keys)) def cmdNICK(self, nick): self.connection.sendMessage("NICK", nick) def cmdPING(self, message): self.connection.sendMessage("PING", ":{}".format(message)) def cmdPONG(self, message): self.connection.sendMessage("PONG", ":{}".format(message)) def cmdQUIT(self, reason): self.connection.sendMessage("QUIT", ":{}".format(reason)) def cmdUSER(self, ident, gecos): # RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all. # Pass 0 for usermodes instead. self.connection.sendMessage("USER", ident, "0", "*", ":{}".format(gecos))
class OutputHandler(object): def __init__(self, connection): self.connection = connection def cmdJOIN(self, channels, keys=None): chans = channels.split(",") for i in range(len(chans)): if chans[i][0] not in self.connection.supportHelper.chanTypes: chans[i] = "#{}".format(chans[i]) channels = ",".join(chans) if keys: self.connection.sendMessage("JOIN", channels, keys) else: self.connection.sendMessage("JOIN", channels) def cmdNICK(self, nick): self.connection.sendMessage("NICK", nick) def cmdPING(self, message): self.connection.sendMessage("PING", ":{}".format(message)) def cmdPONG(self, message): self.connection.sendMessage("PONG", ":{}".format(message)) def cmdQUIT(self, reason): self.connection.sendMessage("QUIT", ":{}".format(reason)) def cmdUSER(self, ident, gecos): # RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all. # Pass 0 for usermodes instead. self.connection.sendMessage("USER", ident, "0", "*", ":{}".format(gecos))
Remove readmore after-collapse scroll effect
$(function(){ $('.step-section').readmore({ collapsedHeight: 300, heightMargin: 300, speed: 250, moreLink: '<a href="#" class="readmore text-center"><span class="arrow arrow-more"></span></a>', lessLink: '<a href="#" class="readmore text-center"><span class="arrow arrow-less"></span></a>', blockCSS: 'display: block;', // override default CSS, which has width settings that conflict with Foundation // seems like these classes should be added by the library, but they're not... beforeToggle: function(trigger, element, expanded) { if (!expanded) { // The "open" link was clicked $(element).addClass('readmore-expanded'); $(element).removeClass('readmore-collapsed'); } else if (expanded) { // The "close" link was clicked $(element).addClass('readmore-collapsed'); $(element).removeClass('readmore-expanded'); } }, }); });
$(function(){ $('.step-section').readmore({ collapsedHeight: 300, heightMargin: 300, speed: 250, moreLink: '<a href="#" class="readmore text-center"><span class="arrow arrow-more"></span></a>', lessLink: '<a href="#" class="readmore text-center"><span class="arrow arrow-less"></span></a>', blockCSS: 'display: block;', // override default CSS, which has width settings that conflict with Foundation // seems like these classes should be added by the library, but they're not... beforeToggle: function(trigger, element, expanded) { if (!expanded) { // The "open" link was clicked $(element).addClass('readmore-expanded'); $(element).removeClass('readmore-collapsed'); } else if (expanded) { // The "close" link was clicked $(element).addClass('readmore-collapsed'); $(element).removeClass('readmore-expanded'); } }, afterToggle: function(trigger, element, expanded) { if(! expanded) { // The "Close" link was clicked $('html, body').animate( { scrollTop: element.offset().top }, {duration: 250 } ); } }, }); });
Add support for memcache with Drupal config via override.settings.php.
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'nginx', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } }, { type: 'list', name: 'cacheInternal', message: 'Choose a cache backend:', default: 'memcache', choices: [ 'memcache', 'database' ] } ]; module.exports = prompts;
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'nginx', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } } ]; module.exports = prompts;
Change guard and use lodash
const { pick, get } = require('lodash') const { authorisedRequest } = require('../../lib/authorised-request') const config = require('../../config') function fetchRawCompanyListItems(token, id) { return authorisedRequest(token, { method: 'GET', url: `${config.apiRoot}/v4/company-list/${id}/item`, }) } const fetchRawCompanyList = (token) => authorisedRequest(token, { method: 'GET', url: `${config.apiRoot}/v4/company-list`, }) const transformRawCompany = ({ latest_interaction, company }) => ({ company: pick(company, ['id', 'name']), latestInteraction: pick(latest_interaction, ['date', 'id', 'subject']), ditParticipants: latest_interaction ? latest_interaction.dit_participants.map((participant) => ({ name: get(participant, 'adviser.name'), team: get(participant, 'team.name'), })) : [], }) const fetchCompanyLists = (token) => fetchRawCompanyList(token).then(({ results }) => Promise.all( results.map((list) => fetchRawCompanyListItems(token, list.id).then(({ results }) => ({ ...pick(list, ['id', 'name']), companies: results.map(transformRawCompany), })) ) ) ) module.exports = { fetchCompanyLists, }
const { pick } = require('lodash') const { authorisedRequest } = require('../../lib/authorised-request') const config = require('../../config') function fetchRawCompanyListItems(token, id) { return authorisedRequest(token, { method: 'GET', url: `${config.apiRoot}/v4/company-list/${id}/item`, }) } const fetchRawCompanyList = (token) => authorisedRequest(token, { method: 'GET', url: `${config.apiRoot}/v4/company-list`, }) const transformRawCompany = ({ latest_interaction, company }) => ({ company: pick(company, ['id', 'name']), latestInteraction: pick(latest_interaction, ['date', 'id', 'subject']), ditParticipants: latest_interaction ? latest_interaction.dit_participants.map((participant) => ({ name: participant.adviser ? participant.adviser.name : '', team: participant.team ? participant.team.name : '', })) : [], }) const fetchCompanyLists = (token) => fetchRawCompanyList(token).then(({ results }) => Promise.all( results.map((list) => fetchRawCompanyListItems(token, list.id).then(({ results }) => ({ ...pick(list, ['id', 'name']), companies: results.map(transformRawCompany), })) ) ) ) module.exports = { fetchCompanyLists, }
Fix branch in caching logic
from app.clients import factualClient from app.util import log from factual import APIException CROSSWALK_CACHE_VERSION = 1 def getVenueIdentifiers(yelpID): yelpURL = "https://yelp.com/biz/%s" % yelpID mapping = { "id": yelpID, "version": CROSSWALK_CACHE_VERSION, "yelp": { "url": yelpURL } } try: obj = factualClient.crosswalk().filters({"url": yelpURL}).data() if len(obj) == 0: return mapping, True factualID = obj[0]["factual_id"] mapping["factualID"] = factualID idList = factualClient.crosswalk().filters({"factual_id": factualID}).data() for idObj in idList: namespace = idObj["namespace"] del idObj["factual_id"] del idObj["namespace"] mapping[namespace] = idObj return mapping, True except APIException: log.error("Factual API failed again") except Exception: log.exception("Factual problem " + yelpID) return mapping, False
from app.clients import factualClient from app.util import log from factual import APIException CROSSWALK_CACHE_VERSION = 1 def getVenueIdentifiers(yelpID): yelpURL = "https://yelp.com/biz/%s" % yelpID mapping = { "id": yelpID, "version": CROSSWALK_CACHE_VERSION, "yelp": { "url": yelpURL } } try: obj = factualClient.crosswalk().filters({"url": yelpURL}).data() if len(obj) == 0: return mapping factualID = obj[0]["factual_id"] mapping["factualID"] = factualID idList = factualClient.crosswalk().filters({"factual_id": factualID}).data() for idObj in idList: namespace = idObj["namespace"] del idObj["factual_id"] del idObj["namespace"] mapping[namespace] = idObj return mapping, True except APIException: log.error("Factual API failed again") except Exception: log.exception("Factual problem " + yelpID) return mapping, False
Fix exception syntax for Python3.
""" Filter submodule for libhxl. David Megginson Started February 2015 License: Public Domain Documentation: https://github.com/HXLStandard/libhxl-python/wiki """ import sys from hxl import HXLException from hxl.model import HXLDataProvider, HXLColumn class HXLFilterException(HXLException): pass def run_script(func): try: func(sys.argv[1:], sys.stdin, sys.stdout) except BaseException as e: print >>sys.stderr, "Fatal error (" + e.__class__.__name__ + "): " + e.message print >>sys.stderr, "Exiting ..." sys.exit(2) def fix_tag(t): """trim whitespace and add # if needed""" t = t.strip() if not t.startswith('#'): t = '#' + t return t def parse_tags(s): """Parse tags out from a comma-separated list""" return list(map(fix_tag, s.split(','))) def find_column(tag, columns): """Find the first column in a list with tag""" for column in columns: if column.hxlTag == tag: return column return None
""" Filter submodule for libhxl. David Megginson Started February 2015 License: Public Domain Documentation: https://github.com/HXLStandard/libhxl-python/wiki """ import sys from hxl import HXLException from hxl.model import HXLDataProvider, HXLColumn class HXLFilterException(HXLException): pass def run_script(func): try: func(sys.argv[1:], sys.stdin, sys.stdout) except BaseException, e: print >>sys.stderr, "Fatal error (" + e.__class__.__name__ + "): " + e.message print >>sys.stderr, "Exiting ..." sys.exit(2) def fix_tag(t): """trim whitespace and add # if needed""" t = t.strip() if not t.startswith('#'): t = '#' + t return t def parse_tags(s): """Parse tags out from a comma-separated list""" return list(map(fix_tag, s.split(','))) def find_column(tag, columns): """Find the first column in a list with tag""" for column in columns: if column.hxlTag == tag: return column return None
Update tests for Listings pages
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class ListingsTest extends TestCase { /** * Test to see that the Listings pages load. * @dataProvider listingRoutes * @return void */ public function testListingRoutesLoadProperly($routeName, $value) { $this->get(route($routeName))->assertSee($value); } public function listingRoutes() { return [ 'Machines listing' => ['machines.index', 'Equipment Inventory - Active'], 'Modality listing' => ['machines.showModalityIndex', 'List equipment by modality'], 'Location listing' => ['machines.showLocationIndex', 'List equipment by location'], 'Manufacturer listing' => ['machines.showManufacturerIndex', 'List equipment by manufacturer'], 'Inactive machines listing' => ['machines.inactive', 'Equipment Inventory - Inactive'], 'Removed machines listing' => ['machines.removed', 'Equipment Inventory - Removed'], 'Test equipment listing' => ['testequipment.index', 'Equipment Inventory - Test Equipment'], 'Test equipment cal dates listing' => ['testequipment.showCalDates', 'Recent Test Equipment Calibration Dates'], ]; } }
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\WithoutMiddleware; use Tests\TestCase; class ListingsTest extends TestCase { use WithoutMiddleware; /** * Test to see that the Listings pages load. * @dataProvider listingPages * @return void */ public function testListingPagesLoadProperly($routeName, $value) { $this->get(route($routeName))->assertSee($value); } public function listingPages() { return [ 'Machines listing' => ['machines.index', 'Equipment Inventory - Active'], 'Modality listing' => ['machines.showModalityIndex', 'List equipment by modality'], 'Location listing' => ['machines.showLocationIndex', 'List equipment by location'], 'Manufacturer listing' => ['machines.showManufacturerIndex', 'List equipment by manufacturer'], 'Inactive machines listing' => ['machines.inactive', 'Equipment Inventory - Inactive'], 'Removed machines listing' => ['machines.removed', 'Equipment Inventory - Removed'], 'Test equipment listing' => ['testequipment.index', 'Equipment Inventory - Test Equipment'], 'Test equipment cal dates listing' => ['testequipment.showCalDates', 'Recent Test Equipment Calibration Dates'], ]; } }
Add LCTY to locality 🎢
var through2 = require('through2'); function featureCodeToLayer(featureCode) { switch (featureCode) { case 'PCLI': return 'country'; case 'ADM1': return 'region'; case 'ADM2': return 'county'; case 'ADMD': return 'localadmin'; case 'PPL': case 'PPLA': case 'PPLA2': case 'PPLA3': case 'PPLA4': case 'PPLC': case 'PPLF': case 'PPLG': case 'PPLL': case 'PPLS': case 'LCTY': case 'STLMT': return 'locality'; case 'ADM4': case 'ADM5': case 'PPLX': return 'neighborhood'; default: return 'venue'; } } function create() { return through2.obj(function(data, enc, next) { data.layer = featureCodeToLayer(data.feature_code); next(null, data); }); } module.exports = { featureCodeToLayer: featureCodeToLayer, create: create };
var through2 = require('through2'); function featureCodeToLayer(featureCode) { switch (featureCode) { case 'PCLI': return 'country'; case 'ADM1': return 'region'; case 'ADM2': return 'county'; case 'ADMD': return 'localadmin'; case 'PPL': case 'PPLA': case 'PPLA2': case 'PPLA3': case 'PPLA4': case 'PPLC': case 'PPLF': case 'PPLG': case 'PPLL': case 'PPLS': case 'STLMT': return 'locality'; case 'ADM4': case 'ADM5': case 'PPLX': return 'neighborhood'; default: return 'venue'; } } function create() { return through2.obj(function(data, enc, next) { data.layer = featureCodeToLayer(data.feature_code); next(null, data); }); } module.exports = { featureCodeToLayer: featureCodeToLayer, create: create };
Rewrite code to use formManager
const FormManager = require('../../common_functions/form_manager'); const TelegramBot = (() => { 'use strict'; const form = '#frm_telegram_bot'; const onLoad = () => { const bot_name = 'binary_test_bot'; FormManager.init(form, [ { selector: '#token', validations: ['req'], exclude_request: 1 } ]); FormManager.handleSubmit({ form_selector: form, fnc_response_handler: () => { const token = $('#token').val(); const url = `https://t.me/${bot_name}/?start=${token}`; window.location.assign(url); } }); }; const onUnload = () => { $(form).off('submit'); }; return { onLoad: onLoad, onUnload: onUnload, }; })(); module.exports = TelegramBot;
const TelegramBot = (() => { 'use strict'; const form = '#frm_telegram_bot'; const onLoad = () => { const bot_name = 'binary_test_bot'; $(form).on('submit', (e) => { e.preventDefault(); const token = $('#token').val(); const url = `https://t.me/${bot_name}/?start=${token}`; window.location.assign(url); }); }; const onUnload = () => { $(form).off('submit'); }; return { onLoad : onLoad, onUnload: onUnload, }; })(); module.exports = TelegramBot;
Downgrade Wildfly to work around basic auth bug As described in https://issues.redhat.com/browse/WFLY-15478, Wildfly 25.0.0.Final rejects all requests that use basic auth with a 401 response. 25.0.0.Final is, at the time of writing, the latest available Wildfly Docker image so we need to downgrade to 24.0.0.Final. Closes gh-28956
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.deployment; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; /** * Deployment tests for Wildfly. * * @author Christoph Dreis * @author Scott Frederick */ @Testcontainers(disabledWithoutDocker = true) class WildflyDeploymentTests extends AbstractDeploymentTests { @Container static WarDeploymentContainer container = new WarDeploymentContainer("jboss/wildfly:24.0.0.Final", "/opt/jboss/wildfly/standalone/deployments", DEFAULT_PORT); @Override WarDeploymentContainer getContainer() { return container; } }
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.deployment; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; /** * Deployment tests for Wildfly. * * @author Christoph Dreis * @author Scott Frederick */ @Testcontainers(disabledWithoutDocker = true) class WildflyDeploymentTests extends AbstractDeploymentTests { @Container static WarDeploymentContainer container = new WarDeploymentContainer("jboss/wildfly:latest", "/opt/jboss/wildfly/standalone/deployments", DEFAULT_PORT); @Override WarDeploymentContainer getContainer() { return container; } }
Fix redirect after poll creation Redirect to /#/Manage/<ManageId> rather than /Manage/<ManageId>
(function () { angular .module('GVA.Creation') .controller('CreateBasicPageController', ['$scope', 'AccountService', 'PollService', function ($scope, AccountService, PollService) { $scope.openLoginDialog = function () { AccountService.openLoginDialog($scope); }; $scope.openRegisterDialog = function () { AccountService.openRegisterDialog($scope); }; $scope.createPoll = function (question) { PollService.createPoll(question, function (data) { window.location.href = "/#/Manage/" + data.ManageId; }); }; }]); })();
(function () { angular .module('GVA.Creation') .controller('CreateBasicPageController', ['$scope', 'AccountService', 'PollService', function ($scope, AccountService, PollService) { $scope.openLoginDialog = function () { AccountService.openLoginDialog($scope); }; $scope.openRegisterDialog = function () { AccountService.openRegisterDialog($scope); }; $scope.createPoll = function (question) { PollService.createPoll(question, function (data) { window.location.href = "/Manage/" + data.ManageId; }); }; }]); })();
Revert "Added exception is scan rank is 0 which it is when scanning broken." This reverts commit 5b0d56cecfec5abfff80fb28173ff07807c657cd.
package org.eclipse.scanning.api.scan.rank; import org.eclipse.scanning.api.points.IPosition; /** * * Please use this class to figure out the correct slice * from a position in a scan. * * @author Matthew Gerring * */ class ScanRankService implements IScanRankService { public IScanSlice createScanSlice(IPosition position, int... datashape) { final int scanRank = position.getScanRank(); final int[] start = new int[scanRank+datashape.length]; final int[] stop = new int[scanRank+datashape.length]; for (int dim = 0; dim < scanRank; dim++) { start[dim] = position.getIndex(dim); stop[dim] = position.getIndex(dim)+1; } int index = 0; for (int i = datashape.length; i>0; i--) { start[start.length-i] = 0; stop[stop.length-i] = datashape[index]; index++; } return new ScanSlice(start, stop, null); } }
package org.eclipse.scanning.api.scan.rank; import org.eclipse.scanning.api.points.AbstractPosition; import org.eclipse.scanning.api.points.IPosition; /** * * Please use this class to figure out the correct slice * from a position in a scan. * * @author Matthew Gerring * */ class ScanRankService implements IScanRankService { public IScanSlice createScanSlice(IPosition position, int... datashape) { final int scanRank = position.getScanRank(); if (scanRank==0) throw new IllegalArgumentException("A zero scan rank is not allowed"); final int[] start = new int[scanRank+datashape.length]; final int[] stop = new int[scanRank+datashape.length]; for (int dim = 0; dim < scanRank; dim++) { start[dim] = position.getIndex(dim); stop[dim] = position.getIndex(dim)+1; } int index = 0; for (int i = datashape.length; i>0; i--) { start[start.length-i] = 0; stop[stop.length-i] = datashape[index]; index++; } return new ScanSlice(start, stop, null); } }
Test broken harvest doesn't break everything.
"""Tests related to the remotes.tasks functions.""" from django_celery_beat.models import IntervalSchedule, PeriodicTask from jobs.models import Post from ..models import Source from ..tasks import setup_periodic_tasks, harvest_sources def test_make_tasks(): """Ensure that setup makes some tasks/schedules.""" setup_periodic_tasks(None) intervals = IntervalSchedule.objects.all().count() tasks = PeriodicTask.objects.all().count() assert intervals > 0 assert tasks > 0 def test_harvest_sources(fossjobs_rss_feed, mocker): """Verify that harvest sources calls harvest.""" mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed) Source.objects.all().delete() Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/') pre_posts = Post.objects.all().count() harvest_sources() post_posts = Post.objects.all().count() assert pre_posts != post_posts assert post_posts > 0 def test_broken_harvest(mocker): """Verify that broken harvest doesn't throw.""" mocker.patch('feedparser.parse', side_effect=lambda x: 'broken') Source.objects.all().delete() Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/') harvest_sources() # If that raises, then we've got an issue. assert True
"""Tests related to the remotes.tasks functions.""" from django_celery_beat.models import IntervalSchedule, PeriodicTask from jobs.models import Post from ..models import Source from ..tasks import setup_periodic_tasks, harvest_sources def test_make_tasks(): """Ensure that setup makes some tasks/schedules.""" setup_periodic_tasks(None) intervals = IntervalSchedule.objects.all().count() tasks = PeriodicTask.objects.all().count() assert intervals > 0 assert tasks > 0 def test_harvest_sources(fossjobs_rss_feed, mocker): """Verify that harvest sources calls harvest.""" mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed) Source.objects.all().delete() Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/') pre_posts = Post.objects.all().count() harvest_sources() post_posts = Post.objects.all().count() assert pre_posts != post_posts assert post_posts > 0
Fix Python2.6 format string placeholder.
from __future__ import absolute_import, unicode_literals import os import tempfile DB = os.path.join(tempfile.gettempdir(), 'fake_useragent.json') BROWSERS_STATS_PAGE = 'http://www.w3schools.com/browsers/browsers_stats.asp' BROWSER_BASE_PAGE = 'http://useragentstring.com/pages/useragentstring.php?name={0}' # noqa BROWSERS_COUNT_LIMIT = 50 REPLACEMENTS = { ' ': '', '_': '', } SHORTCUTS = { 'internet explorer': 'internetexplorer', 'ie': 'internetexplorer', 'msie': 'internetexplorer', 'google': 'chrome', 'googlechrome': 'chrome', 'ff': 'firefox', } OVERRIDES = { 'IE': 'Internet Explorer', }
from __future__ import absolute_import, unicode_literals import os import tempfile DB = os.path.join(tempfile.gettempdir(), 'fake_useragent.json') BROWSERS_STATS_PAGE = 'http://www.w3schools.com/browsers/browsers_stats.asp' BROWSER_BASE_PAGE = 'http://useragentstring.com/pages/useragentstring.php?name={}' # noqa BROWSERS_COUNT_LIMIT = 50 REPLACEMENTS = { ' ': '', '_': '', } SHORTCUTS = { 'internet explorer': 'internetexplorer', 'ie': 'internetexplorer', 'msie': 'internetexplorer', 'google': 'chrome', 'googlechrome': 'chrome', 'ff': 'firefox', } OVERRIDES = { 'IE': 'Internet Explorer', }
Support time series data represented in epoch time
// Copyright: 2013 PMSI-AlignAlytics // License: "https://github.com/PMSI-AlignAlytics/dimple/blob/master/MIT-LICENSE.txt" // Source: /src/objects/axis/methods/_parseDate.js this._parseDate = function (inDate) { // A javascript date object var outDate; if (!isNaN(inDate)) { // If inDate is a number, assume it's epoch time outDate = new Date(inDate); } else if (this.dateParseFormat === null || this.dateParseFormat === undefined) { // If nothing has been explicity defined you are in the hands of the browser gods // may they smile upon you... outDate = Date.parse(inDate); } else { outDate = d3.time.format(this.dateParseFormat).parse(inDate); } // Return the date return outDate; };
// Copyright: 2013 PMSI-AlignAlytics // License: "https://github.com/PMSI-AlignAlytics/dimple/blob/master/MIT-LICENSE.txt" // Source: /src/objects/axis/methods/_parseDate.js this._parseDate = function (inDate) { // A javascript date object var outDate; if (this.dateParseFormat === null || this.dateParseFormat === undefined) { // If nothing has been explicity defined you are in the hands of the browser gods // may they smile upon you... outDate = Date.parse(inDate); } else { outDate = d3.time.format(this.dateParseFormat).parse(inDate); } // Return the date return outDate; };
Print variables for initial testing
#!/usr/bin/env python import requests import json import sys import argparse parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed') parser.add_argument('--url', help='URL where Monorail is located') parser.add_argument('--pr', help='List of pull requests we will ask for') args = parser.parse_args() curl_uri = '/deploy-info?pr=' if (args.url): if args.url.startswith('http'): request_url = args.url+curl_uri else: request_url = 'http://'+args.url+curl_uri else: print 'We need an URL' exit(1) if (args.pr): pull_requests = args.pr.split() pull_requests = ",".join(pull_requests) else: print 'A list of PRs is needed' exit(1) try: r = requests.get(request_url+pull_requests) except: print 'Something went wrong querying Monorail' exit(2) json_list = r.json() services=json_list['services'] deploynotes=json_list['deployNotes'] print 'deploynotes:' print deploynotes print '\nservices:' print services if deploynotes == 'True': print 'There are deployNotes so we cannot continue' exit(3) if len(services) == 0: print 'There are not services defined so we cannot continue' exit(4) exit (0)
#!/usr/bin/env python import requests import json import sys import argparse parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed') parser.add_argument('--url', help='URL where Monorail is located') parser.add_argument('--pr', help='List of pull requests we will ask for') args = parser.parse_args() curl_uri = '/deploy-info?pr=' if (args.url): if args.url.startswith('http'): request_url = args.url+curl_uri else: request_url = 'http://'+args.url+curl_uri else: print 'We need an URL' exit(1) if (args.pr): pull_requests = args.pr.split() pull_requests = ",".join(pull_requests) else: print 'A list of PRs is needed' exit(1) try: r = requests.get(request_url+pull_requests) except: print 'Something went wrong querying Monorail' exit(2) json_list = r.json() services=json_list['services'] deploynotes=json_list['deployNotes'] if deploynotes == 'True': print 'There are deployNotes so we cannot continue' exit(3) if len(services) == 0: print 'There are not services defined so we cannot continue' exit(4) exit (0)
Fix query string update helper.
# coding: utf-8 import random import urlparse from string import ascii_letters, digits from urllib import urlencode # From http://tools.ietf.org/html/rfc6750#section-2.1 BEARER_TOKEN_CHARSET = ascii_letters + digits + '-._~+/' def random_hash(length): return ''.join(random.sample(BEARER_TOKEN_CHARSET, length)) def random_hash_generator(length): return lambda: random_hash(length) def update_parameters(url, parameters): """ Updates a URL's existing GET parameters. @url: a URL string. @parameters: a dictionary of parameters, {string:string}. """ parsed_url = urlparse.urlparse(url) existing_query_parameters = urlparse.parse_qsl(parsed_url.query) # Read http://docs.python.org/2/library/urlparse.html#urlparse.urlparse # if this is confusing. return urlparse.urlunparse(( parsed_url.scheme, parsed_url.netloc, parsed_url.path, parsed_url.params, urlencode(existing_query_parameters + parameters.items()), parsed_url.fragment ))
# coding: utf-8 import random import urlparse from string import ascii_letters, digits from urllib import urlencode # From http://tools.ietf.org/html/rfc6750#section-2.1 BEARER_TOKEN_CHARSET = ascii_letters + digits + '-._~+/' def random_hash(length): return ''.join(random.sample(BEARER_TOKEN_CHARSET, length)) def random_hash_generator(length): return lambda: random_hash(length) def update_parameters(url, parameters): """ Updates a URL's existing GET parameters. @url: a URL string. @parameters: a dictionary of parameters, {string:string}. """ parsed_url = urlparse(url) query_parameters = urlparse.parse_qsl(parsed_url.query) parsed_url.query = urlencode(query_parameters + parameters.items()) return urlparse.urlunparse(parsed_url)
Save the values of the instructions to concept results if available
import {hashToCollection} from './hashToCollection' export function getConceptResultsForSentenceCombining(question) { const directions = question.instructions || "Combine the sentences."; const prompt = question.prompt.replace(/(<([^>]+)>)/ig, "").replace(/&nbsp;/ig, "") const answer = question.attempts[0].submitted let conceptResults = []; if (question.attempts[0].response) { conceptResults = hashToCollection(question.attempts[0].response.conceptResults) || [] } else { conceptResults = []; } if (conceptResults.length === 0) { conceptResults = [{ conceptUID: question.conceptID, correct: false }] } return conceptResults.map((conceptResult) => { return { concept_uid: conceptResult.conceptUID, metadata: { correct: conceptResult.correct ? 1 : 0, directions, prompt, answer } } }) }
import {hashToCollection} from './hashToCollection' export function getConceptResultsForSentenceCombining(question) { const directions = "Combine the sentences."; const prompt = question.prompt.replace(/(<([^>]+)>)/ig, "").replace(/&nbsp;/ig, "") const answer = question.attempts[0].submitted let conceptResults = []; if (question.attempts[0].response) { conceptResults = hashToCollection(question.attempts[0].response.conceptResults) || [] } else { conceptResults = []; } if (conceptResults.length === 0) { conceptResults = [{ conceptUID: question.conceptID, correct: false }] } return conceptResults.map((conceptResult) => { return { concept_uid: conceptResult.conceptUID, metadata: { correct: conceptResult.correct ? 1 : 0, directions, prompt, answer } } }) }
Fix broxen import in Python 3
"""Core pep438 utility functions""" from __future__ import unicode_literals import requests try: import xmlrpclib except: import xmlrpc.client as xmlprclib import lxml.html from requirements import parse def valid_package(package_name): """Return bool if package_name is a valid package on PyPI""" response = requests.head('https://pypi.python.org/pypi/%s' % package_name) if response.status_code != 404: response.raise_for_status() return response.status_code != 404 def get_urls(package_name): """Return list of URLs on package's PyPI page that would be crawled""" response = requests.get('https://pypi.python.org/simple/%s' % package_name) response.raise_for_status() page = lxml.html.fromstring(response.content) crawled_urls = {link.get('href') for link in page.xpath('//a') if link.get('rel') in ("homepage", "download")} return crawled_urls def get_pypi_packages(fileobj): """Return all PyPI-hosted packages from file-like object""" return [p['name'] for p in parse(fileobj) if not p.get('uri')] def get_pypi_user_packages(user): client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') return [x[1] for x in client.user_packages(user)]
"""Core pep438 utility functions""" from __future__ import unicode_literals import requests import xmlrpclib import lxml.html from requirements import parse def valid_package(package_name): """Return bool if package_name is a valid package on PyPI""" response = requests.head('https://pypi.python.org/pypi/%s' % package_name) if response.status_code != 404: response.raise_for_status() return response.status_code != 404 def get_urls(package_name): """Return list of URLs on package's PyPI page that would be crawled""" response = requests.get('https://pypi.python.org/simple/%s' % package_name) response.raise_for_status() page = lxml.html.fromstring(response.content) crawled_urls = {link.get('href') for link in page.xpath('//a') if link.get('rel') in ("homepage", "download")} return crawled_urls def get_pypi_packages(fileobj): """Return all PyPI-hosted packages from file-like object""" return [p['name'] for p in parse(fileobj) if not p.get('uri')] def get_pypi_user_packages(user): client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') return [x[1] for x in client.user_packages(user)]
Add Etag header to proxy response from s3
import boto import logging from tpt import private_settings from boto.s3.key import Key from django.http import StreamingHttpResponse from django.http import Http404 logger = logging.getLogger(__name__) def stream_object(key_name): s3 = boto.connect_s3( aws_access_key_id = private_settings.AWS_ACCESS_KEY_ID, aws_secret_access_key = private_settings.AWS_SECRET_ACCESS_KEY) bucket = s3.get_bucket(private_settings.AWS_S3_BUCKET, validate=False) key = bucket.get_key(key_name) if not key: logger.warn('Unable to find key "{}" in bucket "{}"'.format(key_name, private_settings.AWS_S3_BUCKET)) raise Http404() response = StreamingHttpResponse(key) if key.etag: response['Etag'] = key.etag if key.content_type: response['Content-Type'] = key.content_type else: response['Content-Type'] = 'text/plain' if key.size: response['Content-Length'] = key.size return response
import boto import logging from tpt import private_settings from boto.s3.key import Key from django.http import StreamingHttpResponse from django.http import Http404 logger = logging.getLogger(__name__) def stream_object(key_name): s3 = boto.connect_s3( aws_access_key_id = private_settings.AWS_ACCESS_KEY_ID, aws_secret_access_key = private_settings.AWS_SECRET_ACCESS_KEY) bucket = s3.get_bucket(private_settings.AWS_S3_BUCKET, validate=False) key = bucket.get_key(key_name) if not key: logger.warn('Unable to find key "{}" in bucket "{}"'.format(key_name, private_settings.AWS_S3_BUCKET)) raise Http404() response = StreamingHttpResponse(key) if key.content_type: response['Content-Type'] = key.content_type else: response['Content-Type'] = 'text/plain' if key.size: response['Content-Length'] = key.size return response
Fix warnings under Python 3
from __future__ import absolute_import from ofxparse import OfxParser, OfxPrinter from unittest import TestCase from os import close, remove from tempfile import mkstemp import sys sys.path.append('..') from .support import open_file class TestOfxWrite(TestCase): def test_write(self): with open_file('fidelity.ofx') as f: ofx = OfxParser.parse(f) self.assertEqual(str(ofx), "") def test_using_ofx_printer(self): with open_file('checking.ofx') as f: ofx = OfxParser.parse(f) fd, name = mkstemp() close(fd) printer = OfxPrinter(ofx=ofx, filename=name) printer.write(tabs=1) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from ofxparse import OfxParser as op, OfxPrinter from unittest import TestCase from os import close, remove from tempfile import mkstemp import sys sys.path.append('..') from .support import open_file class TestOfxWrite(TestCase): def test_write(self): test_file = open_file('fidelity.ofx') ofx_doc = op.parse(test_file) self.assertEqual(str(ofx_doc), "") def test_using_ofx_printer(self): test_file = open_file('checking.ofx') ofx_doc = op.parse(test_file) fd, name = mkstemp() close(fd) printer = OfxPrinter(ofx=ofx_doc, filename=name) printer.write(tabs=1) if __name__ == "__main__": import unittest unittest.main()
Add connection details as environment variables
package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Value("${endpoint}") private String endpoint; @Value("${port}") private String port; @Value("${username}") private String username; @Value("${password}") private String password; @Value("${replicationGroup}") private String replicationGroup; @Value("${namespace}") private String namespace; @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://" + endpoint + ":" + port, username, password, certificate); } @Bean public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion("2.7"); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials(null, null, namespace, replicationGroup); } }
package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://104.197.239.202:4443", "root", "ChangeMe", certificate); } @Bean public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion("2.7"); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository", "ns1", "urn:storageos:ReplicationGroupInfo:f81a7335-cadf-48fb-8eda-4856b250e9de:global"); } }
Fix proto lang handler to work minified and to use the type style for types like uint32.
// Copyright (C) 2006 Google Inc. // // 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. /** * @fileoverview * Registers a language handler for Protocol Buffers as described at * http://code.google.com/p/protobuf/. * * Based on the lexical grammar at * http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715 * * @author mikesamuel@gmail.com */ PR['registerLangHandler'](PR['sourceDecorator']({ 'keywords': ( 'bytes,default,double,enum,extend,extensions,false,' + 'group,import,max,message,option,' + 'optional,package,repeated,required,returns,rpc,service,' + 'syntax,to,true'), 'types': /^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/, 'cStyleComments': true }), ['proto']);
// Copyright (C) 2006 Google Inc. // // 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. /** * @fileoverview * Registers a language handler for Protocol Buffers as described at * http://code.google.com/p/protobuf/. * * Based on the lexical grammar at * http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715 * * @author mikesamuel@gmail.com */ PR['registerLangHandler'](PR['sourceDecorator']({ keywords: ( 'bool bytes default double enum extend extensions false fixed32 ' + 'fixed64 float group import int32 int64 max message option ' + 'optional package repeated required returns rpc service ' + 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 ' + 'uint64'), cStyleComments: true }), ['proto']);
Include test templates in distributions. This probably wasn't working before, although apparently I didn't notice. But then no one really runs tests for their 3PA, do they? This is v1.2.
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.2' package_data = { 'render_as': [ 'test_templates/avoid_clash_with_real_app/*.html', 'test_templates/render_as/*.html', ], } setup( name=PACKAGE, version=VERSION, description="Template rendering indirector based on object class", packages=[ 'render_as', 'render_as/templatetags', ], package_data=package_data, license='MIT', author='James Aylett', author_email='james@tartarus.org', install_requires=[ 'Django~=1.10', ], classifiers=[ 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.1' package_data = { 'render_as': [ 'templates/avoid_clash_with_real_app/*.html', 'templates/render_as/*.html', ], } setup( name=PACKAGE, version=VERSION, description="Template rendering indirector based on object class", packages=[ 'render_as', 'render_as/templatetags', ], package_data=package_data, license='MIT', author='James Aylett', author_email='james@tartarus.org', install_requires=[ 'Django~=1.10', ], classifiers=[ 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Update to protect against no val().
(function() { (function($) { $.fn.inputDefaults = function(options) { var opts; opts = $.extend({}, $.fn.inputDefaults.defaults, options); return this.each(function() { var $el, defaultValue; $el = $(this); defaultValue = $el.data("defaultValue") || opts.value; if (!$el.val()) { $el.val(defaultValue); } return $el.focus(function() { if ($el.val() === defaultValue) { return $el.val(""); } }).blur(function() { if (!$el.val()) { return $el.val(defaultValue); } }); }); }; return $.fn.inputDefaults.defaults = { value: "Please enter a value..." }; })(jQuery); }).call(this);
(function($) { $.fn.inputDefaults = function(options) { var opts; opts = $.extend({}, $.fn.inputDefaults.defaults, options); return this.each(function() { var $el, defaultValue; $el = $(this); defaultValue = $el.data("defaultValue") || opts.value; if ($el.val() === "") { $el.val(defaultValue); } return $el.focus(function() { if ($el.val() === defaultValue) { return $el.val(""); } }).blur(function() { if ($el.val() === "") { return $el.val(defaultValue); } }); }); }; return $.fn.inputDefaults.defaults = { value: "Please enter a value..." }; })(jQuery);
Add author info in the document info if it doesn't exist.
exports.nit = function(env) { var $ = env.$; // at least one author var authors = $(".section#authors address"); if (authors.length < 1) { return env.error("No authors"); } var hauth = $("#document .authors"); if (hauth.length < 1) { hauth = $("<div class='authors'/>"); hauth.appendTo($("#document")); } hauth.empty(); hauth.comment("Automatically generated from $('.section#authors address')"); authors.each(function() { var author = $("<div>").addClass("author"); // Only pull out the default (hopefully English-ified) name from the // author information into the header. // Note: "initial" is not a valid RFC 6350 property name. var initial = $(".initial[lang='']", this).text(); if (initial.length === 0) { initial = $(".n .given-name[lang='']", this).text().slice(0,1) + "."; } $("<span>").addClass("initial").text(initial).appendTo(author); $("<span>").addClass("surname").text($(".n .family-name[lang='']", this).text()).appendTo(author); $("<span>").addClass("company").text($(".org[lang='']", this).text()).appendTo(author); author.appendTo(hauth); }); };
exports.nit = function(env) { var $ = env.$; // at least one author var authors = $(".section#authors address"); if (authors.length < 1) { return env.error("No authors"); } var hauth = $("#document .authors"); hauth.empty(); hauth.comment("Automatically generated from $('.section#authors address')"); authors.each(function() { var author = $("<div>").addClass("author"); // Only pull out the default (hopefully English-ified) name from the // author information into the header. // Note: "initial" is not a valid RFC 6350 property name. var initial = $(".initial[lang='']", this).text(); if (initial.length === 0) { initial = $(".n .given-name[lang='']", this).text().slice(0,1) + "."; } $("<span>").addClass("initial").text(initial).appendTo(author); $("<span>").addClass("surname").text($(".n .family-name[lang='']", this).text()).appendTo(author); $("<span>").addClass("company").text($(".org[lang='']", this).text()).appendTo(author); author.appendTo(hauth); }); };
Read from standard input and perform on each line The analyze script can now be run with, for example - echo "Message" | python analyze.py - cat | python analyze.py (enter messages and end with Ctrl-D) - python analyze.py < filename - MapReduce (at some point)
import sys import re def main(argv): # Load the positive and negative words words = {} with open("words/positive.txt") as file: for line in file: words[line.rstrip()] = 1 with open("words/negative.txt") as file: for line in file: words[line.rstrip()] = -1 # Perform the sentiment analysis for message in sys.stdin: score = 0 found = 0 for w in message.split(): # Only keep alphanumeric characters and some punctuation. w = re.sub(r'[^\-\'+\w]', '', w).lower() if w in words: score += words[w] found += 1 print(round(score / float(found) if found != 0 else 0, 2)) if __name__ == "__main__": main(sys.argv[1:])
import sys import re def main(argv): # Message to perform sentiment analysis on message = argv[0] if len(argv) > 0 else "" if message == "": print("Usage: python analyze.py [message]") sys.exit(1) # Load the positive and negative words words = {} with open("words/positive.txt") as file: for line in file: words[line.rstrip()] = 1 with open("words/negative.txt") as file: for line in file: words[line.rstrip()] = -1 # Perform the sentiment analysis score = 0 found = 0 for w in message.split(): # Only keep alphanumeric characters and some punctuation. w = re.sub(r'[^\-\'+\w]', '', w).lower() if w in words: score += words[w] found += 1 print(round(score / float(found) if found != 0 else 0, 2)) if __name__ == "__main__": main(sys.argv[1:])
Fix lastInsertId for OCI8 adapter
<?php /** * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\DB; class AdapterOCI8 extends Adapter { public function lastInsertId($table) { if($table !== null) { $suffix = '_SEQ'; $table = '"'.$table.$suffix.'"'; } return $this->conn->realLastInsertId($table); } public function fixupStatement($statement) { $statement = str_replace( '`', '"', $statement ); $statement = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $statement ); $statement = str_ireplace( 'UNIX_TIMESTAMP()', "(cast(sys_extract_utc(systimestamp) as date) - date'1970-01-01') * 86400", $statement ); return $statement; } }
<?php /** * Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\DB; class AdapterOCI8 extends Adapter { public function lastInsertId($table) { if($table !== null) { $suffix = '_SEQ'; $table = '"'.$table.$suffix.'"'; $table = $this->conn->replaceTablePrefix( $table ); } return $this->conn->lastInsertId($table); } public function fixupStatement($statement) { $statement = str_replace( '`', '"', $statement ); $statement = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $statement ); $statement = str_ireplace( 'UNIX_TIMESTAMP()', "(cast(sys_extract_utc(systimestamp) as date) - date'1970-01-01') * 86400", $statement ); return $statement; } }
Replace bodyParser by json middleware
var express = require('express'); var _ = require('lodash'); var app = express(); app.use(express.favicon('public/img/favicon.ico')); app.use(express.static('public')); app.use(express.logger('dev')); app.use(express.json()); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); var Situation = require('./lib/situation'); app.post('/process', function(req, res) { var situ = new Situation(req.body.situation); var resp = situ.get('simulation'); res.send({ params: req.body.situation, situation: _.extend({}, situ.computedValues, situ.userValues), response: resp, claimedValues: situ.claimedValues }); }); app.get('/', function(req, res){ res.render('index'); }); app.listen(process.env.PORT || 5000);
var express = require('express'); var _ = require('lodash'); var app = express(); app.use(express.favicon('public/img/favicon.ico')); app.use(express.static('public')); app.use(express.logger('dev')); app.use(express.bodyParser()); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); var Situation = require('./lib/situation'); app.post('/process', function(req, res) { var situ = new Situation(req.body.situation); var resp = situ.get('simulation'); res.send({ params: req.body.situation, situation: _.extend({}, situ.computedValues, situ.userValues), response: resp, claimedValues: situ.claimedValues }); }); app.get('/', function(req, res){ res.render('index'); }); app.listen(process.env.PORT || 5000);
Make the lib imports work on other computers than Simon's
#!/usr/bin/env python import sys, os root = os.path.dirname(__file__) paths = ( os.path.join(root), os.path.join(root, "djangopeople", "lib"), ) for path in paths: if not path in sys.path: sys.path.insert(0, path) from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
#!/usr/bin/env python import sys paths = ( '/home/simon/sites/djangopeople.net', '/home/simon/sites/djangopeople.net/djangopeoplenet', '/home/simon/sites/djangopeople.net/djangopeoplenet/djangopeople/lib', ) for path in paths: if not path in sys.path: sys.path.insert(0, path) from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Stop kim responding to herself if there are multiple instances running.
var Slack = require('slack-client'), Kimbot = require('./kimbot'), Foursquare = require('./clients/foursquare'), OpenWeather = require('./clients/openweather'); var responses = [ '안녕! It\'s a nice day! Why not head to the market? I recommend the ' + 'Bibbimbap!', 'สวัสดี! A busy day with lots of meetings, but there\'s always time for ' + 'Thai!', 'Chào bạn! Take a trip to Camden Town and sample the excellent ' + 'Vietnamese food!', 'Hola! Burritos all round!', 'Let\'s try something new... what do you suggest?' ]; var foursquare = new Foursquare(process.env.FS_CLIENT_ID, process.env.FS_CLIENT_SECRET); var weather = new OpenWeather(process.env.OW_APP_ID); var slack = new Slack(process.env.SLACK_BOT_KEY, true, true); var kimbot = new Kimbot(slack, responses, { foursquare: foursquare, weather: weather }); slack.on('message', function (message) { // Inside AnonFn. to ensure not called with slacks 'this' scope. if (message.user !== slack.self.id) { kimbot.respond(message); } }); slack.login();
var Slack = require('slack-client'), Kimbot = require('./kimbot'), Foursquare = require('./clients/foursquare'), OpenWeather = require('./clients/openweather'); var responses = [ '안녕! It\'s a nice day! Why not head to the market? I recommend the ' + 'Bibbimbap!', 'สวัสดี! A busy day with lots of meetings, but there\'s always time for ' + 'Thai!', 'Chào bạn! Take a trip to Camden Town and sample the excellent ' + 'Vietnamese food!', 'Hola! Burritos all round!', 'Let\'s try something new... what do you suggest?' ]; var foursquare = new Foursquare(process.env.FS_CLIENT_ID, process.env.FS_CLIENT_SECRET); var weather = new OpenWeather(process.env.OW_APP_ID); var slack = new Slack(process.env.SLACK_BOT_KEY, true, true); var kimbot = new Kimbot(slack, responses, { foursquare: foursquare, weather: weather }); slack.on('message', function (message) { // Inside AnonFn. to ensure not called with slacks 'this' scope. kimbot.respond(message); }); slack.login();
Add locale to package data
#!/usr/bin/env python from setuptools import setup from fandjango import __version__ setup( name = 'fandjango', version = __version__, description = "Fandjango makes it stupidly easy to create Facebook applications with Django.", author = "Johannes Gorset", author_email = "jgorset@gmail.com", url = "http://github.com/jgorset/fandjango", packages = [ 'fandjango', 'fandjango.migrations', 'fandjango.templatetags' ], package_data = { 'fandjango': ['templates/*', 'locale/*'] }, install_requires = [ 'facepy>=0.4.2', 'requests==0.7.6' ], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ] )
#!/usr/bin/env python from setuptools import setup from fandjango import __version__ setup( name = 'fandjango', version = __version__, description = "Fandjango makes it stupidly easy to create Facebook applications with Django.", author = "Johannes Gorset", author_email = "jgorset@gmail.com", url = "http://github.com/jgorset/fandjango", packages = [ 'fandjango', 'fandjango.migrations', 'fandjango.templatetags' ], package_data = { 'fandjango': ['templates/*'] }, install_requires = [ 'facepy>=0.4.2', 'requests==0.7.6' ], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ] )
Add "email an invoice" method | Q | A | ------------- | --- | Branch | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | n/a | License | MIT | Doc PR | n/a See: https://www.zoho.com/books/api/v3/invoices/#email-an-invoice
<?php namespace OpsWay\ZohoBooks\Api; class Invoices extends BaseApi { const API_PATH = 'invoices'; const API_KEY = 'invoice'; public function applyCredits($invoiceId, $data) { $this->client->post(static::API_PATH.'/'.$invoiceId.'/credits', $this->organizationId, $data); return true; } public function markAsSent($invoiceId) { $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/sent', $this->organizationId); return true; } public function markAsVoid($invoiceId) { $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/void', $this->organizationId); return true; } /** * Email an invoice to the customer * * @see: https://www.zoho.com/books/api/v3/invoices/#email-an-invoice * * @param string $invoiceId * @param array $data * * @return bool */ public function email($invoiceId, array $data = []) { $this->client->post(static::API_PATH.'/'.$invoiceId.'/email', $this->organizationId, $data); return true; } }
<?php namespace OpsWay\ZohoBooks\Api; class Invoices extends BaseApi { const API_PATH = 'invoices'; const API_KEY = 'invoice'; public function applyCredits($invoiceId, $data) { $this->client->post(static::API_PATH.'/'.$invoiceId.'/credits', $this->organizationId, $data); return true; } public function markAsSent($invoiceId) { $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/sent', $this->organizationId); return true; } public function markAsVoid($invoiceId) { $this->client->post(static::API_PATH.'/'.$invoiceId.'/status/void', $this->organizationId); return true; } }
Load reconstructive.js using an absolute path
/* eslint-env serviceworker */ // This makes a module available named "reconstructive" importScripts('/reconstructive.js') // Customize configs (defaults should work for IPWB out of the box) // reconstructive.init({ // version: 'reconstructive.js:v1', // urimPattern: self.location.origin + '/memento/<datetime>/<urir>', // showBanner: false // }) // Add any custom exclusions or modify or delete default ones //> reconstructive.exclusions //< { //< notGet: f (event, config), //< localResource: f (event, config) //< } reconstructive.exclusions.selfScript = function (event, config) { event.request.url.endsWith('reconstructive.js') } // Pass a custom function to generate banner markup // reconstructive.bannerCreator(f (event, rewritten, config)) // Or update the rewriting logic // reconstructive.updateRewriter(f (event, rewritten, config)) // This is unnecessary, but can be useful for debugging or in future self.addEventListener('install', function (event) { console.log('Installing ServiceWorker.') }) // This is unnecessary, but can be useful for debugging or in future self.addEventListener('activate', function (event) { console.log('Activating ServiceWorker.') }) self.addEventListener("fetch", function(event) { console.log('A fetch event triggered:', event); // Add any custom logic here to conditionally call the reroute function reconstructive.reroute(event); })
/* eslint-env serviceworker */ // This makes a module available named "reconstructive" importScripts('reconstructive.js') // Customize configs (defaults should work for IPWB out of the box) // reconstructive.init({ // version: 'reconstructive.js:v1', // urimPattern: self.location.origin + '/memento/<datetime>/<urir>', // showBanner: false // }) // Add any custom exclusions or modify or delete default ones //> reconstructive.exclusions //< { //< notGet: f (event, config), //< localResource: f (event, config) //< } reconstructive.exclusions.selfScript = function (event, config) { event.request.url.endsWith('reconstructive.js') } // Pass a custom function to generate banner markup // reconstructive.bannerCreator(f (event, rewritten, config)) // Or update the rewriting logic // reconstructive.updateRewriter(f (event, rewritten, config)) // This is unnecessary, but can be useful for debugging or in future self.addEventListener('install', function (event) { console.log('Installing ServiceWorker.') }) // This is unnecessary, but can be useful for debugging or in future self.addEventListener('activate', function (event) { console.log('Activating ServiceWorker.') }) self.addEventListener("fetch", function(event) { console.log('A fetch event triggered:', event); // Add any custom logic here to conditionally call the reroute function reconstructive.reroute(event); })
Drop the __init__ call to object.__init__, RPython doesn't like it and it doesn't doa nything
class BaseBox(object): pass class Token(BaseBox): def __init__(self, name, value, source_pos=None): self.name = name self.value = value self.source_pos = source_pos def __eq__(self, other): return self.name == other.name and self.value == other.value def gettokentype(self): return self.name def getsourcepos(self): return self.source_pos def getstr(self): return self.value class SourcePosition(object): def __init__(self, idx, lineno, colno): self.idx = idx self.lineno = lineno self.colno = colno
class BaseBox(object): pass class Token(BaseBox): def __init__(self, name, value, source_pos=None): BaseBox.__init__(self) self.name = name self.value = value self.source_pos = source_pos def __eq__(self, other): return self.name == other.name and self.value == other.value def gettokentype(self): return self.name def getsourcepos(self): return self.source_pos def getstr(self): return self.value class SourcePosition(object): def __init__(self, idx, lineno, colno): self.idx = idx self.lineno = lineno self.colno = colno
Add modules to repl for testing
var util = require('util') , twitter = require('twitter') , colors = require('colors') , repl = require('repl') , keys = require('./keys') , local = repl.start() , first = true var twish = new twitter(keys) local.context.repl = local local.context.colors = colors local.context.twish = twish local.defineCommand('tweet', function(tweet){ twish .verifyCredentials(function(data) { console.log(util.inspect(data)) }) .updateStatus(tweet, function(data) { console.log(util.inspect(data)) }) }) local.commands['.tweet'].help = 'Tweet as currently signed in user' twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){ stream.on('data', function(data){ if(first){ first = false return } setTimeout(function(){ var obj = {} obj.user = data.user.screen_name obj.text = data.text obj.data = data.created_at process.stdout.write(JSON.stringify(obj, null, ' ')) }, 500) }) }) module.exports = twish
var util = require('util') , twitter = require('twitter') , colors = require('colors') , repl = require('repl') , keys = require('./keys') , local = repl.start() , first = true var twish = new twitter(keys) local.context.repl = local local.defineCommand('tweet', function(tweet){ twish .verifyCredentials(function(data) { console.log(util.inspect(data)) }) .updateStatus(tweet, function(data) { console.log(util.inspect(data)) }) }) local.commands['.tweet'].help = 'Tweet as currently signed in user' twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){ stream.on('data', function(data){ if(first){ first = false return } setTimeout(function(){ var obj = {} obj.user = data.user.screen_name obj.text = data.text obj.data = data.created_at process.stdout.write(JSON.stringify(obj, null, ' ')) }, 500) }) }) module.exports = twish
Fix data reference for selecting hospitals I think this is a d3 change that happened when I updated libraries? That’s when it broke
HospitalCheckup.Behaviors = { HospitalSelect: Marionette.Behavior.extend({ events: { "click .bar": "displayHospital", "click .range-bar": "displayHospital", "click .stat-circle": "displayHospital", "click .y.axis text": "displayHospital" }, displayHospital: function(e){ var data = d3.select(e.currentTarget)[0][0].__data__; if(!data.id){ //clicks on hospital label text won't register ID, tried everything to attach it to DOM but failed data = HospitalCheckup.SectionsApp.Section.chartView.collection.findWhere({ display_name: data }).get("id"); } else { data = data.id; } this.view.trigger("hospital:change", data); } }) } Marionette.Behaviors.behaviorsLookup = function(){ return HospitalCheckup.Behaviors; }
HospitalCheckup.Behaviors = { HospitalSelect: Marionette.Behavior.extend({ events: { "click .bar": "displayHospital", "click .range-bar": "displayHospital", "click .stat-circle": "displayHospital", "click .y.axis text": "displayHospital" }, displayHospital: function(e){ var data = d3.selectAll(e.currentTarget)[0].__data__; if(!data.id){ //clicks on hospital label text won't register ID, tried everything to attach it to DOM but failed data = HospitalCheckup.SectionsApp.Section.chartView.collection.findWhere({ display_name: data }).get("id"); } else { data = data.id; } this.view.trigger("hospital:change", data); } }) } Marionette.Behaviors.behaviorsLookup = function(){ return HospitalCheckup.Behaviors; }
Add missing key prop to blog post list
import React from 'react'; import {Helmet} from 'react-helmet'; import Logo from '../../common/Logo'; import StyledLink from '../../common/StyledLink'; import NewsletterSignupForm from '../NewsletterSignupForm'; import { Title, Wrapper, Divider, BlogPostCardWrapper, BlogPostDate, BlogPostDescription, } from './index.styles'; import posts from '../posts/index.json'; const BlogPostCard = ({id, date, title, description}) => ( <BlogPostCardWrapper> <StyledLink href={`/blog/${id}`}>{title}</StyledLink> <BlogPostDate>{date}</BlogPostDate> <BlogPostDescription>{description}</BlogPostDescription> </BlogPostCardWrapper> ); export default () => ( <React.Fragment> <Helmet> <title>Blog | Six Degrees of Wikipedia</title> </Helmet> <Logo /> <Wrapper> <Title>A blog about building, maintaining, and promoting Six Degrees of Wikipedia</Title> <Divider /> {posts.map((postInfo) => ( <React.Fragment key={postInfo.id}> <BlogPostCard {...postInfo} /> <Divider /> </React.Fragment> ))} <NewsletterSignupForm /> </Wrapper> </React.Fragment> );
import React from 'react'; import {Helmet} from 'react-helmet'; import Logo from '../../common/Logo'; import StyledLink from '../../common/StyledLink'; import NewsletterSignupForm from '../NewsletterSignupForm'; import { Title, Wrapper, Divider, BlogPostCardWrapper, BlogPostDate, BlogPostDescription, } from './index.styles'; import posts from '../posts/index.json'; const BlogPostCard = ({id, date, title, description}) => ( <BlogPostCardWrapper> <StyledLink href={`/blog/${id}`}>{title}</StyledLink> <BlogPostDate>{date}</BlogPostDate> <BlogPostDescription>{description}</BlogPostDescription> </BlogPostCardWrapper> ); export default () => ( <React.Fragment> <Helmet> <title>Blog | Six Degrees of Wikipedia</title> </Helmet> <Logo /> <Wrapper> <Title>A blog about building, maintaining, and promoting Six Degrees of Wikipedia</Title> <Divider /> {posts.map((postInfo) => ( <React.Fragment> <BlogPostCard {...postInfo} /> <Divider /> </React.Fragment> ))} <NewsletterSignupForm /> </Wrapper> </React.Fragment> );
Enable lookup via enter and click.
$(document).ready(function() { function repLookup() { var street = $('#lookup-street').val(); var zip = $('#lookup-zip').val(); if ((street.trim() != '') && (zip.trim() != '')) { $('#lookup-error').html(''); smartyGetGeo(street, zip); } else { $('#lookup-error').html('Please enter a street address and zip code.') } } // On Click, lookup address. $('#lookup-submit').click(function() { repLookup(); }); $("#lookup-street, #lookup-zip").keyup(function (e) { if (e.keyCode == 13) { repLookup(); } }); $('#new-search-link').click(function() { $('#reps-list-mine').toggle(); $('#reps-list-mine-scorecards').html(''); $('#reps-lookup').toggle(); }); $('#letter-signup-outside-us').click(function() { $('#country-code').toggle(); }); // Check for "Thank You" response from action center; var thanks = getParameterByName('thankyou'); if (thanks == 1) { location.href = 'thanks/'; } effRecentSigners(); effSignupParter(); $('.privacy-notice-popover').popover(); });
$(document).ready(function() { // On Click, lookup address. $('#lookup-submit').click(function() { var street = $('#lookup-street').val(); var zip = $('#lookup-zip').val(); if ((street.trim() != '') && (zip.trim() != '')) { $('#lookup-error').html(''); smartyGetGeo(street, zip); } else { $('#lookup-error').html('Please enter a street address and zip code.') } }); $('#new-search-link').click(function() { $('#reps-list-mine').toggle(); $('#reps-list-mine-scorecards').html(''); $('#reps-lookup').toggle(); }); $('#letter-signup-outside-us').click(function() { $('#country-code').toggle(); }); // Check for "Thank You" response from action center; var thanks = getParameterByName('thankyou'); if (thanks == 1) { location.href = 'thanks/'; } effRecentSigners(); effSignupParter(); $('.privacy-notice-popover').popover(); });
Fix todo: constructor will now complain if not called with new keyword.
var GreyTab = window.GreyTab || {}; GreyTab.model = GreyTab.model || {}; GreyTab.model.SObject = function(){ if(!(this instanceof GreyTab.model.SObject)) throw Error("Constructor called as a function. Use the new keyword"); /** * Since javascript has methods and data intermixed on objects we need to keep fields off the root type * since they can conceivably be anything. * @type {Object} */ this.fields = {}; this.applyFieldData = function(newFieldData){ var fieldKey, me = this; for(fieldKey in newFieldData){ Object.keys(newFieldData).forEach(function(key){ me.fields[key] = newFieldData[key]; }); } } };
var GreyTab = window.GreyTab || {}; GreyTab.model = GreyTab.model || {}; GreyTab.model.SObject = function(){ //TODO: validate being called with new /** * Since javascript has methods and data intermixed on objects we need to keep fields off the root type * since they can conceivably be anything. * @type {Object} */ this.fields = {}; this.applyFieldData = function(newFieldData){ var fieldKey, me = this; for(fieldKey in newFieldData){ Object.keys(newFieldData).forEach(function(key){ me.fields[key] = newFieldData[key]; }); } } };
Increment version to trigger release of previous changes
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, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.4', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
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, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.3', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
Change public dir to working dir, not dist
var loopback = require('loopback'); var boot = require('loopback-boot'); var path = require('path'); var app = module.exports = loopback(); // Set up the /favicon.ico app.use(loopback.favicon()); // request pre-processing middleware app.use(loopback.compress()); // -- Add your pre-processing middleware here -- // boot scripts mount components like REST API boot(app, __dirname); // -- Mount static files here-- // All static middleware should be registered at the end, as all requests // passing the static middleware are hitting the file system // Example: // app.use(loopback.static(path.resolve(__dirname', '../client'))); app.use(loopback.static(path.resolve(__dirname, '../client/app'))); // Requests that get this far won't be handled // by any middleware. Convert them into a 404 error // that will be handled later down the chain. app.use(loopback.urlNotFound()); // The ultimate error handler. app.use(loopback.errorHandler()); app.start = function() { // start the web server return app.listen(function() { app.emit('started'); console.log('Web server listening at: %s', app.get('url')); }); }; // start the server if `$ node server.js` if (require.main === module) { app.start(); }
var loopback = require('loopback'); var boot = require('loopback-boot'); var path = require('path'); var app = module.exports = loopback(); // Set up the /favicon.ico app.use(loopback.favicon()); // request pre-processing middleware app.use(loopback.compress()); // -- Add your pre-processing middleware here -- // boot scripts mount components like REST API boot(app, __dirname); // -- Mount static files here-- // All static middleware should be registered at the end, as all requests // passing the static middleware are hitting the file system // Example: // app.use(loopback.static(path.resolve(__dirname', '../client'))); app.use(loopback.static(path.resolve(__dirname, '../client/dist'))); // Requests that get this far won't be handled // by any middleware. Convert them into a 404 error // that will be handled later down the chain. app.use(loopback.urlNotFound()); // The ultimate error handler. app.use(loopback.errorHandler()); app.start = function() { // start the web server return app.listen(function() { app.emit('started'); console.log('Web server listening at: %s', app.get('url')); }); }; // start the server if `$ node server.js` if (require.main === module) { app.start(); }
Add onticks and offticks to model. Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@ninjablocks.com>
package channels type DemandState struct { Rated *float64 `json:"rated,omitempty"` // rated maximum power, in Watts ObservedMax *float64 `json:"observedMax,omitempty"` // the observed max current power for this device Current *float64 `json:"current,omitempty"` // average power for current period Peak *float64 `json:"peak,omitempty"` // peak instantaneous power in averaging period Goal *float64 `json:"goal,omitempty"` // goal power for averaging period Controlled *float64 `json:"controlled,omitempty"` // average controlled power Uncontrolled *float64 `json:"uncontrolled,omitempty"` // average uncontrolled power Period *int `json:"period,omitempty"` // averaging period, in seconds OnTicks *int `json:"onTicks,omitempty"` // the number of seconds since last switch on OffTicks *int `json:"offTicks,omitempty"` // the number of seconds since last switch off } type DemandChannel struct { baseChannel } func NewDemandChannel() *DemandChannel { return &DemandChannel{ baseChannel: baseChannel{protocol: "demand"}, } } func (c *DemandChannel) SendState(demandState *DemandState) error { return c.SendEvent("state", demandState) }
package channels type DemandState struct { Rated *float64 `json:"rated,omitempty"` // rated maximum power, in Watts ObservedMax *float64 `json:"observedMax,omitempty"` // the observed max current power for this device Current *float64 `json:"current,omitempty"` // average power for current period Peak *float64 `json:"peak,omitempty"` // peak instantaneous power in averaging period Goal *float64 `json:"goal,omitempty"` // goal power for averaging period Controlled *float64 `json:"controlled,omitempty"` // average controlled power Uncontrolled *float64 `json:"uncontrolled,omitempty"` // average uncontrolled power Period *int `json:"period,omitempty"` // averaging period, in secon } type DemandChannel struct { baseChannel } func NewDemandChannel() *DemandChannel { return &DemandChannel{ baseChannel: baseChannel{protocol: "demand"}, } } func (c *DemandChannel) SendState(demandState *DemandState) error { return c.SendEvent("state", demandState) }
Fix Choice Admin listing and adding/editing
<?php // src/Effi/QCMBundle/Admin/ChoiceAdmin.php namespace Effi\QCMBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; class ChoiceAdmin extends Admin { // FORMULAIRE EDITION AJOUT protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('user', 'entity', array('class' => 'Effi\UserBundle\Entity\User')) ->add('question', 'entity', array('class' => 'Effi\QCMBundle\Entity\Question', 'property' => 'label')) ; } // FORMULAIRE FILTRE protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('user') ; } // FORMULAIRE LISTE protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('id') ->add('user') ->add('question', null, array('associated_tostring' => 'getLabel')) ; } }
<?php // src/Effi/QCMBundle/Admin/ChoiceAdmin.php namespace Effi\QCMBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; class ChoiceAdmin extends Admin { // FORMULAIRE EDITION AJOUT protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('user', 'entity', array('class' => 'Effi/UserBundle/Entity/User')) ->add('question', 'entity', array('class' => 'Effi/QCMBundle/Entity/Question')) ; } // FORMULAIRE FILTRE protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('user') ->add('question') ; } // FORMULAIRE LISTE protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('id') ->add('user') ->add('question') ; } }
Fix arguments order of reqon.deprecated.build_terms().
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') return build_terms(reql, query['$query']) def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') return build_terms(query['$query'], reql) def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql
Add player name to log about portal disabling
package net.simpvp.Portals; import java.util.ArrayList; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; /** * Checks all broken obsidian blocks, checking that they were not part of * a portal that now will have to be deactivated. If they were, deactivate * said portal(s). */ public class BlockBreak implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) public void onBlockBreak(BlockBreakEvent event) { if (event.getBlock().getType() != Material.OBSIDIAN) return; Block block = event.getBlock(); ArrayList<PortalLocation> portals = SQLite.obsidian_checker(block); for (PortalLocation portal : portals) { if (PortalCheck.is_valid_portal(portal.block, block) == false) { Portals.instance.getLogger().info("Query returned positive by " + event.getPlayer().getName() + ". Disabling this portal at " + portal.block.getWorld().getName() + " " + portal.block.getX() + " " + portal.block.getY() + " " + portal.block.getZ()); SQLite.delete_portal_pair(portal.id); } } } }
package net.simpvp.Portals; import java.util.ArrayList; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; /** * Checks all broken obsidian blocks, checking that they were not part of * a portal that now will have to be deactivated. If they were, deactivate * said portal(s). */ public class BlockBreak implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) public void onBlockBreak(BlockBreakEvent event) { if (event.getBlock().getType() != Material.OBSIDIAN) return; Block block = event.getBlock(); ArrayList<PortalLocation> portals = SQLite.obsidian_checker(block); for (PortalLocation portal : portals) { if (PortalCheck.is_valid_portal(portal.block, block) == false) { Portals.instance.getLogger().info("Query returned positive. " + "Disabling this portal at " + portal.block.getWorld().getName() + " " + portal.block.getX() + " " + portal.block.getY() + " " + portal.block.getZ()); SQLite.delete_portal_pair(portal.id); } } } }
Simplify tests by turning off effects
if(!this.chai) { chai = require("chai"); } var expect = chai.expect; (function($) { var cleanupDom = function(){ $('body >:not(#mocha)').remove() }; $.fx.off = true; describe('Featherlight', function() { afterEach(cleanupDom); it ('works on items with data-featherlight by default', function() { var $bound = $('#auto-bound') expect($('img').length).to.equal(0); $bound.click(); expect($('.featherlight img')).to.be.visible; expect($('.featherlight img')).to.have.attr('src').equal('fixtures/photo.jpeg'); $('.featherlight').click(); expect($('img')).to.not.be.visible; }); describe('jQuery#featherlight', function() { it('is chainable', function() { // Not a bad test to run on collection methods. var $all_links = $('a') expect($all_links.featherlight()).to.equal($all_links); }); }); describe('jQuery.featherlight', function() { it('opens a dialog box', function() { $.featherlight('<p class="testing">This is a test<p>'); expect($('.featherlight p.testing')).to.be.visible; }); }); }); }(jQuery));
if(!this.chai) { chai = require("chai"); } var expect = chai.expect; (function($) { var cleanupDom = function(){ $('body >:not(#mocha)').remove() }; describe('Featherlight', function() { afterEach(cleanupDom); it ('works on items with data-featherlight by default', function(done) { var $bound = $('#auto-bound') expect($('img').length).to.equal(0); $bound.click(); setTimeout(function() { expect($('.featherlight img')).to.be.visible; expect($('.featherlight img')).to.have.attr('src').equal('fixtures/photo.jpeg'); $('.featherlight').click(); }, 500 ); setTimeout(function() { expect($('img')).to.not.be.visible; done(); }, 1000 ); }); describe('jQuery#featherlight', function() { it('is chainable', function() { // Not a bad test to run on collection methods. var $all_links = $('a') expect($all_links.featherlight()).to.equal($all_links); }); }); describe('jQuery.featherlight', function() { it('opens a dialog box', function() { $.featherlight('<p class="testing">This is a test<p>'); expect($('.featherlight p.testing')).to.be.visible; }); }); }); }(jQuery));
Check AST after translating statements.
'''Module for handling assembly language code.''' import sys import traceback from transf import transformation from transf import parse import ir.check from machine.pentium.data import * from machine.pentium.binary import * from machine.pentium.logical import * from machine.pentium.shift import * from machine.pentium.control import * from machine.pentium.flag import * from machine.pentium.misc import * from machine.pentium.simplify import simplify class OpcodeDispatch(transformation.Transformation): """Transformation to quickly dispatch the transformation to the appropriate transformation.""" def apply(self, trm, ctx): if not trm.rmatch('Asm(_, [*])'): raise exception.Failure opcode, operands = trm.args opcode = opcode.value try: trf = eval("asm" + opcode.upper()) except NameError: sys.stderr.write("warning: don't now how to translate opcode '%s'\n" % opcode) raise transf.exception.Failure try: return trf.apply(operands, ctx) except exception.Failure: sys.stderr.write("warning: failed to translate opcode '%s'\n" % opcode) traceback.print_exc() raise parse.Transfs(''' doStmt = ?Asm(opcode, _) & ( OpcodeDispatch() & Map(ir.check.stmt) + ![<id>] ) ; Try(simplify) + ![<id>] doModule = ~Module(<lists.MapConcat(doStmt)>) ''', debug=False)
'''Module for handling assembly language code.''' import sys import traceback from transf import transformation from transf import parse from machine.pentium.data import * from machine.pentium.binary import * from machine.pentium.logical import * from machine.pentium.shift import * from machine.pentium.control import * from machine.pentium.flag import * from machine.pentium.misc import * from machine.pentium.simplify import simplify class OpcodeDispatch(transformation.Transformation): """Transformation to quickly dispatch the transformation to the appropriate transformation.""" def apply(self, trm, ctx): if not trm.rmatch('Asm(_, [*])'): raise exception.Failure opcode, operands = trm.args opcode = opcode.value try: trf = eval("asm" + opcode.upper()) except NameError: sys.stderr.write("warning: don't now how to translate opcode '%s'\n" % opcode) raise transf.exception.Failure try: return trf.apply(operands, ctx) except exception.Failure: sys.stderr.write("warning: failed to translate opcode '%s'\n" % opcode) traceback.print_exc() raise parse.Transfs(''' doStmt = ?Asm(opcode, _) & ( OpcodeDispatch() + ![<id>] ) ; Try(simplify) + ![<id>] doModule = ~Module(<lists.MapConcat(doStmt)>) ''')
Fix errors causing assertions to faile in IE.
import helpers from '../lib/helpers'; import skate from '../../src/skate'; describe('ignoring', function () { it('should ignore a flagged element', function () { var called = 0; // Test insertion before. document.body.innerHTML = '<div></div><div id="container-1" data-skate-ignore><div><div></div></div></div><div></div>'; document.getElementById('container-1').innerHTML = '<div><div></div></div>'; // Now register. skate('div', { insert: function () { ++called; } }); // Ensure the document is sync'd. skate.init(document.body); // Test insertion after. document.body.innerHTML = '<div></div><div id="container-2" data-skate-ignore><div><div></div></div></div><div></div>'; document.getElementById('container-2').innerHTML = '<div><div></div></div>'; // Ensure all new content is sync'd. skate.init(document.body); expect(called).to.equal(4); }); });
import helpers from '../lib/helpers'; import skate from '../../src/skate'; describe('ignoring', function () { it('should ignore a flagged element', function () { var called = 0; // Test insertion before. document.body.innerHTML = '<div></div><div id="container-1" data-skate-ignore><div><div></div></div></div><div></div>'; document.getElementById('container-1').innerHTML = '<div><div></div></div>'; // Now register. skate('div', { insert: function () { ++called; } }); // Ensure the document is sync'd. skate.init(document.body); // Test insertion after. document.body.innerHTML = '<div></div><div id="container-2" data-skate-ignore><div><div></div></div></div><div></div>'; document.getElementById('container-2').innerHTML = '<div><div></div></div>'; // Ensure all new content is sync'd. skate.init(document.body); called.should.equal(4); }); });
Change language to en_US for patient view API
var express = require('express'); var router = express.Router(); var pipe = require('../transformers/pipe'); router.post('/\\$cds-hook', function(req, res, next) { var context = { requestParams: req.query || {}, language: "en_US", nation: "US", cards: ["reminders", "guidelink", "cmrlink"] }; pipe.execute(req, res, next, context); }); router.get('/\\$cds-hook-metadata', function(req, res, next) { res.json({ "resourceType" : "Parameters", "parameter" : [{ "name" : "name", "valueString" : "EBMeDS patient view" }, { "name" : "description", "valueString" : "EBMeDS patient view" }, { "name" : "activity", "valueCoding" : { "system" : "http://cds-hooks.smarthealthit.org/activity", "code" : "patient-view" } } ] }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var pipe = require('../transformers/pipe'); router.post('/\\$cds-hook', function(req, res, next) { var context = { requestParams: req.query || {}, language: "fi", nation: "fi", cards: ["reminders", "guidelink", "cmrlink"] }; pipe.execute(req, res, next, context); }); router.get('/\\$cds-hook-metadata', function(req, res, next) { res.json({ "resourceType" : "Parameters", "parameter" : [{ "name" : "name", "valueString" : "EBMeDS patient view" }, { "name" : "description", "valueString" : "EBMeDS patient view" }, { "name" : "activity", "valueCoding" : { "system" : "http://cds-hooks.smarthealthit.org/activity", "code" : "patient-view" } } ] }); }); module.exports = router;
Revert "add 505 and 403 to retry status codes due to amazon s3 random fails while uploading images" This reverts changeset r457 --HG-- extra : convert_revision : svn%3Ab85faa78-f9eb-468e-a121-7cced6da292c%40461
import scrapy # Scrapy core settings BOT_NAME = 'scrapy' BOT_VERSION = scrapy.__version__ ENGINE_DEBUG = False # Download configuration options USER_AGENT = '%s/%s' % (BOT_NAME, BOT_VERSION) DOWNLOAD_TIMEOUT = 180 # 3mins CONCURRENT_DOMAINS = 8 # number of domains to scrape in parallel REQUESTS_PER_DOMAIN = 8 # max simultaneous requests per domain CACHE2_EXPIRATION_SECS = 48 * 60 * 60 # seconds while cached response is still valid (a negative value means "never expires") LOG_ENABLED = True # LOGLEVEL = 'DEBUG' # default loglevel LOGFILE = None # None means sys.stderr by default LOG_STDOUT = False # DEFAULT_ITEM_CLASS = 'scrapy.item.ScrapedItem' SCHEDULER = 'scrapy.core.scheduler.Scheduler' MEMORYSTORE = 'scrapy.core.scheduler.MemoryStore' PRIORITIZER = 'scrapy.core.prioritizers.RandomPrioritizer' EXTENSIONS = [] # contrib.middleware.retry.RetryMiddleware default settings RETRY_TIMES = 3 RETRY_HTTP_CODES = ['500', '503', '504', '400', '408', '200']
import scrapy # Scrapy core settings BOT_NAME = 'scrapy' BOT_VERSION = scrapy.__version__ ENGINE_DEBUG = False # Download configuration options USER_AGENT = '%s/%s' % (BOT_NAME, BOT_VERSION) DOWNLOAD_TIMEOUT = 180 # 3mins CONCURRENT_DOMAINS = 8 # number of domains to scrape in parallel REQUESTS_PER_DOMAIN = 8 # max simultaneous requests per domain CACHE2_EXPIRATION_SECS = 48 * 60 * 60 # seconds while cached response is still valid (a negative value means "never expires") LOG_ENABLED = True # LOGLEVEL = 'DEBUG' # default loglevel LOGFILE = None # None means sys.stderr by default LOG_STDOUT = False # DEFAULT_ITEM_CLASS = 'scrapy.item.ScrapedItem' SCHEDULER = 'scrapy.core.scheduler.Scheduler' MEMORYSTORE = 'scrapy.core.scheduler.MemoryStore' PRIORITIZER = 'scrapy.core.prioritizers.RandomPrioritizer' EXTENSIONS = [] # contrib.middleware.retry.RetryMiddleware default settings RETRY_TIMES = 3 RETRY_HTTP_CODES = ['500', '503', '504', '400', '408', '200'] # amazon s3 images backend sometimes fails to authenticate or validate http protocol RETRY_HTTP_CODES = RETRY_HTTP_CODES + ['505', '403']
Set theme for activator target help.
package sk.henrichg.phoneprofilesplus; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class ActivatorTargetHelpsActivity extends AppCompatActivity { public static ActivatorTargetHelpsActivity activity; //public static ActivateProfileActivity activatorActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); overridePendingTransition(0, 0); activity = this; } @Override protected void onResume() { super.onResume(); if (ActivateProfileActivity.getInstance() == null) { finish(); return; } GlobalGUIRoutines.setTheme(this, true, false, false); GlobalGUIRoutines.setLanguage(getBaseContext()); ActivateProfileActivity.getInstance().showTargetHelps(); } @Override public void finish() { super.finish(); overridePendingTransition(0, 0); } }
package sk.henrichg.phoneprofilesplus; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class ActivatorTargetHelpsActivity extends AppCompatActivity { public static ActivatorTargetHelpsActivity activity; //public static ActivateProfileActivity activatorActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); overridePendingTransition(0, 0); activity = this; } @Override protected void onResume() { super.onResume(); if (ActivateProfileActivity.getInstance() == null) { finish(); return; } ActivateProfileActivity.getInstance().showTargetHelps(); } @Override public void finish() { super.finish(); overridePendingTransition(0, 0); } }
Fix stats job job's name
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler sys.path.append('/d1lod') from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def update_job(): q.enqueue(jobs.update_graph) @sched.scheduled_job('interval', hours=1) def stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', hours=1) def export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() time.sleep(10) sched.start()
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler sys.path.append('/d1lod') from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def update_job(): q.enqueue(jobs.update_graph) @sched.scheduled_job('interval', hours=1) def debug_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', hours=1) def export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() time.sleep(10) sched.start()
Fix inclusion of static files into the package and increase the version-number a bit.
# # Copyright 2013 by Arnold Krille <arnold@arnoldarts.de> # # 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 distutils.core import setup setup( name="workout", version="0.2.1", description="Store and display workout-data from FIT-files in mezzanine.", author="Arnold Krille", author_email="arnold@arnoldarts.de", url="http://github.com/kampfschlaefer/mezzanine-workout", license=open('LICENSE', 'r').read(), packages=['workout'], package_data={'workout': ['templates/workout/*', 'static/*']}, install_requires=['fitparse==0.0.1-dev'], dependency_links=['git+https://github.com/kampfschlaefer/python-fitparse.git@ng#egg=fitparse-0.0.1-dev'], )
# # Copyright 2013 by Arnold Krille <arnold@arnoldarts.de> # # 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 distutils.core import setup setup( name="workout", version="0.2.0", description="Store and display workout-data from FIT-files in mezzanine.", author="Arnold Krille", author_email="arnold@arnoldarts.de", url="http://github.com/kampfschlaefer/mezzanine-workout", license=open('LICENSE', 'r').read(), packages=['workout'], package_data={'workout': ['templates/workout/*']}, install_requires=['fitparse==0.0.1-dev'], dependency_links=['git+https://github.com/kampfschlaefer/python-fitparse.git@ng#egg=fitparse-0.0.1-dev'], )
Set the root controller namespace.
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * All of the application's route middleware keys. * * @var array */ protected $middleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', ]; /** * Called before routes are registered. * * Register any model bindings or pattern based filters. * * @param \Illuminate\Routing\Router $router * @param \Illuminate\Contracts\Routing\UrlGenerator $url * @return void */ public function before(Router $router, UrlGenerator $url) { $url->setRootControllerNamespace('App\Http\Controllers'); } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => 'App\Http\Controllers'], function($router) { require app_path('Http/routes.php'); }); } }
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * All of the application's route middleware keys. * * @var array */ protected $middleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', ]; /** * Called before routes are registered. * * Register any model bindings or pattern based filters. * * @param \Illuminate\Routing\Router $router * @return void */ public function before(Router $router) { // } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => 'App\Http\Controllers'], function($router) { require app_path('Http/routes.php'); }); } }
Clean up old authentication checks; list is always authenticated
<h2>Podcasts</h2> <div class="podcasts"> <?php foreach($podcasts as $podcast): ?> <h3> <?php echo link_to_with_icon($podcast->getTitle(), "web", $podcast->getUri()); ?> </h3> <ul> <li> <div> &nbsp; <?php echo link_to_with_icon('Edit', "cog", 'podcast/edit?id='.$podcast->getId()); ?> <?php echo link_to_with_icon('Add episode', "add", 'episode/add?podcast_id='.$podcast->getId()); ?> </div> </li> </ul> <?php endforeach; ?> <?php if($sf_user->isAuthenticated()): ?> <p><?php echo link_to_with_icon('New podcast…', "add", 'podcast/add'); ?></p> <?php endif; ?>
<h2>Podcasts</h2> <div class="podcasts"> <?php foreach($podcasts as $podcast): ?> <h3> <?php echo link_to_with_icon($podcast->getTitle(), "web", $podcast->getUri()); ?> </h3> <?php if($sf_user->isAuthenticated()): ?> <ul> <li> <div> &nbsp; <?php echo link_to_with_icon('Edit', "cog", 'podcast/edit?id='.$podcast->getId()); ?> <?php echo link_to_with_icon('Add episode', "add", 'episode/add?podcast_id='.$podcast->getId()); ?> </div> </li> </ul> <?php endif; ?> <?php endforeach; ?> <?php if($sf_user->isAuthenticated()): ?> <p><?php echo link_to_with_icon('New podcast…', "add", 'podcast/add'); ?></p> <?php endif; ?>
Exclude the test for WELD-1086 temporarily
package org.jboss.weld.tests.ejb; import javax.ejb.Stateless; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class EJBCallTest { @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap .create(JavaArchive.class, "test.jar") .addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")); } @Stateless public static class SomeService { public String someMethod() { return "test"; } } @Inject SomeService someService; @Test @Ignore("WELD-1086") public void testStatelessCall() { Assert.assertEquals("test", someService.someMethod()); } }
package org.jboss.weld.tests.ejb; import javax.ejb.Stateless; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class EJBCallTest { @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap .create(JavaArchive.class, "test.jar") .addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")); } @Stateless public static class SomeService { public String someMethod() { return "test"; } } @Inject SomeService someService; @Test public void testStatelessCall() { Assert.assertEquals("test", someService.someMethod()); } }
Fix access to class member url in Generic Json Facade
<?php namespace Nectary\Facades; use Nectary\Models\Json_Feed; use Nectary\Facades\Rss_Facade; class Generic_Json_Facade extends Rss_Facade { private $url; public function load_dependencies() { return array( $this, 'get_feed' ); } public function get_feed( $url ) { $this->url = $url; return new Json_Feed( $url, array( $this, 'get_curl_feed_data' ) ); } public function get_curl_feed_data() { $session = curl_init( $this->url ); curl_setopt( $session, CURLOPT_RETURNTRANSFER, true ); $json = curl_exec( $session ); if ( curl_error( $session ) ) { throw new Exception( 'JSON Call failed ' . curl_strerror( curl_errno( $session ) ) ); } curl_close( $session ); return $json; } }
<?php namespace Nectary\Facades; use Nectary\Models\Json_Feed; use Nectary\Facades\Rss_Facade; class Generic_Json_Facade extends Rss_Facade { private $url; public function load_dependencies() { return array( $this, 'get_feed' ); } public function get_feed( $url ) { $this->url = $url; return new Json_Feed( $url, array( $this, 'get_curl_feed_data' ) ); } public function get_curl_feed_data() { $session = curl_init( $url ); curl_setopt( $session, CURLOPT_RETURNTRANSFER, true ); $json = curl_exec( $session ); if ( curl_error( $session ) ) { throw new Exception( 'JSON Call failed ' . curl_strerror( curl_errno( $session ) ) ); } curl_close( $session ); return $json; } }
Add one more 'need root' phrase
patterns = ['permission denied', 'EACCES', 'pkg: Insufficient privileges', 'you cannot perform this operation unless you are root', 'non-root users cannot', 'Operation not permitted', 'root privilege', 'This command has to be run under the root user.', 'This operation requires root.', 'requested operation requires superuser privilege', 'must be run as root', 'must run as root', 'must be superuser', 'must be root', 'need to be root', 'need root', 'only root can ', 'You don\'t have access to the history DB.', 'authentication is required'] def match(command, settings): for pattern in patterns: if pattern.lower() in command.stderr.lower()\ or pattern.lower() in command.stdout.lower(): return True return False def get_new_command(command, settings): return u'sudo {}'.format(command.script)
patterns = ['permission denied', 'EACCES', 'pkg: Insufficient privileges', 'you cannot perform this operation unless you are root', 'non-root users cannot', 'Operation not permitted', 'root privilege', 'This command has to be run under the root user.', 'This operation requires root.', 'requested operation requires superuser privilege', 'must be run as root', 'must be superuser', 'must be root', 'need to be root', 'need root', 'only root can ', 'You don\'t have access to the history DB.', 'authentication is required'] def match(command, settings): for pattern in patterns: if pattern.lower() in command.stderr.lower()\ or pattern.lower() in command.stdout.lower(): return True return False def get_new_command(command, settings): return u'sudo {}'.format(command.script)
Update to the serialization module - only construct object mapper once.
package org.rcsb.mmtf.serialization; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.msgpack.jackson.dataformat.MessagePackFactory; import org.rcsb.mmtf.dataholders.MmtfStructure; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; /** * A message pack implementation of the {@link MmtfStructure} serializer / deserializer. * @author Anthony Bradley * */ public class MessagePackSerialization implements MmtfStructureSerializationInterface { private ObjectMapper objectMapper; /** * Constructor for the {@link MessagePackSerialization} class. * Generates {@link ObjectMapper} and sets to include non-null. */ public MessagePackSerialization() { objectMapper = new ObjectMapper(new MessagePackFactory()); objectMapper.setSerializationInclusion(Include.NON_NULL); } @Override public MmtfStructure deserialize(InputStream inputStream){ MmtfStructure mmtfBean = null; try { mmtfBean = objectMapper.readValue(inputStream, MmtfStructure.class); } catch (IOException e) { e.printStackTrace(); } return mmtfBean; } @Override public void serialize(MmtfStructure mmtfStructure, OutputStream outputStream) { try { objectMapper.writeValue(outputStream, mmtfStructure); } catch (IOException e) { e.printStackTrace(); } } }
package org.rcsb.mmtf.serialization; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.msgpack.jackson.dataformat.MessagePackFactory; import org.rcsb.mmtf.dataholders.MmtfStructure; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; /** * A message pack implementation of the {@link MmtfStructure} serializer / deserializer. * @author Anthony Bradley * */ public class MessagePackSerialization implements MmtfStructureSerializationInterface { @Override public MmtfStructure deserialize(InputStream inputStream){ MmtfStructure mmtfBean = null; try { mmtfBean = new ObjectMapper(new MessagePackFactory()).readValue(inputStream, MmtfStructure.class); } catch (IOException e) { e.printStackTrace(); } return mmtfBean; } @Override public void serialize(MmtfStructure mmtfStructure, OutputStream outputStream) { ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory()); objectMapper.setSerializationInclusion(Include.NON_NULL); try { objectMapper.writeValue(outputStream, mmtfStructure); } catch (IOException e) { e.printStackTrace(); } } }
Add shorthand tasks for applying changes to html, js, and css
'use strict'; let fs = require('fs'); let gulp = require('gulp'); let jshint = require('gulp-jshint'); let stylish = require('jshint-stylish'); let concat = require('gulp-concat'); let csslint = require('gulp-csslint'); let babel = require('gulp-babel'); gulp.task('lintjs', () => { return gulp.src('./portal/js/*.js') .pipe(jshint('.jshintrc')) .pipe(jshint.reporter(stylish)); }); gulp.task('concatjs', () => { return gulp.src('./portal/js/*.js') .pipe(babel({ presets: ['es2015'] })) .pipe(concat('main.js')) .pipe(gulp.dest('./static/javascript/')); }); gulp.task('concatcss', () => { return gulp.src('./portal/css/*.css') .pipe(concat('main.css')) .pipe(gulp.dest('./static/stylesheets/')); }); gulp.task('copyhtml', () => { return gulp.src('./portal/html/*.html') .pipe(gulp.dest('./views/')); }); // Shorthand tasks for applying changes to single resources gulp.task('js', ['lintjs', 'concatjs']); gulp.task('css', ['concatcss']); gulp.task('html', ['copyhtml']); gulp.task('build', ['lintjs', 'concatjs', 'concatcss', 'copyhtml']);
'use strict'; let fs = require('fs'); let gulp = require('gulp'); let jshint = require('gulp-jshint'); let stylish = require('jshint-stylish'); let concat = require('gulp-concat'); let csslint = require('gulp-csslint'); let babel = require('gulp-babel'); gulp.task('lintjs', () => { return gulp.src('./portal/js/*.js') .pipe(jshint('.jshintrc')) .pipe(jshint.reporter(stylish)); }); gulp.task('concatjs', () => { return gulp.src('./portal/js/*.js') .pipe(babel({ presets: ['es2015'] })) .pipe(concat('main.js')) .pipe(gulp.dest('./static/javascript/')); }); gulp.task('concatcss', () => { return gulp.src('./portal/css/*.css') .pipe(concat('main.css')) .pipe(gulp.dest('./static/stylesheets/')); }); gulp.task('copyhtml', () => { return gulp.src('./portal/html/*.html') .pipe(gulp.dest('./views/')); }); gulp.task('build', ['lintjs', 'concatjs', 'concatcss', 'copyhtml']);
Remove unused Trending Hashtag placeholder
@if ($trendingHashtags) <div class="bg-white p-3 mb-3"> <h5>United States trends</h5> <ul class="list-unstyled mb-0"> @foreach ($trendingHashtags as $key => $value) <li class="mb-2"> <a href="{{ route('hashtags.index', strtolower($key)) }}">#{{ $key }}</a> <div class="text-muted"> {{ $value }} {{ str_plural('post', $value) }} </div> </li> @endforeach </ul> </div> @endif
@if ($trendingHashtags) <div class="bg-white p-3 mb-3"> <h5>United States trends</h5> <ul class="list-unstyled mb-0"> <li class="mb-2"> <a href="#">#Laravel</a> <br> <span class="text-muted" style="font-size: 13px;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est.</span> </li> @foreach ($trendingHashtags as $key => $value) <li class="mb-2"> <a href="{{ route('hashtags.index', strtolower($key)) }}">#{{ $key }}</a> <div class="text-muted"> {{ $value }} {{ str_plural('post', $value) }} </div> </li> @endforeach </ul> </div> @endif
Fix keyToSlice for array/object filter values
'use strict'; let juri = require('juri')(), pattern = /(^|[+\-:])(\w+|\([^(]+\))/g; exports.sliceToKey = (s) => s.type + (s.join ? '+' + juri.encode(s.join) : '') + (s.link ? '-' + juri.encode(s.link) : '') + (s.order ? ':' + s.order : '') + (s.filter ? '!' + juri.encode(s.filter) : ''); exports.keyToSlice = (k) => { let s = {}, parts = k.split('!'); s.filter = juri.decode(parts[1]); parts[0].match(pattern).forEach((part, i) => { if (i === 0) { s.type = part; } else if (part[0] === '+') { s.join = juri.decode(part.substr(1)); } else if (part[0] === '-') { s.link = juri.decode(part.substr(1)); } else if (part[0] === ':') { s.order = part.substr(1); } }); return s; };
'use strict'; let juri = require('juri')(), pattern = /(^|[+\-:!])(\w+|\([^(]+\))/g; exports.sliceToKey = (s) => s.type + (s.join ? '+' + juri.encode(s.join) : '') + (s.link ? '-' + juri.encode(s.link) : '') + (s.order ? ':' + s.order : '') + (s.filter ? '!' + juri.encode(s.filter) : ''); exports.keyToSlice = (k) => { let s = {}; k.match(pattern).forEach((part, i) => { if (i === 0) { s.type = part; } else if (part[0] === '+') { s.join = juri.decode(part.substr(1)); } else if (part[0] === '-') { s.link = juri.decode(part.substr(1)); } else if (part[0] === ':') { s.order = part.substr(1); } else if (part[0] === '!') { s.filter = juri.decode(part.substr(1)); } }); return s; };
:new: Add a new has method
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) indieLinter.onDidUpdateMessages(messages => { this.emitter.emit('did-update-messages', {linter: indieLinter, messages}) }) this.emit('observe', indieLinter) return indieLinter } has(indieLinter) { return this.indieLinters.has(indieLinter) } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.emitter.on('observe', callback) } // Private method onDidUpdateMessages(callback) { return this.emitter.on('did-update-messages', callback) } dispose() { this.subscriptions.dispose() } }
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) indieLinter.onDidUpdateMessages(messages => { this.emitter.emit('did-update-messages', {linter: indieLinter, messages}) }) this.emit('observe', indieLinter) return indieLinter } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.emitter.on('observe', callback) } // Private method onDidUpdateMessages(callback) { return this.emitter.on('did-update-messages', callback) } dispose() { this.subscriptions.dispose() } }
Remove error-prone, previously commented Mongo annotation See e26638d0a3cd1655a9955a96ce271485b6c17950
package org.oasis_eu.portal.core.mongo.model.images; import org.joda.time.DateTime; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; /** * User: schambon * Date: 9/3/14 */ @Document(collection = "image_download_attempt") public class ImageDownloadAttempt { @Id private String id; @Indexed(unique = true) private String url; private DateTime time; public String getId() { return id; } public void setId(String id) { this.id = id; } public DateTime getTime() { return time; } public void setTime(DateTime time) { this.time = time; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package org.oasis_eu.portal.core.mongo.model.images; import org.joda.time.DateTime; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; /** * User: schambon * Date: 9/3/14 */ @Document(collection = "image_download_attempt") public class ImageDownloadAttempt { @Id private String id; @Indexed(unique = true) private String url; @Indexed(expireAfterSeconds = 900) private DateTime time; public String getId() { return id; } public void setId(String id) { this.id = id; } public DateTime getTime() { return time; } public void setTime(DateTime time) { this.time = time; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
Expand ignored directories to match behaviour of the go tool The go tool currently ignore directories that start with a dot or an underscore, or are called 'testdata'. This patch augments the ignore logic of goconvey to match what Go does by default.
package system import ( "log" "os" "path/filepath" "strings" ) type FileSystem struct{} func (self *FileSystem) Walk(root string, step filepath.WalkFunc) { err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if self.isMetaDirectory(info) { return filepath.SkipDir } return step(path, info, err) }) if err != nil { log.Println("Error while walking file system:", err) panic(err) } } func (self *FileSystem) isMetaDirectory(info os.FileInfo) bool { name := info.Name() return info.IsDir() && (strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") || name == "testdata") } func (self *FileSystem) Exists(directory string) bool { info, err := os.Stat(directory) return err == nil && info.IsDir() } func NewFileSystem() *FileSystem { return &FileSystem{} }
package system import ( "log" "os" "path/filepath" "strings" ) type FileSystem struct{} func (self *FileSystem) Walk(root string, step filepath.WalkFunc) { err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if self.isMetaDirectory(info) { return filepath.SkipDir } return step(path, info, err) }) if err != nil { log.Println("Error while walking file system:", err) panic(err) } } func (self *FileSystem) isMetaDirectory(info os.FileInfo) bool { return info.IsDir() && strings.HasPrefix(info.Name(), ".") } func (self *FileSystem) Exists(directory string) bool { info, err := os.Stat(directory) return err == nil && info.IsDir() } func NewFileSystem() *FileSystem { return &FileSystem{} }
Comment out initial response to include refactored answer
// Reverse Words /*RULES: Function takes a string parameter Reverse every word in the string Return new string NOTE: Order of words shouldn't change Can't use the array.reverse() method */ /*PSEUDOCODE 1) Split array by words 2) For each word, 2a) Push last letter of each individual element into a new array 2b) When done, push new array into new empty str array 2c) Continue doing this for all words 3) Join new array 4) Return new string */ // This was my initial response, and it works fine! But could be slightly refactored for cleaner code. // function reverseWords(str){ // var strArr = str.split(" "); // var emptyWordArr = []; // var emptyStrArr = []; // var index = 0; // strArr.forEach(function(word){ // word = word.split(''); // index = (word.length); // while (index > -1){ // emptyWordArr.push(word[index]) // index--; // } // emptyStrArr.push(emptyWordArr.join('')); // emptyWordArr = []; // }); // return emptyStrArr.join(' '); // }
// Reverse Words /*RULES: Function takes a string parameter Reverse every word in the string Return new string NOTE: Order of words shouldn't change Can't use the array.reverse() method */ /*PSEUDOCODE 1) Split array by words 2) For each word, 2a) Push last letter of each individual element into a new array 2b) When done, push new array into new empty str array 2c) Continue doing this for all words 3) Join new array 4) Return new string */ function reverseWords(str){ var strArr = str.split(" "); var emptyWordArr = []; var emptyStrArr = []; var index = 0; strArr.forEach(function(word){ word = word.split(''); index = (word.length); while (index > -1){ emptyWordArr.push(word[index]) index--; } emptyStrArr.push(emptyWordArr.join('')); emptyWordArr = []; }); return emptyStrArr.join(' '); }
Remove comment, offset observer will throw runtime exceptions
package nakadi; /** * Can be called by the {@link StreamObserver} to indicate a batch has been processed. * * Typically this is used to implement a checkpointer that can store the position of the * client in the stream to track their progress. */ public interface StreamOffsetObserver { /** * Receives a {@link StreamCursorContext} that can be used to checkpoint (or more generally, * observe) progress in the stream. * <p></p> * The default observer for a subscription based {@link StreamProcessor} (one which has been * given a subscription id via {@link StreamConfiguration#subscriptionId} is * {@link SubscriptionOffsetObserver}. This will checkpoint back to the server each time * it's called. This behaviour can be replaced by supplying a different checkpointer via * {@link StreamProcessor.Builder#streamOffsetObserver}. * * @param streamCursorContext the batch's {@link StreamCursorContext}. * */ void onNext(StreamCursorContext streamCursorContext) throws NakadiException; }
package nakadi; /** * Can be called by the {@link StreamObserver} to indicate a batch has been processed. * * Typically this is used to implement a checkpointer that can store the position of the * client in the stream to track their progress. */ public interface StreamOffsetObserver { /** * Receives a {@link StreamCursorContext} that can be used to checkpoint (or more generally, * observe) progress in the stream. * <p></p> * The default observer for a subscription based {@link StreamProcessor} (one which has been * given a subscription id via {@link StreamConfiguration#subscriptionId} is * {@link SubscriptionOffsetObserver}. This will checkpoint back to the server each time * it's called. This behaviour can be replaced by supplying a different checkpointer via * {@link StreamProcessor.Builder#streamOffsetObserver}. * * @param streamCursorContext the batch's {@link StreamCursorContext}. * * todo: see if we need to declare checked exceptions here to force the observer to handle. */ void onNext(StreamCursorContext streamCursorContext) throws NakadiException; }
[tests] Add a failing test that demonstrates wrong handling of data The ping handler adds the data directly to the response_kwargs, allowing internal kwargs to be overwritten. `send_message()` and `build_message()` should not accept `**additional_data`, but `additional_data: dict = None` instead.
from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': {'some': 'data', 'other': 'data', 'handler': 'foo'} }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' assert data['data']['handler'] == 'foo' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1
from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': {'some': 'data', 'other': 'data'} }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1
Fix direct glyph selection with select method
from __future__ import absolute_import import unittest from mock import patch from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.validation import check_integrity class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] plot = figure() plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) renderer = plot.select({'type': GlyphRenderer})[0] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'COLON_IN_CATEGORY_LABEL', 'Category label contains colons', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) if __name__ == '__main__': unittest.main()
from __future__ import absolute_import import unittest from mock import patch from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.validation import check_integrity class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] p = figure() p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) renderer = p.renderers[-1] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'COLON_IN_CATEGORY_LABEL', 'Category label contains colons', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) if __name__ == '__main__': unittest.main()
Ch18: Add date URL kwarg options to PostGetMixin.
from django.shortcuts import get_object_or_404 from .models import Post class PostGetMixin: month_url_kwarg = 'month' year_url_kwarg = 'year' errors = { 'url_kwargs': "Generic view {} must be called with " "year, month, and slug.", } def get_object(self, queryset=None): year = self.kwargs.get( self.year_url_kwarg) month = self.kwargs.get( self.month_url_kwarg) slug = self.kwargs.get( self.slug_url_kwarg) if (year is None or month is None or slug is None): raise AttributeError( self.errors['url_kwargs'].format( self.__class__.__name__)) return get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug__iexact=slug)
from django.shortcuts import get_object_or_404 from .models import Post class PostGetMixin: errors = { 'url_kwargs': "Generic view {} must be called with " "year, month, and slug.", } def get_object(self, queryset=None): year = self.kwargs.get('year') month = self.kwargs.get('month') slug = self.kwargs.get('slug') if (year is None or month is None or slug is None): raise AttributeError( self.errors['url_kwargs'].format( self.__class__.__name__)) return get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug__iexact=slug)
Move table JS outside of scrolling
$(document).ready(function () { var sections = $('div.section'); var activeLink = null; var bottomHeightThreshold = $(document).height() - 30; $(window).scroll(function (event) { var distanceFromTop = $(this).scrollTop(); var currentSection = null; if(distanceFromTop + window.innerHeight > bottomHeightThreshold) { currentSection = $(sections[sections.length - 1]); } else { sections.each(function () { var section = $(this); if (section.offset().top - 1 < distanceFromTop) { currentSection = section; } }); } if (activeLink) { activeLink.parent().removeClass('active'); } if (currentSection) { activeLink = $('.sphinxsidebar a[href="#' + currentSection.attr('id') + '"]'); activeLink.parent().addClass('active'); } }); const tables = document.querySelectorAll('.py-attribute-table[data-move-to-id]'); tables.forEach(table => { let element = document.getElementById(table.getAttribute('data-move-to-id')); let parent = element.parentNode; // insert ourselves after the element parent.insertBefore(table, element.nextSibling); }); });
$(document).ready(function () { var sections = $('div.section'); var activeLink = null; var bottomHeightThreshold = $(document).height() - 30; $(window).scroll(function (event) { var distanceFromTop = $(this).scrollTop(); var currentSection = null; if(distanceFromTop + window.innerHeight > bottomHeightThreshold) { currentSection = $(sections[sections.length - 1]); } else { sections.each(function () { var section = $(this); if (section.offset().top - 1 < distanceFromTop) { currentSection = section; } }); } if (activeLink) { activeLink.parent().removeClass('active'); } if (currentSection) { activeLink = $('.sphinxsidebar a[href="#' + currentSection.attr('id') + '"]'); activeLink.parent().addClass('active'); } const tables = document.querySelectorAll('.py-attribute-table[data-move-to-id]'); tables.forEach(table => { let element = document.getElementById(table.getAttribute('data-move-to-id')); let parent = element.parentNode; // insert ourselves after the element parent.insertBefore(table, element.nextSibling); }); }); });
Return a sample result, so can test methods that perform a sample git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@907681 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.protocol.http.sampler; import java.net.URL; /** * Dummy HTTPSampler class for use by classes that need an HTTPSampler, but that * don't need an actual sampler, e.g. for Parsing testing. */ public final class HTTPNullSampler extends HTTPSamplerBase { private static final long serialVersionUID = 240L; /** * Returns a sample Result with the request fields filled in. * * {@inheritDoc} */ @Override protected HTTPSampleResult sample(URL u, String method, boolean areFollowingRedirec, int depth) { HTTPSampleResult res = new HTTPSampleResult(); res.sampleStart(); res.setURL(u); res.sampleEnd(); return res; // throw new UnsupportedOperationException("For test purposes only"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.protocol.http.sampler; import java.net.URL; /** * Dummy HTTPSampler class for use by classes that need an HTTPSampler, but that * don't need an actual sampler, e.g. for Parsing testing. */ public final class HTTPNullSampler extends HTTPSamplerBase { private static final long serialVersionUID = 240L; /* * (non-Javadoc) * * @see org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase#sample(java.net.URL, * java.lang.String, boolean, int) */ @Override protected HTTPSampleResult sample(URL u, String s, boolean b, int i) { throw new UnsupportedOperationException("For test purposes only"); } }
FIX other two sample data load for Windows
import cPickle from os.path import dirname from os.path import join import numpy as np def load_letters(): """Load the OCR letters dataset. This is a chain classification task. Each example consists of a word, segmented into letters. The first letter of each word is ommited from the data, as it was a capital letter (in contrast to all other letters). """ module_path = dirname(__file__) data_file = open(join(module_path, 'letters.pickle'),'rb') data = cPickle.load(data_file) # we add an easy to use image representation: data['images'] = [np.hstack([l.reshape(16, 8) for l in word]) for word in data['data']] return data def load_scene(): module_path = dirname(__file__) data_file = open(join(module_path, 'scene.pickle'),'rb') return cPickle.load(data_file) def load_snakes(): module_path = dirname(__file__) data_file = open(join(module_path, 'snakes.pickle'),'rb') return cPickle.load(data_file)
import cPickle from os.path import dirname from os.path import join import numpy as np def load_letters(): """Load the OCR letters dataset. This is a chain classification task. Each example consists of a word, segmented into letters. The first letter of each word is ommited from the data, as it was a capital letter (in contrast to all other letters). """ module_path = dirname(__file__) data_file = open(join(module_path, 'letters.pickle'),'rb') data = cPickle.load(data_file) # we add an easy to use image representation: data['images'] = [np.hstack([l.reshape(16, 8) for l in word]) for word in data['data']] return data def load_scene(): module_path = dirname(__file__) data_file = open(join(module_path, 'scene.pickle')) return cPickle.load(data_file) def load_snakes(): module_path = dirname(__file__) data_file = open(join(module_path, 'snakes.pickle')) return cPickle.load(data_file)
Add python 3.5 to trove classifiers
import setuptools setuptools.setup( name="{{ cookiecutter.package_name }}", version="{{ cookiecutter.package_version }}", url="{{ cookiecutter.package_url }}", author="{{ cookiecutter.author_name }}", author_email="{{ cookiecutter.author_email }}", description="{{ cookiecutter.package_description }}", long_description=open('README.rst').read(), packages=setuptools.find_packages(), install_requires=[], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
import setuptools setuptools.setup( name="{{ cookiecutter.package_name }}", version="{{ cookiecutter.package_version }}", url="{{ cookiecutter.package_url }}", author="{{ cookiecutter.author_name }}", author_email="{{ cookiecutter.author_email }}", description="{{ cookiecutter.package_description }}", long_description=open('README.rst').read(), packages=setuptools.find_packages(), install_requires=[], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
Update Sami theme as default.
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('3.*') ->addFromTags('4.*'); return new Sami($iterator, array( 'theme' => 'default', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__.'/build/sami/%version%', 'cache_dir' => __DIR__.'/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ]);
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('3.*') ->addFromTags('4.*'); return new Sami($iterator, [ 'theme' => 'default', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__.'/build/sami/%version%', 'cache_dir' => __DIR__.'/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ]);
Make sure to add the apple id
import json import xml.etree.ElementTree as etree table = etree.Element("table", attrib={ "id": "apple", "class": "tablesorter", "cellspacing": "1", "cellpadding": "0", }) thead = etree.SubElement(table, "thead") tbody = etree.SubElement(table, "tbody") tr = etree.SubElement(thead, "tr") for heading in ["Product", "Release Date", "Original Price", "Stock Value Today"]: th = etree.SubElement(tr, "th") th.text = heading for product in json.load(open("apple-specs-with-current.json")): row = etree.SubElement(tbody, "tr") value = 0 data = [ product["name"], product["introduction-date"].split("T")[0], "$" + unicode(product["original-price"]), "${:d}".format(int(product["stock-shares"] * 599.55)), ] for field in data: td = etree.SubElement(row, "td") td.text = field print etree.tostring(table)
import json import xml.etree.ElementTree as etree table = etree.Element("table", attrib={ "class": "tablesorter", "cellspacing": "1", "cellpadding": "0", }) thead = etree.SubElement(table, "thead") tbody = etree.SubElement(table, "tbody") tr = etree.SubElement(thead, "tr") for heading in ["Product", "Release Date", "Original Price", "Stock Value Today"]: th = etree.SubElement(tr, "th") th.text = heading for product in json.load(open("apple-specs-with-current.json")): row = etree.SubElement(tbody, "tr") value = 0 data = [ product["name"], product["introduction-date"].split("T")[0], "$" + unicode(product["original-price"]), "${:d}".format(int(product["stock-shares"] * 599.55)), ] for field in data: td = etree.SubElement(row, "td") td.text = field print etree.tostring(table)
Make the integration test fail, so we can see the request / response
import righteous from ConfigParser import SafeConfigParser from ..compat import unittest class RighteousIntegrationTestCase(unittest.TestCase): def setUp(self): config = SafeConfigParser() config.read('righteous.config') if not config.has_section('auth'): raise Exception('Please create a righteous.config file with ' 'appropriate credentials') self.auth = dict( (key, config.get('auth', key)) for key in config.options('auth')) self.server = dict( (key, config.get('server-defaults', key)) for key in config.options('server-defaults')) righteous.init( self.auth['username'], self.auth['password'], self.auth['account_id'], **self.server) self.config = config self.username = self.auth['username'] def test_login(self): self.assertTrue(righteous.login())
import righteous from ConfigParser import SafeConfigParser from ..compat import unittest class RighteousIntegrationTestCase(unittest.TestCase): def setUp(self): config = SafeConfigParser() config.read('righteous.config') if not config.has_section('auth'): raise Exception('Please create a righteous.config file with ' 'appropriate credentials') self.auth = dict( (key, config.get('auth', key)) for key in config.options('auth')) self.server = dict( (key, config.get('server-defaults', key)) for key in config.options('server-defaults')) righteous.init( self.auth['username'], self.auth['password'], self.auth['account_id'], **self.server) self.config = config self.username = self.auth['username'] def test_login(self): self.assertTrue(righteous.login()) assert False
Remove unused form class variable.
<?php namespace Backend\Modules\Analytics\Actions; use Backend\Core\Engine\Base\ActionDelete; use Backend\Core\Engine\Model; /** * This is the reset-action. It will remove your coupling with analytics * * @author Wouter Sioen <wouter@sumocoders.be> */ final class Reset extends ActionDelete { public function execute() { $this->get('fork.settings')->delete($this->getModule(), 'certificate'); $this->get('fork.settings')->delete($this->getModule(), 'email'); $this->get('fork.settings')->delete($this->getModule(), 'account'); $this->get('fork.settings')->delete($this->getModule(), 'web_property_id'); $this->get('fork.settings')->delete($this->getModule(), 'profile'); return $this->redirect(Model::createURLForAction('Settings')); } }
<?php namespace Backend\Modules\Analytics\Actions; use Backend\Core\Engine\Base\ActionDelete; use Backend\Core\Engine\Model; /** * This is the reset-action. It will remove your coupling with analytics * * @author Wouter Sioen <wouter@sumocoders.be> */ final class Reset extends ActionDelete { /** * The form instance * * @var Form */ private $form; public function execute() { $this->get('fork.settings')->delete($this->getModule(), 'certificate'); $this->get('fork.settings')->delete($this->getModule(), 'email'); $this->get('fork.settings')->delete($this->getModule(), 'account'); $this->get('fork.settings')->delete($this->getModule(), 'web_property_id'); $this->get('fork.settings')->delete($this->getModule(), 'profile'); return $this->redirect(Model::createURLForAction('Settings')); } }
Fix line addressing issue on 'cd' command
#!/usr/bin/env python3 import re from whalelinter.app import App from whalelinter.dispatcher import Dispatcher from whalelinter.commands.command import ShellCommand from whalelinter.commands.apt import Apt @Dispatcher.register(token='run', command='cd') class Cd(ShellCommand): def __init__(self, **kwargs): App._collecter.throw(2002, kwargs.get('lineno')) @Dispatcher.register(token='run', command='rm') class Rm(ShellCommand): def __init__(self, **kwargs): rf_flags_regex = re.compile("(-.*[rRf].+-?[rRf]|-[rR]f|-f[rR])") rf_flags = True if [i for i in kwargs.get('args') if rf_flags_regex.search(i)] else False cache_path_regex = re.compile("/var/lib/apt/lists(\/\*?)?") cache_path = True if [i for i in kwargs.get('args') if cache_path_regex.search(i)] else False if rf_flags and cache_path: if (int(Apt._has_been_used) < int(kwargs.get('lineno'))): Apt._has_been_used = 0
#!/usr/bin/env python3 import re from whalelinter.app import App from whalelinter.dispatcher import Dispatcher from whalelinter.commands.command import ShellCommand from whalelinter.commands.apt import Apt @Dispatcher.register(token='run', command='cd') class Cd(ShellCommand): def __init__(self, **kwargs): App._collecter.throw(2002, self.line) return False @Dispatcher.register(token='run', command='rm') class Rm(ShellCommand): def __init__(self, **kwargs): rf_flags_regex = re.compile("(-.*[rRf].+-?[rRf]|-[rR]f|-f[rR])") rf_flags = True if [i for i in kwargs.get('args') if rf_flags_regex.search(i)] else False cache_path_regex = re.compile("/var/lib/apt/lists(\/\*?)?") cache_path = True if [i for i in kwargs.get('args') if cache_path_regex.search(i)] else False if rf_flags and cache_path: if (int(Apt._has_been_used) < int(kwargs.get('lineno'))): Apt._has_been_used = 0
Remove @Immutable annotation from abstract class.
/* * Copyright (c) 2008-2011 Graham Allan * * 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.mutabilitydetector.locations; import javax.annotation.Nonnull; public abstract class ClassName { private final String asString; public ClassName(@Nonnull String className) { this.asString = className; } public String asString() { return asString; } @Override public String toString() { return asString(); } @Override public int hashCode() { return asString.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ClassName other = (ClassName) obj; return asString.equals(other.asString); } }
/* * Copyright (c) 2008-2011 Graham Allan * * 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.mutabilitydetector.locations; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; @Immutable public abstract class ClassName { private final String asString; public ClassName(@Nonnull String className) { this.asString = className; } public String asString() { return asString; } @Override public String toString() { return asString(); } @Override public int hashCode() { return asString.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ClassName other = (ClassName) obj; return asString.equals(other.asString); } }
Fix test - forgot feature switch removal
<?php namespace Tests\GtmPlugin\EventListener; use GtmPlugin\EventListener\EnvironmentListener; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Xynnn\GoogleTagManagerBundle\Service\GoogleTagManager; /** * Class EnvironmentListenerTest * @package Tests\GtmPlugin\EventListener * @covers \GtmPlugin\EventListener\EnvironmentListener */ class EnvironmentListenerTest extends \PHPUnit_Framework_TestCase { public function testEnvironmentIsAddedToGtmObject() { $gtm = new GoogleTagManager(true, 'id1234'); $listener = new EnvironmentListener($gtm, 'test_env'); $mock = $this->getMockBuilder(GetResponseEvent::class)->disableOriginalConstructor()->getMock(); $listener->onKernelRequest($mock); $this->assertArrayHasKey('env', $gtm->getData()); $this->assertSame($gtm->getData()['env'], 'test_env'); } }
<?php namespace Tests\GtmPlugin\EventListener; use GtmPlugin\EventListener\EnvironmentListener; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Xynnn\GoogleTagManagerBundle\Service\GoogleTagManager; /** * Class EnvironmentListenerTest * @package Tests\GtmPlugin\EventListener * @covers \GtmPlugin\EventListener\EnvironmentListener */ class EnvironmentListenerTest extends \PHPUnit_Framework_TestCase { public function testEnvironmentIsAddedToGtmObject() { $gtm = new GoogleTagManager(true, 'id1234'); $listener = new EnvironmentListener(true, $gtm, 'test_env'); $mock = $this->getMockBuilder(GetResponseEvent::class)->disableOriginalConstructor()->getMock(); $listener->onKernelRequest($mock); $this->assertArrayHasKey('env', $gtm->getData()); $this->assertSame($gtm->getData()['env'], 'test_env'); } }
Return our actual port to avoid some potential conflicts
//test cookie passing var http = require("http"); var fs = require("fs"); var querystring = require("querystring"); express = require('express'), connect = require('connect'), sys = require('sys'), app = express.createServer(); var stdin = process.openStdin(); stdin.setEncoding('utf8'); stdin.on('data', function (chunk) { var processInfo = JSON.parse(chunk); process.chdir(processInfo.workingDirectory); app.listen(processInfo.port, function() { console.log(JSON.stringify({port: app.address().port})); }); }); app.get('/test', function(req, res) { console.log("Cookie test"); res.cookie('rememberme', 'yes', { maxAge: 900000 }); res.writeHead(200, { 'Content-Type': 'text/html' }); // res.cookie('locker_proxy_cookie_test', 'works'); res.end(); });
//test cookie passing var http = require("http"); var fs = require("fs"); var querystring = require("querystring"); express = require('express'), connect = require('connect'), sys = require('sys'), app = express.createServer(); var stdin = process.openStdin(); stdin.setEncoding('utf8'); stdin.on('data', function (chunk) { var processInfo = JSON.parse(chunk); process.chdir(processInfo.workingDirectory); app.listen(processInfo.port, function() { var returnedInfo = {port: processInfo.port}; console.log(JSON.stringify(returnedInfo)); }); }); app.get('/test', function(req, res) { res.cookie('rememberme', 'yes', { maxAge: 900000 }); res.writeHead(200, { 'Content-Type': 'text/html' }); // res.cookie('locker_proxy_cookie_test', 'works'); res.end(); });
Fix public body search index by indexing jurisdiction name
from django.conf import settings from haystack import indexes from haystack import site from publicbody.models import PublicBody from helper.searchindex import QueuedRealTimeSearchIndex PUBLIC_BODY_BOOSTS = getattr(settings, "FROIDE_PUBLIC_BODY_BOOSTS", {}) class PublicBodyIndex(QueuedRealTimeSearchIndex): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='') topic_auto = indexes.EdgeNgramField(model_attr='topic_name') topic_slug = indexes.CharField(model_attr='topic__slug') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def index_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print "Boosting %s at %f" % (obj, data['boost']) return data site.register(PublicBody, PublicBodyIndex)
from django.conf import settings from haystack import indexes from haystack import site from publicbody.models import PublicBody from helper.searchindex import QueuedRealTimeSearchIndex PUBLIC_BODY_BOOSTS = getattr(settings, "FROIDE_PUBLIC_BODY_BOOSTS", {}) class PublicBodyIndex(QueuedRealTimeSearchIndex): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction', default='') topic_auto = indexes.EdgeNgramField(model_attr='topic_name') topic_slug = indexes.CharField(model_attr='topic__slug') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def index_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print "Boosting %s at %f" % (obj, data['boost']) return data site.register(PublicBody, PublicBodyIndex)
Update Task definition to include modules instead of module names
from typing import Callable, List import torch.nn as nn from torch.utils.data import DataLoader class Task(object): """A task for use in an MMTL MetalModel Args: name: The name of the task TODO: replace this with a more fully-featured path through the network input_module: The input module head_module: The task head module data: A list of DataLoaders (instances and labels) to feed through the network. The list contains [train, dev, test]. scorers: A list of Scorers that return metrics_dict objects. """ def __init__( self, name: str, input_module: nn.Module, head_module: nn.Module, data_loaders: List[DataLoader], scorers: List[Callable] = None, ) -> None: if len(data_loaders) != 3: msg = "Arg data_loaders must be a list of length 3 [train, valid, test]" raise Exception(msg) self.name = name self.input_module = input_module self.head_module = head_module self.data_loaders = data_loaders self.scorers = scorers
from typing import Callable, List from torch.utils.data import DataLoader class Task(object): """A task for use in an MMTL MetalModel Args: name: The name of the task input_name: The name of the input module to use head_name: The name of the task head module to use TODO: replace this with a more fully-featured path through the network data: A list of DataLoaders (instances and labels) to feed through the network. The list contains [train, dev, test]. scorers: A list of Scorers that return metrics_dict objects. """ def __init__( self, name: str, input_name: str, head_name: str, data_loaders: List[DataLoader], scorers: List[Callable] = None, ) -> None: if len(data_loaders) != 3: msg = "Arg data_loaders must be a list of length 3 [train, valid, test]" raise Exception(msg) self.name = name self.input_name = input_name self.head_name = head_name self.data_loaders = data_loaders self.scorers = scorers
Fix db deletion, take 2
import os from uuid import uuid4 from unittest import TestCase import webtest from daybed.db import DatabaseConnection HERE = os.path.dirname(os.path.abspath(__file__)) class BaseWebTest(TestCase): """Base Web Test to test your cornice service. It setups the database before each test and delete it after. """ def setUp(self): self.db_name = os.environ['DB_NAME'] = 'daybed-tests-%s' % uuid4() self.app = webtest.TestApp("config:tests.ini", relative_to=HERE) self.db_server = self.app.app.registry.settings['db_server'] self.db_base = self.db_server[self.db_name] self.db = DatabaseConnection(self.db_base) def tearDown(self): # Delete Test DB self.db_server.delete(self.db_name) def put_valid_definition(self): """Create a valid definition named "todo". """ # Put a valid definition self.app.put_json('/definitions/todo', self.valid_definition, headers=self.headers)
import os from uuid import uuid4 from unittest import TestCase import webtest from daybed.db import DatabaseConnection HERE = os.path.dirname(os.path.abspath(__file__)) class BaseWebTest(TestCase): """Base Web Test to test your cornice service. It setups the database before each test and delete it after. """ def setUp(self): self.db_name = os.environ['DB_NAME'] = 'daybed-tests-%s' % uuid4() self.db_server = self.app.app.registry.settings['db_server'] self.db_base = self.db_server[self.db_name] self.db = DatabaseConnection(self.db_base) self.app = webtest.TestApp("config:tests.ini", relative_to=HERE) def tearDown(self): # Delete Test DB self.db_server.delete(self.db_name) def put_valid_definition(self): """Create a valid definition named "todo". """ # Put a valid definition self.app.put_json('/definitions/todo', self.valid_definition, headers=self.headers)