text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
[test] Update test so it matches the Windows output git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@369595 91177308-0d34-0410-b5e6-96231b3b80d8
# coding=utf8 """ Test that C++ supports char8_t correctly. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class CxxChar8_tTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler="clang", compiler_version=['<', '7.0']) def test(self): """Test that C++ supports char8_t correctly.""" self.build() exe = self.getBuildArtifact("a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # FIXME: We should be able to test this with target variable, but the # data formatter output is broken. lldbutil.run_break_set_by_symbol(self, 'main') self.runCmd("run", RUN_SUCCEEDED) self.expect( "frame variable a", substrs=["(char8_t)", "0x61 u8'a'"]) self.expect( "frame variable ab", substrs=['(const char8_t *)' , 'u8"你好"']) self.expect( "frame variable abc", substrs=['(char8_t [9])', 'u8"你好"'])
# coding=utf8 """ Test that C++ supports char8_t correctly. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class CxxChar8_tTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler="clang", compiler_version=['<', '7.0']) def test(self): """Test that C++ supports char8_t correctly.""" self.build() exe = self.getBuildArtifact("a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # FIXME: We should be able to test this with target variable, but the # data formatter output is broken. lldbutil.run_break_set_by_symbol(self, 'main') self.runCmd("run", RUN_SUCCEEDED) self.expect( "frame variable a", substrs=["(char8_t) ::a = 0x61 u8'a'"]) self.expect( "frame variable ab", substrs=['(const char8_t *) ::ab', 'u8"你好"']) self.expect( "frame variable abc", substrs=['(char8_t [9]) ::abc = u8"你好"'])
Make flake8 happy for spd
"""Digital leben workflow.""" from adhocracy_core.workflows import add_workflow from adhocracy_core.workflows.standard import standard_meta digital_leben_meta = standard_meta \ .transform(('states', 'participate', 'acm'), {'principals': ['participant', 'moderator', 'creator', 'initiator'], # noqa 'permissions': [['create_proposal', None, None, None, 'Allow'], # noqa ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa ['edit_comment', None, None, 'Allow', None], # noqa ['create_rate', 'Allow', None, None, None], # noqa ['edit_rate', None, None, 'Allow', None], # noqa ]}) def includeme(config): """Add workflow.""" add_workflow(config.registry, digital_leben_meta, 'digital_leben')
"""Digital leben workflow.""" from adhocracy_core.workflows import add_workflow from adhocracy_core.workflows.standard import standard_meta digital_leben_meta = standard_meta \ .transform(('states', 'participate', 'acm'), {'principals': [ 'participant', 'moderator', 'creator', 'initiator'], # noqa 'permissions': [['create_proposal', None, None, None, 'Allow'], # noqa ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa ['edit_comment', None, None, 'Allow', None ], # noqa ['create_rate', 'Allow', None, None, None ], # noqa ['edit_rate', None, None, 'Allow', None ], # noqa ]}) def includeme(config): """Add workflow.""" add_workflow(config.registry, digital_leben_meta, 'digital_leben')
Resolve all the JS errors
$(document).ready(function () { /*Navigation initialization*/ var navigation = $('#navigation'); var navShown = false; var navController = $('#nav-controller'); if (navController) { navController.on('click', function () { if (navShown) { navigation.removeClass('show-nav'); navigation.addClass('hide-nav'); navShown = false; } else { navigation.removeClass('hide-nav'); navigation.addClass('show-nav'); navShown = true; } }); } /*Bootstrap Popover initialization*/ $(function () { $('[data-toggle="popover"]').popover() }); /*Verical scorlling*/ $(function () { function scrollHorizontally(e) { e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); document.getElementById('horizontal-scrolling').scrollLeft -= (delta * 40); // Multiplied by 40 e.preventDefault(); } var horizontalScrolling = document.getElementById('horizontal-scrolling'); if (horizontalScrolling) { if (horizontalScrolling.addEventListener) { // IE9, Chrome, Safari, Opera horizontalScrolling.addEventListener("mousewheel", scrollHorizontally, false); // Firefox horizontalScrolling.addEventListener("DOMMouseScroll", scrollHorizontally, false); } else { // IE 6/7/8 horizontalScrolling.attachEvent("onmousewheel", scrollHorizontally); } } }); });
$(document).ready(function () { /*Navigation initialization*/ var navigation = $('#navigation'); var navShown = false; var navController = $('#nav-controller'); if (navController) { navController.on('click', function () { if (navShown) { navigation.removeClass('show-nav'); navigation.addClass('hide-nav'); navShown = false; } else { navigation.removeClass('hide-nav'); navigation.addClass('show-nav'); navShown = true; } }); } /*Bootstrap Popover initialization*/ $(function () { $('[data-toggle="popover"]').popover() }); /*Verical scorlling*/ $(function () { function scrollHorizontally(e) { e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); document.getElementById('horizontal-scrolling').scrollLeft -= (delta * 40); // Multiplied by 40 e.preventDefault(); } var horizontalScrolling = document.getElementById('horizontal-scrolling'); if (horizontalScrolling) { if (horizontalScrolling.addEventListener) { // IE9, Chrome, Safari, Opera horizontalScrolling.addEventListener("mousewheel", scrollHorizontally, false); // Firefox horizontalScrolling.addEventListener("DOMMouseScroll", scrollHorizontally, false); } else { // IE 6/7/8 horizontalScrolling.attachEvent("onmousewheel", scrollHorizontally); } } }); /*File uplad button*/ document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; });
Add missing Everex Token and Ripple
const Lang = imports.lang; const Local = imports.misc.extensionUtils.getCurrentExtension(); const BaseProvider = Local.imports.BaseProvider; const Api = new Lang.Class({ Name: 'BXinTH.Api', Extends: BaseProvider.Api, apiName: "BX.in.th", currencies: ['THB'], coins: ['BTC','mBTC','ETH','DAS','REP','GNO', 'OMG', 'EVX', 'XRP'],//? interval: 60, // unclear, should be safe attributes: { last: function (options) { const renderCurrency = BaseProvider.CurrencyRenderer(options); const renderChange = BaseProvider.ChangeRenderer(); const find = (currency, coin, tickerObj) => { let result = { "last_price": 0, "change": 0 } Object.keys(tickerObj).forEach((k) => { let current = tickerObj[k]; if (current['primary_currency'] === currency && current['secondary_currency'] === coin) { result = current; } }); return result; }; const coin = BaseProvider.baseCoin(options.coin); return { text: (data) => renderCurrency(find(options.currency, coin, data)["last_price"]), change: (data) => renderChange(find(options.currency, coin, data)["change"]) }; } }, getLabel: function (options) { return "BXinTH " + options.currency + "/" + options.coin; }, getUrl: function (options) { return "https://bx.in.th/api/"; } });
const Lang = imports.lang; const Local = imports.misc.extensionUtils.getCurrentExtension(); const BaseProvider = Local.imports.BaseProvider; const Api = new Lang.Class({ Name: 'BXinTH.Api', Extends: BaseProvider.Api, apiName: "BX.in.th", currencies: ['THB'], coins: ['BTC','mBTC','ETH','DAS','REP','GNO', 'OMG'],//? interval: 60, // unclear, should be safe attributes: { last: function (options) { const renderCurrency = BaseProvider.CurrencyRenderer(options); const renderChange = BaseProvider.ChangeRenderer(); const find = (currency, coin, tickerObj) => { let result = { "last_price": 0, "change": 0 } Object.keys(tickerObj).forEach((k) => { let current = tickerObj[k]; if (current['primary_currency'] === currency && current['secondary_currency'] === coin) { result = current; } }); return result; }; const coin = BaseProvider.baseCoin(options.coin); return { text: (data) => renderCurrency(find(options.currency, coin, data)["last_price"]), change: (data) => renderChange(find(options.currency, coin, data)["change"]) }; } }, getLabel: function (options) { return "BXinTH " + options.currency + "/" + options.coin; }, getUrl: function (options) { return "https://bx.in.th/api/"; } });
Add bail option to mochacli to halt on the first failed test.
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: ['.tmp'], babel: { options: { sourceMap: true }, dist: { files: { 'dist/index.js': 'src/index.js' } }, test: { files: { '.tmp/tests.js': 'test/tests.js' } } }, jshint: { all: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ], options: { jshintrc: '.jshintrc' } }, mochacli: { all: ['.tmp/**/*.js'], options: { reporter: 'spec', ui: 'tdd', timeout: 10000, bail: 'true' } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-mocha-cli'); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('build', ['babel:dist']); grunt.registerTask('test', ['jshint', 'build', 'babel:test', 'mochacli']); grunt.registerTask('default', ['test']); };
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: ['.tmp'], babel: { options: { sourceMap: true }, dist: { files: { 'dist/index.js': 'src/index.js' } }, test: { files: { '.tmp/tests.js': 'test/tests.js' } } }, jshint: { all: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ], options: { jshintrc: '.jshintrc' } }, mochacli: { all: ['.tmp/**/*.js'], options: { reporter: 'spec', ui: 'tdd', timeout: 10000 } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-mocha-cli'); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('build', ['babel:dist']); grunt.registerTask('test', ['jshint', 'build', 'babel:test', 'mochacli']); grunt.registerTask('default', ['test']); };
Switch to small gif image.
import {assert} from 'chai'; import {jsdom} from 'jsdom'; import {ImageTransformer} from '../src/imagetransformer'; describe('image transformer', function() { beforeEach(function() { this.document = jsdom(); }); it('should accept a mimetype', function() { var imt = new ImageTransformer('image/png'); assert.equal(imt.mimetype, "image/png"); var imt2 = new ImageTransformer('image/jpeg'); assert.equal(imt2.mimetype, "image/jpeg"); }); describe('#transform', function() { it('should create an <img> with the right mimetype', function() { var imt = new ImageTransformer('image/png'); var imageData = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; var el = imt.transform(imageData, this.document); assert.equal(el.src, "data:image/png;base64," + imageData); assert.equal(el.localName, "img"); assert.equal(el.innerHTML, ""); var imt2 = new ImageTransformer('image/gif'); imageData = "R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs="; var el2 = imt2.transform(imageData, this.document); assert.equal(el2.src, "data:image/gif;base64," + imageData); assert.equal(el2.localName, "img"); assert.equal(el2.innerHTML, ""); }); }); });
import {assert} from 'chai'; import {jsdom} from 'jsdom'; import {ImageTransformer} from '../src/imagetransformer'; describe('image transformer', function() { beforeEach(function() { this.document = jsdom(); }); it('should accept a mimetype', function() { var imt = new ImageTransformer('image/png'); assert.equal(imt.mimetype, "image/png"); var imt2 = new ImageTransformer('image/jpeg'); assert.equal(imt2.mimetype, "image/jpeg"); }); describe('#transform', function() { it('should create an <img> with the right mimetype', function() { var imt = new ImageTransformer('image/png'); var imageData = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; var el = imt.transform(imageData, this.document); assert.equal(el.src, "data:image/png;base64," + imageData); assert.equal(el.localName, "img"); assert.equal(el.innerHTML, ""); var imt2 = new ImageTransformer('image/gif'); var el2 = imt2.transform(imageData, this.document); assert.equal(el2.src, "data:image/gif;base64," + imageData); assert.equal(el2.localName, "img"); assert.equal(el2.innerHTML, ""); }); }); });
Remove a reference to search.update
import unittest from amqp import Message from mock import patch from sir.amqp.message import (InvalidMessageContentException, Message as PMessage, MESSAGE_TYPES) class AmqpMessageTest(unittest.TestCase): @staticmethod def _parsed_message(body="artist 123 456", channel="search.index"): msg = Message(body=body) parsed_message = PMessage.from_amqp_message(channel, msg) return parsed_message def test_message_parses(self): parsed_message = self._parsed_message() self.assertEqual(parsed_message.entity_type, "artist") self.assertEqual(parsed_message.message_type, MESSAGE_TYPES.index) def test_invalid_channel_raises(self): self.assertRaises(ValueError, self._parsed_message, channel="foo.bar") @patch("sir.amqp.message.SCHEMA", new={'entity': None}) def test_invalid_entity_raises(self): self.assertRaises(ValueError, self._parsed_message) def test_message_too_short_raises(self): self.assertRaises(InvalidMessageContentException, self._parsed_message, body="foo") def test_non_delete_converts_to_int(self): parsed_message = self._parsed_message(channel="search.index") map(lambda id_: self.assertTrue(isinstance(id_, int)), parsed_message.ids)
import unittest from amqp import Message from mock import patch from sir.amqp.message import (InvalidMessageContentException, Message as PMessage, MESSAGE_TYPES) class AmqpMessageTest(unittest.TestCase): @staticmethod def _parsed_message(body="artist 123 456", channel="search.index"): msg = Message(body=body) parsed_message = PMessage.from_amqp_message(channel, msg) return parsed_message def test_message_parses(self): parsed_message = self._parsed_message() self.assertEqual(parsed_message.entity_type, "artist") self.assertEqual(parsed_message.message_type, MESSAGE_TYPES.index) def test_invalid_channel_raises(self): self.assertRaises(ValueError, self._parsed_message, channel="foo.bar") @patch("sir.amqp.message.SCHEMA", new={'entity': None}) def test_invalid_entity_raises(self): self.assertRaises(ValueError, self._parsed_message) def test_message_too_short_raises(self): self.assertRaises(InvalidMessageContentException, self._parsed_message, body="foo") def test_non_delete_converts_to_int(self): for c in ("search.index", "search.update"): parsed_message = self._parsed_message(channel=c) map(lambda id_: self.assertTrue(isinstance(id_, int)), parsed_message.ids)
Adjust in a BC way to introduce TestCase
from datetime import datetime from django.core.files import File from django.conf import settings from armstrong.dev.tests.utils import ArmstrongTestCase from armstrong.dev.tests.utils.backports import * from armstrong.dev.tests.utils.concrete import * from armstrong.dev.tests.utils.users import * from ..models import Section import fudge class TestCase(ArmstrongTestCase): def setUp(self): super(ArmSectionsTestCase, self).setUp() self.sections = [] data = [ ('Local', 'local', 'All about local', None), ('Sports', 'sports', 'All about sports', None), ('College', 'college', 'All about college sports', 1), ('Pro', 'pro', 'All about pro sports', 1), ('US', 'us', 'All about US sports', 3), ('Weather', 'weather', 'All about weather', None), ] for title, slug, summary, parent in data: if parent is not None: parent = self.sections[parent] self.sections.append(Section.objects.create( title=title, slug=slug, summary=summary, parent=parent, )) # TODO: Refactor the test cases to remove ArmSectionsTestCase ArmSectionsTestCase = TestCase
from datetime import datetime from django.core.files import File from django.conf import settings from armstrong.dev.tests.utils import ArmstrongTestCase from armstrong.dev.tests.utils.backports import * from armstrong.dev.tests.utils.concrete import * from armstrong.dev.tests.utils.users import * from ..models import Section import fudge class ArmSectionsTestCase(ArmstrongTestCase): def setUp(self): super(ArmSectionsTestCase, self).setUp() self.sections = [] data = [ ('Local', 'local', 'All about local', None), ('Sports', 'sports', 'All about sports', None), ('College', 'college', 'All about college sports', 1), ('Pro', 'pro', 'All about pro sports', 1), ('US', 'us', 'All about US sports', 3), ('Weather', 'weather', 'All about weather', None), ] for title, slug, summary, parent in data: if parent is not None: parent = self.sections[parent] self.sections.append(Section.objects.create( title=title, slug=slug, summary=summary, parent=parent, ))
Create book if one doesn't exist during tag creation
from braces.views import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.shortcuts import ( get_object_or_404, redirect ) from contacts.models import ( Book, BookOwner, ) class BookOwnerMixin(LoginRequiredMixin): def get_queryset(self): if self.kwargs.get('book'): try: bookowner = BookOwner.objects.get( user=self.request.user, book_id=self.kwargs.get('book'), ) return self.model.objects.for_user( self.request.user, book=bookowner.book, ) except BookOwner.DoesNotExist: pass return self.model.objects.for_user(self.request.user) def get_object(self, queryset=None): instance = super(BookOwnerMixin, self).get_object(queryset) if not instance.can_be_viewed_by(self.request.user): raise PermissionDenied return instance def form_valid(self, form): try: form.instance.book = BookOwner.objects.get( user=self.request.user ).book except BookOwner.DoesNotExist: form.instance.book = Book.objects.create( name="{}'s Contacts".format(self.request.user), ) BookOwner.objects.create(book=form.instance.book, user=self.request.user) return super(BookOwnerMixin, self).form_valid(form)
from braces.views import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.shortcuts import ( get_object_or_404, redirect ) from contacts.models import ( Book, BookOwner, ) class BookOwnerMixin(LoginRequiredMixin): def get_queryset(self): if self.kwargs.get('book'): try: bookowner = BookOwner.objects.get( user=self.request.user, book_id=self.kwargs.get('book'), ) return self.model.objects.for_user( self.request.user, book=bookowner.book, ) except BookOwner.DoesNotExist: pass return self.model.objects.for_user(self.request.user) def get_object(self, queryset=None): instance = super(BookOwnerMixin, self).get_object(queryset) if not instance.can_be_viewed_by(self.request.user): raise PermissionDenied return instance def form_valid(self, form): form.instance.book = BookOwner.objects.get( user=self.request.user ).book response = super(BookOwnerMixin, self).form_valid(form) return response
Use Chrome in headless mode
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['@angular/cli'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, coverageIstanbulReporter: { reports: [ config.watch ? 'html' : 'text-summary', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'coverage-istanbul'] : ['progress', 'kjhtml'], port: 8081, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], customLaunchers: { ChromeNoSandbox: { base: 'Chrome', flags: ['--headless'], }, }, singleRun: false }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['@angular/cli'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, coverageIstanbulReporter: { reports: [ config.watch ? 'html' : 'text-summary', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'coverage-istanbul'] : ['progress', 'kjhtml'], port: 8081, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeNoSandbox'], customLaunchers: { ChromeNoSandbox: { base: 'Chrome', flags: ['--no-sandbox'], }, }, singleRun: false }); };
Change of import of libraries. Tried to fix issue displayed below. [root@alarm BeagleDash]# python3.3 CANtoUDP.py Traceback (most recent call last): File "CANtoUDP.py", line 10, in <module> listeners = [csv, UDPSender()] TypeError: 'module' object is not callable Exception AttributeError: "'super' object has no attribute '__del__'" in <bound method CSVWriter.__del__ of <can.CAN.CSVWriter object at 0xb6867730>> ignored
from can import Listener from socket import socket class UDPSender(Listener): dataConvert = {"0x600": {"String":"RPM:", "Slot":0, "Conversion":1}, "0x601": {"String":"OIL:", "Slot":2, "Conversion":(1/81.92)}} def __init__(self, IP="10.0.0.4", PORT=5555): self.ip = IP self.port = PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def on_message_received(self, msg): udpMessage = self.can_to_udp_message(msg) if udpMessage: self.sock.sendto(udpMessage.encode(), (self.ip, self.port)) def can_to_udp_message(self, msg): hexId = msg.arbritation_id if self.dataConvert.get(hexId): dataId = self.dataConvert[hexId]["String"] dataSlot = self.dataConvert[hexId]["Slot"] dataConversion = self.dataConvert[hexID]["Conversion"] data = ( (msg.data[dataSlot] << 8) + msg.data[dataSlot + 1] ) * dataConversion udpMessage = dataId + data return udpMessage else: return None def __del__(self): self.sock.close()
from can import Listener import socket class UDPSender(Listener): dataConvert = {"0x600": {"String":"RPM:", "Slot":0, "Conversion":1}, "0x601": {"String":"OIL:", "Slot":2, "Conversion":(1/81.92)}} def __init__(self, IP="10.0.0.4", PORT=5555): self.ip = IP self.port = PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def on_message_received(self, msg): udpMessage = self.can_to_udp_message(msg) if udpMessage: self.sock.sendto(udpMessage.encode(), (self.ip, self.port)) def can_to_udp_message(self, msg): hexId = msg.arbritation_id if self.dataConvert.get(hexId): dataId = self.dataConvert[hexId]["String"] dataSlot = self.dataConvert[hexId]["Slot"] dataConversion = self.dataConvert[hexID]["Conversion"] data = ( (msg.data[dataSlot] << 8) + msg.data[dataSlot + 1] ) * dataConversion udpMessage = dataId + data return udpMessage else: return None def __del__(self): self.sock.close()
Add all available servers to status
'use strict'; const has = require('has'); function collectPoolStatus(stats, { type, host, pool }) { const poolStats = [ ['_allConnections', 'open'], ['_freeConnections', 'sleeping'], ['_acquiringConnections', 'waiting'] ] .filter(([mysqljsProp]) => has(pool, mysqljsProp) && Array.isArray(pool[mysqljsProp])) .reduce( (stats, [mysqljsProp, floraProp]) => ({ ...stats, [floraProp]: pool[mysqljsProp].length }), {} ); poolStats.open -= poolStats.sleeping; stats[type] = stats[type] || {}; stats[type][host] = poolStats; return stats; } // a cluster contains master/slave pools function collectClusterStatus(stats, [database, poolCluster]) { return { ...stats, [database]: Object.entries(poolCluster._nodes) .map(([identifier, { pool }]) => { const [type, host] = identifier.split('_'); return { type: `${type.toLowerCase()}s`, host, pool }; }) .reduce(collectPoolStatus, {}) }; } module.exports = (pools) => Object.entries(pools).reduce( (stats, [server, databases]) => ({ ...stats, [server]: Object.entries(databases) .filter(([, poolCluster]) => has(poolCluster, '_nodes') && typeof poolCluster._nodes === 'object') .reduce(collectClusterStatus, {}) }), {} );
'use strict'; const has = require('has'); function collectPoolStatus(stats, { type, host, pool }) { const poolStats = [ ['_allConnections', 'open'], ['_freeConnections', 'sleeping'], ['_acquiringConnections', 'waiting'] ] .filter(([mysqljsProp]) => has(pool, mysqljsProp) && Array.isArray(pool[mysqljsProp])) .reduce( (stats, [mysqljsProp, floraProp]) => ({ ...stats, [floraProp]: pool[mysqljsProp].length }), {} ); poolStats.open -= poolStats.sleeping; return { ...stats, [type]: { [host]: poolStats } }; } // a cluster contains master/slave pools function collectClusterStatus(stats, [database, poolCluster]) { return { ...stats, [database]: Object.entries(poolCluster._nodes) .map(([identifier, { pool }]) => { const [type, host] = identifier.split('_'); return { type: `${type.toLowerCase()}s`, host, pool }; }) .reduce(collectPoolStatus, {}) }; } module.exports = (pools) => Object.entries(pools).reduce( (stats, [server, databases]) => ({ ...stats, [server]: Object.entries(databases) .filter(([, poolCluster]) => has(poolCluster, '_nodes') && typeof poolCluster._nodes === 'object') .reduce(collectClusterStatus, {}) }), {} );
Fix undefined class Profile in templates
<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Twig\Compiler; use Twig\Node\Node; /** * Represents a profile enter node. * * @author Fabien Potencier <[email protected]> */ class Twig_Profiler_Node_EnterProfile extends Node { public function __construct($extensionName, $type, $name, $varName) { parent::__construct([], ['extension_name' => $extensionName, 'name' => $name, 'type' => $type, 'var_name' => $varName]); } public function compile(Compiler $compiler) { $compiler ->write(sprintf('$%s = $this->env->getExtension(', $this->getAttribute('var_name'))) ->repr($this->getAttribute('extension_name')) ->raw(");\n") ->write(sprintf('$%s->enter($%s = new \Twig\Profiler\Profile($this->getTemplateName(), ', $this->getAttribute('var_name'), $this->getAttribute('var_name').'_prof')) ->repr($this->getAttribute('type')) ->raw(', ') ->repr($this->getAttribute('name')) ->raw("));\n\n") ; } } class_alias('Twig_Profiler_Node_EnterProfile', 'Twig\Profiler\Node\EnterProfileNode', false);
<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Twig\Compiler; use Twig\Node\Node; use Twig\Profiler\Profile; /** * Represents a profile enter node. * * @author Fabien Potencier <[email protected]> */ class Twig_Profiler_Node_EnterProfile extends Node { public function __construct($extensionName, $type, $name, $varName) { parent::__construct([], ['extension_name' => $extensionName, 'name' => $name, 'type' => $type, 'var_name' => $varName]); } public function compile(Compiler $compiler) { $compiler ->write(sprintf('$%s = $this->env->getExtension(', $this->getAttribute('var_name'))) ->repr($this->getAttribute('extension_name')) ->raw(");\n") ->write(sprintf('$%s->enter($%s = new Profile($this->getTemplateName(), ', $this->getAttribute('var_name'), $this->getAttribute('var_name').'_prof')) ->repr($this->getAttribute('type')) ->raw(', ') ->repr($this->getAttribute('name')) ->raw("));\n\n") ; } } class_alias('Twig_Profiler_Node_EnterProfile', 'Twig\Profiler\Node\EnterProfileNode', false);
Change logger messages to info
# -*- coding: utf-8 -*- import logging import urllib2 from openerp.http import request from openerp.osv import orm logger = logging.getLogger(__name__) class ir_http(orm.AbstractModel): _inherit = 'ir.http' def _handle_exception(self, exception, code=500): code = getattr(exception, 'code', code) if code == 404: page = request.httprequest.path logger.info("404 code... %s" % (page)) url = request.registry['ir.config_parameter'].get_param(request.cr, request.uid, 'website.notfound_redirect_url') if url: url_request = "%s%s" % (url, page) logger.info("The redirect url: %s" % (url_request)) try: req = urllib2.Request(url_request) request_old = urllib2.urlopen(req) except (urllib2.HTTPError, urllib2.URLError): request_old = False else: request_old = False if not request_old: logger.info("URL not found: %s" % (url_request)) return super(ir_http, self)._handle_exception(exception, code) else: logger.info("Redirect to %s" % (url_request)) return request.redirect(url_request, code=302) return super(ir_http, self)._handle_exception(exception, code)
# -*- coding: utf-8 -*- import logging import urllib2 from openerp.http import request from openerp.osv import orm logger = logging.getLogger(__name__) class ir_http(orm.AbstractModel): _inherit = 'ir.http' def _handle_exception(self, exception, code=500): code = getattr(exception, 'code', code) if code == 404: page = request.httprequest.path logger.warning("404 code... %s" % (page)) url = request.registry['ir.config_parameter'].get_param(request.cr, request.uid, 'website.notfound_redirect_url') if url: url_request = "%s%s" % (url, page) logger.info("The redirect url: %s" % (url_request)) try: req = urllib2.Request(url_request) request_old = urllib2.urlopen(req) except (urllib2.HTTPError, urllib2.URLError): request_old = False else: request_old = False if not request_old: logger.warning("URL not found: %s" % (url_request)) return super(ir_http, self)._handle_exception(exception, code) else: logger.warning("Redirect to %s" % (url_request)) return request.redirect(url_request, code=302) return super(ir_http, self)._handle_exception(exception, code)
Create more meaning for the template variable
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var template; var index = -1; if ( configs.ignoringCase ) { template = oldToken.toLowerCase(); while(( index = string .toLowerCase() .indexOf( template, index === -1 ? 0 : index + newToken.length ) ) !== -1 ) { string = string .substring( 0, index ) + newToken + string.substring( index + newToken.length ); } return string; } return string.split( oldToken ).join( newToken ); } }; }, ignoreCase: function() { return replaceAll.call({ ignoringCase: true }, oldToken ); } }; }; module.exports = { all: replaceAll };
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var _token; var index = -1; if ( configs.ignoringCase ) { _token = oldToken.toLowerCase(); while(( index = string .toLowerCase() .indexOf( _token, index === -1 ? 0 : index + newToken.length ) ) !== -1 ) { string = string .substring( 0, index ) + newToken + string.substring( index + newToken.length ); } return string; } return string.split( oldToken ).join( newToken ); } }; }, ignoreCase: function() { return replaceAll.call({ ignoringCase: true }, oldToken ); } }; }; module.exports = { all: replaceAll };
Use serialized subject where possible
package org.github.pesan.tools.servicespy.action; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.subjects.ReplaySubject; import io.reactivex.subjects.Subject; import org.github.pesan.tools.servicespy.action.entry.LogEntry; import org.github.pesan.tools.servicespy.action.entry.RequestEntry; import org.github.pesan.tools.servicespy.action.entry.ResponseEntry; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service public class ActionService { private final RequestIdGenerator requestIdGenerator; private final int maxEntryCount; private Subject<LogEntry> buffer; public ActionService( RequestIdGenerator requestIdGenerator, @Value("${actions.limit:200}") int maxEntryCount) { this.requestIdGenerator = requestIdGenerator; this.maxEntryCount = maxEntryCount; init(); } private void init() { buffer = ReplaySubject.<LogEntry>createWithSize(maxEntryCount).toSerialized(); } public Observable<LogEntry> list() { return buffer.take(1, TimeUnit.MILLISECONDS); } public Observable<LogEntry> streamList() { return buffer; } public void log(RequestEntry requestEntry, ResponseEntry responseEntry) { buffer.onNext(new LogEntry(requestIdGenerator.next(), requestEntry, responseEntry)); } public Completable clear() { return Completable.fromAction(this::init); } }
package org.github.pesan.tools.servicespy.action; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.subjects.ReplaySubject; import io.reactivex.subjects.Subject; import org.github.pesan.tools.servicespy.action.entry.LogEntry; import org.github.pesan.tools.servicespy.action.entry.RequestEntry; import org.github.pesan.tools.servicespy.action.entry.ResponseEntry; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service public class ActionService { private final RequestIdGenerator requestIdGenerator; private final int maxEntryCount; private Subject<LogEntry> buffer; private ReplaySubject<LogEntry> replay; public ActionService( RequestIdGenerator requestIdGenerator, @Value("${actions.limit:200}") int maxEntryCount) { this.requestIdGenerator = requestIdGenerator; this.maxEntryCount = maxEntryCount; init(); } private void init() { replay = ReplaySubject.createWithSize(maxEntryCount); buffer = replay.toSerialized(); } public Observable<LogEntry> list() { return replay.take(1, TimeUnit.MILLISECONDS); } public Observable<LogEntry> streamList() { return replay; } public void log(RequestEntry requestEntry, ResponseEntry responseEntry) { buffer.onNext(new LogEntry(requestIdGenerator.next(), requestEntry, responseEntry)); } public Completable clear() { return Completable.fromAction(this::init); } }
Add global chai `expect` for system tests
#!/usr/bin/env node require('shelljs/global'); require('colors'); var async = require('async'), fs = require('fs'), path = require('path'), expect = require('chai').expect, Mocha = require('mocha'), SPEC_SOURCE_DIR = './test/system'; module.exports = function (exit) { // banner line console.log('\nRunning system tests using mocha...'.yellow.bold); async.series([ // run test specs using mocha function (next) { var mocha = new Mocha(); fs.readdir(SPEC_SOURCE_DIR, function (err, files) { if (err) { return next(err); } files.filter(function (file) { return (file.substr(-8) === '.test.js'); }).forEach(function (file) { mocha.addFile(path.join(SPEC_SOURCE_DIR, file)); }); // start the mocha run global.expect = expect; // for easy reference mocha.run(function (err) { // clear references and overrides delete global.expect; err && console.error(err.stack || err); next(err ? 1 : 0); }); // cleanup mocha = null; }); } ], exit); }; // ensure we run this script exports if this is a direct stdin.tty run !module.parent && module.exports(exit);
#!/usr/bin/env node require('shelljs/global'); require('colors'); var async = require('async'), fs = require('fs'), path = require('path'), Mocha = require('mocha'), SPEC_SOURCE_DIR = './test/system'; module.exports = function (exit) { // banner line console.log('\nRunning system tests using mocha...'.yellow.bold); async.series([ // run test specs using mocha function (next) { var mocha = new Mocha(); fs.readdir(SPEC_SOURCE_DIR, function (err, files) { if (err) { return next(err); } files.filter(function (file) { return (file.substr(-8) === '.test.js'); }).forEach(function (file) { mocha.addFile(path.join(SPEC_SOURCE_DIR, file)); }); // start the mocha run mocha.run(next); mocha = null; // cleanup }); } ], exit); }; // ensure we run this script exports if this is a direct stdin.tty run !module.parent && module.exports(exit);
Remove nodeunit as that test is bad
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ benchmark: { singleTest: { src: ['benchmarks/singleTest.js'], dest: 'results/singleTest.csv' }, loneFunction: { src: ['benchmarks/loneFunction.js'], dest: 'results/loneFunction.csv' }, suites: { src: ['benchmarks/suites.js'], dest: 'results/suites.csv' }, mixedSuite: { src: ['benchmarks/mixedSuite.js'], dest: 'results/mixedSuite.csv' }, fibonacci: { src: ['benchmarks/fibonacci.js'], dest: 'results/fibonacci.csv' } }, jshint: { options: { jshintrc: true }, all: { src: ['Gruntfile.js', 'lib/**/*.js', 'tasks/**/*.js', 'benchmarks/*.js'] } }, nodeunit: { files: ['test/**/*_test.js'] }, watch: { all: { files: ['<%= jshint.all.src %>', '<%= nodeunit.files %>'], tasks: ['default'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadTasks('tasks'); grunt.registerTask('default', ['jshint']); };
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ benchmark: { singleTest: { src: ['benchmarks/singleTest.js'], dest: 'results/singleTest.csv' }, loneFunction: { src: ['benchmarks/loneFunction.js'], dest: 'results/loneFunction.csv' }, suites: { src: ['benchmarks/suites.js'], dest: 'results/suites.csv' }, mixedSuite: { src: ['benchmarks/mixedSuite.js'], dest: 'results/mixedSuite.csv' }, fibonacci: { src: ['benchmarks/fibonacci.js'], dest: 'results/fibonacci.csv' } }, jshint: { options: { jshintrc: true }, all: { src: ['Gruntfile.js', 'lib/**/*.js', 'tasks/**/*.js', 'benchmarks/*.js'] } }, nodeunit: { files: ['test/**/*_test.js'] }, watch: { all: { files: ['<%= jshint.all.src %>', '<%= nodeunit.files %>'], tasks: ['default'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadTasks('tasks'); grunt.registerTask('default', ['jshint', 'nodeunit']); };
NXP-11577: Fix Sonar Major violation: Hide Utility Class Constructor
package org.nuxeo.drive.service.impl; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.nuxeo.ecm.core.api.IdRef; public class RootDefinitionsHelper { private RootDefinitionsHelper() { // Utility class } public static Map<String, Set<IdRef>> parseRootDefinitions( String rootDefinitions) { Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>(); if (rootDefinitions != null) { String[] rootDefinitionComponents = StringUtils.split( rootDefinitions, ","); for (String rootDefinition : rootDefinitionComponents) { String[] rootComponents = StringUtils.split(rootDefinition, ":"); String repoName = rootComponents[0].trim(); Set<IdRef> refs = lastActiveRootRefs.get(repoName); if (refs == null) { refs = new HashSet<IdRef>(); lastActiveRootRefs.put(repoName, refs); } refs.add(new IdRef(rootComponents[1].trim())); } } return lastActiveRootRefs; } }
package org.nuxeo.drive.service.impl; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.nuxeo.ecm.core.api.IdRef; public class RootDefinitionsHelper { public static Map<String, Set<IdRef>> parseRootDefinitions(String rootDefinitions) { Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>(); if (rootDefinitions != null) { String[] rootDefinitionComponents = StringUtils.split( rootDefinitions, ","); for (String rootDefinition : rootDefinitionComponents) { String[] rootComponents = StringUtils.split(rootDefinition, ":"); String repoName = rootComponents[0].trim(); Set<IdRef> refs = lastActiveRootRefs.get(repoName); if (refs == null) { refs = new HashSet<IdRef>(); lastActiveRootRefs.put(repoName, refs); } refs.add(new IdRef(rootComponents[1].trim())); } } return lastActiveRootRefs; } }
Handle empty "component" streams Implement read(byte[],int,int) as optimisation
package org.bouncycastle.asn1; import java.io.InputStream; import java.io.IOException; class ConstructedOctetStream extends InputStream { private final ASN1ObjectParser _parser; private boolean _first = true; private InputStream _currentStream; ConstructedOctetStream( ASN1ObjectParser parser) { _parser = parser; } public int read(byte[] b, int off, int len) throws IOException { if (_currentStream == null) { if (!_first) { return -1; } ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); if (s == null) { return -1; } _first = false; _currentStream = s.getOctetStream(); } for (;;) { int numRead = _currentStream.read(b, off, len); if (numRead >= 0) { return numRead; } ASN1OctetStringParser aos = (ASN1OctetStringParser)_parser.readObject(); if (aos == null) { _currentStream = null; return -1; } _currentStream = aos.getOctetStream(); } } public int read() throws IOException { if (_currentStream == null) { if (!_first) { return -1; } ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); if (s == null) { return -1; } _first = false; _currentStream = s.getOctetStream(); } for (;;) { int b = _currentStream.read(); if (b >= 0) { return b; } ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); if (s == null) { _currentStream = null; return -1; } _currentStream = s.getOctetStream(); } } }
package org.bouncycastle.asn1; import java.io.InputStream; import java.io.IOException; class ConstructedOctetStream extends InputStream { private final ASN1ObjectParser _parser; private boolean _first = true; private InputStream _currentStream; ConstructedOctetStream( ASN1ObjectParser parser) { _parser = parser; } public int read() throws IOException { if (_first) { ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); if (s == null) { return -1; } _first = false; _currentStream = s.getOctetStream(); } else if (_currentStream == null) { return -1; } int b = _currentStream.read(); if (b < 0) { ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject(); if (s == null) { _currentStream = null; return -1; } _currentStream = s.getOctetStream(); return _currentStream.read(); } else { return b; } } }
Sort by name if location not available
$(function () { var locationList = $("#location-list"); function populateLocations(data) { locationList.empty(); $.each(data.features, function(i, v) { $("<li/>").appendTo(locationList) .toggleClass("lead", i == 0 && data.locationKnown) .html(v.properties.details); }); } if (locationList.length > 0) { $.getJSON("sites.geojson", function(data) { populateLocations({ locationKnown: false, features: data.features }); var d = $.Deferred(); navigator.geolocation.getCurrentPosition( function(position) { var distanceTo = function(feature) { return geolib.getDistance({ 'longitude': position.coords.longitude, 'latitude': position.coords.latitude }, { 'longitude': feature.geometry.coordinates[0], 'latitude': feature.geometry.coordinates[1] }); }; // sort features by distance data.features.sort(function(a, b) { return distanceTo(a) - distanceTo(b); }); d.resolve({ locationKnown: true, features: data.features }); }, function() { function name(feature) { var details = feature.properties.details; return $('<div>'+details+'</div>').text(); } // sort features by distance data.features.sort(function(a, b) { return name(a).localeCompare(name(b)); }); d.resolve({ locationKnown: false, features: data.features }); }, { enableHighAccuracy: false } ); d.promise().done(populateLocations); }); } });
$(function () { var locationList = $("#location-list"); function populateLocations(features) { locationList.empty(); $.each(features, function(i, v) { $("<li/>").appendTo(locationList) .toggleClass("lead", i == 0) .html(v.properties.details); }); } if (locationList.length > 0) { $.getJSON("sites.geojson", function(data) { populateLocations(data.features); var d = $.Deferred(); navigator.geolocation.getCurrentPosition( function(position) { var distanceTo = function(feature) { return geolib.getDistance({ 'longitude': position.coords.longitude, 'latitude': position.coords.latitude }, { 'longitude': feature.geometry.coordinates[0], 'latitude': feature.geometry.coordinates[1] }); }; // sort features by distance data.features.sort(function(a, b) { return distanceTo(a) - distanceTo(b); }); d.resolve(data.features); }, function() { // use original order d.resolve(data.features); }, { enableHighAccuracy: false } ); d.promise().done(populateLocations); }); } });
Tweak comment about field ID Co-Authored-By: jryans <[email protected]>
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; export default class Field extends React.PureComponent { static propTypes = { // The field's ID, which binds the input and label together. id: PropTypes.string.isRequired, // The field's <input> type. Defaults to "text". type: PropTypes.string, // The field's label string. label: PropTypes.string, // The field's placeholder string. placeholder: PropTypes.string, // All other props pass through to the <input>. } render() { const extraProps = Object.assign({}, this.props); // Remove explicit props delete extraProps.id; delete extraProps.type; delete extraProps.placeholder; delete extraProps.label; return <div className="mx_Field"> <input id={this.props.id} type={this.props.type || "text"} placeholder={this.props.placeholder} {...extraProps} /> <label htmlFor={this.props.id}>{this.props.label}</label> </div>; } }
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; export default class Field extends React.PureComponent { static propTypes = { // The field's id, which binds the input and label together. id: PropTypes.string.isRequired, // The field's <input> type. Defaults to "text". type: PropTypes.string, // The field's label string. label: PropTypes.string, // The field's placeholder string. placeholder: PropTypes.string, // All other props pass through to the <input>. } render() { const extraProps = Object.assign({}, this.props); // Remove explicit props delete extraProps.id; delete extraProps.type; delete extraProps.placeholder; delete extraProps.label; return <div className="mx_Field"> <input id={this.props.id} type={this.props.type || "text"} placeholder={this.props.placeholder} {...extraProps} /> <label htmlFor={this.props.id}>{this.props.label}</label> </div>; } }
Allow arbitrary kwargs for die utility function. by: Glenn, Giles
# Copyright (c) 2011 Resolver Systems Ltd. # All Rights Reserved # try: import unittest2 as unittest except ImportError: import unittest from datetime import timedelta from mock import call class ResolverTestMixins(object): def assertCalledOnce(self, mock, *args, **kwargs): if mock.call_args_list == []: self.fail('Not called') self.assertEquals(mock.call_args_list, [call(*args, **kwargs)]) def assert_decorated_with(self, fn, decorator): self.assertIn(decorator.__name__, fn.decorated_by) def assert_decorated_with(self, fn, decorator): self.assertIn(decorator.__name__, fn.decorated_by) def assert_datetime_approximately_equals(self, actual, expected, minutes_leeway=10): self.assertTrue( expected - timedelta(minutes=minutes_leeway) <= actual <= expected + timedelta(minutes=minutes_leeway), "%r is not within %s minutes of %r" % (actual, minutes_leeway, expected) ) class ResolverTestCase(unittest.TestCase, ResolverTestMixins): maxDiff = None def die(exception=None): if exception is None: exception = AssertionError('die called') def inner_die(*_, **__): raise exception return inner_die def is_iterable(seq): return hasattr(seq, "__iter__")
# Copyright (c) 2011 Resolver Systems Ltd. # All Rights Reserved # try: import unittest2 as unittest except ImportError: import unittest from datetime import timedelta from mock import call class ResolverTestMixins(object): def assertCalledOnce(self, mock, *args, **kwargs): if mock.call_args_list == []: self.fail('Not called') self.assertEquals(mock.call_args_list, [call(*args, **kwargs)]) def assert_decorated_with(self, fn, decorator): self.assertIn(decorator.__name__, fn.decorated_by) def assert_decorated_with(self, fn, decorator): self.assertIn(decorator.__name__, fn.decorated_by) def assert_datetime_approximately_equals(self, actual, expected, minutes_leeway=10): self.assertTrue( expected - timedelta(minutes=minutes_leeway) <= actual <= expected + timedelta(minutes=minutes_leeway), "%r is not within %s minutes of %r" % (actual, minutes_leeway, expected) ) class ResolverTestCase(unittest.TestCase, ResolverTestMixins): maxDiff = None def die(exception=None): if exception is None: exception = AssertionError('die called') def inner_die(*_): raise exception return inner_die def is_iterable(seq): return hasattr(seq, "__iter__")
Fix slot release on method exception
import functools from pkit.slot import get_slot_pool def acquire(pool_name): """Actor's method decorator to auto-acquire a slot before execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) try: # Unix semaphores are acquired through sem_post and sem_wait # syscalls, which can potentially fail. slots_pool.acquire() except OSError: pass res = method(self, *args, **kwargs) return res return wrapper return decorator def release(pool_name): """Actors method decorator to auto-release a used slot after execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) try: res = method(self, *args, **kwargs) except Exception: raise finally: try: slots_pool.release() except OSError: pass return res return wrapper return decorator
import functools from pkit.slot import get_slot_pool def acquire(pool_name): """Actor's method decorator to auto-acquire a slot before execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) try: # Unix semaphores are acquired through sem_post and sem_wait # syscalls, which can potentially fail. slots_pool.acquire() except OSError: pass res = method(self, *args, **kwargs) return res return wrapper return decorator def release(pool_name): """Actors method decorator to auto-release a used slot after execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) res = method(self, *args, **kwargs) try: slots_pool.release() except OSError: pass return res return wrapper return decorator
Remove .export-action-download now that reports.download_export.js is gone
hqDefine("reports/js/base", function() { $(function() { hqImport("reports/js/filters/main").init(); var initial_page_data = hqImport("hqwebapp/js/initial_page_data").get; var defaultConfig = initial_page_data('default_config') || {}; if (initial_page_data('has_datespan')) { defaultConfig.date_range = 'last7'; } else { defaultConfig.date_range = null; } defaultConfig.has_ucr_datespan = false; defaultConfig.datespan_filters = []; defaultConfig.datespan_slug = null; var $savedReports = $("#savedReports"); if ($savedReports.length) { $savedReports.reportConfigEditor({ filterForm: $("#reportFilters"), items: initial_page_data('report_configs'), defaultItem: defaultConfig, saveUrl: hqImport("hqwebapp/js/initial_page_data").reverse("add_report_config"), }); } $('#email-enabled').tooltip({ placement: 'right', html: true, title: gettext("You can email a saved version<br />of this report."), }); }); });
hqDefine("reports/js/base", function() { $(function() { hqImport("reports/js/filters/main").init(); var initial_page_data = hqImport("hqwebapp/js/initial_page_data").get; var defaultConfig = initial_page_data('default_config') || {}; if (initial_page_data('has_datespan')) { defaultConfig.date_range = 'last7'; } else { defaultConfig.date_range = null; } defaultConfig.has_ucr_datespan = false; defaultConfig.datespan_filters = []; defaultConfig.datespan_slug = null; var $savedReports = $("#savedReports"); if ($savedReports.length) { $savedReports.reportConfigEditor({ filterForm: $("#reportFilters"), items: initial_page_data('report_configs'), defaultItem: defaultConfig, saveUrl: hqImport("hqwebapp/js/initial_page_data").reverse("add_report_config"), }); } $('#email-enabled').tooltip({ placement: 'right', html: true, title: gettext("You can email a saved version<br />of this report."), }); $(document).on('click', '.export-action-download', function() { var $modalBody = $("#export-download-status .modal-body"); $modalBody.text("Fetching..."); $("#export-download-status .modal-header h3 span").text($(this).data("formname")); $.getJSON($(this).data('dlocation'), function(d) { $modalBody.empty().load(d.download_url); }); }); }); });
Fix require of bluebird when installing from npm
var webpack = require('webpack'); var ejs = require('ejs'); var MIN = process.argv.indexOf('-p') > -1; function getBanner() { var pkg = require('./bower.json'); var banner = ['/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' * @version v<%= pkg.version %>', ' * @link <%= pkg.homepage %>', ' * @license <%= pkg.license %>', ' */', ''].join('\n'); return ejs.render(banner, {pkg: pkg}); } module.exports = { entry: __dirname + '/src/angular-bluebird-promises.js', output: { path: __dirname + '/dist', filename: MIN ? 'angular-bluebird-promises.min.js' : 'angular-bluebird-promises.js', libraryTarget: 'umd' }, externals: { angular: 'angular', bluebird: { root: 'Promise', commonjs: 'bluebird', commonjs2: 'bluebird', amd: 'bluebird' } }, devtool: MIN ? 'source-map' : null, module: { preLoaders: [{ test: /.*\.js$/, loaders: ['eslint'], exclude: /node_modules/ }], loaders: [{ test: /.*\.js$/, loaders: ['ng-annotate'], exclude: /node_modules/ }] }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.BannerPlugin(getBanner(), { raw: true, entryOnly: true }) ] };
var webpack = require('webpack'); var ejs = require('ejs'); var MIN = process.argv.indexOf('-p') > -1; function getBanner() { var pkg = require('./bower.json'); var banner = ['/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' * @version v<%= pkg.version %>', ' * @link <%= pkg.homepage %>', ' * @license <%= pkg.license %>', ' */', ''].join('\n'); return ejs.render(banner, {pkg: pkg}); } module.exports = { entry: __dirname + '/src/angular-bluebird-promises.js', output: { path: __dirname + '/dist', filename: MIN ? 'angular-bluebird-promises.min.js' : 'angular-bluebird-promises.js', libraryTarget: 'umd' }, externals: { angular: 'angular', bluebird: 'Promise' }, devtool: MIN ? 'source-map' : null, module: { preLoaders: [{ test: /.*\.js$/, loaders: ['eslint'], exclude: /node_modules/ }], loaders: [{ test: /.*\.js$/, loaders: ['ng-annotate'], exclude: /node_modules/ }] }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.BannerPlugin(getBanner(), { raw: true, entryOnly: true }) ] };
webadmin: Remove host device table repeated column. Fix Bug #9493. Remove host device table repeated column result from Host Device Filter. Signed-off-by: wxt <[email protected]>
package org.ovirt.engine.ui.webadmin.section.main.view.tab.host; import org.ovirt.engine.core.common.businessentities.HostDeviceView; import org.ovirt.engine.ui.common.system.ClientStorage; import org.ovirt.engine.ui.common.uicommon.model.SearchableTableModelProvider; import org.ovirt.engine.ui.common.widget.uicommon.hosts.hostdev.HostDeviceFilterWidget; import org.ovirt.engine.ui.uicommonweb.models.vms.hostdev.HostDeviceListModel; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.EventBus; public class HostDeviceModelTable extends HostDeviceModelBaseTable<HostDeviceListModel> { private HostDeviceFilterWidget filterPanel; public HostDeviceModelTable( SearchableTableModelProvider<HostDeviceView, HostDeviceListModel> modelProvider, EventBus eventBus, ClientStorage clientStorage) { super(modelProvider, eventBus, clientStorage); filterPanel = new HostDeviceFilterWidget(); initTableOverhead(); } protected void initTableOverhead() { filterPanel.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { getModel().setFilter(filterPanel.getCheckBox().getValue()); } }); getTable().setTableOverhead(filterPanel); getTable().setTableTopMargin(20); } }
package org.ovirt.engine.ui.webadmin.section.main.view.tab.host; import org.ovirt.engine.core.common.businessentities.HostDeviceView; import org.ovirt.engine.ui.common.system.ClientStorage; import org.ovirt.engine.ui.common.uicommon.model.SearchableTableModelProvider; import org.ovirt.engine.ui.common.widget.uicommon.hosts.hostdev.HostDeviceFilterWidget; import org.ovirt.engine.ui.uicommonweb.models.vms.hostdev.HostDeviceListModel; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.EventBus; public class HostDeviceModelTable extends HostDeviceModelBaseTable<HostDeviceListModel> { private HostDeviceFilterWidget filterPanel; public HostDeviceModelTable( SearchableTableModelProvider<HostDeviceView, HostDeviceListModel> modelProvider, EventBus eventBus, ClientStorage clientStorage) { super(modelProvider, eventBus, clientStorage); filterPanel = new HostDeviceFilterWidget(); initTable(); } @Override public void initTable() { super.initTable(); initTableOverhead(); } protected void initTableOverhead() { filterPanel.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { getModel().setFilter(filterPanel.getCheckBox().getValue()); } }); getTable().setTableOverhead(filterPanel); getTable().setTableTopMargin(20); } }
Remove unused variables: util, self
var fs = require('fs') , findExec = require('find-exec') , child_process = require('child_process') , players = [ 'mplayer', 'afplay', 'mpg123', 'mpg321', 'play' ] function Play(opts){ var opts = opts || {} this.players = opts.players || players this.player = opts.player || findExec(this.players) var exec = child_process.exec this.play = function(what, next){ var next = next || function(){} if (!what) return next(new Error("No audio file specified")); try { if (!fs.statSync(what).isFile()){ return next(new Error(what + " is not a file")); } } catch (err){ return next(new Error("File doesn't exist: " + what)); } if (!this.player){ return next(new Error("Couldn't find a suitable audio player")) } exec(this.player + ' ' + what, function(err, stdout, stderr){ if (err) return next(err) return next(); }) } this.test = function(next) { this.play('./assets/test.mp3', next) } } module.exports = function(opts){ return new Play(opts) }
var fs = require('fs') , util = require('util') , findExec = require('find-exec') , child_process = require('child_process') , players = [ 'mplayer', 'afplay', 'mpg123', 'mpg321', 'play' ] function Play(opts){ var opts = opts || {} this.players = opts.players || players this.player = opts.player || findExec(this.players) var exec = child_process.exec this.play = function(what, next){ var self = this, next = next || function(){} if (!what) return next(new Error("No audio file specified")); try { if (!fs.statSync(what).isFile()){ return next(new Error(what + " is not a file")); } } catch (err){ return next(new Error("File doesn't exist: " + what)); } if (!this.player){ return next(new Error("Couldn't find a suitable audio player")) } exec(this.player + ' ' + what, function(err, stdout, stderr){ if (err) return next(err) return next(); }) } this.test = function(next) { this.play('./assets/test.mp3', next) } } module.exports = function(opts){ return new Play(opts) }
Add unserialized cache component test
<?php declare(strict_types=1); namespace BEAR\Package; use BEAR\AppMeta\Meta; use BEAR\Package\Context\CliModule; use BEAR\Package\Module\AppMetaModule; use BEAR\Sunday\Extension\Application\AppInterface; use FakeVendor\HelloWorld\Module\AppModule; use FakeVendor\HelloWorld\Module\ProdModule; use PHPUnit\Framework\TestCase; use Psr\Cache\CacheItemPoolInterface; use Ray\Di\AbstractModule; use Ray\Di\Injector; use Ray\PsrCacheModule\Annotation\Shared; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use function assert; use function serialize; use function unserialize; class NewAppTest extends TestCase { public function testGetInstanceByHand(): AppInterface { $module = new AppMetaModule(new Meta('FakeVendor\HelloWorld'), new ProdModule(new CliModule(new AppModule()))); $module->override(new class extends AbstractModule{ protected function configure() { $this->bind(CacheItemPoolInterface::class)->annotatedWith(Shared::class)->to(FilesystemAdapter::class); } }); $app = (new Injector($module, __DIR__ . '/tmp'))->getInstance(AppInterface::class); $this->assertInstanceOf(AppInterface::class, $app); assert($app instanceof AppInterface); return $app; } /** * @depends testGetInstanceByHand */ public function testSerializable(AppInterface $app): void { $this->assertInstanceOf(AppInterface::class, unserialize(serialize(unserialize(serialize($app))))); } }
<?php declare(strict_types=1); namespace BEAR\Package; use BEAR\AppMeta\Meta; use BEAR\Package\Context\CliModule; use BEAR\Package\Module\AppMetaModule; use BEAR\Sunday\Extension\Application\AppInterface; use FakeVendor\HelloWorld\Module\AppModule; use FakeVendor\HelloWorld\Module\ProdModule; use PHPUnit\Framework\TestCase; use Psr\Cache\CacheItemPoolInterface; use Ray\Di\AbstractModule; use Ray\Di\Injector; use Ray\PsrCacheModule\Annotation\Shared; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use function assert; use function serialize; use function unserialize; class NewAppTest extends TestCase { public function testGetInstanceByHand(): AppInterface { $module = new AppMetaModule(new Meta('FakeVendor\HelloWorld'), new ProdModule(new CliModule(new AppModule()))); $module->override(new class extends AbstractModule{ protected function configure() { $this->bind(CacheItemPoolInterface::class)->annotatedWith(Shared::class)->to(FilesystemAdapter::class); } }); $app = (new Injector($module, __DIR__ . '/tmp'))->getInstance(AppInterface::class); $this->assertInstanceOf(AppInterface::class, $app); assert($app instanceof AppInterface); return $app; } /** * @depends testGetInstanceByHand */ public function testSerializable(AppInterface $app): void { $this->assertInstanceOf(AppInterface::class, unserialize(serialize($app))); } }
Fix electron behaviour when cancelling http basic auth
const electron = require('electron'); const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; module.exports = { createAuthWindow: function(mainWindow, loginCallback) { var loginWindow = new BrowserWindow({ frame: false, height: 250, modal: true, parent: mainWindow, movable: false, resizable: false, show: false, width: 230, }); loginWindow.once('ready-to-show', function() { loginWindow.show(); loginWindow.focus(); loginWindow.webContents.executeJavaScript('\ var ipcRenderer = require("electron").ipcRenderer;\ const form = document.getElementById("login-form");\ document.getElementById("trigramme").focus();\ form.addEventListener("submit", function(event) {\ event.preventDefault();\ const username = document.getElementById("trigramme").value;\ const password = document.getElementById("password").value;\ ipcRenderer.send("login-message", [username, password]);\ });\ document.addEventListener("keydown", event => {\ if (event.key === "Escape" || event.keyCode === 27) {\ ipcRenderer.send("login-message");\ }\ });' ); }); loginWindow.loadURL('http://localhost:2626/login'); ipcMain.once('login-message', function(event, usernameAndPassword) { try { loginWindow.close(); loginCallback(usernameAndPassword[0], usernameAndPassword[1]); } catch(e) { /* Do nothing */ } }); }};
const electron = require('electron'); const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; module.exports = { createAuthWindow: function(mainWindow, loginCallback) { var loginWindow = new BrowserWindow({ frame: false, height: 250, modal: true, parent: mainWindow, movable: false, resizable: false, show: false, width: 230, }); loginWindow.once('ready-to-show', function() { loginWindow.show(); loginWindow.focus(); loginWindow.webContents.executeJavaScript('\ var ipcRenderer = require("electron").ipcRenderer;\ const form = document.getElementById("login-form");\ console.log(form);\ document.getElementById("trigramme").focus();\ form.addEventListener("submit", function(event) {\ console.log("submit");\ event.preventDefault();\ const username = document.getElementById("trigramme").value;\ const password = document.getElementById("password").value;\ ipcRenderer.send("login-message", [username, password]);\ });\ document.addEventListener("keydown", event => {\ if (event.key === "Escape" || event.keyCode === 27) {\ window.close();\ }\ });' ); }); loginWindow.loadURL('http://localhost:2626/login'); ipcMain.once('login-message', function(event, usernameAndPassword) { try { loginWindow.close(); loginCallback(usernameAndPassword[0], usernameAndPassword[1]); } catch(e) { /* Do nothing */ } }); }};
Update `ConfirmEmailForm` to use `user_service.validate_key`
from django.contrib.auth.models import User from django.core.signing import BadSignature, SignatureExpired from django import forms from . import user_service class SubscribeForm(forms.Form): email = forms.EmailField() tags = forms.CharField() def clean_tags(self): tags = self.cleaned_data['tags'].split(',') return [t.strip().lower() for t in tags] class UnsubscribeForm(forms.Form): email = forms.EmailField() class ConfirmEmailForm(forms.Form): email = forms.EmailField() subscribe = forms.IntegerField() code = forms.CharField(max_length=80) def clean_subscribe(self): value = bool(self.cleaned_data['subscribe']) self.cleaned_data['subscribe'] = value return value def clean(self): cleaned_data = super(ConfirmEmailForm, self).clean() if self.errors: return cleaned_data email = cleaned_data['email'] code = cleaned_data['code'] for_subscription = cleaned_data['subscribe'] user = User.objects.filter(username=email).first() if not user: raise forms.ValidationError('Email not found') self.cleaned_data['user'] = user try: user_service.validate_key(key=code, user=user, for_subscription=for_subscription) except BadSignature: raise forms.ValidationError('Invalid Link') except SignatureExpired: raise forms.ValidationError('Link expired, please regenerate') return cleaned_data
from django.contrib.auth.models import User from django import forms class SubscribeForm(forms.Form): email = forms.EmailField() tags = forms.CharField() def clean_tags(self): tags = self.cleaned_data['tags'].split(',') return [t.strip().lower() for t in tags] class UnsubscribeForm(forms.Form): email = forms.EmailField() class ConfirmEmailForm(forms.Form): email = forms.EmailField() subscribe = forms.IntegerField() code = forms.CharField(max_length=80) def clean_subscribe(self): value = bool(self.cleaned_data['subscribe']) self.cleaned_data['subscribe'] = value return value def clean(self): cleaned_data = super(ConfirmEmailForm, self).clean() if self.errors: return cleaned_data email = cleaned_data['email'] code = cleaned_data['code'] user = User.objects.filter(username=email).first() if not user: raise forms.ValidationError('Email not found') self.cleaned_data['user'] = user if user.emailverification.is_key_expired(): raise forms.ValidationError('Link expired, please regenerate') if not user.emailverification.key == code: raise forms.ValidationError('Invalid Link') return cleaned_data
Fix __repr__ bug for CompletedApplication
import random from faker import Faker from .. import db from sqlalchemy.orm import validates class CompletedApplication(db.Model): id = db.Column(db.Integer, primary_key=True) student_profile_id = db.Column( db.Integer, db.ForeignKey('student_profile.id'), nullable=False) # college name college = db.Column(db.String, index=True) # statuses include 'Pending Results', 'Accepted', 'Denied', 'Waitlisted', # 'Deferred' status = db.Column(db.String, index=True) @validates('status') def validate_status(self, key, status): assert status in ['Pending Results', 'Accepted', 'Denied', 'Waitlisted', 'Deferred'] return status @staticmethod def generate_fake(count=2): fake = Faker() names = random.sample([ 'Cornell', 'Princeton', 'University of Florida', 'University of Richmond', ], count) statuses = ['Pending Results', 'Accepted', 'Denied', 'Waitlisted', 'Deferred'] comp_apps = [] for i in range(count): comp_apps.append( CompletedApplication( college=names[i], status=random.choice(statuses))) return comp_apps def __repr__(self): return '<CompletedApplication {}, {}>'.format( self.college, self.status)
import random from faker import Faker from .. import db from sqlalchemy.orm import validates class CompletedApplication(db.Model): id = db.Column(db.Integer, primary_key=True) student_profile_id = db.Column( db.Integer, db.ForeignKey('student_profile.id'), nullable=False) # college name college = db.Column(db.String, index=True) # statuses include 'Pending Results', 'Accepted', 'Denied', 'Waitlisted', # 'Deferred' status = db.Column(db.String, index=True) @validates('status') def validate_status(self, key, status): assert status in ['Pending Results', 'Accepted', 'Denied', 'Waitlisted', 'Deferred'] return status @staticmethod def generate_fake(count=2): fake = Faker() names = random.sample([ 'Cornell', 'Princeton', 'University of Florida', 'University of Richmond', ], count) statuses = ['Pending Results', 'Accepted', 'Denied', 'Waitlisted', 'Deferred'] comp_apps = [] for i in range(count): comp_apps.append( CompletedApplication( college=names[i], status=random.choice(statuses))) return comp_apps def __repr__(self): return '<CompletedApplication {}, {}>'.format( self.name, self.status)
MAINT: Add a 'count_nonzero' function to use with numpy 1.5.1.
"""Functions copypasted from newer versions of numpy. """ from __future__ import division, print_function, absolute_import import warnings import numpy as np from scipy.lib._version import NumpyVersion if NumpyVersion(np.__version__) > '1.7.0.dev': _assert_warns = np.testing.assert_warns else: def _assert_warns(warning_class, func, *args, **kw): r""" Fail unless the given callable throws the specified warning. This definition is copypasted from numpy 1.9.0.dev. The version in earlier numpy returns None. Parameters ---------- warning_class : class The class defining the warning that `func` is expected to throw. func : callable The callable to test. *args : Arguments Arguments passed to `func`. **kwargs : Kwargs Keyword arguments passed to `func`. Returns ------- The value returned by `func`. """ with warnings.catch_warnings(record=True) as l: warnings.simplefilter('always') result = func(*args, **kw) if not len(l) > 0: raise AssertionError("No warning raised when calling %s" % func.__name__) if not l[0].category is warning_class: raise AssertionError("First warning for %s is not a " "%s( is %s)" % (func.__name__, warning_class, l[0])) return result if NumpyVersion(np.__version__) >= '1.6.0': count_nonzero = np.count_nonzero else: def count_nonzero(a): return (a != 0).sum()
"""Functions copypasted from newer versions of numpy. """ from __future__ import division, print_function, absolute_import import warnings import numpy as np from scipy.lib._version import NumpyVersion if NumpyVersion(np.__version__) > '1.7.0.dev': _assert_warns = np.testing.assert_warns else: def _assert_warns(warning_class, func, *args, **kw): r""" Fail unless the given callable throws the specified warning. This definition is copypasted from numpy 1.9.0.dev. The version in earlier numpy returns None. Parameters ---------- warning_class : class The class defining the warning that `func` is expected to throw. func : callable The callable to test. *args : Arguments Arguments passed to `func`. **kwargs : Kwargs Keyword arguments passed to `func`. Returns ------- The value returned by `func`. """ with warnings.catch_warnings(record=True) as l: warnings.simplefilter('always') result = func(*args, **kw) if not len(l) > 0: raise AssertionError("No warning raised when calling %s" % func.__name__) if not l[0].category is warning_class: raise AssertionError("First warning for %s is not a " "%s( is %s)" % (func.__name__, warning_class, l[0])) return result
Improve subscribe links formatting on small screen
<?php if (is_active_sidebar('sidebar-right')) { ?> <div class="col-md-3" id="sidebar-right"> <?php do_action('before_sidebar'); ?> <?php dynamic_sidebar('sidebar-right'); ?> <aside class="widget"> <h1 class="widget-title">Subscribe</h1> <ul class="subscribe-links"> <li> <a href="https://overcast.fm"> <img src="<?php echo get_template_directory_uri() ?>/img/icons/icon-overcast.svg" /> <p>Overcast</p> </a> </li> <li> <a href="http://www.itunes.com"> <img src="<?php echo get_template_directory_uri() ?>/img/icons/icon-itunes.svg" /> <p>iTunes</p> </a> </li> <li> <a href="<?php echo site_url(); ?>/feed/mp3/"> <img src="<?php echo get_template_directory_uri() ?>/img/icons/icon-rss.svg" /> <p>RSS</p> </a> </li> </ul> <div class="clearfix"></div> </aside> </div> <?php } ?>
<?php if (is_active_sidebar('sidebar-right')) { ?> <div class="col-md-3" id="sidebar-right"> <?php do_action('before_sidebar'); ?> <?php dynamic_sidebar('sidebar-right'); ?> <aside class="widget"> <h1 class="widget-title">Subscribe</h1> <ul class="subscribe-links"> <li> <a href="https://overcast.fm"> <img src="<?php echo get_template_directory_uri() ?>/img/icons/icon-overcast.svg" /> Overcast </a> </li> <li> <a href="http://www.itunes.com"> <img src="<?php echo get_template_directory_uri() ?>/img/icons/icon-itunes.svg" /> iTunes </a> </li> <li> <a href="<?php echo site_url(); ?>/feed/mp3/"> <img src="<?php echo get_template_directory_uri() ?>/img/icons/icon-rss.svg" /> RSS </a> </li> </ul> <div class="clearfix"></div> </aside> </div> <?php } ?>
Add function to outputter that returns the raw string to print
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader STATIC = ( 'yaml_out', 'text_out', 'raw_out', 'json_out', ) def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' print(get_printout(out, opts)(data).rstrip()) def get_printout(out, opts=None, **kwargs): ''' Return a printer function ''' for outputter in STATIC: if outputter in opts: if opts[outputter]: if outputter == 'text_out': out = 'txt' else: out = outputter if out is None: out = 'pprint' if out.endswith('_out'): out = out[:-4] if opts is None: opts = {} opts.update(kwargs) if not 'color' in opts: opts['color'] = not bool(opts.get('no_color', False)) outputters = salt.loader.outputters(opts) if not out in outputters: return outputters['pprint'] return outputters[out] def out_format(data, out, opts=None): ''' Return the formatted outputter string for the passed data ''' return get_printout(out, opts)(data).rstrip()
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader STATIC = ( 'yaml_out', 'text_out', 'raw_out', 'json_out', ) def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' print(get_printout(out, opts)(data).rstrip()) def get_printout(out, opts=None, **kwargs): ''' Return a printer function ''' for outputter in STATIC: if outputter in opts: if opts[outputter]: if outputter == 'text_out': out = 'txt' else: out = outputter if out is None: out = 'pprint' if out.endswith('_out'): out = out[:-4] if opts is None: opts = {} opts.update(kwargs) if not 'color' in opts: opts['color'] = not bool(opts.get('no_color', False)) outputters = salt.loader.outputters(opts) if not out in outputters: return outputters['pprint'] return outputters[out]
Fix condition to show the Delete Enrollment option
<div class="btn-group"> @if (Auth::user()->student->isEnrolledInCourse($course)) <button type="button" class="btn btn-outline-secondary btn-sm disabled">Enrolled</button> @if ($settings->withinEnrollmentPeriod() && Auth::student()->getEnrollmentInCourse($course)->isDeletable()) {{-- Show dropdown to remove enrollment in course. --}} <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu dropdown-menu-right"> <form action="{{ route('enrollments.destroy', $course->id) }}" method="post"> {{ csrf_field() }} {{ method_field('DELETE') }} <button type="submit" class="dropdown-item btn btn-sm text-danger">Delete enrollment</button> </form> </div> @endif @elseif ($settings->withinEnrollmentPeriod()) {{-- Show button to enroll in course. --}} <form action="{{ route('enrollments.store', $course->id) }}" method="post"> {{ csrf_field() }} <button type="submit" class="btn btn-success btn-sm">Enroll in course</button> </form> @endif </div>
<div class="btn-group"> @if (Auth::user()->student->isEnrolledInCourse($course)) <button type="button" class="btn btn-outline-secondary btn-sm disabled">Enrolled</button> @if ($settings->withinExchangePeriod() && Auth::student()->getEnrollmentInCourse($course)->isDeletable()) {{-- Show dropdown to remove enrollment in course. --}} <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu dropdown-menu-right"> <form action="{{ route('enrollments.destroy', $course->id) }}" method="post"> {{ csrf_field() }} {{ method_field('DELETE') }} <button type="submit" class="dropdown-item btn btn-sm text-danger">Delete enrollment</button> </form> </div> @endif @elseif ($settings->withinEnrollmentPeriod()) {{-- Show button to enroll in course. --}} <form action="{{ route('enrollments.store', $course->id) }}" method="post"> {{ csrf_field() }} <button type="submit" class="btn btn-success btn-sm">Enroll in course</button> </form> @endif </div>
Allow <del> and <ins> html tags.
import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "del", "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles )
import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles )
Add missing void return types in console responder.
<?php /** * PHP version 7.1 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace Ewallet\ManageWallet; use Ewallet\Memberships\{MemberId, MembersRepository}; use Symfony\Component\Console\Input\InputInterface; class TransferFundsConsoleResponder implements TransferFundsResponder { /** @var InputInterface */ private $input; /** @var MembersRepository */ private $members; /** @var TransferFundsConsole */ private $console; public function __construct( InputInterface $input, MembersRepository $members, TransferFundsConsole $console ) { $this->input = $input; $this->members = $members; $this->console = $console; } /** * @param string[] $messages * @param string[] $values */ public function respondToInvalidTransferInput(array $messages, array $values): void { $this->console->printError($messages); } public function respondToEnterTransferInformation(MemberId $senderId): void { $this->console->printRecipients($this->members->excluding($senderId)); $this->input->setArgument('recipientId', $this->console->promptRecipientId()); $this->input->setArgument('amount', $this->console->promptAmountToTransfer()); } public function respondToTransferCompleted(TransferFundsSummary $summary): void { $this->console->printSummary($summary); } }
<?php /** * PHP version 7.1 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace Ewallet\ManageWallet; use Ewallet\Memberships\{MemberId, MembersRepository}; use Symfony\Component\Console\Input\InputInterface; class TransferFundsConsoleResponder implements TransferFundsResponder { /** @var InputInterface */ private $input; /** @var MembersRepository */ private $members; /** @var TransferFundsConsole */ private $console; public function __construct( InputInterface $input, MembersRepository $members, TransferFundsConsole $console ) { $this->input = $input; $this->members = $members; $this->console = $console; } /** * @param string[] $messages * @param string[] $values */ public function respondToInvalidTransferInput(array $messages, array $values) { $this->console->printError($messages); } public function respondToEnterTransferInformation(MemberId $senderId) { $this->console->printRecipients($this->members->excluding($senderId)); $this->input->setArgument('recipientId', $this->console->promptRecipientId()); $this->input->setArgument('amount', $this->console->promptAmountToTransfer()); } public function respondToTransferCompleted(TransferFundsSummary $summary) { $this->console->printSummary($summary); } }
Add default for possible undefined destructuring
import debugModule from "debug"; const debug = debugModule("debugger:session:selectors"); import { createSelectorTree, createLeaf } from "reselect-tree"; import evm from "lib/evm/selectors"; import solidity from "lib/solidity/selectors"; const session = createSelectorTree({ /** * session.info */ info: { /** * session.info.affectedInstances */ affectedInstances: createLeaf( [evm.info.instances, evm.info.contexts, solidity.info.sources, solidity.info.sourceMaps], (instances, contexts, sources, sourceMaps) => Object.assign({}, ...Object.entries(instances).map( ([address, {context}]) => { debug("instances %O", instances); debug("contexts %O", contexts); let { contractName, binary } = contexts[context]; let { sourceMap } = sourceMaps[context] || {}; let { source } = sourceMap ? // look for source ID between second and third colons (HACK) sources[sourceMap.match(/^[^:]+:[^:]+:([^:]+):/)[1]] : {}; return { [address]: { contractName, source, binary } }; } ) ) ) } }); export default session;
import debugModule from "debug"; const debug = debugModule("debugger:session:selectors"); import { createSelectorTree, createLeaf } from "reselect-tree"; import evm from "lib/evm/selectors"; import solidity from "lib/solidity/selectors"; const session = createSelectorTree({ /** * session.info */ info: { /** * session.info.affectedInstances */ affectedInstances: createLeaf( [evm.info.instances, evm.info.contexts, solidity.info.sources, solidity.info.sourceMaps], (instances, contexts, sources, sourceMaps) => Object.assign({}, ...Object.entries(instances).map( ([address, {context}]) => { debug("instances %O", instances); debug("contexts %O", contexts); let { contractName, binary } = contexts[context]; let { sourceMap } = sourceMaps[context]; let { source } = sourceMap ? // look for source ID between second and third colons (HACK) sources[sourceMap.match(/^[^:]+:[^:]+:([^:]+):/)[1]] : {}; return { [address]: { contractName, source, binary } }; } ) ) ) } }); export default session;
Fix formatting broken by phpstorm
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * Asset form * * note: title is hidden (filled from the controller based on AssetTypeTitle form) */ class AssetType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('title', 'hidden') //use the AssetTypeTile to display the title ->add('value', 'number', [ 'grouping' => true, 'precision' => 2, 'invalid_message' => 'asset.value.type' ]) ->add('description', 'textarea') ->add('valuationDate', 'date',[ 'widget' => 'text', 'input' => 'datetime', 'format' => 'dd-MM-yyyy', 'invalid_message' => 'Enter a valid date' ]) ->add('id', 'hidden') ->add('save', 'submit'); } public function getName() { return 'asset'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( [ 'translation_domain' => 'report-assets', ]); } }
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * Asset form * * note: title is hidden (filled from the controller based on AssetTypeTitle form) */ class AssetType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('title', 'hidden') //use the AssetTypeTile to display the title ->add('value', 'number', [ 'grouping' => true, 'precision' => 2, 'invalid_message' => 'asset.value.type' ]) ->add('description', 'textarea') ->add('valuationDate', 'date',[ 'widget' => 'text', 'input' => 'datetime', 'format' => 'dd-MM-yyyy', 'invalid_message' => 'Enter a valid date' ]) ->add('id', 'hidden') ->add('save', 'submit'); } public function getName() { return 'asset'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( [ 'translation_domain' => 'report-assets', ]); } }
Fix monolog event handler compatibility
<?php /** * Spiral Framework. * * @license MIT * @author Anton Titov (Wolfy-J) */ declare(strict_types=1); namespace Spiral\Monolog; use Monolog\Handler\AbstractHandler; use Monolog\Logger; use Spiral\Logger\Event\LogEvent; use Spiral\Logger\ListenerRegistryInterface; final class EventHandler extends AbstractHandler { /** @var ListenerRegistryInterface */ private $listenerRegistry; /** * @param ListenerRegistryInterface $listenerRegistry * @param int $level * @param bool $bubble */ public function __construct( ListenerRegistryInterface $listenerRegistry, int $level = Logger::DEBUG, bool $bubble = true ) { $this->listenerRegistry = $listenerRegistry; parent::__construct($level, $bubble); } /** * @param array $record * @return bool */ public function handle(array $record): bool { $e = new LogEvent( $record['datetime'], $record['channel'], strtolower(Logger::getLevelName($record['level'])), $record['message'], $record['context'] ); foreach ($this->listenerRegistry->getListeners() as $listener) { call_user_func($listener, $e); } return true; } }
<?php /** * Spiral Framework. * * @license MIT * @author Anton Titov (Wolfy-J) */ declare(strict_types=1); namespace Spiral\Monolog; use Monolog\Handler\AbstractHandler; use Monolog\Logger; use Spiral\Logger\Event\LogEvent; use Spiral\Logger\ListenerRegistryInterface; final class EventHandler extends AbstractHandler { /** @var ListenerRegistryInterface */ private $listenerRegistry; /** * @param ListenerRegistryInterface $listenerRegistry * @param int $level * @param bool $bubble */ public function __construct( ListenerRegistryInterface $listenerRegistry, int $level = Logger::DEBUG, bool $bubble = true ) { $this->listenerRegistry = $listenerRegistry; parent::__construct($level, $bubble); } /** * @param array $record * @return bool|void */ public function handle(array $record) { $e = new LogEvent( $record['datetime'], $record['channel'], strtolower(Logger::getLevelName($record['level'])), $record['message'], $record['context'] ); foreach ($this->listenerRegistry->getListeners() as $listener) { call_user_func($listener, $e); } } }
Set _version requirement for annotation
from tornado.web import Finish from biothings.web.api.es.handlers.base_handler import ESRequestHandler class BiothingHandler(ESRequestHandler): ''' Handle requests to the annotation lookup endpoint. ''' name = 'annotation' def pre_query_builder_hook(self, options): ''' Set GA tracking object. ''' if self.request.method == 'POST': self.ga_event_object({'qsize': len(options.esqb.ids)}) return options def pre_query_hook(self, options, query): ''' Request _version field. ''' options.es.version = True return super().pre_query_hook(options, query) def pre_finish_hook(self, options, res): ''' Return single result for GET. Also does not return empty results. ''' if isinstance(res, dict): if not res.get('hits'): self.send_error(404, reason=self.web_settings.ID_NOT_FOUND_TEMPLATE.format(bid=options.esqb.bid)) raise Finish() # TODO res = res['hits'][0] res.pop('_score') elif isinstance(res, list): for hit in res: hit.pop('_score', None) return res
from tornado.web import Finish from biothings.web.api.es.handlers.base_handler import ESRequestHandler class BiothingHandler(ESRequestHandler): ''' Handle requests to the annotation lookup endpoint. ''' name = 'annotation' def pre_query_builder_hook(self, options): ''' Inject bid(s) in esqb_kwargs. Set GA tracking object. ''' if self.request.method == 'GET': options.esqb['bid'] = self.path_args[0] # TODO elif self.request.method == 'POST': self.ga_event_object({'qsize': len(options.esqb.ids)}) return options def pre_finish_hook(self, options, res): ''' Return single result for GET. Also does not return empty results. ''' if isinstance(res, dict): if not res.get('hits'): self.send_error(404, reason=self.web_settings.ID_NOT_FOUND_TEMPLATE.format(bid=options.esqb.bid)) raise Finish() res = res['hits'][0] res.pop('_score') elif isinstance(res, list): for hit in res: hit.pop('_score', None) return res
Fix external script invocation failing with ENOENT error
'use strict'; const childProcess = require('child_process'); const fs = require('fs'); module.exports = function(type) { process.argv.shift(); process.argv.shift(); var path = process.argv.length < 1 ? 'output_data' : process.argv[0]; var process_generate = childProcess.spawn(__dirname + '/../node_modules/podigg/bin/generate-' + type + '.js', process.argv); process_generate.stdout.pipe(process.stdout); process_generate.stderr.pipe(process.stderr); process_generate.on('close', (code_generate) => { if(!code_generate) { var process_convert = childProcess.spawn(__dirname + '/../node_modules/gtfs2lc/bin/gtfs2lc.js', [path + '/gtfs', '-f', 'turtle', '-r', '-t', '-a']); process_convert.stdout.pipe(fs.createWriteStream(path + '/lc.ttl')); process_convert.stderr.pipe(process.stderr); process_convert.on('close', (code_convert) => { if (code_generate) { throw new Error('Conversion exited with exit code ' + code_convert); } }); } else { throw new Error('Generation exited with exit code ' + code_generate); } }); }
'use strict'; const childProcess = require('child_process'); const fs = require('fs'); module.exports = function(type) { process.argv.shift(); process.argv.shift(); var path = process.argv.length < 1 ? 'output_data' : process.argv[0]; var process_generate = childProcess.spawn('./node_modules/podigg/bin/generate-' + type + '.js', process.argv); process_generate.stdout.pipe(process.stdout); process_generate.stderr.pipe(process.stderr); process_generate.on('close', (code_generate) => { if(!code_generate) { var process_convert = childProcess.spawn('./node_modules/gtfs2lc/bin/gtfs2lc.js', [path + '/gtfs', '-f', 'turtle', '-r', '-t', '-a']); process_convert.stdout.pipe(fs.createWriteStream(path + '/lc.ttl')); process_convert.stderr.pipe(process.stderr); process_convert.on('close', (code_convert) => { if (code_generate) { throw new Error('Conversion exited with exit code ' + code_convert); } }); } else { throw new Error('Generation exited with exit code ' + code_generate); } }); }
Fix PEP8 and add more data Added tvdb_id and tvrage_id entries to returned data
from __future__ import unicode_literals, division, absolute_import import logging import requests from flexget import plugin from flexget.event import event from flexget.entry import Entry log = logging.getLogger('sonarr') class Sonarr(object): schema = { 'type': 'object', 'properties': { 'base_url': {'type': 'string'}, 'port': {'type': 'number'}, 'api_key': {'type': 'string'} }, 'required': ['api_key', 'base_url', 'port'], 'additionalProperties': False } def on_task_input(self, task, config): url = '%s:%s/api/series' % (config['base_url'], config['port']) headers = {'X-Api-Key': config['api_key']} json = task.requests.get(url, headers=headers).json() entries = [] for show in json: entry = Entry(title=show['title'], url='', series_name=show['title'], tvdb_id=show['tvdbId'], tvrage_id=show['tvRageId']) if entry.isvalid(): entries.append(entry) else: log.debug('Invalid entry created? %s' % entry) return entries @event('plugin.register') def register_plugin(): plugin.register(Sonarr, 'sonarr', api_ver=2)
from __future__ import unicode_literals, division, absolute_import import logging import requests from flexget import plugin from flexget.event import event from flexget.entry import Entry log = logging.getLogger('sonarr') class Sonarr(object): schema = { 'type': 'object', 'properties': { 'base_url': {'type': 'string'}, 'port': {'type': 'number'}, 'api_key': {'type':'string'} }, 'required': ['api_key', 'base_url', 'port'], 'additionalProperties': False } def on_task_input(self, task, config): url = '%s:%s/api/series' % (config['base_url'], config['port']) headers = {'X-Api-Key': config['api_key']} json = task.requests.get(url, headers=headers).json() entries = [] for show in json: showName = show['title'] entry = Entry(title=showName, url = '', series_name=showName) if entry.isvalid(): entries.append(entry) else: log.debug('Invalid entry created? %s' % entry) return entries @event('plugin.register') def register_plugin(): plugin.register(Sonarr, 'sonarr', api_ver=2)
Put php docblock for the class
<?php /** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace PHPRouter; /** * @author Jefersson Nathan <[email protected]> * * @package PHPRouter */ class RouteCollection extends \SplObjectStorage { /** * {@inheritDoc} * * @param Route $attachObject */ public function attach(Route $attachObject) { parent::attach($attachObject); } /** * Fetch all routers stored on this collection of router * and return it. * * @return Route[] */ public function all() { $temp = []; foreach ($this as $router) { $temp[] = $router; } return $temp; } }
<?php /** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace PHPRouter; class RouteCollection extends \SplObjectStorage { /** * {@inheritDoc} * * @param Route $attachObject */ public function attach(Route $attachObject) { parent::attach($attachObject); } /** * Fetch all routers stored on this collection of router * and return it. * * @return Route[] */ public function all() { $temp = []; foreach ($this as $router) { $temp[] = $router; } return $temp; } }
Remove protected class access, add module docstrings.
"""Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
Add view for update gallery action
<?php defined('M2_MICRO') or die('Direct Access to this location is not allowed.'); /** * Gallery Controller class * @name $galleryController * @package M2 Micro Framework * @subpackage Modules * @author Alexander Chaika * @since 0.2RC1 */ class GalleryController extends Controller { /** * Default gallery action * @param array $options * @return array $result */ public function indexAction($options) { return $this->listAction($options); } /** * List gallery action * @param array $options * @return array $result */ public function listAction($options) { // Get category ID $tags = System::getInstance()->getCmd('id'); // Get category title if ($tags) { $options['data'] = $this->model->getGalleryByTags($tags); $options['title'] = 'Search by tags: ' . implode(', ', $tags); } else { $options['data'] = $this->model->getGallery(); $options['title'] = Application::$config['site_title_' . Application::$config['language']]; } // Get category items and render it $options['module'] = 'gallery'; $options['body'] = $this->view->renderItemsArray($options); return $options; } /** * Runs updates in gallery */ public function updateAction() { // Run actions and get stats $parsed = $this->model->updateFSList(); $resized = $this->model->rebuildThumbnails(); // Compile response $options['title'] = 'Gallery updates'; $options['body'] = '<p>' . count($parsed) . ' ' . T('was parsed') . '</p><p>' . count($resized) . ' ' . T('was resuzed') . '</p>'; return $options; } }
<?php defined('M2_MICRO') or die('Direct Access to this location is not allowed.'); /** * Gallery Controller class * @name $galleryController * @package M2 Micro Framework * @subpackage Modules * @author Alexander Chaika * @since 0.2RC1 */ class GalleryController extends Controller { /** * Default gallery action * @param array $options * @return array $result */ public function indexAction($options) { return $this->listAction($options); } /** * List gallery action * @param array $options * @return array $result */ public function listAction($options) { // Get category ID $tags = System::getInstance()->getCmd('id'); // Get category title if ($tags) { $options['data'] = $this->model->getGalleryByTags($tags); $options['title'] = 'Search by tags: ' . implode(', ', $tags); } else { $options['data'] = $this->model->getGallery(); $options['title'] = Application::$config['site_title_' . Application::$config['language']]; } // get category items and render it $options['module'] = 'gallery'; $options['body'] = $this->view->renderItemsArray($options); return $options; } }
Fix the initial cancel bug
(function ($) { var slice = Array.prototype.slice; $.defer = function (func, delay) { var args = slice.call(arguments, 2), isCancelled = false, cancel = function (reject /* = true */) { clearTimeout(timerId); isCancelled = true; if ((!arguments.length || reject) && deferred.state() === "pending") { deferred.reject(null, promise, args); } }, deferred = $.Deferred(), timerId = setTimeout(function () { deferred.notify(promise, args); if (isCancelled) { return; } try { var result = func.apply(this, args); deferred.resolve(result, promise, args); } catch (e) { deferred.reject(e, promise, args); } }, delay), promise = deferred.promise(); promise.cancel = cancel; return promise; }; })(jQuery);
(function ($) { var slice = Array.prototype.slice; $.defer = function (func, delay) { var args = slice.call(arguments, 2), cancel = function (reject /* = true */) { clearTimeout(timerId); if ((!arguments.length || reject) && deferred.state() === "pending") { deferred.reject(null, promise, args); } }, deferred = $.Deferred(), timerId = setTimeout(function () { deferred.notify(promise, args); // if they cancel inside the progress call-back... if (deferred.state() === "rejected") { return; } try { var result = func.apply(this, args); deferred.resolve(result, promise, args); } catch (e) { deferred.reject(e, promise, args); } }, delay), promise = deferred.promise(); promise.cancel = cancel; return promise; }; })(jQuery);
Move instead of symlink because we blow that dir away.
import re import os from django.conf import settings from doc_builder.base import BaseBuilder from projects.utils import run latex_re = re.compile('the LaTeX files are in (.*)\.') pdf_re = re.compile('Output written on (.*?)') class Builder(BaseBuilder): def build(self, project): self._cd_makefile(project) latex_results = run('make latex') match = latex_re.search(latex_results[1]) if match: latex_dir = match.group(1).strip() os.chdir(latex_dir) pdf_results = run('make') #Check the return code was good before symlinking pdf_match = pdf_re.search(pdf_results[1]) if pdf_match: from_path = os.path.join(os.getcwd(), "%s.pdf" % pdf_match.group(1).strip()) to_path = os.path.join(settings.MEDIA_ROOT, 'pdf', project.slug, 'latest') if not os.path.exists(to_path): os.makedirs(to_path) to_file = os.path.join(to_path, '%s.pdf' % project.slug) if os.path.exists(to_file): run('mv -f %s %s' % (from_path, to_file)) else: print "File doesn't exist, not symlinking." else: print "PDF Building failed. Moving on." if project.build_pdf: project.build_pdf = False project.save()
import re import os from django.conf import settings from doc_builder.base import BaseBuilder from projects.utils import run latex_re = re.compile('the LaTeX files are in (.*)\.') pdf_re = re.compile('Output written on (.*?)') class Builder(BaseBuilder): def build(self, project): self._cd_makefile(project) latex_results = run('make latex') match = latex_re.search(latex_results[1]) if match: latex_dir = match.group(1).strip() os.chdir(latex_dir) pdf_results = run('make') #Check the return code was good before symlinking pdf_match = pdf_re.search(pdf_results[1]) if pdf_match: from_path = os.path.join(os.getcwd(), "%s.pdf" % project.slug) to_path = os.path.join(settings.MEDIA_ROOT, 'pdf', project.slug, 'latest') if not os.path.exists(to_path): os.makedirs(to_path) to_file = os.path.join(to_path, pdf_match.group(1).strip()) if os.path.exists(to_file): run('ln -sf %s %s' % (from_path, to_file)) else: print "File doesn't exist, not symlinking." else: print "PDF Building failed. Moving on." if project.build_pdf: project.build_pdf = False project.save()
Make sock_read return the number of bytes read (value in )
package mars.mips.instructions.syscalls; import mars.util.*; import mars.mips.hardware.*; import mars.simulator.*; import mars.*; import java.net.Socket; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; public class SyscallSocketRead extends AbstractSyscall { public SyscallSocketRead() { super(102, "SocketRead"); } public void simulate(ProgramStatement statement) throws ProcessingException { int fd = RegisterFile.getValue(4); int buffAddr = RegisterFile.getValue(5); int maxLen = RegisterFile.getValue(6); byte[] buff = new byte[maxLen]; try { int bytesRead = Sockets.getSocket(fd).getInputStream().read(buff); RegisterFile.updateRegister(3, bytesRead); } catch (IOException e) { e.printStackTrace(); System.out.println(e.toString()); throw new ProcessingException(); } for (int i = 0; i < maxLen; i++) { // TODO: Make sure this actually writes as expected. May be limited to byte-aligned writing, which // will require some fancy bit-string flicking try { Globals.memory.setByte(buffAddr++, buff[i]); } catch (Exception e) { System.out.println("Choked on address: " + buffAddr); e.printStackTrace(); throw new ProcessingException(); } } } }
package mars.mips.instructions.syscalls; import mars.util.*; import mars.mips.hardware.*; import mars.simulator.*; import mars.*; import java.net.Socket; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; public class SyscallSocketRead extends AbstractSyscall { public SyscallSocketRead() { super(102, "SocketRead"); } public void simulate(ProgramStatement statement) throws ProcessingException { int fd = RegisterFile.getValue(4); int buffAddr = RegisterFile.getValue(5); int maxLen = RegisterFile.getValue(6); byte[] buff = new byte[maxLen]; try { int bytesRead = Sockets.getSocket(fd).getInputStream().read(buff); } catch (IOException e) { e.printStackTrace(); System.out.println(e.toString()); throw new ProcessingException(); } for (int i = 0; i < maxLen; i++) { // TODO: Make sure this actually writes as expected. May be limited to byte-aligned writing, which // will require some fancy bit-string flicking try { Globals.memory.setByte(buffAddr++, buff[i]); } catch (Exception e) { System.out.println("Choked on address: " + buffAddr); e.printStackTrace(); throw new ProcessingException(); } } } }
Fix {X} no momento que vota e dá o erro
jQuery( function( $ ) { $('.js-vote-button').click(function() { var post_id = $(this).data('post_id'); var panel = $(this).closest('.panel-heading'); $.ajax({ url: vote.ajaxurl, dataType: 'json', method: 'POST', data: { action: 'rhs_vote', post_id: post_id }, beforeSend: function () { $('#votebox-'+post_id).html('<i class="fa fa-spinner fa-pulse fa-fw"></i>'); }, success: function (data) { $('#votebox-'+post_id+' i').remove(); if(data){ if(data['error']) { var alrt = '<div class="alert alert-danger"><p><i class="fa fa-exclamation-triangle"></i> '+data['error']+'</p></div>'; $('#votebox-'+post_id).html('<i class="fa fa-remove"></i>'); $('div.vdivide').css({"top": "-49px", "border": "none"}); } if(data['success']) { $('#votebox-'+post_id).parent('.votebox').html(data['success']); } } $(alrt).hide(); $(panel).children('.alert').fadeOut(); $(panel).prepend(alrt).fadeIn(); } }); }); });
jQuery( function( $ ) { $('.js-vote-button').click(function() { var post_id = $(this).data('post_id'); var panel = $(this).closest('.panel-heading'); $.ajax({ url: vote.ajaxurl, dataType: 'json', method: 'POST', data: { action: 'rhs_vote', post_id: post_id }, beforeSend: function () { $('#votebox-'+post_id).html('<i class="fa fa-spinner fa-pulse fa-fw"></i>'); }, success: function (data) { $('#votebox-'+post_id+' i').remove(); if(data){ if(data['error']) { var alrt = '<div class="alert alert-danger"><p><i class="fa fa-exclamation-triangle"></i> '+data['error']+'</p></div>'; $('#votebox-'+post_id).html('<i class="fa fa-remove"></i>'); } if(data['success']) { $('#votebox-'+post_id).parent('.votebox').html(data['success']); } } $(alrt).hide(); $(panel).children('.alert').fadeOut(); $(panel).prepend(alrt).fadeIn(); } }); }); });
Use array_key_exists() instead of isset() So that it works when modifying the field value to null, too.
<?php /** Tatoeba Project, free collaborative creation of languages corpuses project Copyright (C) 2014 Gilles Bedel This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ class AppModel extends Model { /** * Function to be used in beforeSave(). * Checks if the save() is about to update any of the provided $fields. * Precondition: the save() is NOT creating a new record, which means * $this->data[$this->alias][$this->primaryKey] is set. */ protected function isModifyingFields($fields) { foreach ($fields as $field) { if (array_key_exists($field, $this->data[$this->alias])) { $conditions = array( $this->primaryKey => $this->data[$this->alias][$this->primaryKey] ); $value = $this->field($field, $conditions); if ($this->data[$this->alias][$field] != $value) return true; } } return false; } }
<?php /** Tatoeba Project, free collaborative creation of languages corpuses project Copyright (C) 2014 Gilles Bedel This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ class AppModel extends Model { /** * Function to be used in beforeSave(). * Checks if the save() is about to update any of the provided $fields. * Precondition: the save() is NOT creating a new record, which means * $this->data[$this->alias][$this->primaryKey] is set. */ protected function isModifyingFields($fields) { foreach ($fields as $field) { if (isset($this->data[$this->alias][$field])) { $conditions = array( $this->primaryKey => $this->data[$this->alias][$this->primaryKey] ); $value = $this->field($field, $conditions); if ($this->data[$this->alias][$field] != $value) return true; } } return false; } }
Support all the fortran grammars
"use babel"; export default { config: { executable: { type: "string", default: "gfortran" }, gfortran_flags: { type: "string", default: "-Wall -Wextra" }, }, activate: () => { require("atom-package-deps").install("linter-gfortran"); }, provideLinter: () => { const helpers = require("atom-linter"); const regex = "(?<file>.+):(?<line>\\d+):(?<col>\\d+):((.|\\n)*)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)"; const tmpdir = require('tmp').dirSync().name; return { name: "gfortran", grammarScopes: [ "source.fortran.free", "source.fortran.fixed", "source.fortran.modern", "source.fortran.punchcard" ], scope: "file", lintOnFly: false, lint: (activeEditor) => { const command = atom.config.get("linter-gfortran.executable"); const file = activeEditor.getPath(); const args = ["-fsyntax-only", "-J", tmpdir]; args.push(file); return helpers.exec(command, args, {stream: "stderr"}).then(output => helpers.parse(output, regex) ); } }; } };
"use babel"; export default { config: { executable: { type: "string", default: "gfortran" }, gfortran_flags: { type: "string", default: "-Wall -Wextra" }, }, activate: () => { require("atom-package-deps").install("linter-gfortran"); }, provideLinter: () => { const helpers = require("atom-linter"); const regex = "(?<file>.+):(?<line>\\d+):(?<col>\\d+):((.|\\n)*)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)"; const tmpdir = require('tmp').dirSync().name; return { name: "gfortran", grammarScopes: ["source.fortran.free"], scope: "file", lintOnFly: false, lint: (activeEditor) => { const command = atom.config.get("linter-gfortran.executable"); const file = activeEditor.getPath(); const args = ["-fsyntax-only", "-J", tmpdir]; args.push(file); return helpers.exec(command, args, {stream: "stderr"}).then(output => helpers.parse(output, regex) ); } }; } };
Fix a pass by reference, and don't create APIs for hidden directories
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\API'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { // parent::boot($router); } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $scan = scandir(app_path('API')); $directories = array_splice($scan, 0, 2); foreach ($directories as $directory) { if (is_dir(app_path('API/'.$directory)) && substr($directory, 0, 1) != '.') { $router->group(['namespace' => $this->namespace.'\\'.$directory.'\\Http', 'prefix' => $directory.'/api'], function ($router) use ($directory) { require app_path('API/'.$directory.'/routes.php'); }); } } } }
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\API'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { // parent::boot($router); } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $directories = array_splice(scandir(app_path('API')), 0, 2); foreach ($directories as $directory) { if (is_dir(app_path('API/'.$directory))) { $router->group(['namespace' => $this->namespace.'\\'.$directory.'\\Http', 'prefix' => $directory.'/api'], function ($router) use ($directory) { require app_path('API/'.$directory.'/routes.php'); }); } } } }
Fix cancel session invite so that it doesn't require admin rights
(function () { 'use strict'; function cancelSessionInviteCtrl($scope, $state, $stateParams, currentUser, $translate, alertService, usSpinnerService, cdEventsService) { usSpinnerService.spin('session-spinner'); var applicationId = $stateParams.applicationId; var eventId = $stateParams.eventId; currentUser = currentUser.data; if (_.isEmpty(currentUser)) { return $state.go('error-404-no-headers'); } var application = { id: applicationId, eventId: eventId }; cdEventsService.removeApplicant(application, function (response) { var successMessage = $translate.instant('Thank you for confirming you will not be in attendance; your application has now been cancelled.'); if (response.ok === true) { alertService.showAlert(successMessage); } else { alertService.showAlert($translate.instant(response.why)); } $state.go('home'); }, function (err) { if (err) { console.error(err); alertService.showError($translate.instant('Invalid application cancellation link.')); } $state.go('home'); }) } angular.module('cpZenPlatform') .controller('cancel-session-invite-controller', ['$scope', '$state', '$stateParams', 'currentUser', '$translate', 'alertService', 'usSpinnerService', 'cdEventsService', cancelSessionInviteCtrl]); })();
(function () { 'use strict'; function cancelSessionInviteCtrl($scope, $state, $stateParams, currentUser, $translate, alertService, usSpinnerService, cdEventsService) { usSpinnerService.spin('session-spinner'); var applicationId = $stateParams.applicationId; var ticketId = $stateParams.eventId; currentUser = currentUser.data; if (_.isEmpty(currentUser)) { return $state.go('error-404-no-headers'); } var application = { id: applicationId, ticketId: ticketId, updateAction: 'delete', deleted: true }; $scope.showAlertBanner = function (application, successMessage) { return (application.status === 'approved' || application.attended || application.deleted) && successMessage !== undefined; } cdEventsService.bulkApplyApplications([application], function (applications) { var successMessage = $translate.instant('Thank you for confirming you will not be in attendance; your ticket has now been cancelled.'); if (_.isEmpty(applications)) { return; } if ($scope.showAlertBanner(applications[0], successMessage)) { alertService.showAlert(successMessage); } else if (applications.ok === true) { alertService.showAlert(successMessage); } else { alertService.showAlert($translate.instant(applications.why)); } $state.go('home'); }, function (err) { if (err) { console.error(err); alertService.showError($translate.instant('Invalid ticket cancellation link.')); } }) } angular.module('cpZenPlatform') .controller('cancel-session-invite-controller', ['$scope', '$state', '$stateParams', 'currentUser', '$translate', 'alertService', 'usSpinnerService', 'cdEventsService', cancelSessionInviteCtrl]); })();
Fix de-parametize in URL utility jQuery replaces encoded spaces with plus signs. To prevent encoding of the plus sign itself, they are replaced with a space prior to decoding. Signed-off-by: Byron Ruth <[email protected]>
/* global define */ define(['jquery'], function($) { /* * Utility method for parsing links. See: * http://stackoverflow.com/a/6644749/407954 * https://developer.mozilla.org/en-US/docs/Web/API/window.location */ var linkParser = function(href) { var a = document.createElement('a'); a.href = href; return a; }; /* * Augments/changes a URL's query parameters. Takes a URL and object * of URL params. */ var alterUrlParams = function(href, data) { if (!data) return href; // Parse the href into a temporary anchor element var a = linkParser(href); // Parse existing params on URL var params = {}, search = a.search.substr(1).split('&'); // De-parametize URL for (var i = 0; i< search.length; i++) { var param = search[i].split('='); if (param[0]) { // Reverse what jQuery parametize logic params[param[0]] = decodeURIComponent(param[1].replace('+', ' ')); } } // Update params hash with passed params $.extend(params, data); // Reset parameters on the href a.search = '?' + $.param(params); return a.href; }; return { linkParser: linkParser, alterUrlParams: alterUrlParams }; });
/* global define */ define(['jquery'], function($) { /* * Utility method for parsing links. See: * http://stackoverflow.com/a/6644749/407954 * https://developer.mozilla.org/en-US/docs/Web/API/window.location */ var linkParser = function(href) { var a = document.createElement('a'); a.href = href; return a; }; /* * Augments/changes a URL's query parameters. Takes a URL and object * of URL params. */ var alterUrlParams = function(href, data) { if (!data) return href; // Parse the href into a temporary anchor element var a = linkParser(href); // Parse existing params on URL var params = {}, search = a.search.substr(1).split('&'); // De-parametize URL for (var i = 0; i< search.length; i++) { var param = search[i].split('='); if (param[0]) { params[param[0]] = window.decodeURIComponent(param[1]); } } // Update params hash with passed params $.extend(params, data); // Reset parameters on the href a.search = '?' + $.param(params); return a.href; }; return { linkParser: linkParser, alterUrlParams: alterUrlParams }; });
Fix the port to 9092
package com.splicemachine.kafka; import java.io.IOException; import java.util.Properties; import kafka.server.KafkaConfig; import kafka.server.KafkaServerStartable; import kafka.utils.TestUtils; public class TestKafkaCluster { KafkaServerStartable kafkaServer; public TestKafkaCluster(String connectString) throws Exception { KafkaConfig config = getKafkaConfig(connectString); kafkaServer = new KafkaServerStartable(config); kafkaServer.startup(); } public static void main(String [] args) throws Exception { TestKafkaCluster cluster; if (args.length==1) cluster = new TestKafkaCluster(args[0]); else throw new RuntimeException("No zookeper local"); } private static KafkaConfig getKafkaConfig(final String zkConnectString) { scala.collection.Iterator<Properties> propsI = TestUtils.createBrokerConfigs(1,true).iterator(); assert propsI.hasNext(); Properties props = propsI.next(); assert props.containsKey("zookeeper.connect"); props.put("zookeeper.connect", zkConnectString); props.put("port","9092"); return new KafkaConfig(props); } public String getKafkaBrokerString() { return String.format("localhost:%d", kafkaServer.serverConfig().port()); } public int getKafkaPort() { return kafkaServer.serverConfig().port(); } public void stop() throws IOException { kafkaServer.shutdown(); } }
package com.splicemachine.kafka; import java.io.IOException; import java.util.Properties; import kafka.server.KafkaConfig; import kafka.server.KafkaServerStartable; import kafka.utils.TestUtils; public class TestKafkaCluster { KafkaServerStartable kafkaServer; public TestKafkaCluster(String connectString) throws Exception { KafkaConfig config = getKafkaConfig(connectString); kafkaServer = new KafkaServerStartable(config); kafkaServer.startup(); } public static void main(String [] args) throws Exception { TestKafkaCluster cluster; if (args.length==1) cluster = new TestKafkaCluster(args[0]); else throw new RuntimeException("No zookeper local"); } private static KafkaConfig getKafkaConfig(final String zkConnectString) { scala.collection.Iterator<Properties> propsI = TestUtils.createBrokerConfigs(1,true).iterator(); assert propsI.hasNext(); Properties props = propsI.next(); assert props.containsKey("zookeeper.connect"); props.put("zookeeper.connect", zkConnectString); return new KafkaConfig(props); } public String getKafkaBrokerString() { return String.format("localhost:%d", kafkaServer.serverConfig().port()); } public int getKafkaPort() { return kafkaServer.serverConfig().port(); } public void stop() throws IOException { kafkaServer.shutdown(); } }
Move `&&` at the beginning of line to end of previous line
<?php declare (strict_types = 1); ?><!DOCTYPE html> <html <?php \language_attributes(); ?>> <head> <meta charset="<?php \bloginfo('charset'); ?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <![endif]--> <link rel="profile" href="http://gmpg.org/xfn/11" /> <?php if (\Jentil()->utilities->page->is('singular') && \pings_open(\get_queried_object()) ) { ?> <link rel="pingback" href="<?php \bloginfo('pingback_url'); ?>" /> <?php } ?> <!--[if lt IE 9]> <script src="<?php echo \Jentil()->utilities->fileSystem->dir( 'url', '/dist/vendor/html5shiv.min.js' ); ?>"></script> <script src="<?php echo \Jentil()->utilities->fileSystem->dir( 'url', '/dist/vendor/respond.min.js' ); ?>"></script> <![endif]--> <?php \wp_head(); ?> </head> <body <?php \body_class(); ?>> <div id="wrap" class="site hfeed">
<?php declare (strict_types = 1); ?><!DOCTYPE html> <html <?php \language_attributes(); ?>> <head> <meta charset="<?php \bloginfo('charset'); ?>" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <![endif]--> <link rel="profile" href="http://gmpg.org/xfn/11" /> <?php if (\Jentil()->utilities->page->is('singular') && \pings_open(\get_queried_object()) ) { ?> <link rel="pingback" href="<?php \bloginfo('pingback_url'); ?>" /> <?php } ?> <!--[if lt IE 9]> <script src="<?php echo \Jentil()->utilities->fileSystem->dir( 'url', '/dist/vendor/html5shiv.min.js' ); ?>"></script> <script src="<?php echo \Jentil()->utilities->fileSystem->dir( 'url', '/dist/vendor/respond.min.js' ); ?>"></script> <![endif]--> <?php \wp_head(); ?> </head> <body <?php \body_class(); ?>> <div id="wrap" class="site hfeed">
Fix typo in redis error message
# -*- coding: utf-8 -*- """ Interface to Redis-storage. @author: Seva Zhidkov @contact: [email protected] @license: The MIT license Copyright (C) 2015 """ from .utils import logger # We will catch all import exceptions in bot.py from redis import StrictRedis class Storage: def __init__(self, bot): """ Create new storage for bot :param bot: Bot object :return: """ self.bot = bot # Connect to Redis. # If we had problems with Redis - just set self.redis to None. # Not redis-required modules must work without Redis. try: self.redis = StrictRedis(host=bot.config.get('SHELDON_REDIS_HOST', 'localhost'), port=int( bot.config.get('SHELDON_REDIS_PORT', '6379') ), db=int( bot.config.get('SHELDON_REDIS_DB', '0') ) ) except Exception as error: logger.error_log_message('Error while connecting Redis:') logger.error_log_message(str(error.__traceback__)) self.redis = None
# -*- coding: utf-8 -*- """ Interface to Redis-storage. @author: Seva Zhidkov @contact: [email protected] @license: The MIT license Copyright (C) 2015 """ from .utils import logger # We will catch all import exceptions in bot.py from redis import StrictRedis class Storage: def __init__(self, bot): """ Create new storage for bot :param bot: Bot object :return: """ self.bot = bot # Connect to Redis. # If we had problems with Redis - just set self.redis to None. # Not redis-required modules must work without Redis. try: self.redis = StrictRedis(host=bot.config.get('SHELDON_REDIS_HOST', 'localhost'), port=int( bot.config.get('SHELDON_REDIS_PORT', '6379') ), db=int( bot.config.get('SHELDON_REDIS_DB', '0') ) ) except Exception as error: logger.error_log_message('Error while connection Redis:') logger.error_log_message(str(error.__traceback__)) self.redis = None
crosvm: Enable clippy in windows LUCI For linux based systems, clippy continues to run in health_check BUG=b:257249038 TEST=CQ Change-Id: I39d3d45a0db72c61e79fd2c51b195b82c067a244 Reviewed-on: https://chromium-review.googlesource.com/c/crosvm/crosvm/+/3993934 Reviewed-by: Dennis Kempin <[email protected]> Commit-Queue: Vikram Auradkar <[email protected]>
# Copyright 2022 The ChromiumOS Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from recipe_engine.post_process import Filter PYTHON_VERSION_COMPATIBILITY = "PY3" DEPS = [ "crosvm", "recipe_engine/buildbucket", "recipe_engine/context", "recipe_engine/properties", "recipe_engine/step", ] def RunSteps(api): # Note: The recipe does work on linux as well, if the required dependencies have been installed # on the host via ./tools/install-deps. # This allows the build to be tested via `./recipe.py run build_windows` with api.crosvm.host_build_context(): api.step( "Build crosvm tests", [ "vpython3", "./tools/run_tests", "--verbose", "--build-only", ], ) api.step( "Run crosvm tests", [ "vpython3", "./tools/run_tests", "--verbose", ], ) api.step( "Clippy windows crosvm", [ "vpython3", "./tools/clippy", ], ) def GenTests(api): filter_steps = Filter("Build crosvm tests", "Run crosvm tests") yield ( api.test( "build", api.buildbucket.ci_build(project="crosvm/crosvm"), ) + api.post_process(filter_steps) )
# Copyright 2022 The ChromiumOS Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from recipe_engine.post_process import Filter PYTHON_VERSION_COMPATIBILITY = "PY3" DEPS = [ "crosvm", "recipe_engine/buildbucket", "recipe_engine/context", "recipe_engine/properties", "recipe_engine/step", ] def RunSteps(api): # Note: The recipe does work on linux as well, if the required dependencies have been installed # on the host via ./tools/install-deps. # This allows the build to be tested via `./recipe.py run build_windows` with api.crosvm.host_build_context(): api.step( "Build crosvm tests", [ "vpython3", "./tools/run_tests", "--verbose", "--build-only", ], ) api.step( "Run crosvm tests", [ "vpython3", "./tools/run_tests", "--verbose", ], ) def GenTests(api): filter_steps = Filter("Build crosvm tests", "Run crosvm tests") yield ( api.test( "build", api.buildbucket.ci_build(project="crosvm/crosvm"), ) + api.post_process(filter_steps) )
Set except import error on add introspection rules south
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db.models.fields import CharField from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from tags.models import Tag @python_2_unicode_compatible class TagField(CharField): def __init__(self, verbose_name=_('Tags'), max_length=4000, blank=True, null=True, help_text=_('A comma-separated list of tags.'), **kwargs): kwargs['max_length'] = max_length kwargs['blank'] = blank kwargs['null'] = null kwargs['verbose_name'] = verbose_name kwargs['help_text'] = help_text self.max_length = max_length self.blank = blank self.null = null self.verbose_name = verbose_name self.help_text = help_text CharField.__init__(self, **kwargs) def pre_save(self, model_instance, add): str_tags = getattr(model_instance, self.name) if str_tags: tags = set(str_tags.split(',')) for tag in tags: Tag.objects.get_or_create(name=tag) return ','.join(tags) return super(TagField, self).pre_save(model_instance, add) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^tags\.fields\.TagField"]) except ImportError: pass
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db.models.fields import CharField from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from tags.models import Tag @python_2_unicode_compatible class TagField(CharField): def __init__(self, verbose_name=_('Tags'), max_length=4000, blank=True, null=True, help_text=_('A comma-separated list of tags.'), **kwargs): kwargs['max_length'] = max_length kwargs['blank'] = blank kwargs['null'] = null kwargs['verbose_name'] = verbose_name kwargs['help_text'] = help_text self.max_length = max_length self.blank = blank self.null = null self.verbose_name = verbose_name self.help_text = help_text CharField.__init__(self, **kwargs) def pre_save(self, model_instance, add): str_tags = getattr(model_instance, self.name) if str_tags: tags = set(str_tags.split(',')) for tag in tags: Tag.objects.get_or_create(name=tag) return ','.join(tags) return super(TagField, self).pre_save(model_instance, add) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^tags\.fields\.TagField"]) except: pass
Allow multiple sequential rpc requests
<?php namespace OldSound\RabbitMqBundle\RabbitMq; use OldSound\RabbitMqBundle\RabbitMq\BaseAmqp; use PhpAmqpLib\Message\AMQPMessage; class RpcClient extends BaseAmqp { protected $requests = 0; protected $replies = array(); protected $queueName; public function initClient() { list($this->queueName, ,) = $this->getChannel()->queue_declare("", false, false, true, true); } public function addRequest($msgBody, $server, $requestId = null, $routingKey = '') { if (empty($requestId)) { throw new \InvalidArgumentException('You must provide a $requestId'); } $msg = new AMQPMessage($msgBody, array('content_type' => 'text/plain', 'reply_to' => $this->queueName, 'correlation_id' => $requestId)); $this->getChannel()->basic_publish($msg, $server, $routingKey); $this->requests++; } public function getReplies() { $this->getChannel()->basic_consume($this->queueName, '', false, true, false, false, array($this, 'processMessage')); while (count($this->replies) < $this->requests) { $this->getChannel()->wait(); } $this->getChannel()->basic_cancel($this->queueName); $this->requests = 0; return $this->replies; } public function processMessage(AMQPMessage $msg) { $this->replies[$msg->get('correlation_id')] = unserialize($msg->body); } }
<?php namespace OldSound\RabbitMqBundle\RabbitMq; use OldSound\RabbitMqBundle\RabbitMq\BaseAmqp; use PhpAmqpLib\Message\AMQPMessage; class RpcClient extends BaseAmqp { protected $requests = 0; protected $replies = array(); protected $queueName; public function initClient() { list($this->queueName, ,) = $this->getChannel()->queue_declare("", false, false, true, true); } public function addRequest($msgBody, $server, $requestId = null, $routingKey = '') { if (empty($requestId)) { throw new \InvalidArgumentException('You must provide a $requestId'); } $msg = new AMQPMessage($msgBody, array('content_type' => 'text/plain', 'reply_to' => $this->queueName, 'correlation_id' => $requestId)); $this->getChannel()->basic_publish($msg, $server, $routingKey); $this->requests++; } public function getReplies() { $this->getChannel()->basic_consume($this->queueName, '', false, true, false, false, array($this, 'processMessage')); while (count($this->replies) < $this->requests) { $this->getChannel()->wait(); } $this->getChannel()->basic_cancel($this->queueName); return $this->replies; } public function processMessage(AMQPMessage $msg) { $this->replies[$msg->get('correlation_id')] = unserialize($msg->body); } }
Augment number of retrieved actions to the max
import R from 'ramda'; import {Observable} from 'rx'; const trelloSinkDriver = R.curry( ( boardId, input$ ) => { return { actions$: Observable.create( ( observer ) => { input$.subscribe( () => { Trello.get( '/boards/' + boardId + '/actions', { filter: 'createCard,deleteCard,updateCard', fields: 'data,date,type', limit: 1000 }, observer.onNext.bind( observer ), ( err ) => { console.log( 'Error when trying to retrieve board actions', err ); } ); } ); } ), lists$: Observable.create( ( observer ) => { input$.subscribe( () => { Trello.get( '/boards/' + boardId + '/lists', { cards: 'open', card_fields: '' }, observer.onNext.bind( observer ), ( err ) => { console.log( 'Error when trying to retrieve board lists', err ); } ); } ); } ) }; } ); function makeTrelloDriver ( boardId ) { Trello.authorize( { type: 'popup', name: 'Trello Kanban', scope: { read: true }, persist: true, expiration: 'never', success: () => console.log( 'Connected to Trello.' ), error: () => console.log( 'Error on Trello connexion.' ) } ); return trelloSinkDriver( boardId ); } export {makeTrelloDriver};
import R from 'ramda'; import {Observable} from 'rx'; const trelloSinkDriver = R.curry( ( boardId, input$ ) => { return { actions$: Observable.create( ( observer ) => { input$.subscribe( () => { Trello.get( '/boards/' + boardId + '/actions', { filter: 'createCard,deleteCard,updateCard', fields: 'data,date,type', limit: 500 }, observer.onNext.bind( observer ), ( err ) => { console.log( 'Error when trying to retrieve board actions', err ); } ); } ); } ), lists$: Observable.create( ( observer ) => { input$.subscribe( () => { Trello.get( '/boards/' + boardId + '/lists', { cards: 'open', card_fields: '' }, observer.onNext.bind( observer ), ( err ) => { console.log( 'Error when trying to retrieve board lists', err ); } ); } ); } ) }; } ); function makeTrelloDriver ( boardId ) { Trello.authorize( { type: 'popup', name: 'Trello Kanban', scope: { read: true }, persist: true, expiration: 'never', success: () => console.log( 'Connected to Trello.' ), error: () => console.log( 'Error on Trello connexion.' ) } ); return trelloSinkDriver( boardId ); } export {makeTrelloDriver};
Update documentation link and text
import React from 'react'; import AuthStore from '../stores/AuthStore'; import AlertPanel from './AlertPanel'; import Config from '../config/Config'; import MetadataStore from '../stores/MetadataStore'; const METHODS_TO_BIND = [ 'handleUserLogout' ]; module.exports = class AccessDeniedPage extends React.Component { constructor() { super(...arguments); METHODS_TO_BIND.forEach((method) => { this[method] = this[method].bind(this); }); } handleUserLogout() { AuthStore.logout(); } getFooter() { return ( <button className="button button-primary" onClick={this.handleUserLogout}> Log out </button> ); } render() { return ( <div className="flex-container-col fill-height"> <div className="page-content container-scrollable inverse"> <div className="container container-fluid container-pod flex-container-col"> <AlertPanel footer={this.getFooter()} title="Access Denied"> <p> You do not have access to this service. <br /> Please contact your {Config.productName} administrator. </p> <p className="flush-bottom"> See the security <a href={MetadataStore.buildDocsURI('/administration/id-and-access-mgt/')} target="_blank">documentation</a> for more information. </p> </AlertPanel> </div> </div> </div> ); } };
import React from 'react'; import AuthStore from '../stores/AuthStore'; import AlertPanel from './AlertPanel'; import Config from '../config/Config'; import MetadataStore from '../stores/MetadataStore'; const METHODS_TO_BIND = [ 'handleUserLogout' ]; module.exports = class AccessDeniedPage extends React.Component { constructor() { super(...arguments); METHODS_TO_BIND.forEach((method) => { this[method] = this[method].bind(this); }); } handleUserLogout() { AuthStore.logout(); } getFooter() { return ( <button className="button button-primary" onClick={this.handleUserLogout}> Log out </button> ); } render() { return ( <div className="flex-container-col fill-height"> <div className="page-content container-scrollable inverse"> <div className="container container-fluid container-pod flex-container-col"> <AlertPanel footer={this.getFooter()} title="Access Denied"> <p> You do not have access to this service. <br /> Please contact your {Config.productName} administrator. </p> <p className="flush-bottom"> See the <a href={MetadataStore.buildDocsURI('/administration/security/managing-authentication/')} target="_blank">Security and Authentication</a> documentation for more information. </p> </AlertPanel> </div> </div> </div> ); } };
Check for empty cluster dr files.
#!/usr/bin/env python3 from collections import defaultdict import hashlib import json import os import sys from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: stats['bad json'] += 1 pass else: if not ('url' in data and 'title' in data and 'content' in data): stats['no url/title/content'] += 1 continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) writer.write(doc) stats['ok'] += 1 written += 1 if not written: print('No docs written for {}'.format(cluster_dr)) os.remove(cluster_dr) print('Stats\t{}'.format(dict(stats)))
#!/usr/bin/env python3 import hashlib import json import os import sys print(sys.path) from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) for filename in sorted(f for f in files if f.endswith('.readability')): dr_filename = filename.replace('.readability', '.dr') if not dr_filename in files: path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: pass else: if not ('url' in data and 'title' in data and 'content' in data): continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) print(doc) writer.write(doc)
Add option to images links to open in parent tab or new tab
<?php namespace actsmart\actsmart\Actuators\WebChat; class WebChatImageMessage extends WebChatMessage { private $imgSrc = null; private $imgLink = null; private $linkNewTab = true; /** * @param $imgSrc * @return $this */ public function setImgSrc($imgSrc) { $this->imgSrc = $imgSrc; return $this; } /** * @param $imgLink * @return $this */ public function setImgLink($imgLink) { $this->imgLink = $imgLink; return $this; } /** * @param $linkNewTab * @return $this */ public function setLinkNewTab($linkNewTab) { $this->linkNewTab = $linkNewTab; return $this; } /** * @return null|string */ public function getImgSrc() { return $this->imgSrc; } /** * @return null|string */ public function getImgLink() { return $this->imgLink; } /** * @return bool */ public function getLinkNewTab() { return $this->linkNewTab; } public function getMessageToPost() { return [ 'author' => 'them', 'type' => 'image', 'data' => [ 'img_src' => $this->getImgSrc(), 'img_link' => $this->getImgLink(), 'link_new_tab' => $this->getLinkNewTab() ] ]; } }
<?php namespace actsmart\actsmart\Actuators\WebChat; class WebChatImageMessage extends WebChatMessage { private $imgSrc = null; private $imgLink = null; /** * @param $imgSrc * @return $this */ public function setImgSrc($imgSrc) { $this->imgSrc = $imgSrc; return $this; } /** * @param $imgLink * @return $this */ public function setImgLink($imgLink) { $this->imgLink = $imgLink; return $this; } /** * @return null|string */ public function getImgSrc() { return $this->imgSrc; } /** * @return null|string */ public function getImgLink() { return $this->imgLink; } public function getMessageToPost() { return [ 'author' => 'them', 'type' => 'image', 'data' => [ 'img_src' => $this->getImgSrc(), 'img_link' => $this->getImgLink() ] ]; } }
Delete `randomSample()' because it is no longer used.
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen # Alias class name in order to provide a more intuitive API. new = PacketMorpher
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen def randomSample( self ): """Return a random sample of the stored probability distribution.""" return self.dist.randomSample() # Alias class name in order to provide a more intuitive API. new = PacketMorpher
Update to use Google Aviator test log
import os import base64 from requests import Session, Request from OpenSSL import crypto url = 'http://ct.googleapis.com/aviator/ct/v1/get-roots' s = Session() r = Request('GET', url) prepped = r.prepare() r = s.send(prepped) if r.status_code == 200: roots = r.json() # RFC 6962 defines the certificate objects as base64 encoded certs. # Importantly, these are not PEM formatted certs but base64 encoded # ASN.1 (DER) encoded for i in roots: certs = roots[i] for k in certs: try: certobj = crypto.load_certificate(crypto.FILETYPE_ASN1,base64.b64decode(k)) subject = certobj.get_subject() print 'CN={},OU={},O={},L={},S={},C={}'.format(subject.commonName, subject.organizationalUnitName, subject.organizationName, subject.localityName, subject.stateOrProvinceName, subject.countryName) except: print subject.get_components()
import os import base64 from requests import Session, Request from OpenSSL import crypto #url = 'http://ct.googleapis.com/aviator/ct/v1/get-roots' url = 'https://ct.api.venafi.com/ct/v1/get-roots' s = Session() r = Request('GET', url) prepped = r.prepare() r = s.send(prepped) if r.status_code == 200: roots = r.json() # RFC 6962 defines the certificate objects as base64 encoded certs. # Importantly, these are not PEM formatted certs but base64 encoded # ASN.1 (DER) encoded for i in roots: certs = roots[i] for k in certs: try: certobj = crypto.load_certificate(crypto.FILETYPE_ASN1,base64.b64decode(k)) subject = certobj.get_subject() print 'CN={},OU={},O={},L={},S={},C={}'.format(subject.commonName, subject.organizationalUnitName, subject.organizationName, subject.localityName, subject.stateOrProvinceName, subject.countryName) except: print subject.get_components()
Use adapter position instead of layout params position as causing IndexOutOfBoundsException otherwise
package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.content.Context; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; import com.veyndan.redditclient.post.DepthCalculatorDelegate; public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration { @Px private final int childInsetMultiplier; public TreeInsetItemDecoration(@NonNull final Context context, @DimenRes final int childInsetMultiplierRes) { childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes); } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { if (parent.getAdapter() instanceof DepthCalculatorDelegate) { final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter(); final int position = parent.getChildAdapterPosition(view); final int inset = position == RecyclerView.NO_POSITION ? 0 : depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier; outRect.set(inset, 0, 0, 0); } else { throw new IllegalStateException("RecyclerView's Adapter must implement " + "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " + "a decoration"); } } }
package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.content.Context; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; import com.veyndan.redditclient.post.DepthCalculatorDelegate; public class TreeInsetItemDecoration extends RecyclerView.ItemDecoration { @Px private final int childInsetMultiplier; public TreeInsetItemDecoration(@NonNull final Context context, @DimenRes final int childInsetMultiplierRes) { childInsetMultiplier = context.getResources().getDimensionPixelOffset(childInsetMultiplierRes); } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { if (parent.getAdapter() instanceof DepthCalculatorDelegate) { final DepthCalculatorDelegate depthCalculatorDelegate = (DepthCalculatorDelegate) parent.getAdapter(); final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams(); final int position = layoutParams.getViewLayoutPosition(); final int inset = depthCalculatorDelegate.depthForPosition(position) * childInsetMultiplier; outRect.set(inset, 0, 0, 0); } else { throw new IllegalStateException("RecyclerView's Adapter must implement " + "DepthCalculatorDelegate in order for TreeInsetItemDecoration to be used as " + "a decoration"); } } }
Load babel polyfills, to work in less ES6 ready browsers.
import React from 'react'; import 'babel/polyfill'; import Logo from './components/logo' import SocialButtons from './components/social-buttons' import Navigation from './components/navigation' import Home from './components/home'; import Footer from './components/footer'; import AppUrl from './appurl' class Page { render() { let appUrl = new AppUrl(); const siteComponent = this.props.siteComponent; return ( <div id="wrapper" className="pure-g"> <header className="pure-u-2-3"> <Logo/> <SocialButtons/> <Navigation appUrl={appUrl} /> </header> {siteComponent} <Footer /> </div> ) } } const rerender = (siteComponent = <Home />) => { React.render(<Page siteComponent={siteComponent} />, document.getElementById('app')); }; import {parse as parseUrl} from 'url'; import Chronicle from './lexicon/chronicle' window.addEventListener('hashchange', ({newURL: newUrl}) => { const parsedUrl = parseUrl(newUrl); processUrl(parsedUrl); }); function processUrl(parsedUrl) { if (parsedUrl && parsedUrl.hash && parsedUrl.hash.startsWith('#/')) { if (parsedUrl.hash.match(/^#\/chronicle/)) { Chronicle.componentWithData((chronicleComponent) => { rerender(chronicleComponent); }); } } else { rerender(<Home />); } } processUrl();
import React from 'react'; import Logo from './components/logo' import SocialButtons from './components/social-buttons' import Navigation from './components/navigation' import Home from './components/home'; import Footer from './components/footer'; import AppUrl from './appurl' class Page { render() { let appUrl = new AppUrl(); const siteComponent = this.props.siteComponent; return ( <div id="wrapper" className="pure-g"> <header className="pure-u-2-3"> <Logo/> <SocialButtons/> <Navigation appUrl={appUrl} /> </header> {siteComponent} <Footer /> </div> ) } } const rerender = (siteComponent = <Home />) => { React.render(<Page siteComponent={siteComponent} />, document.getElementById('app')); }; import {parse as parseUrl} from 'url'; import Chronicle from './lexicon/chronicle' window.addEventListener('hashchange', ({newURL: newUrl}) => { const parsedUrl = parseUrl(newUrl); processUrl(parsedUrl); }); function processUrl(parsedUrl) { if (parsedUrl && parsedUrl.hash && parsedUrl.hash.startsWith('#/')) { if (parsedUrl.hash.match(/^#\/chronicle/)) { Chronicle.componentWithData((chronicleComponent) => { rerender(chronicleComponent); }); } } else { rerender(<Home />); } } processUrl();
Move tokens null check to method.
<?php namespace Symfony\Upgrade\Fixer; use Symfony\CS\Tokenizer\Token; use Symfony\CS\Tokenizer\Tokens; class FormGetnameToGetblockprefixFixer extends FormTypeFixer { /** * {@inheritdoc} */ public function fix(\SplFileInfo $file, $content) { $tokens = Tokens::fromCode($content); if ($this->isFormType($tokens)) { $this->fixGetNameMethod($tokens); } return $tokens->generateCode(); } private function matchGetNameMethod(Tokens $tokens) { return $tokens->findSequence([ [T_PUBLIC, 'public'], [T_FUNCTION], [T_STRING, 'getName'], '(', ')' ]); } private function fixGetNameMethod(Tokens $tokens) { $matchedTokens = $this->matchGetNameMethod($tokens); if (null === $matchedTokens) { return; } $matchedIndexes = array_keys($matchedTokens); $matchedIndex = $matchedIndexes[count($matchedIndexes) - 3]; $matchedTokens[$matchedIndex]->setContent('getBlockPrefix'); } /** * {@inheritdoc} */ public function getDescription() { return 'The method FormTypeInterface::getName() was deprecated, you should now implement FormTypeInterface::getBlockPrefix() instead.'; } }
<?php namespace Symfony\Upgrade\Fixer; use Symfony\CS\Tokenizer\Token; use Symfony\CS\Tokenizer\Tokens; class FormGetnameToGetblockprefixFixer extends FormTypeFixer { /** * @inheritdoc */ public function fix(\SplFileInfo $file, $content) { $tokens = Tokens::fromCode($content); if ($this->isFormType($tokens) && null !== $this->matchGetNameMethod($tokens)) { $this->fixGetNameMethod($tokens); } return $tokens->generateCode(); } private function matchGetNameMethod(Tokens $tokens) { return $tokens->findSequence([ [T_PUBLIC, 'public'], [T_FUNCTION], [T_STRING, 'getName'], '(', ')' ]); } private function fixGetNameMethod(Tokens $tokens) { $matchedTokens = $this->matchGetNameMethod($tokens); $matchedIndexes = array_keys($matchedTokens); $matchedIndex = $matchedIndexes[count($matchedIndexes) - 3]; $matchedTokens[$matchedIndex]->setContent('getBlockPrefix'); } /** * @inheritdoc */ public function getDescription() { return 'The method FormTypeInterface::getName() was deprecated, you should now implement FormTypeInterface::getBlockPrefix() instead.'; } }
Use more updated api methods
/* Collapse remember * Use a cookie to "remember" the state of bootstrap collapse divs * use the 'collapse-remember' class to get this functionality */ $(document).ready(function () { const state_cookie_c = 'collapse-remember'; var page = window.location.pathname; var state = Cookies.getJSON(state_cookie_c); if (state === undefined) { state = {}; Cookies.set(state_cookie_c, state); } if (state.hasOwnProperty(page)) { Object.keys(state[page]).forEach(function (collapse_id) { if (state[page][collapse_id]) { console.log('showing: '+collapse_id); $('#'+collapse_id).collapse('show'); } }); } $(".collapse-remember").on('show.bs.collapse', function () { state = Cookies.getJSON(state_cookie_c); if (state[page] === undefined) { state[page] = {}; } var id = $(this).attr('id'); console.log('Shown: ' + id); state[page][id] = true; Cookies.set(state_cookie_c, state); }); $(".collapse-remember").on('hide.bs.collapse', function () { state = Cookies.getJSON(state_cookie_c); if (state[page] === undefined) { state[page] = {}; } var id = $(this).attr('id'); console.log('Hidden: ' + id); state[page][id] = false; Cookies.set(state_cookie_c, state); }); });
/* Collapse remember * Use a cookie to "remember" the state of bootstrap collapse divs * use the 'collapse-remember' class to get this functionality */ $(document).ready(function () { const state_cookie_c = 'collapse-remember'; var page = window.location.pathname; var state = Cookies.getJSON(state_cookie_c); if (state === undefined) { state = {}; Cookies.set(state_cookie_c, state); } if (state.hasOwnProperty(page)) { Object.keys(state[page]).forEach(function (collapse_id) { if (state[page][collapse_id]) { console.log('showing: '+collapse_id); $('#'+collapse_id).addClass('show'); } }); } $(".collapse-remember").on('shown.bs.collapse', function () { state = Cookies.getJSON(state_cookie_c); if (state[page] === undefined) { state[page] = {}; } var id = $(this).attr('id'); console.log('Shown: ' + id); state[page][id] = true; Cookies.set(state_cookie_c, state); }); $(".collapse-remember").on('hidden.bs.collapse', function () { state = Cookies.getJSON(state_cookie_c); if (state[page] === undefined) { state[page] = {}; } var id = $(this).attr('id'); console.log('Hidden: ' + id); state[page][id] = false; Cookies.set(state_cookie_c, state); }); });
Fix thread-safety issue in stagecraft Django middleware is not thread-safe. We should store this context on the request object instance. Django always calls `process_response`, but it is possible that `process_request` has been skipped. So we have a guard checking that it’s safe to log the response time. See https://docs.djangoproject.com/en/1.7/topics/http/middleware/#process_request
# encoding: utf-8 from __future__ import unicode_literals import logging import time logger = logging.getLogger(__name__) class RequestLoggerMiddleware(object): def process_request(self, request): request.start_request_time = time.time() logger.info("{method} {path}".format( method=request.method, path=request.get_full_path()), extra={ 'request_method': request.method, 'http_host': request.META.get('HTTP_HOST'), 'http_path': request.get_full_path(), 'request_id': request.META.get('HTTP_REQUEST_ID') }) def process_response(self, request, response): if hasattr(request, 'start_request_time'): elapsed_time = time.time() - request.start_request_time logger.info("{method} {path} : {status} {secs:.6f}s".format( method=request.method, path=request.get_full_path(), status=response.status_code, secs=elapsed_time), extra={ 'request_method': request.method, 'http_host': request.META.get('HTTP_HOST'), 'http_path': request.get_full_path(), 'status': response.status_code, 'request_time': elapsed_time, }) return response
# encoding: utf-8 from __future__ import unicode_literals import logging import time logger = logging.getLogger(__name__) class RequestLoggerMiddleware(object): def process_request(self, request): self.request_time = time.time() logger.info("{method} {path}".format( method=request.method, path=request.get_full_path()), extra={ 'request_method': request.method, 'http_host': request.META.get('HTTP_HOST'), 'http_path': request.get_full_path(), 'request_id': request.META.get('HTTP_REQUEST_ID') }) def process_response(self, request, response): elapsed_time = time.time() - self.request_time logger.info("{method} {path} : {status} {secs:.6f}s".format( method=request.method, path=request.get_full_path(), status=response.status_code, secs=elapsed_time), extra={ 'request_method': request.method, 'http_host': request.META.get('HTTP_HOST'), 'http_path': request.get_full_path(), 'status': response.status_code, 'request_time': elapsed_time, }) return response
Split out 'test' from 'jshint' subcommands in grunt
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'lib/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, tape: { options: { pretty: true, output: 'console' }, //files: ['test/**/*.js'] files: ['test/test.js'] }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] }, doxx: { all: { src: 'lib', target: 'docs', options: { title: 'LineRate Node.js REST API module', template: 'doxx.jade', readme: 'README.md' } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-doxx'); grunt.loadNpmTasks('grunt-tape'); grunt.registerTask('test', ['tape']); grunt.registerTask('jshint', ['jshint']); grunt.registerTask('default', ['jshint', 'tape', 'doxx']); };
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'lib/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, tape: { options: { pretty: true, output: 'console' }, //files: ['test/**/*.js'] files: ['test/test.js'] }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] }, doxx: { all: { src: 'lib', target: 'docs', options: { title: 'LineRate Node.js REST API module', template: 'doxx.jade', readme: 'README.md' } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-doxx'); grunt.loadNpmTasks('grunt-tape'); grunt.registerTask('test', ['jshint', 'tape']); grunt.registerTask('default', ['jshint', 'tape', 'doxx']); };
Decrease retry delay in fault tolerant execution tests Some tests are written to fail with an external failure what causes tasks being retried several times.
/* * 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 io.trino.testing; import com.google.common.collect.ImmutableMap; import java.util.Map; public final class FaultTolerantExecutionConnectorTestHelper { private FaultTolerantExecutionConnectorTestHelper() {} public static Map<String, String> getExtraProperties() { return ImmutableMap.<String, String>builder() .put("retry-policy", "TASK") .put("retry-initial-delay", "50ms") .put("retry-max-delay", "100ms") .put("fault-tolerant-execution-partition-count", "5") .put("fault-tolerant-execution-target-task-input-size", "10MB") .put("fault-tolerant-execution-target-task-split-count", "4") // to trigger spilling .put("exchange.deduplication-buffer-size", "1kB") .put("fault-tolerant-execution-task-memory", "1GB") .buildOrThrow(); } }
/* * 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 io.trino.testing; import com.google.common.collect.ImmutableMap; import java.util.Map; public final class FaultTolerantExecutionConnectorTestHelper { private FaultTolerantExecutionConnectorTestHelper() {} public static Map<String, String> getExtraProperties() { return ImmutableMap.<String, String>builder() .put("retry-policy", "TASK") .put("fault-tolerant-execution-partition-count", "5") .put("fault-tolerant-execution-target-task-input-size", "10MB") .put("fault-tolerant-execution-target-task-split-count", "4") // to trigger spilling .put("exchange.deduplication-buffer-size", "1kB") .put("fault-tolerant-execution-task-memory", "1GB") .buildOrThrow(); } }
Add control when creating a new refresh token and there is no refresh_token key in the response
<?php namespace Edujugon\GoogleAds\Console; use Edujugon\GoogleAds\Auth\OAuth2; use Illuminate\Console\Command; class RefreshTokenCommand extends Command { /** * Console command signature * * @var string */ protected $signature = 'googleads:token:generate'; /** * Description * * @var string */ protected $description = 'Generate a new refresh token for Google Adwords API'; /** * Generate refresh token * */ public function handle() { $oAth2 = (new OAuth2())->build(); $authorizationUrl = $oAth2->buildFullAuthorizationUri(); // Show authorization URL $this->line(sprintf( "Log into the Google account you use for AdWords and visit the following URL:\n%s", $authorizationUrl )); // Retrieve token $accessToken = $this->ask('After approving the token enter the authorization code here:'); $oAth2->setCode($accessToken); $authToken = $oAth2->fetchAuthToken(); if (!array_key_exists('refresh_token', $authToken)) { $this->error('Couldn\'t find refresh_token key in the response.'); $this->comment('Below you can check the whole response:'); $this->line(json_encode($authToken)); return; } $this->comment('Copy the refresh token in your googleads configuration file (config/google-ads.php)'); // Print refresh token $this->line(sprintf( 'Refresh token: "%s"', $authToken['refresh_token'] )); } }
<?php namespace Edujugon\GoogleAds\Console; use Edujugon\GoogleAds\Auth\OAuth2; use Illuminate\Console\Command; class RefreshTokenCommand extends Command { /** * Console command signature * * @var string */ protected $signature = 'googleads:token:generate'; /** * Description * * @var string */ protected $description = 'Generate a new refresh token for Google Adwords API'; /** * Generate refresh token * */ public function handle() { $oAth2 = (new OAuth2())->build(); $authorizationUrl = $oAth2->buildFullAuthorizationUri(); // Show authorization URL $this->line(sprintf( "Log into the Google account you use for AdWords and visit the following URL:\n%s", $authorizationUrl )); // Retrieve token $accessToken = $this->ask('After approving the token enter the authorization code here:'); $oAth2->setCode($accessToken); $authToken = $oAth2->fetchAuthToken(); $this->comment('Copy the refresh token in your googleads configuration file (config/google-ads.php)'); // Print refresh token $this->line(sprintf( 'Refresh token: "%s"', $authToken['refresh_token'] )); } }
Fix text to prove that behavior
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock from exam import fixture from sentry.testutils import TestCase from sentry.interfaces import User from sentry.models import Event class UserTest(TestCase): @fixture def event(self): return mock.Mock(spec=Event()) @fixture def interface(self): return User(id=1, email='[email protected]', favorite_color='brown') def test_serialize_behavior(self): assert self.interface.serialize() == { 'id': 1, 'username': None, 'email': '[email protected]', 'ip_address': None, 'data': {'favorite_color': 'brown'} } @mock.patch('sentry.interfaces.render_to_string') def test_to_html(self, render_to_string): interface = User(**self.interface.serialize()) interface.to_html(self.event) render_to_string.assert_called_once_with('sentry/partial/interfaces/user.html', { 'is_public': False, 'event': self.event, 'user_ip_address': None, 'user_id': 1, 'user_username': None, 'user_email': '[email protected]', 'user_data': {'favorite_color': 'brown'}, }) def test_to_html_public(self): result = self.interface.to_html(self.event, is_public=True) assert result == ''
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock from exam import fixture from sentry.testutils import TestCase from sentry.interfaces import User from sentry.models import Event class UserTest(TestCase): @fixture def event(self): return mock.Mock(spec=Event()) @fixture def interface(self): return User(id=1, email='[email protected]', favorite_color='brown') def test_serialize_behavior(self): assert self.interface.serialize() == { 'id': 1, 'username': None, 'email': '[email protected]', 'ip_address': None, 'data': {'favorite_color': 'brown'} } @mock.patch('sentry.interfaces.render_to_string') def test_to_html(self, render_to_string): self.interface.to_html(self.event) render_to_string.assert_called_once_with('sentry/partial/interfaces/user.html', { 'is_public': False, 'event': self.event, 'user_ip_address': None, 'user_id': 1, 'user_username': None, 'user_email': '[email protected]', 'user_data': {'favorite_color': 'brown'}, }) def test_to_html_public(self): result = self.interface.to_html(self.event, is_public=True) assert result == ''
Allow bypassing body payload directly
const Errors = require('./../../errors'); const Message = require('./../index'); const JSON_CONTENT_TYPE = "application/json"; Message.request.addInterceptor(requestInterceptorBodyParser); function requestInterceptorBodyParser() { return new Promise((resolve, reject) => { let body = []; this.request.__request__ .on('error', error => { reject(new Errors.Fatal(error)); }) .on('data', chunk => { body.push(chunk); }) .on('end', data => { body = data || Buffer.concat(body).toString(); if(body == ''){ resolve(); } switch (this.request.headers['content-type']) { case JSON_CONTENT_TYPE: try{ resolve(JSONBodyParser(body, this.request)); }catch(error){ reject(error); } break; default: reject(new Errors.Fatal("Incorrect Content-Type of the request. Expected 'application/json'.")); } }); }); } function JSONBodyParser(body, messageRequest) { try { body && (messageRequest.body = JSON.parse(body)); } catch (error){ throw new Errors.BadRequest("Invalid JSON in request body."); } }
const Errors = require('./../../errors'); const Message = require('./../index'); const JSON_CONTENT_TYPE = "application/json"; Message.request.addInterceptor(requestInterceptorBodyParser); function requestInterceptorBodyParser() { return new Promise((resolve, reject) => { let body = []; this.request.__request__ .on('error', error => { reject(new Errors.Fatal(error)); }) .on('data', chunk => { body.push(chunk); }) .on('end', () => { body = Buffer.concat(body).toString(); if(body == ''){ resolve(); } switch (this.request.headers['content-type']) { case JSON_CONTENT_TYPE: try{ resolve(JSONBodyParser(body, this.request)); }catch(error){ reject(error); } break; default: reject(new Errors.Fatal("Incorrect Content-Type of the request. Expected 'application/json'.")); } }); }); } function JSONBodyParser(body, messageRequest) { try { body && (messageRequest.body = JSON.parse(body)); } catch (error){ throw new Errors.BadRequest("Invalid JSON in request body."); } }
Fix integrity error reusing db in tests Base `setUpClass` needs to be called first so the transaction is initialized before we mutate the data. This solves a conflic raised when using `--reuse-db`.
from django.contrib.auth.models import User from django.test import TestCase, override_settings class TestLanguageSwitching(TestCase): @classmethod def setUpClass(cls): super(TestLanguageSwitching, cls).setUpClass() User.objects.create_user( username="admin", password="admin", email="[email protected]" ) def setUp(self): self.client.login(username="admin", password="admin") def test_displays_language_form(self): self.client.get("/administration/language/") self.assertTemplateUsed("language_form.html") @override_settings(LANGUAGE_CODE="es") def test_selects_correct_language_on_form(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="es-es") def test_falls_back_to_generic_language(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="en-us") def test_switch_language(self): response = self.client.post( "/i18n/setlang/", {"language": "fr", "next": "/administration/language/"}, follow=True, ) assert response.context["language_selection"] == "fr"
from django.contrib.auth.models import User from django.test import TestCase, override_settings class TestLanguageSwitching(TestCase): @classmethod def setUpClass(cls): User.objects.create_user( username="admin", password="admin", email="[email protected]" ) super(TestLanguageSwitching, cls).setUpClass() def setUp(self): self.client.login(username="admin", password="admin") def test_displays_language_form(self): self.client.get("/administration/language/") self.assertTemplateUsed("language_form.html") @override_settings(LANGUAGE_CODE="es") def test_selects_correct_language_on_form(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="es-es") def test_falls_back_to_generic_language(self): response = self.client.get("/administration/language/") assert response.context["language_selection"] == "es" @override_settings(LANGUAGE_CODE="en-us") def test_switch_language(self): response = self.client.post( "/i18n/setlang/", {"language": "fr", "next": "/administration/language/"}, follow=True, ) assert response.context["language_selection"] == "fr"
Delete to existing constructor and fix typo
// Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.ReferenceFieldValue; public class ReferenceDataType extends DataType { private final DocumentType targetType; public ReferenceDataType(DocumentType targetType, int id) { super(buildTypeName(targetType), id); this.targetType = targetType; } private ReferenceDataType(DocumentType targetType) { this(targetType, buildTypeName(targetType).hashCode()); } private static String buildTypeName(DocumentType targetType) { return "Reference<" + targetType.getName() + ">"; } // Creates a new type where the numeric ID is based on the hash of targetType public static ReferenceDataType createWithInferredId(DocumentType targetType) { return new ReferenceDataType(targetType); } public DocumentType getTargetType() { return targetType; } @Override public ReferenceFieldValue createFieldValue() { return new ReferenceFieldValue(this); } @Override public Class<? extends ReferenceFieldValue> getValueClass() { return ReferenceFieldValue.class; } @Override public boolean isValueCompatible(FieldValue value) { if (value == null) { return false; } if (!ReferenceFieldValue.class.isAssignableFrom(value.getClass())) { return false; } ReferenceFieldValue rhs = (ReferenceFieldValue)value; return rhs.getDataType().equals(this); } }
// Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.ReferenceFieldValue; public class ReferenceDataType extends DataType { private final DocumentType targetType; public ReferenceDataType(DocumentType targetType, int id) { super(buildTypeName(targetType), id); this.targetType = targetType; } private ReferenceDataType(DocumentType targetType) { super(buildTypeName(targetType), 0); setId(getName().hashCode()); this.targetType = targetType; } private static String buildTypeName(DocumentType targetType) { return "Reference<" + targetType.getName() + ">"; } // Creates a new type where the numeric ID is based no the hash of targetType public static ReferenceDataType createWithInferredId(DocumentType targetType) { return new ReferenceDataType(targetType); } public DocumentType getTargetType() { return targetType; } @Override public ReferenceFieldValue createFieldValue() { return new ReferenceFieldValue(this); } @Override public Class<? extends ReferenceFieldValue> getValueClass() { return ReferenceFieldValue.class; } @Override public boolean isValueCompatible(FieldValue value) { if (value == null) { return false; } if (!ReferenceFieldValue.class.isAssignableFrom(value.getClass())) { return false; } ReferenceFieldValue rhs = (ReferenceFieldValue)value; return rhs.getDataType().equals(this); } }
Use spaces instead of tabs
angular .module('ngSharepoint.Lists') .factory('Query', function() { var Query = function() { //this.__queries = {}; }; Query.prototype.unpackItem = function(item) { var query = this; var obj = {}; if (Array.isArray(query.__values)) { query.__values.forEach(function(key) { var value = item.get_item(key); obj[key] = query.__trim(value); }); }else { Object.getOwnPropertyNames(query.__values).forEach(function(key) { var value = item.get_item(key); obj[key] = query.__trim(value); }); } return obj; }; Query.prototype.packItem = function(item) { var query = this; Object.getOwnPropertyNames(query.__values).forEach(function(key) { item.set_item(key, query.__trim(query.__values[key])); }); }; Query.prototype.then = function(success, reject) { return this.__execute().then(success, reject); }; Query.prototype.__trim = function(value) { if (value !== null && value !== undefined && typeof value === 'string') { return value.trim(); }else { return value; } }; return (Query); });
angular .module('ngSharepoint.Lists') .factory('Query', function() { var Query = function() { //this.__queries = {}; }; Query.prototype.unpackItem = function(item) { var query = this; var obj = {}; if (Array.isArray(query.__values)) { query.__values.forEach(function(key) { var value = item.get_item(key); obj[key] = query.__trim(value); }); }else { Object.getOwnPropertyNames(query.__values).forEach(function(key) { var value = item.get_item(key); obj[key] = query.__trim(value); }); } return obj; }; Query.prototype.packItem = function(item) { var query = this; Object.getOwnPropertyNames(query.__values).forEach(function(key) { item.set_item(key, query.__trim(query.__values[key])); }); }; Query.prototype.then = function(success, reject) { return this.__execute().then(success, reject); }; Query.prototype.__trim = function(value) { if (value !== null && value !== undefined && typeof value === 'string') { return value.trim(); }else { return value; } }; return (Query); });
Fix contributor URL using id instead of username [SWIK-1953]
import React from 'react'; import {creatorAttribute} from './util/ContributorsUtil'; import {contains} from './util/ContributorsUtil'; import UserPicture from '../../../common/UserPicture'; class ContributorItem extends React.Component { render() { return ( <a className="item" href={'/user/' + this.props.data.username} target='_blank'> <div className="ui image"> <UserPicture picture={ this.props.data.picture } username={ this.props.data.username } link={ false } private={ false } size={ 'mini' } avatar={ true } width= { 24 } bordered={ false } alt={'""'}/> </div> <div className="content"> <div className="description"> {this.props.data.username} </div> <div className="extra">{this.props.data.organization}</div> </div> </a> ); } } export default ContributorItem;
import React from 'react'; import {creatorAttribute} from './util/ContributorsUtil'; import {contains} from './util/ContributorsUtil'; import UserPicture from '../../../common/UserPicture'; class ContributorItem extends React.Component { render() { let link = '/user/' + this.props.data.id; let func = () => { window.open(link);return false; }; return ( <a className="item" href="#" onClick={func}> <div className="ui image"> <UserPicture picture={ this.props.data.picture } username={ this.props.data.username } link={ false } private={ false } size={ 'mini' } avatar={ true } width= { 24 } bordered={ false } alt={'""'}/> </div> <div className="content"> <div className="description"> {this.props.data.username} </div> <div className="extra">{this.props.data.organization}</div> </div> </a> ); } } export default ContributorItem;
[test] Use single quotes for consistency.
var expect = require('expect.js'), qrcode = require('./../lib/main'), sinon = require('sinon'); describe('in the main module', function() { describe('the generate method', function () { describe('when not providing a callback', function () { beforeEach(function () { sinon.stub(console, 'log'); }); afterEach(function () { sinon.sandbox.restore(); console.log.reset(); }); it('logs to the console', function () { qrcode.generate('test'); expect(console.log.called).to.be(true); }); }); describe('when providing a callback', function () { it('will call the callback', function () { var cb = sinon.spy(); qrcode.generate('test', cb); expect(cb.called).to.be(true); }); it('will not call the console.log method', function () { qrcode.generate('test', sinon.spy()); expect(console.log.called).to.be(false); }); }); describe('the QR Code', function () { it('should be a string', function (done) { qrcode.generate('test', function(result) { expect(result).to.be.a('string'); done(); }); }); it('should not end with a newline', function (done) { qrcode.generate('test', function(result) { expect(result).not.to.match(/\n$/); done(); }); }); }); }); });
var expect = require("expect.js"), qrcode = require('./../lib/main'), sinon = require("sinon"); describe('in the main module', function() { describe("the generate method", function () { describe("when not providing a callback", function () { beforeEach(function () { sinon.stub(console, "log"); }); afterEach(function () { sinon.sandbox.restore(); console.log.reset(); }); it("logs to the console", function () { qrcode.generate("test"); expect(console.log.called).to.be(true); }); }); describe("when providing a callback", function () { it("will call the callback", function () { var cb = sinon.spy(); qrcode.generate("test", cb); expect(cb.called).to.be(true); }); it("will not call the console.log method", function () { qrcode.generate("test", sinon.spy()); expect(console.log.called).to.be(false); }); }); describe("the QR Code", function () { it("should be a string", function (done) { qrcode.generate("test", function(result) { expect(result).to.be.a('string'); done(); }); }); it("should not end with a newline", function (done) { qrcode.generate("test", function(result) { expect(result).not.to.match(/\n$/); done(); }); }); }); }); });
Correct location of Protractor executable
'use strict'; var path = require('path'); var yargs = require('yargs'); var merge = require('lodash.merge'); var flatten = require('./lib/flatten'); module.exports = function(grunt) { grunt.registerMultiTask('ptor', 'Run Protractor e2e tests.', function() { var done = function() {}; if (process.env.NODE_ENV !== 'test') { done = this.async(); } // Get command line args, parse into object. var argv = yargs.argv; // Remove unneeded options. delete argv._; delete argv.$0; // Merge command line args over task-specific and/or target-specific options. var options = merge(this.options(), argv); // Yank out configFile option as this gets treated separately. var configFile = options.configFile; delete options.configFile; // Flatten options so we can pass these along to Protractor. var flattened = flatten(options); // Generate the Protractor command line args. var args = Object.keys(flattened).map(function(key) { return '--' + key + '=' + flattened[key]; }); args.unshift(configFile); // Locate protractor executable. var cmd = path.join(require.resolve('protractor'), '../../bin/protractor'); // Liftoff. grunt.util.spawn({ cmd: cmd, args: args, opts: { stdio: 'inherit' } }, function(error, result, code) { if (code) { return done(false); } done(); }); }); };
'use strict'; var path = require('path'); var yargs = require('yargs'); var merge = require('lodash.merge'); var flatten = require('./lib/flatten'); module.exports = function(grunt) { grunt.registerMultiTask('ptor', 'Run Protractor e2e tests.', function() { var done = function() {}; if (process.env.NODE_ENV !== 'test') { done = this.async(); } // Get command line args, parse into object. var argv = yargs.argv; // Remove unneeded options. delete argv._; delete argv.$0; // Merge command line args over task-specific and/or target-specific options. var options = merge(this.options(), argv); // Yank out configFile option as this gets treated separately. var configFile = options.configFile; delete options.configFile; // Flatten options so we can pass these along to Protractor. var flattened = flatten(options); // Generate the Protractor command line args. var args = Object.keys(flattened).map(function(key) { return '--' + key + '=' + flattened[key]; }); args.unshift(configFile); // Locate protractor executable. var cmd = path.join(__dirname, '../node_modules/.bin/protractor'); // Liftoff. grunt.util.spawn({ cmd: cmd, args: args, opts: { stdio: 'inherit' } }, function(error, result, code) { if (code) { return done(false); } done(); }); }); };
Remove codecov dependency because it's now a github action
"""Mailmerge build and install configuration.""" from pathlib import Path import setuptools # Read the contents of README file PROJECT_DIR = Path(__file__).parent README = PROJECT_DIR/"README.md" LONG_DESCRIPTION = README.open().read() setuptools.setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=LONG_DESCRIPTION, long_description_content_type="text/markdown", version="2.2.0", author="Andrew DeOrio", author_email="[email protected]", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "click", "jinja2", "markdown", "html5" ], extras_require={ "dev": [ "pdbpp", "twine", "tox", ], "test": [ "check-manifest", "freezegun", "pycodestyle", "pydocstyle", "pylint", "pytest", "pytest-cov", "pytest-mock", "sh", ], }, python_requires='>=3.6', entry_points={ "console_scripts": [ "mailmerge = mailmerge.__main__:main", ] }, )
"""Mailmerge build and install configuration.""" from pathlib import Path import setuptools # Read the contents of README file PROJECT_DIR = Path(__file__).parent README = PROJECT_DIR/"README.md" LONG_DESCRIPTION = README.open().read() setuptools.setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=LONG_DESCRIPTION, long_description_content_type="text/markdown", version="2.2.0", author="Andrew DeOrio", author_email="[email protected]", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "click", "jinja2", "markdown", "html5" ], extras_require={ "dev": [ "pdbpp", "twine", "tox", ], "test": [ "check-manifest", "codecov>=1.4.0", "freezegun", "pycodestyle", "pydocstyle", "pylint", "pytest", "pytest-cov", "pytest-mock", "sh", ], }, python_requires='>=3.6', entry_points={ "console_scripts": [ "mailmerge = mailmerge.__main__:main", ] }, )
Fix passing sets to batchable methods Sets don't support indexing, so convert them to lists.
import functools ITERABLE_TYPES = ( list, set, tuple, ) try: from numpy import ndarray ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,) except ImportError: pass def isiterable(v): return isinstance(v, ITERABLE_TYPES) def batchable(func=None, batch_size=100): def do_batch(*args, **kwargs): _batch_size = kwargs.pop('batch_size', batch_size) if isiterable(args[0]): _self = None to_batch = args[0] args = args[1:] else: _self = args[0] to_batch = args[1] args = args[2:] if not isiterable(to_batch): to_batch = [to_batch] if isinstance(to_batch, set): to_batch = list(to_batch) for _batch in [ to_batch[i:i+_batch_size] for i in xrange(0, len(to_batch), _batch_size) ]: if _self is None: func(_batch, *args, **kwargs) else: func(_self, _batch, *args, **kwargs) if func is None: return functools.partial(batchable, batch_size=batch_size) return do_batch
import functools ITERABLE_TYPES = ( list, set, tuple, ) try: from numpy import ndarray ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,) except ImportError: pass def isiterable(v): return isinstance(v, ITERABLE_TYPES) def batchable(func=None, batch_size=100): def do_batch(*args, **kwargs): _batch_size = kwargs.pop('batch_size', batch_size) if isiterable(args[0]): _self = None to_batch = args[0] args = args[1:] else: _self = args[0] to_batch = args[1] args = args[2:] if not isiterable(to_batch): to_batch = [to_batch] for _batch in [ to_batch[i:i+_batch_size] for i in xrange(0, len(to_batch), _batch_size) ]: if _self is None: func(_batch, *args, **kwargs) else: func(_self, _batch, *args, **kwargs) if func is None: return functools.partial(batchable, batch_size=batch_size) return do_batch
Change arrow function to an IE11 compatible function Imports https://github.com/api-platform/core/pull/2899 and fixes https://github.com/nelmio/NelmioApiDocBundle/issues/1517
// This file is part of the API Platform project. // // (c) Kévin Dunglas <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. window.onload = function() { const data = JSON.parse(document.getElementById('swagger-data').innerText); const ui = SwaggerUIBundle({ spec: data.spec, dom_id: '#swagger-ui', validatorUrl: null, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: 'StandaloneLayout' }); const storageKey = 'nelmio_api_auth'; // if we have auth in storage use it if (sessionStorage.getItem(storageKey)) { try { ui.authActions.authorize(JSON.parse(sessionStorage.getItem(storageKey))); } catch (ignored) { // catch any errors here so it does not stop script execution } } // hook into authorize to store the auth in local storage when user performs authorization const currentAuthorize = ui.authActions.authorize; ui.authActions.authorize = function (payload) { sessionStorage.setItem(storageKey, JSON.stringify(payload)); return currentAuthorize(payload); }; // hook into logout to clear auth from storage if user logs out const currentLogout = ui.authActions.logout; ui.authActions.logout = function (payload) { sessionStorage.removeItem(storageKey); return currentLogout(payload); }; window.ui = ui; };
// This file is part of the API Platform project. // // (c) Kévin Dunglas <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. window.onload = () => { const data = JSON.parse(document.getElementById('swagger-data').innerText); const ui = SwaggerUIBundle({ spec: data.spec, dom_id: '#swagger-ui', validatorUrl: null, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: 'StandaloneLayout' }); const storageKey = 'nelmio_api_auth'; // if we have auth in storage use it if (sessionStorage.getItem(storageKey)) { try { ui.authActions.authorize(JSON.parse(sessionStorage.getItem(storageKey))); } catch (ignored) { // catch any errors here so it does not stop script execution } } // hook into authorize to store the auth in local storage when user performs authorization const currentAuthorize = ui.authActions.authorize; ui.authActions.authorize = function (payload) { sessionStorage.setItem(storageKey, JSON.stringify(payload)); return currentAuthorize(payload); }; // hook into logout to clear auth from storage if user logs out const currentLogout = ui.authActions.logout; ui.authActions.logout = function (payload) { sessionStorage.removeItem(storageKey); return currentLogout(payload); }; window.ui = ui; };
Raise TypeError if positional batchable argument is missing e.g. if it's erroneously been passed as a named argument.
from __future__ import absolute_import, division, print_function from builtins import range import functools ITERABLE_TYPES = ( list, set, tuple, ) MISSING_POSITIONAL_ERR = 'Required positional argument (pos 1) not found' try: from numpy import ndarray ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,) except ImportError: pass def isiterable(v): return isinstance(v, ITERABLE_TYPES) def batchable(func=None, batch_size=100): def do_batch(*args, **kwargs): if len(args) == 0: raise TypeError(MISSING_POSITIONAL_ERR) _batch_size = kwargs.pop('batch_size', batch_size) if isiterable(args[0]): _self = None to_batch = args[0] args = args[1:] else: if len(args) == 1: raise TypeError(MISSING_POSITIONAL_ERR) _self = args[0] to_batch = args[1] args = args[2:] if not isiterable(to_batch): to_batch = [to_batch] if isinstance(to_batch, set): to_batch = list(to_batch) for _batch in [ to_batch[i:i+_batch_size] for i in range(0, len(to_batch), _batch_size) ]: if _self is None: func(_batch, *args, **kwargs) else: func(_self, _batch, *args, **kwargs) if func is None: return functools.partial(batchable, batch_size=batch_size) return do_batch
from __future__ import absolute_import, division, print_function from builtins import range import functools ITERABLE_TYPES = ( list, set, tuple, ) try: from numpy import ndarray ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,) except ImportError: pass def isiterable(v): return isinstance(v, ITERABLE_TYPES) def batchable(func=None, batch_size=100): def do_batch(*args, **kwargs): _batch_size = kwargs.pop('batch_size', batch_size) if isiterable(args[0]): _self = None to_batch = args[0] args = args[1:] else: _self = args[0] to_batch = args[1] args = args[2:] if not isiterable(to_batch): to_batch = [to_batch] if isinstance(to_batch, set): to_batch = list(to_batch) for _batch in [ to_batch[i:i+_batch_size] for i in range(0, len(to_batch), _batch_size) ]: if _self is None: func(_batch, *args, **kwargs) else: func(_self, _batch, *args, **kwargs) if func is None: return functools.partial(batchable, batch_size=batch_size) return do_batch
Support all Apollo's subscriptions transport sub-protocol
<?php namespace Siler\Graphql; use Ratchet\ConnectionInterface; use Ratchet\MessageComponentInterface; use Ratchet\WebSocket\WsServerInterface; use Siler\Graphql; class SubscriptionServer implements MessageComponentInterface, WsServerInterface { protected $manager; public function __construct(SubscriptionManager $manager) { $this->manager = $manager; } public function onOpen(ConnectionInterface $conn) { } public function onMessage(ConnectionInterface $conn, $message) { $data = json_decode($message, true); switch ($data['type']) { case Graphql\INIT: return $this->manager->handleInit($conn); case Graphql\SUBSCRIPTION_START: return $this->manager->handleSubscriptionStart($conn, $data); case Graphql\SUBSCRIPTION_DATA: return $this->manager->handleSubscriptionData($data); case Graphql\SUBSCRIPTION_END: return $this->manager->handleSubscriptionEnd($conn, $data); } } public function onClose(ConnectionInterface $conn) { } public function onError(ConnectionInterface $conn, \Exception $exception) { } public function getSubProtocols() { return ['graphql-ws', 'graphql-subscriptions']; } }
<?php namespace Siler\Graphql; use Ratchet\ConnectionInterface; use Ratchet\MessageComponentInterface; use Ratchet\WebSocket\WsServerInterface; use Siler\Graphql; class SubscriptionServer implements MessageComponentInterface, WsServerInterface { protected $manager; public function __construct(SubscriptionManager $manager) { $this->manager = $manager; } public function onOpen(ConnectionInterface $conn) { } public function onMessage(ConnectionInterface $conn, $message) { $data = json_decode($message, true); switch ($data['type']) { case Graphql\INIT: return $this->manager->handleInit($conn); case Graphql\SUBSCRIPTION_START: return $this->manager->handleSubscriptionStart($conn, $data); case Graphql\SUBSCRIPTION_DATA: return $this->manager->handleSubscriptionData($data); case Graphql\SUBSCRIPTION_END: return $this->manager->handleSubscriptionEnd($conn, $data); } } public function onClose(ConnectionInterface $conn) { } public function onError(ConnectionInterface $conn, \Exception $exception) { } public function getSubProtocols() { return ['graphql-subscriptions']; } }
JBEHAVE-243: Verify content of table as string. git-svn-id: 1c3b30599278237804f5418c838e2a3e6391d478@1570 df8dfae0-ecdd-0310-b8d8-a050f7ac8317
package org.jbehave.scenario.definition; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ExamplesTableBehaviour { String tableAsString = "|one|two|\n" + "|11|12|\n" + "|21|22|\n"; @Test public void shouldParseTableIntoHeadersAndRows() { ExamplesTable table = new ExamplesTable(tableAsString); ensureTableContentIsParsed(table); assertEquals(tableAsString, table.toString()); } @Test public void shouldTrimTableBeforeParsing() { String untrimmedTableAsString = "\n \n" +tableAsString + "\n \n"; ExamplesTable table = new ExamplesTable(untrimmedTableAsString); ensureTableContentIsParsed(table); assertEquals(untrimmedTableAsString, table.toString()); } private void ensureTableContentIsParsed(ExamplesTable table) { assertEquals(asList("one", "two"), table.getHeaders()); assertEquals(2, table.getRows().size()); assertEquals("11", tableElement(table, 0, "one")); assertEquals("12", tableElement(table, 0, "two")); assertEquals("21", tableElement(table, 1, "one")); assertEquals("22", tableElement(table, 1, "two")); } private String tableElement(ExamplesTable table, int row, String header) { return table.getRow(row).get(header); } }
package org.jbehave.scenario.definition; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ExamplesTableBehaviour { @Test public void shouldParseTableIntoHeadersAndRows() { String tableAsString = "|one|two|\n" + "|11|12|\n" + "|21|22|\n"; ensureTableContentIsParsed(new ExamplesTable(tableAsString)); } @Test public void shouldTrimTableBeforeParsing() { String tableAsString = "|one|two|\n" + "|11|12|\n" + "|21|22|\n"; ensureTableContentIsParsed(new ExamplesTable("\n \n" +tableAsString + "\n \n")); } private void ensureTableContentIsParsed(ExamplesTable table) { assertEquals(asList("one", "two"), table.getHeaders()); assertEquals(2, table.getRows().size()); assertEquals("11", tableElement(table, 0, "one")); assertEquals("12", tableElement(table, 0, "two")); assertEquals("21", tableElement(table, 1, "one")); assertEquals("22", tableElement(table, 1, "two")); } private String tableElement(ExamplesTable table, int row, String header) { return table.getRow(row).get(header); } }
Add osm id into exportde nodes [skip ci]
const parseNode = (node) => { const parsedNode = { osmId: node.$.id, name: null, amenity: null, address: { location: { latitude: parseFloat(node.$.lat), longitude: parseFloat(node.$.lon), }, }, }; node.$children.forEach(child => { if (typeof child === 'string' || !child.$) return; switch (child.$.k) { case 'website': parsedNode.website = child.$.v; break; case 'addr:housenumber': parsedNode.address.houseNumber = child.$.v; break; case 'addr:postcode': parsedNode.address.postcode = child.$.v; break; case 'addr:street': parsedNode.address.street = child.$.v; break; case 'addr:city': parsedNode.address.city = child.$.v; break; case 'amenity': parsedNode.amenity = child.$.v; break; case 'name': parsedNode.name = child.$.v; break; case 'cuisine': parsedNode.cuisine = child.$.v; break; case 'takeaway': parsedNode.takeaway = child.$.v; break; default: break; } }) return parsedNode; }; module.exports = parseNode;
const parseNode = (node) => { const parsedNode = { name: null, amenity: null, address: { location: { latitude: parseFloat(node.$.lat), longitude: parseFloat(node.$.lon), }, }, }; node.$children.forEach(child => { if (typeof child === 'string' || !child.$) return; switch (child.$.k) { case 'website': parsedNode.website = child.$.v; break; case 'addr:housenumber': parsedNode.address.houseNumber = child.$.v; break; case 'addr:postcode': parsedNode.address.postcode = child.$.v; break; case 'addr:street': parsedNode.address.street = child.$.v; break; case 'addr:city': parsedNode.address.city = child.$.v; break; case 'amenity': parsedNode.amenity = child.$.v; break; case 'name': parsedNode.name = child.$.v; break; case 'cuisine': parsedNode.cuisine = child.$.v; break; case 'takeaway': parsedNode.takeaway = child.$.v; break; default: break; } }) return parsedNode; }; module.exports = parseNode;
Improve check for single by only issuing search once
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchDepthFirst::getVertices() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vertex){ //for each vertices if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchDepthFirst($vertex); $newVertices = $alg->getVertices(); //get all vertices of this component $components++; foreach ($newVertices as $v){ //mark the vertices of this component as visited $visitedVertices[$v->getId()] = true; } } } return $components; //return number of components } }
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmConnectedComponents::getNumberOfComponents() */ public function isSingle(){ return ($this->getNumberOfComponents() === 1); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchDepthFirst::getVertices() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vertex){ //for each vertices if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchDepthFirst($vertex); $newVertices = $alg->getVertices(); //get all vertices of this component $components++; foreach ($newVertices as $v){ //mark the vertices of this component as visited $visitedVertices[$v->getId()] = true; } } } return $components; //return number of components } }
Use uvloop because apparently it's fast.
#!/usr/bin/env python3.6 import argparse import asyncio import logging import sys from pathlib import Path from MoMMI.logsetup import setup_logs # Do this BEFORE we import master, because it does a lot of event loop stuff. if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except: pass from MoMMI.master import master def main() -> None: version = sys.version_info if version.major < 3 or (version.major == 3 and version.minor < 6): logging.critical("You need at least Python 3.6 to run MoMMI.") sys.exit(1) setup_logs() parser = argparse.ArgumentParser() parser.add_argument("--config-dir", "-c", default="./config", help="The directory to read config files from.", dest="config", type=Path) parser.add_argument("--storage-dir", "-s", default="./data", help="The directory to use for server data storage.", dest="data", type=Path) args = parser.parse_args() master.start(args.config, args.data) if __name__ == "__main__": main()
#!/usr/bin/env python3 import argparse import asyncio import logging import sys from pathlib import Path from MoMMI.logsetup import setup_logs # Do this BEFORE we import master, because it does a lot of event loop stuff. if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) from MoMMI.master import master def main() -> None: version = sys.version_info if version.major < 3 or (version.major == 3 and version.minor < 6): logging.critical("You need at least Python 3.6 to run MoMMI.") sys.exit(1) setup_logs() parser = argparse.ArgumentParser() parser.add_argument("--config-dir", "-c", default="./config", help="The directory to read config files from.", dest="config", type=Path) parser.add_argument("--storage-dir", "-s", default="./data", help="The directory to use for server data storage.", dest="data", type=Path) args = parser.parse_args() master.start(args.config, args.data) if __name__ == "__main__": main()
Remove broken reference to Image.LoaderError This exception has not existed since Willow 0.3. Type checking on the 'except' line only happens when an exception occurs, so most of the time this is harmless, but if an unrelated exception occurs here (such as that caused by a faulty filetype library: https://github.com/h2non/filetype.py/issues/130) the real exception gets masked by an AttributeError for the missing definition.
import os from functools import lru_cache from django.core.checks import Warning, register from willow.image import Image @lru_cache() def has_jpeg_support(): wagtail_jpg = os.path.join(os.path.dirname(__file__), "check_files", "wagtail.jpg") succeeded = True with open(wagtail_jpg, "rb") as f: try: Image.open(f) except IOError: succeeded = False return succeeded @lru_cache() def has_png_support(): wagtail_png = os.path.join(os.path.dirname(__file__), "check_files", "wagtail.png") succeeded = True with open(wagtail_png, "rb") as f: try: Image.open(f) except IOError: succeeded = False return succeeded @register("files") def image_library_check(app_configs, **kwargs): errors = [] if not has_jpeg_support(): errors.append( Warning( "JPEG image support is not available", hint="Check that the 'libjpeg' library is installed, then reinstall Pillow.", ) ) if not has_png_support(): errors.append( Warning( "PNG image support is not available", hint="Check that the 'zlib' library is installed, then reinstall Pillow.", ) ) return errors
import os from functools import lru_cache from django.core.checks import Warning, register from willow.image import Image @lru_cache() def has_jpeg_support(): wagtail_jpg = os.path.join(os.path.dirname(__file__), "check_files", "wagtail.jpg") succeeded = True with open(wagtail_jpg, "rb") as f: try: Image.open(f) except (IOError, Image.LoaderError): succeeded = False return succeeded @lru_cache() def has_png_support(): wagtail_png = os.path.join(os.path.dirname(__file__), "check_files", "wagtail.png") succeeded = True with open(wagtail_png, "rb") as f: try: Image.open(f) except (IOError, Image.LoaderError): succeeded = False return succeeded @register("files") def image_library_check(app_configs, **kwargs): errors = [] if not has_jpeg_support(): errors.append( Warning( "JPEG image support is not available", hint="Check that the 'libjpeg' library is installed, then reinstall Pillow.", ) ) if not has_png_support(): errors.append( Warning( "PNG image support is not available", hint="Check that the 'zlib' library is installed, then reinstall Pillow.", ) ) return errors
Use proper import from utils
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from modeltrans.manager import transform_translatable_fields from modeltrans.utils import (build_localized_fieldname, split_translated_fieldname) from tests.app.models import Blog class UtilsTest(TestCase): def test_split_translated_fieldname(self): self.assertEquals( split_translated_fieldname('title_nl'), ('title', 'nl') ) self.assertEquals( split_translated_fieldname('full_name_nl'), ('full_name', 'nl') ) def test_transform_translatable_fields(self): self.assertEquals( transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}), { 'i18n': { 'title_nl': 'foo' }, 'title': 'bar' } ) def test_build_localized_fieldname(self): self.assertEquals( build_localized_fieldname('title', 'nl'), 'title_nl' ) self.assertEquals( build_localized_fieldname('category__name', 'nl'), 'category__name_nl' )
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from modeltrans.manager import (split_translated_fieldname, transform_translatable_fields) from modeltrans.utils import build_localized_fieldname from tests.app.models import Blog class UtilsTest(TestCase): def test_split_translated_fieldname(self): self.assertEquals( split_translated_fieldname('title_nl'), ('title', 'nl') ) self.assertEquals( split_translated_fieldname('full_name_nl'), ('full_name', 'nl') ) def test_transform_translatable_fields(self): self.assertEquals( transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}), { 'i18n': { 'title_nl': 'foo' }, 'title': 'bar' } ) def test_build_localized_fieldname(self): self.assertEquals( build_localized_fieldname('title', 'nl'), 'title_nl' ) self.assertEquals( build_localized_fieldname('category__name', 'nl'), 'category__name_nl' )
Fix issue with idSelector column/line reporting
'use strict'; const parseSelector = require('../utils/parse-selector'); module.exports = { name: 'idSelector', nodeTypes: ['rule'], message: 'Selectors should not use IDs.', lint: function idSelectorLinter (config, node) { const tree = parseSelector(node); const excludes = config.exclude.map((id) => { // Remove # return id.replace(/^#/, ''); }); const results = []; tree.each((selector) => { selector.walkIds((id) => { if (excludes.indexOf(id.value) !== -1) { return; } const position = node.positionBy({ word: id.toString().trim() }); results.push({ column: position.column, line: position.line, message: this.message }); }); }); if (results.length) { return results; } } };
'use strict'; const parseSelector = require('../utils/parse-selector'); module.exports = { name: 'idSelector', nodeTypes: ['rule'], message: 'Selectors should not use IDs.', lint: function idSelectorLinter (config, node) { const tree = parseSelector(node); const excludes = config.exclude.map((id) => { // Remove # return id.replace(/^#/, ''); }); const results = []; tree.each((selector) => { selector.walkIds((id) => { if (excludes.indexOf(id.value) !== -1) { return; } const position = node.positionBy({ word: id.toString() }); results.push({ column: position.column, line: position.line, message: this.message }); }); }); if (results.length) { return results; } } };
Use import instead of require
#!/usr/bin/env node import q from 'q'; import fs from 'fs'; import path from 'path'; import glob from 'glob'; import xml2js from 'xml2js'; import {deleteSync} from 'del'; module.exports = function(context) { var deferral = q.defer(); var parser = new xml2js.Parser(); fs.readFile('config.xml', 'utf8', function (err, xml) { if (err) { deferral.reject('Unable to load config.xml'); return; } parser.parseString(xml, function (err, config) { if (err) { deferral.reject('Unable to parse config.xml'); return; } if (config.widget === undefined || config.widget['ignore-files'] === undefined) { return; } var ignoreFiles = config.widget['ignore-files']; for (var i = 0, l = ignoreFiles.length; i < l; ++i) { if (ignoreFiles[i].$ === undefined || ignoreFiles[i].$.ignore === undefined) { continue; } glob(ignoreFiles[i].$.ignore, {}, function (er, files) { for (var i = 0, l = files.length; i < l; ++i) { deleteSync(files[i]); console.log('ignore-files.js: File `' + files[i] + '` ignored.'); } }) } deferral.resolve(); }); }); return deferral.promise; };
#!/usr/bin/env node var q = require('q'); var fs = require('fs'); var path = require('path'); var glob = require('glob'); var xml2js = require('xml2js'); var del = require('del'); module.exports = function(context) { var deferral = q.defer(); var parser = new xml2js.Parser(); fs.readFile('config.xml', 'utf8', function (err, xml) { if (err) { deferral.reject('Unable to load config.xml'); return; } parser.parseString(xml, function (err, config) { if (err) { deferral.reject('Unable to parse config.xml'); return; } if (config.widget === undefined || config.widget['ignore-files'] === undefined) { return; } var ignoreFiles = config.widget['ignore-files']; for (var i = 0, l = ignoreFiles.length; i < l; ++i) { if (ignoreFiles[i].$ === undefined || ignoreFiles[i].$.ignore === undefined) { continue; } glob(ignoreFiles[i].$.ignore, {}, function (er, files) { for (var i = 0, l = files.length; i < l; ++i) { del.deleteSync(files[i]); console.log('ignore-files.js: File `' + files[i] + '` ignored.'); } }) } deferral.resolve(); }); }); return deferral.promise; };
Fix test failures in MySQLi test
<?php namespace Doctrine\Tests\DBAL\Functional\Mysqli; class ConnectionTest extends \Doctrine\Tests\DbalFunctionalTestCase { public function setUp() { if (!extension_loaded('mysqli')) { $this->markTestSkipped('mysqli is not installed.'); } $this->resetSharedConn(); parent::setUp(); if ( !($this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\Mysqli\Driver)) { $this->markTestSkipped('MySQLi only test.'); } } public function tearDown() { parent::tearDown(); $this->resetSharedConn(); } public function testDriverOptions() { $driverOptions = array( \MYSQLI_OPT_CONNECT_TIMEOUT => 1, ); $connection = $this->getConnection($driverOptions); $this->assertInstanceOf("\Doctrine\DBAL\Driver\Mysqli\MysqliConnection", $connection); } /** * @expectedException \Doctrine\DBAL\Driver\Mysqli\MysqliException */ public function testUnsupportedDriverOption() { $this->getConnection(array('hello' => 'world')); // use local infile } private function getConnection(array $driverOptions) { return new \Doctrine\DBAL\Driver\Mysqli\MysqliConnection( array( 'host' => $GLOBALS['db_host'], 'dbname' => $GLOBALS['db_name'], ), $GLOBALS['db_username'], $GLOBALS['db_password'], $driverOptions ); } }
<?php namespace Doctrine\Tests\DBAL\Functional\Mysqli; class ConnectionTest extends \Doctrine\Tests\DbalFunctionalTestCase { public function setUp() { if (!extension_loaded('mysqli')) { $this->markTestSkipped('mysqli is not installed.'); } $driver = getenv('DB'); if (false !== $driver && $driver !== 'mysqli') { $this->markTestSkipped('this test case is for mysqli only'); } $this->resetSharedConn(); parent::setUp(); } public function tearDown() { parent::tearDown(); $this->resetSharedConn(); } public function testDriverOptions() { $driverOptions = array( \MYSQLI_OPT_CONNECT_TIMEOUT => 1, ); $connection = $this->getConnection($driverOptions); $this->assertInstanceOf("\Doctrine\DBAL\Driver\Mysqli\MysqliConnection", $connection); } /** * @expectedException \Doctrine\DBAL\Driver\Mysqli\MysqliException */ public function testUnsupportedDriverOption() { $this->getConnection(array('hello' => 'world')); // use local infile } private function getConnection(array $driverOptions) { return new \Doctrine\DBAL\Driver\Mysqli\MysqliConnection( array( 'host' => $GLOBALS['db_host'], 'dbname' => $GLOBALS['db_name'], ), $GLOBALS['db_username'], $GLOBALS['db_password'], $driverOptions ); } }
Fix bug handling exceptions in RevisionMiddleware Recently the RevisionMiddleware was modified to avoid accessing request.user unncessarily for caching purposes. This works well except in some cases it can obscure errors generated elsewhere in a project. The RevisionContextManager has "active" and "inactive" states. If there is an exception handler elsewhere in the middleware stack that generates a new HTTP response, the RevisionMiddleware.process_exception() method will inactivate the RevisionContextManager via _close_revision(). Then the HTTP response will be provided to process_response(). If a user is logged in the middleware will call RevisionContextManager.set_user(), which expects to be in the active state, and throws an error ("no active revision for this thread"). To fix this, check if the RevisionContextManager is in the active state before calling set_user.
"""Middleware used by Reversion.""" from __future__ import unicode_literals from reversion.revisions import revision_context_manager REVISION_MIDDLEWARE_FLAG = "reversion.revision_middleware_active" class RevisionMiddleware(object): """Wraps the entire request in a revision.""" def process_request(self, request): """Starts a new revision.""" request.META[(REVISION_MIDDLEWARE_FLAG, self)] = True revision_context_manager.start() def _close_revision(self, request): """Closes the revision.""" if request.META.get((REVISION_MIDDLEWARE_FLAG, self), False): del request.META[(REVISION_MIDDLEWARE_FLAG, self)] revision_context_manager.end() def process_response(self, request, response): """Closes the revision.""" # look to see if the session has been accessed before looking for user to stop Vary: Cookie if hasattr(request, 'session') and request.session.accessed \ and hasattr(request, "user") and request.user.is_authenticated() \ and revision_context_manager.is_active(): revision_context_manager.set_user(request.user) self._close_revision(request) return response def process_exception(self, request, exception): """Closes the revision.""" revision_context_manager.invalidate() self._close_revision(request)
"""Middleware used by Reversion.""" from __future__ import unicode_literals from reversion.revisions import revision_context_manager REVISION_MIDDLEWARE_FLAG = "reversion.revision_middleware_active" class RevisionMiddleware(object): """Wraps the entire request in a revision.""" def process_request(self, request): """Starts a new revision.""" request.META[(REVISION_MIDDLEWARE_FLAG, self)] = True revision_context_manager.start() def _close_revision(self, request): """Closes the revision.""" if request.META.get((REVISION_MIDDLEWARE_FLAG, self), False): del request.META[(REVISION_MIDDLEWARE_FLAG, self)] revision_context_manager.end() def process_response(self, request, response): """Closes the revision.""" # look to see if the session has been accessed before looking for user to stop Vary: Cookie if hasattr(request, 'session') and request.session.accessed \ and hasattr(request, "user") and request.user.is_authenticated(): revision_context_manager.set_user(request.user) self._close_revision(request) return response def process_exception(self, request, exception): """Closes the revision.""" revision_context_manager.invalidate() self._close_revision(request)
Fix thumb setting on local, causing thumbs to fail.
<?php // direct access protection if(!defined('KIRBY')) die('Direct access is not allowed'); /* ----------------------------------------------------------------------------- Troubleshooting -------------------------------------------------------------------------------- */ c::set('troubleshoot', false); /* ----------------------------------------------------------------------------- Debug -------------------------------------------------------------------------------- */ c::set('debug', true); /* ----------------------------------------------------------------------------- Environment -------------------------------------------------------------------------------- */ c::set('environment', 'local'); /* ----------------------------------------------------------------------------- URL -------------------------------------------------------------------------------- */ c::set('url', ''); // To use root relative URLs: c::set('url', '/'); /* ----------------------------------------------------------------------------- Timezone -------------------------------------------------------------------------------- */ c::set('timezone', 'UTC'); /* ----------------------------------------------------------------------------- Cache -------------------------------------------------------------------------------- */ c::set('cache', false); c::set('cache.driver', 'file'); // Valid values: file, memcached or apc /* ----------------------------------------------------------------------------- Thumbs -------------------------------------------------------------------------------- */ c::set('thumbs.driver','im'); // The thumbnail library which is being used by Kirby's thumb function/class ('gd' or 'im') c::set('thumbs.bin', '/usr/local/bin/convert'); // Path to the convert bin for 'im' thumb driver setting (see: http://j.mp/1LJ8n9E) /* ----------------------------------------------------------------------------- Lazyload images -------------------------------------------------------------------------------- Use `lazysizes.init()` in main.scripts.js and mobile.scripts.js */ c::set('lazyload', true); // Set to true to lazyload images /* ----------------------------------------------------------------------------- Analytics, tracking, site stats -------------------------------------------------------------------------------- */ c::set('analytics.tool', false);
<?php // direct access protection if(!defined('KIRBY')) die('Direct access is not allowed'); /* ----------------------------------------------------------------------------- Troubleshooting -------------------------------------------------------------------------------- */ c::set('troubleshoot', false); /* ----------------------------------------------------------------------------- Debug -------------------------------------------------------------------------------- */ c::set('debug', true); /* ----------------------------------------------------------------------------- Environment -------------------------------------------------------------------------------- */ c::set('environment', 'local'); /* ----------------------------------------------------------------------------- URL -------------------------------------------------------------------------------- */ c::set('url', ''); // To use root relative URLs: c::set('url', '/'); /* ----------------------------------------------------------------------------- Timezone -------------------------------------------------------------------------------- */ c::set('timezone', 'UTC'); /* ----------------------------------------------------------------------------- Cache -------------------------------------------------------------------------------- */ c::set('cache', false); c::set('cache.driver', 'file'); // Valid values: file, memcached or apc /* ----------------------------------------------------------------------------- Thumbs -------------------------------------------------------------------------------- */ c::set('thumbs.driver','im'); // The thumbnail library which is being used by Kirby's thumb function/class ('gd' or 'im') thumb::$defaults['bin'] = '/usr/local/bin/convert'; // Path to the convert bin for 'im' thumb driver setting (see: http://j.mp/1LJ8n9E) /* ----------------------------------------------------------------------------- Lazyload images -------------------------------------------------------------------------------- Use `lazysizes.init()` in main.scripts.js and mobile.scripts.js */ c::set('lazyload', true); // Set to true to lazyload images /* ----------------------------------------------------------------------------- Analytics, tracking, site stats -------------------------------------------------------------------------------- */ c::set('analytics.tool', false);