text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove duplicate keybar host value
from keybar.conf.base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'keybar_test', } } certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates') KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert') KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key') KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert') KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key') KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt') KEYBAR_VERIFY_CLIENT_CERTIFICATE = True KEYBAR_DOMAIN = 'local.keybar.io' KEYBAR_HOST = 'local.keybar.io:9999' PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) CELERY_ALWAYS_EAGER = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True KEYBAR_KDF_ITERATIONS = 100
from keybar.conf.base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'keybar_test', } } certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates') KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert') KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key') KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert') KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key') KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt') KEYBAR_VERIFY_CLIENT_CERTIFICATE = True KEYBAR_DOMAIN = 'local.keybar.io' KEYBAR_HOST = 'local.keybar.io:8443' PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) CELERY_ALWAYS_EAGER = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True KEYBAR_HOST = 'local.keybar.io:9999' KEYBAR_KDF_ITERATIONS = 100
Fix entry title for create-title command
const BaseCommand = require("./BaseCommand.js"); /** * Command for creating entries * @class CreateEntryCommand * @augments BaseCommand */ class CreateEntryCommand extends BaseCommand { /** * Execute the entry creation * @param {ArchiveDataset} obj The archive dataset * @param {String} groupID The ID of the group to create within * @param {String} entryID The ID of the entry to create */ execute(obj, groupID, entryID) { obj.groups = obj.groups || []; const entry = { id: entryID, properties: { title: "" } }; const group = this.searchTools.findGroupByID(obj.groups, groupID); if (!group) { throw new Error("Invalid group ID"); } group.entries = group.entries || []; group.entries.push(entry); } } module.exports = CreateEntryCommand;
const BaseCommand = require("./BaseCommand.js"); /** * Command for creating entries * @class CreateEntryCommand * @augments BaseCommand */ class CreateEntryCommand extends BaseCommand { /** * Execute the entry creation * @param {ArchiveDataset} obj The archive dataset * @param {String} groupID The ID of the group to create within * @param {String} entryID The ID of the entry to create */ execute(obj, groupID, entryID) { obj.groups = obj.groups || []; var entry = { id: entryID, title: "" }; var group = this.searchTools.findGroupByID(obj.groups, groupID); if (!group) { throw new Error("Invalid group ID"); } group.entries = group.entries || []; group.entries.push(entry); } } module.exports = CreateEntryCommand;
Switch to appropriate cursor style when panning active
/*globals svgEditor, svgCanvas*/ /*jslint eqeq: true*/ /* * ext-panning.js * * Licensed under the MIT License * * Copyright(c) 2013 Luis Aguirre * */ /* This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem */ svgEditor.addExtension('ext-panning', function() {'use strict'; return { name: 'Extension Panning', svgicons: svgEditor.curConfig.extPath + 'ext-panning.xml', buttons: [{ id: 'ext-panning', type: 'mode', title: 'Panning', key: 'Q', events: { click: function() { svgCanvas.setMode('ext-panning'); svgEditor.toolButtonClick('#ext-panning') $('#styleoverrides').text('#svgcanvas *{cursor:move;pointer-events:all}, #svgcanvas {cursor:default}'); } } }], mouseDown: function() { if (svgCanvas.getMode() == 'ext-panning') { svgEditor.setPanning(true); return {started: true}; } }, mouseUp: function() { if (svgCanvas.getMode() == 'ext-panning') { svgEditor.setPanning(false); return { keep: false, element: null }; } } }; });
/*globals svgEditor, svgCanvas*/ /*jslint eqeq: true*/ /* * ext-panning.js * * Licensed under the MIT License * * Copyright(c) 2013 Luis Aguirre * */ /* This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem */ svgEditor.addExtension('ext-panning', function() {'use strict'; return { name: 'Extension Panning', svgicons: svgEditor.curConfig.extPath + 'ext-panning.xml', buttons: [{ id: 'ext-panning', type: 'mode', title: 'Panning', key: 'Q', events: { click: function() { svgCanvas.setMode('ext-panning'); svgEditor.toolButtonClick('#ext-panning') } } }], mouseDown: function() { if (svgCanvas.getMode() == 'ext-panning') { svgEditor.setPanning(true); return {started: true}; } }, mouseUp: function() { if (svgCanvas.getMode() == 'ext-panning') { svgEditor.setPanning(false); return { keep: false, element: null }; } } }; });
[INTERNAL] Update ownership for sap.f.ShellBar VT Problem: Visual test of sap.f.ShellBar didn`t refer to any particular control. Change-Id: I6d0db8bd2948012dc08b98b4d7fd0b1059e22a90 Solution: We added a reference to sap.f.ShellBar.
/*global describe, it, element, by, takeScreenshot, expect, browser*/ describe('sap.f.ShellBarVT', function() { 'use strict'; browser.testrunner.currentSuite.meta.controlName = 'sap.f.ShellBar'; it('Test page loaded', function() { element(by.css(".sapUiBody")).click(); expect(takeScreenshot()).toLookAs('initial'); }); it("Mega Menu Expanded", function() { element(by.id("__button3-internalBtn")).click(); expect(takeScreenshot()).toLookAs("megaMenu_expanded"); }); it("ShellBar scale",function() { element(by.id("oTestBtnWidth")).click(); expect(takeScreenshot()).toLookAs("shellBar-scale"); }); it("ShellBar click overflow button",function() { if (element(by.css(".sapFShellBarOverflowButton"))){ element(by.css(".sapFShellBarOverflowButton")).click(); } expect(takeScreenshot()).toLookAs("shellBar-overflow-button-clicked"); }); });
/*global describe,it,element,by,takeScreenshot,expect*/ describe('sap.f.ShellBarVT', function() { 'use strict'; it('Test page loaded', function() { element(by.css(".sapUiBody")).click(); expect(takeScreenshot()).toLookAs('initial'); }); it("Mega Menu Expanded", function() { element(by.id("__button3-internalBtn")).click(); expect(takeScreenshot()).toLookAs("megaMenu_expanded"); }); it("ShellBar scale",function() { element(by.id("oTestBtnWidth")).click(); expect(takeScreenshot()).toLookAs("shellBar-scale"); }); it("ShellBar click overflow button",function() { if (element(by.css(".sapFShellBarOverflowButton"))){ element(by.css(".sapFShellBarOverflowButton")).click(); } expect(takeScreenshot()).toLookAs("shellBar-overflow-button-clicked"); }); });
MDL-34067: Change default to on for text feedback comments in assignment This is the "default default" setting.
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file defines the admin settings for this plugin * * @package assignsubmission_comments * @copyright 2012 NetSpot {@link http://www.netspot.com.au} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $settings->add(new admin_setting_configcheckbox('assignfeedback_comments/default', new lang_string('default', 'assignfeedback_comments'), new lang_string('default_help', 'assignfeedback_comments'), 1));
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file defines the admin settings for this plugin * * @package assignsubmission_comments * @copyright 2012 NetSpot {@link http://www.netspot.com.au} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $settings->add(new admin_setting_configcheckbox('assignfeedback_comments/default', new lang_string('default', 'assignfeedback_comments'), new lang_string('default_help', 'assignfeedback_comments'), 0));
Check if rule.selectors exists before forEach'ing over them
/*jshint node: true, strict: false*/ var css = require('css'); var RULE = 'rule'; module.exports = function(source) { if (this.cacheable) { this.cacheable(); } var stylesheet = css.parse(source).stylesheet; if (stylesheet.parsingErrors.length) { throw new Error('Parsing Error occured.'); } var rules = {}, inline; stylesheet.rules.forEach(function(rule) { inline = ''; if (rule.type === RULE) { inline = rule.declarations.map(function(declaration) { return declaration.property + ': ' + declaration.value; }).join('; '); } if(rule.selectors) { rule.selectors.forEach(function(selector) { rules[selector] = inline; }); } }); return rules; };
/*jshint node: true, strict: false*/ var css = require('css'); var RULE = 'rule'; module.exports = function(source) { if (this.cacheable) { this.cacheable(); } var stylesheet = css.parse(source).stylesheet; if (stylesheet.parsingErrors.length) { throw new Error('Parsing Error occured.'); } var rules = {}, inline; stylesheet.rules.forEach(function(rule) { inline = ''; if (rule.type === RULE) { inline = rule.declarations.map(function(declaration) { return declaration.property + ': ' + declaration.value; }).join('; '); } rule.selectors.forEach(function(selector) { rules[selector] = inline; }); }); return rules; };
Use kebab-case for CSS classes
import {h} from '@cycle/dom'; import Rx from 'rx'; import gameScore from './game-score'; export default function ScorePanel(responses) { const url = 'https://nhl-score-api.herokuapp.com/api/scores/latest'; const request$ = Rx.Observable.just(url); const vtree$ = responses.HTTP .filter(res$ => res$.request === url) .mergeAll() .map(res => ({scores: res.text})) .catch(err => Rx.Observable.just({status: `Failed to fetch latest scores: ${err.message}.`})) .startWith({status: 'Fetching latest scores...'}) .map(state => h('div.score-panel', [ state.scores ? renderScoreList(JSON.parse(state.scores)) : h('div.status', [state.status]) ]) ); return { DOM: vtree$, HTTP: request$ }; } function renderScoreList(scores) { return h('div.score-list', scores ? scores.map(game => gameScore(game.teams, game.scores)) : []); }
import {h} from '@cycle/dom'; import Rx from 'rx'; import gameScore from './game-score'; export default function ScorePanel(responses) { const url = 'https://nhl-score-api.herokuapp.com/api/scores/latest'; const request$ = Rx.Observable.just(url); const vtree$ = responses.HTTP .filter(res$ => res$.request === url) .mergeAll() .map(res => ({scores: res.text})) .catch(err => Rx.Observable.just({status: `Failed to fetch latest scores: ${err.message}.`})) .startWith({status: 'Fetching latest scores...'}) .map(state => h('div.scorePanel', [ state.scores ? renderScoreList(JSON.parse(state.scores)) : h('div.status', [state.status]) ]) ); return { DOM: vtree$, HTTP: request$ }; } function renderScoreList(scores) { return h('div.score-list', scores ? scores.map(game => gameScore(game.teams, game.scores)) : []); }
Increase default MonteCarlo n_sims from 100 to 1000
import random from collections import defaultdict, Counter from . import Player from ..util import utility class MonteCarlo(Player): name = 'MonteCarlo' def __init__(self, n_sims=1000): self.n_sims = n_sims def __repr__(self): return type(self).name def __str__(self): return type(self).name def move(self, game): counter = defaultdict(int) for i in range(self.n_sims): for move in game.legal_moves(): new_game = game.copy() new_game.make_move(move) while not new_game.is_over(): rand_move = random.choice(new_game.legal_moves()) new_game.make_move(rand_move) counter[move] += utility(new_game, game.cur_player()) m = Counter(counter).most_common(1) return m[0][0] ########## # Player # ########## def choose_move(self, game): return self.move(game)
import random from collections import defaultdict, Counter from . import Player from ..util import utility class MonteCarlo(Player): name = 'MonteCarlo' def __init__(self, n_sims=100): self.n_sims = n_sims def __repr__(self): return type(self).name def __str__(self): return type(self).name def move(self, game): counter = defaultdict(int) for i in range(self.n_sims): for move in game.legal_moves(): new_game = game.copy() new_game.make_move(move) while not new_game.is_over(): rand_move = random.choice(new_game.legal_moves()) new_game.make_move(rand_move) counter[move] += utility(new_game, game.cur_player()) m = Counter(counter).most_common(1) return m[0][0] ########## # Player # ########## def choose_move(self, game): return self.move(game)
Make it more clear how password is generated
import string import random import argparse def passgen(length=12): """Generate a strong password with *length* characters""" pool = string.ascii_uppercase + string.ascii_lowercase + string.digits # Using technique from Stack Overflow answer # http://stackoverflow.com/a/23728630 chars = [random.SystemRandom().choice(pool) for _ in range(length)] return "".join(chars) def main(): parser = argparse.ArgumentParser( description="Generate strong random password." ) parser.add_argument("-l", "--length", help="the number of characters to generate " "for each password", type=int, default=12) parser.add_argument("-n", "--number", help="how many passwords to generate", type=int, default=10) args = parser.parse_args() for _ in range(args.number): print passgen(args.length)
import string import random import argparse def passgen(length=12): """Generate a strong password with *length* characters""" pool = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.SystemRandom().choice(pool) for _ in range(length)) def main(): parser = argparse.ArgumentParser( description="Generate strong random password." ) parser.add_argument("-l", "--length", help="the number of characters to generate " "for each password", type=int, default=12) parser.add_argument("-n", "--number", help="how many passwords to generate", type=int, default=10) args = parser.parse_args() for _ in range(args.number): print passgen(args.length)
Switch to datetime based on calls for updates.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 30 01:14:12 2017 @author: colm """ from flask import Flask, jsonify from parse_likecharity import refresh_charities import threading from datetime import datetime refresh_rate = 24 * 60 * 60 #Seconds start_time = datetime.now() # variables that are accessible from anywhere payload = {} # lock to control access to variable dataLock = threading.Lock() # thread handler backgroundThread = threading.Thread() app = Flask(__name__) def update_charities(): print('Updating charities in background thread') global payload global backgroundThread with dataLock: categories, charity_dict = refresh_charities() payload = {'categories':categories, 'charities':charity_dict} print('Running!') # Set the next thread to happen backgroundThread = threading.Timer(refresh_rate, update_charities, ()) backgroundThread.start() @app.route("/gci") def gci(): delta = datetime.now() - start_time if delta.total_seconds() > refresh_rate: categories, charity_dict = refresh_charities() payload = {'categories':categories, 'charities':charity_dict} return jsonify(payload) if __name__ == "__main__": update_charities() app.run(host='0.0.0.0') backgroundThread.cancel() print('test')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 30 01:14:12 2017 @author: colm """ from flask import Flask, jsonify from parse_likecharity import refresh_charities import threading refresh_rate = 24 * 60 * 60 #Seconds # variables that are accessible from anywhere payload = {} # lock to control access to variable dataLock = threading.Lock() # thread handler backgroundThread = threading.Thread() app = Flask(__name__) def update_charities(): print('Updating charities in background thread') global payload global backgroundThread with dataLock: categories, charity_dict = refresh_charities() payload = {'categories':categories, 'charities':charity_dict} print('Running!') # Set the next thread to happen backgroundThread = threading.Timer(refresh_rate, update_charities, ()) backgroundThread.start() @app.route("/") def gci(): return jsonify(payload) if __name__ == "__main__": update_charities() app.run(host='0.0.0.0') backgroundThread.cancel() print('test')
nrf/examples: Update ssd1306 modification example to import correct class.
# NOTE: Modified version to align with implemented I2C API in nrf port. # # Examples usage of SSD1306_SPI on pca10040 # # from machine import Pin, SPI # from ssd1306 import SSD1306_SPI # spi = SPI(0, baudrate=40000000) # dc = Pin.board.PA11 # res = Pin.board.PA12 # cs = Pin.board.PA13 # disp = SSD1306_SPI(128, 64, spi, dc, res, cs) # # # Example usage of SSD1306_I2C on pca10040 # # from machine import Pin, I2C # from ssd1306_mod import SSD1306_I2C_Mod # i2c = I2C(0, Pin.board.PA3, Pin.board.PA4) # disp = SSD1306_I2C_Mod(128, 64, i2c) from ssd1306 import SSD1306_I2C class SSD1306_I2C_Mod(SSD1306_I2C): def write_data(self, buf): buffer = bytearray([0x40]) + buf # Co=0, D/C#=1 self.i2c.writeto(self.addr, buffer)
# NOTE: Modified version to align with implemented I2C API in nrf port. # # Examples usage of SSD1306_SPI on pca10040 # # from machine import Pin, SPI # from ssd1306 import SSD1306_SPI # spi = SPI(0, baudrate=40000000) # dc = Pin.board.PA11 # res = Pin.board.PA12 # cs = Pin.board.PA13 # disp = SSD1306_SPI(128, 64, spi, dc, res, cs) # # # Example usage of SSD1306_I2C on pca10040 # # from machine import Pin, I2C # from ssd1306 import SSD1306_I2C # i2c = I2C(0, Pin.board.PA3, Pin.board.PA4) # disp = SSD1306_I2C_Mod(128, 64, i2c) from ssd1306 import SSD1306_I2C class SSD1306_I2C_Mod(SSD1306_I2C): def write_data(self, buf): buffer = bytearray([0x40]) + buf # Co=0, D/C#=1 self.i2c.writeto(self.addr, buffer)
Revert "catch port in use error" This reverts commit e42774bba30db5f1be94d1e24de1482febfebec2.
'use strict'; var livereload = require('livereload'), connectLr = require('connect-livereload-safe'); module.exports = function(lingon, config) { // add script tag injection middleware to the express server lingon.one('serverConfigure', function() { config = config || {}; config.port = config.port || 35729; // inject browser script tag lingon.server.use(connectLr({ port: config.port })); }); // start the livereload server lingon.one('serverStarted', function() { var server; // set livereload to watch the source dir config.watchDir = config.watchDir || process.cwd() + '/' + lingon.config.sourcePath; // add extensions for livereload to watch config.exts = config.exts || lingon.config.directiveFileTypes.concat(Object.keys(lingon.config.extensionRewrites)); server = livereload.createServer(config); server.watch(config.watchDir); lingon.log('Livereload is listening on port ' + config.port); }); };
'use strict'; var livereload = require('livereload'); var connectLr = require('connect-livereload-safe'); module.exports = function(lingon, config) { // add script tag injection middleware to the express server lingon.one('serverConfigure', function() { config = config || {}; config.port = config.port || 35729; // inject browser script tag lingon.server.use(connectLr({ port: config.port })); process.on('uncaughtException', function(error) { if(error.code == 'EADDRINUSE') { lingon.log.error('Port ' + config.port + ' is already in use, lingon-livereload could not start!'); lingon.log.info('[Info] Try changing the port in your lingon-livereload config'); process.exit(); } }); }); // start the livereload server lingon.one('serverStarted', function() { var server; // set livereload to watch the source dir config.watchDir = config.watchDir || process.cwd() + '/' + lingon.config.sourcePath; // add extensions for livereload to watch config.exts = config.exts || lingon.config.directiveFileTypes.concat(Object.keys(lingon.config.extensionRewrites)); server = livereload.createServer(config); server.watch(config.watchDir); lingon.log('Livereload is listening on port ' + config.port); }); };
Use Electron Prebuilt version from package.json
var fs = require('fs') var exec = require('child_process').exec // get our version var pack = JSON.parse(fs.readFileSync('package.json', 'utf-8')) var version = pack.version // get the electron version var electronPrebuiltPack = JSON.parse(fs.readFileSync('./node_modules/electron-prebuilt/package.json', 'utf-8')) var electronVersion = electronPrebuiltPack.version console.log('Building version ' + version + ' in Brave-darwin-x64 with Electron ' + electronVersion) var cmds = [ 'rm -rf Brave-darwin-x64', 'NODE_ENV=production ./node_modules/webpack/bin/webpack.js', 'rm -f dist/Brave.dmg', './node_modules/electron-packager/cli.js . Brave --overwrite --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel$|babel-(?!polyfill|regenerator-runtime)" --platform=darwin --arch=x64 --version=' + electronVersion + ' --icon=res/app.icns --app-version=' + version ] var cmd = cmds.join(' && ') console.log(cmd) exec(cmd, function (err, stdout, stderr) { if (err) console.error(err) console.log(stdout) })
var fs = require('fs') var exec = require('child_process').exec var pack = JSON.parse(fs.readFileSync('package.json', 'utf-8')) var version = pack.version console.log('Building version ' + version + ' in Brave-darwin-x64') var cmd = 'rm -rf Brave-darwin-x64 && NODE_ENV=production ./node_modules/webpack/bin/webpack.js && rm -f dist/Brave.dmg && ./node_modules/electron-packager/cli.js . Brave --overwrite --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel-|babel" --platform=darwin --arch=x64 --version=0.35.1 --icon=res/app.icns --app-version=' + version console.log(cmd) exec(cmd, function (err, stdout, stderr) { if (err) console.error(err) console.log(stdout) })
Make ESLint config file compatible with ES5
var fs = require('fs'); var path = require('path'); var pluginPath = path.basename(path.basename(__dirname)); var possibleGirderPaths = [ path.basename(path.basename(pluginPath)), path.join(path.basename(pluginPath), 'girder'), process.cwd() ]; /* This requires ES6 */ /* var configPath = possibleGirderPaths .map(function (possibleGirderPath) { return path.join(possibleGirderPath, '.eslintrc'); }) .find(function (configPath) { try { fs.accessSync(configPath); return true; } catch (ignore) { return false; } }); */ var possibleConfigPaths = possibleGirderPaths .map(function (possibleGirderPath) { return path.join(possibleGirderPath, '.eslintrc'); }); var configPath; for (var i = 0, len = possibleConfigPaths.length; i < len; ++i) { try { fs.accessSync(possibleConfigPaths[i]); configPath = possibleConfigPaths[i]; break; } catch (ignore) {} } module.exports = { 'extends': configPath, 'globals': { 'isic': true } };
var fs = require('fs'); var path = require('path'); var pluginPath = path.basename(path.basename(__dirname)); var possibleGirderPaths = [ path.basename(path.basename(pluginPath)), path.join(path.basename(pluginPath), 'girder'), process.cwd() ]; var configPath = possibleGirderPaths .map(function (possibleGirderPath) { return path.join(possibleGirderPath, '.eslintrc'); }) .find(function (configPath) { try { fs.accessSync(configPath); return true; } catch (e) { return false; } }); module.exports = { 'extends': configPath, 'globals': { 'isic': true } };
Add Code field and Normal method to StatusInfo
package medtronic const ( status Command = 0xCE ) // StatusInfo represents the pump's status. type StatusInfo struct { Code byte Bolusing bool Suspended bool } // Normal returns true if the status code indicates normal pump operation. // Observed values: // 0: rewinding // 1: preparing to prime // 2: priming // 3: normal func (s StatusInfo) Normal() bool { return s.Code == 0x03 } // Status returns the pump's status. func (pump *Pump) Status() StatusInfo { data := pump.Execute(status) if pump.Error() != nil { return StatusInfo{} } if len(data) < 4 || data[0] != 3 { pump.BadResponse(status, data) return StatusInfo{} } return StatusInfo{ Code: data[1], Bolusing: data[2] == 1, Suspended: data[3] == 1, } }
package medtronic const ( status Command = 0xCE ) // StatusInfo represents the pump's status. type StatusInfo struct { Normal bool Bolusing bool Suspended bool } // Status returns the pump's status. func (pump *Pump) Status() StatusInfo { data := pump.Execute(status) if pump.Error() != nil { return StatusInfo{} } if len(data) < 4 || data[0] != 3 { pump.BadResponse(status, data) return StatusInfo{} } // Observed values for data[1]: // 0: rewinding // 1: preparing to prime // 2: priming // 3: normal return StatusInfo{ Normal: data[1] == 0x03, Bolusing: data[2] == 1, Suspended: data[3] == 1, } }
Fix peek method to return value instead of object
#!/usr/bin/env python '''Implementation of a simple stack data structure. The stack has push, pop, and peek methods. Items in the stack have a value, and next_item attribute. The stack has a top attribute. ''' class Item(object): def __init__(self, value, next_item=None): self.value = value self.next_item = next_item def __str__(self): return self.value class Stack(object): def __init__(self, top=None): self.top = top def push(self, value): item = Item(value) item.next_item = self.top self.top = item def pop(self): pass def peek(self): return self.top.value
#!/usr/bin/env python '''Implementation of a simple stack data structure. The stack has push, pop, and peek methods. Items in the stack have a value, and next_item attribute. The stack has a top attribute. ''' class Item(object): def __init__(self, value, next_item=None): self.value = value self.next_item = next_item def __str__(self): return self.value class Stack(object): def __init__(self, top=None): self.top = top def push(self, value): item = Item(value) item.next_item = self.top self.top = item def pop(self): pass def peek(self): return self.top
Add Deepth File And KeyWord Options
import sys import urllib2 import getopt import time target = '' depth = 6 file = 'etc/passwd' html = '' prefix = '' url = '' keyword='root' def usage(): print "usage function" try: opts,args = getopt.getopt(sys.argv[1:],"ht:d:f:k:",["help","target=","depth=","file=","keyword="]) for opt, arg in opts: if opt in("-h","--help"): usage() sys.exit() if opt in("-t","--target"): target = arg if not target.startswith('http://', 0, 7): target = 'http://' + target if opt in("-d","--depth"): depth = int(arg) if opt in("-f","--file"): file = arg if file.startswith('/',0,1): file =file[1:] if opt in("-d","--keyword"): keyword = arg except getopt.GetoptError: usage() sys.exit(2) for i in range(0,depth): prefix += '../' url = target + prefix + file print "Testing: ",url try: response = urllib2.urlopen(url) html = response.read() except: pass if(keyword in html): print url, " is Vulnerable" break else: time.sleep(2) continue
import sys import urllib2 import getopt import time target = '' depth = 10 file = 'etc/passwd' html = '' prefix = '' url = '' def usage(): print "usage function" try: opts,args = getopt.getopt(sys.argv[1:],"ht:",["help","target="]) for opt, arg in opts: if opt in("-h","--help"): usage() sys.exit() if opt in("-t","--target"): target = arg if not target.startswith('http://', 0, 7): target = 'http://' + target except getopt.GetoptError: usage() sys.exit(2) for i in range(1,depth+1): prefix += '../' url = target + prefix + file print "Testing: ",url try: response = urllib2.urlopen(url) html = response.read() except: pass if("root" in html): print url, " is Vulnerable" break else: time.sleep(2) continue
Fix cached graph verifier tool to handle case where no graph is cached ATM.
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): cached = flow.get_cached_graph(ignore_balances) if not cached: continue graph = flow.build_graph(ignore_balances) diff = compare(cached, graph) if diff: pp(diff) return False return True def compare(g1, g2): e1 = set(normalize(g1.edges(data=True))) e2 = set(normalize(g2.edges(data=True))) return e1.symmetric_difference(e2) def normalize(edge_list): return ((src, dest, data['capacity'], data['weight'], data['creditline_id']) for src, dest, data in edge_list) if __name__ == '__main__': if verify(): print 'OK.' sys.exit(0) else: print 'Mismatch.' sys.exit(1)
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) diff = compare(cached, graph) if diff: pp(diff) return False return True def compare(g1, g2): e1 = set(normalize(g1.edges(data=True))) e2 = set(normalize(g2.edges(data=True))) return e1.symmetric_difference(e2) def normalize(edge_list): return ((src, dest, data['capacity'], data['weight'], data['creditline_id']) for src, dest, data in edge_list) if __name__ == '__main__': if verify(): print 'OK.' sys.exit(0) else: print 'Mismatch.' sys.exit(1)
Use dumb query parsing to avoid a DoS attack where a { $regex } matcher with evil regex could be inserted into a query http://localhost:8080/api/statistics/counters?area[$regex]=((\w%2B.%2B)%2B)%2BG The URL would: * Have its query value parsed as an object * This was assumed to always be a string and so would be inserted into the search query * A more complex query could be specified through this, such as a regex comparison * The regex in the example above is very expensive and would cause MongoDB to lock at 100% CPU utilisation Never parsing query values as objects avoids this.
const config = require('./config/config'); const express = require('express'); const helmet = require('helmet'); const compression = require('compression'); const path = require('path'); require('./config/mongo'); // don't much like this bare require const app = express(); // we can make some nicer assumptions about security if query values are only // ever strings, not arrays or objects app.set('query parser', 'simple'); app.use(helmet()); app.use(compression()); // Add public API routes const publicRoutes = require('./routes/public'); app.use('/api', publicRoutes); // Serve the built admin UI from /admin app.use('/admin', express.static(path.join(__dirname, 'www-admin'))); app.get('/admin/*', function(req, res) { res.sendFile(path.join(__dirname, 'www-admin', 'index.html')); }); // Serve the built UI from the root app.use(express.static(path.join(__dirname, 'www'))); app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'www', 'index.html')); }); // auto-init if this app is not being initialised by another module if (!module.parent) { app.listen(config.app.port, () => { /* eslint-disable-next-line no-console */ console.log(`Listening on port ${config.app.port}`); }); } module.exports = app;
const config = require('./config/config'); const express = require('express'); const helmet = require('helmet'); const compression = require('compression'); const path = require('path'); require('./config/mongo'); // don't much like this bare require const app = express(); app.use(helmet()); app.use(compression()); // Add public API routes const publicRoutes = require('./routes/public'); app.use('/api', publicRoutes); // Serve the built admin UI from /admin app.use('/admin', express.static(path.join(__dirname, 'www-admin'))); app.get('/admin/*', function(req, res) { res.sendFile(path.join(__dirname, 'www-admin', 'index.html')); }); // Serve the built UI from the root app.use(express.static(path.join(__dirname, 'www'))); app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'www', 'index.html')); }); // auto-init if this app is not being initialised by another module if (!module.parent) { app.listen(config.app.port, () => { /* eslint-disable-next-line no-console */ console.log(`Listening on port ${config.app.port}`); }); } module.exports = app;
Improve failed render error handling
"use strict"; require("dotenv").config(); require('newrelic'); var express = require("express"); var helmet = require("helmet"); var readFile = require("fs-readfile-promise"); var components = require("server-components"); require("./components/item-feed/item-feed"); require("./components/item-carousel/item-carousel"); require("./components/manual-source"); require("./components/twitter-source"); require("./components/github-source"); require("./components/rss-source"); require("./components/oembed-item-wrapper/oembed-item-wrapper"); require("./components/social-media-icons"); require("./components/copyright-notice"); require("./components/google-analytics"); var app = express(); app.use(express.static('static')); app.use(helmet()); app.get('/', function (req, res) { res.set("Strict-Transport-Security", "max-age=31556926"); readFile("index.html").then((html) => { return components.renderPage(html); }).then((output) => { res.send(output); }).catch((error) => { console.error(error, error.message, error.stack); res.status(500).send("Panic, failed to render."); }); }); var port = (process.env.PORT || 8080); app.listen(port, () => console.log(`Listening on ${port}`));
"use strict"; require("dotenv").config(); require('newrelic'); var express = require("express"); var helmet = require("helmet"); var readFile = require("fs-readfile-promise"); var components = require("server-components"); require("./components/item-feed/item-feed"); require("./components/item-carousel/item-carousel"); require("./components/manual-source"); require("./components/twitter-source"); require("./components/github-source"); require("./components/rss-source"); require("./components/oembed-item-wrapper/oembed-item-wrapper"); require("./components/social-media-icons"); require("./components/copyright-notice"); require("./components/google-analytics"); var app = express(); app.use(express.static('static')); app.use(helmet()); app.get('/', function (req, res) { res.set("Strict-Transport-Security", "max-age=31556926"); readFile("index.html").then((html) => { return components.renderPage(html); }).then((output) => { res.send(output); }).catch((error) => { res.send("Panic, failed to render. " + error); }); }); var port = (process.env.PORT || 8080); app.listen(port, () => console.log(`Listening on ${port}`));
Fix IDE complaining about Cache.put only expecting 2 arguments
var azurecache = require('azurecache'); module.exports = function(fake){ if(fake){ exports.get = function(data,callback){ if(typeof callback === 'function'){callback(null,null);} else { return null }}; exports.put = function(id,data,tts){ return true; }; exports.remove = function(data,callback){ if(typeof callback === 'function'){callback(null,null);} else { return null }}; module.exports = exports; } else { module.exports = azurecache.create({ identifier: process.env.CACHE_ENDPOINT, token: process.env.CACHE_KEY, ttl: process.env.CACHE_TTL }); } };
var azurecache = require('azurecache'); module.exports = function(fake){ if(fake){ exports.get = function(data,callback){ if(typeof callback === 'function'){callback(null,null);} else { return null }}; exports.put = function(data,callback){ if(typeof callback === 'function'){callback(null,null);} else { return null }}; exports.remove = function(data,callback){ if(typeof callback === 'function'){callback(null,null);} else { return null }}; module.exports = exports; } else { module.exports = azurecache.create({ identifier: process.env.CACHE_ENDPOINT, token: process.env.CACHE_KEY, ttl: process.env.CACHE_TTL }); } };
Revert "Try to send to 0.0.0.0 instead of localhost" This reverts commit 6eea8961661327251a086b8d1fef2813471a6fc8.
<?php require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php'; defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_ENV') or define('YII_ENV', 'dev'); $config = [ 'id' => 'yii2-papertrail-log-target', 'basePath' => __DIR__, 'bootstrap' => ['log'], 'components' => [ 'log' => [ 'targets' => [ [ 'class' => Rekurzia\Log\PapertrailTarget::class, 'levels' => ['error', 'warning'], 'host' => 'localhost', 'port' => '1234', ], ] ] ] ]; (new yii\web\Application($config))->run();
<?php require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php'; defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_ENV') or define('YII_ENV', 'dev'); $config = [ 'id' => 'yii2-papertrail-log-target', 'basePath' => __DIR__, 'bootstrap' => ['log'], 'components' => [ 'log' => [ 'targets' => [ [ 'class' => Rekurzia\Log\PapertrailTarget::class, 'levels' => ['error', 'warning'], 'host' => '0.0.0.0', 'port' => '1234', ], ] ] ] ]; (new yii\web\Application($config))->run();
Fix regex to optionally match substitution type and better whitespace support
#!/usr/bin/python # Read doc comments and work out what fields to anonymize import inspect import re from nova.db.sqlalchemy import models ANON_CONFIG_RE = re.compile('^\s*:anon\s+(\S+):\s+(\S+)\s+(\S+)?\s*$') def load_configuration(): configs = {} for name, obj in inspect.getmembers(models): if not inspect.isclass(obj): continue if not issubclass(obj, models.NovaBase): continue if not obj.__doc__: continue attributes = [] for line in obj.__doc__.split('\n'): m = ANON_CONFIG_RE.match(line) if m: attributes.append((m.group(1), m.group(2))) if attributes: configs[name] = attributes return configs if __name__ == '__main__': print load_configuration()
#!/usr/bin/python # Read doc comments and work out what fields to anonymize import inspect import re from nova.db.sqlalchemy import models ANON_CONFIG_RE = re.compile('^ *:anon ([^ ]+): ([^ ]+)$') def load_configuration(): configs = {} for name, obj in inspect.getmembers(models): if not inspect.isclass(obj): continue if not issubclass(obj, models.NovaBase): continue if not obj.__doc__: continue attributes = [] for line in obj.__doc__.split('\n'): m = ANON_CONFIG_RE.match(line) if m: attributes.append((m.group(1), m.group(2))) if attributes: configs[name] = attributes return configs if __name__ == '__main__': print load_configuration()
Fix a la carga de paquete en ataque
package comandos; import java.util.HashMap; import mensajeria.PaqueteAtacar; public class Atacar extends ComandoCliente { @Override public void ejecutar() { PaqueteAtacar paqueteAtacar = (PaqueteAtacar) paquete; HashMap<String, Object> datos = juego.getEstadoBatalla().getPersonaje().getTodo(); datos.putAll(paqueteAtacar.getTodoEnemigo()); juego.getEstadoBatalla().getPersonaje().actualizar(datos); datos = juego.getEstadoBatalla().getEnemigo().getTodo(); datos.putAll(paqueteAtacar.getTodoPersonaje()); juego.getEstadoBatalla().getEnemigo().actualizar(datos); juego.getEstadoBatalla().setMiTurno(true); } }
package comandos; import java.util.HashMap; import mensajeria.PaqueteAtacar; public class Atacar extends ComandoCliente { @Override public void ejecutar() { PaqueteAtacar paqueteAtacar = (PaqueteAtacar) paquete; HashMap<String, Object> datos = juego.getEstadoBatalla().getPersonaje().getTodo(); datos.putAll(paqueteAtacar.getTodoPersonaje()); juego.getEstadoBatalla().getPersonaje().actualizar(datos); datos = juego.getEstadoBatalla().getEnemigo().getTodo(); datos.putAll(paqueteAtacar.getTodoEnemigo()); juego.getEstadoBatalla().getEnemigo().actualizar(datos); juego.getEstadoBatalla().setMiTurno(true); } }
Add QWidget to the mock Qt
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QWidget = object QtCore = QtWidgets = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QtCore = QtWidgets = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
Add js files to manifest.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. //= require jquery //= require jquery_ujs //= requre bootstrap //= require kingadmin/king-common //= require kingadmin/king-components //= require kingadmin/king-form-layouts //= require_tree . $(function() { $("#event_begin_date").datepicker( {dateformat: 'yy-mm-dd'}); $("#event_end_date").datepicker( {dateformat: 'yy-mm-dd'}); $("#event_registration_open_date").datepicker( {dateformat: 'yy-mm-dd'}); $("#event_registration_close_date").datepicker( {dateformat: 'yy-mm-dd'}); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // require kingadmin/jquery-2.1.0 //= require jquery //= require jquery_ujs //= requre bootstrap //= require kingadmin/king-common.js //= require_tree . $(function() { $("#event_begin_date").datepicker( {dateformat: 'yy-mm-dd'}); $("#event_end_date").datepicker( {dateformat: 'yy-mm-dd'}); $("#event_registration_open_date").datepicker( {dateformat: 'yy-mm-dd'}); $("#event_registration_close_date").datepicker( {dateformat: 'yy-mm-dd'}); });
Fix variable access for less-loader
const ExtractTextPlugin = require('extract-text-webpack-plugin') const { buildDir } = require('../env') const extractText = new ExtractTextPlugin({ filename: '[contenthash].css' }) extractText.lessConfig = { test: /\.less$/, use: extractText.extract({ use: [ { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true } }, { loader: 'less-loader', options: { sourceMap: true, strictMath: true, strictUnits: true, noIeCompat: true, compress: false, outputSourceFiles: true, sourceMapFileInline: true, globalVars: { 'build-root': `'${buildDir}'` } } } ] }) } module.exports = extractText
const ExtractTextPlugin = require('extract-text-webpack-plugin') const { buildDir } = require('../env') const extractText = new ExtractTextPlugin({ filename: '[contenthash].css' }) extractText.lessConfig = { test: /\.less$/, use: extractText.extract({ use: [ { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true } }, { loader: 'less-loader', options: { sourceMap: true, strictMath: true, strictUnits: true, noIeCompat: true, compress: false, outputSourceFiles: true, sourceMapFileInline: true, globalVars: { 'build-root': buildDir } } } ] }) } module.exports = extractText
Set port on express app explicitly
var express = require('express') , http = require('http') , passport = require('passport') , path = require('path') , User = require('./models/User.js'); var app = express(); app.set('views', __dirname + '/app'); app.set('view engine', 'jade'); app.use(express.logger('dev')) app.use(express.cookieParser()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(path.join(__dirname, 'app'))); app.use(express.session( { secret: "Superdupersecret", cookie: { maxAge: 3600000 * 24 * 365 } })); app.use(passport.initialize()); app.use(passport.session()); passport.use(User.localStrategy); passport.serializeUser(User.serializeUser); passport.deserializeUser(User.deserializeUser); require('./routes.js')(app); app.set('port', process.env.PORT || 8000); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
var express = require('express') , http = require('http') , passport = require('passport') , path = require('path') , User = require('./models/User.js'); var app = express(); app.set('views', __dirname + '/app'); app.set('view engine', 'jade'); app.use(express.logger('dev')) app.use(express.cookieParser()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(path.join(__dirname, 'app'))); app.use(express.session( { secret: "Superdupersecret", cookie: { maxAge: 3600000 * 24 * 365 } })); app.use(passport.initialize()); app.use(passport.session()); passport.use(User.localStrategy); passport.serializeUser(User.serializeUser); passport.deserializeUser(User.deserializeUser); require('./routes.js')(app); http.createServer(app).listen(process.env.port || 8080, function(){ console.log("Express server listening on port " + app.get('port')); });
Fix pylint error for redefined builtin input.
# coding: utf-8 from __future__ import unicode_literals, absolute_import from six.moves import input # pylint:disable=redefined-builtin from .oauth2 import OAuth2 class DeveloperTokenAuth(OAuth2): ENTER_TOKEN_PROMPT = 'Enter developer token: ' def __init__(self, get_new_token_callback=None, **kwargs): self._get_new_token = get_new_token_callback super(DeveloperTokenAuth, self).__init__( client_id=None, client_secret=None, access_token=self._refresh_developer_token(), **kwargs ) def _refresh_developer_token(self): if self._get_new_token is not None: return self._get_new_token() else: return input(self.ENTER_TOKEN_PROMPT) def _refresh(self, access_token): """ Base class override. Ask for a new developer token. """ self._access_token = self._refresh_developer_token() return self._access_token, None
# coding: utf-8 from __future__ import unicode_literals, absolute_import from six.moves import input from .oauth2 import OAuth2 class DeveloperTokenAuth(OAuth2): ENTER_TOKEN_PROMPT = 'Enter developer token: ' def __init__(self, get_new_token_callback=None, **kwargs): self._get_new_token = get_new_token_callback super(DeveloperTokenAuth, self).__init__( client_id=None, client_secret=None, access_token=self._refresh_developer_token(), **kwargs ) def _refresh_developer_token(self): if self._get_new_token is not None: return self._get_new_token() else: return input(self.ENTER_TOKEN_PROMPT) def _refresh(self, access_token): """ Base class override. Ask for a new developer token. """ self._access_token = self._refresh_developer_token() return self._access_token, None
Add 'provider location' as a searchable field for Images
from core.models import Application as Image from api import permissions from api.v2.serializers.details import ImageSerializer from api.v2.views.base import AuthOptionalViewSet from api.v2.views.mixins import MultipleFieldLookup class ImageViewSet(MultipleFieldLookup, AuthOptionalViewSet): """ API endpoint that allows images to be viewed or edited. """ lookup_fields = ("id", "uuid") http_method_names = ['get', 'put', 'patch', 'head', 'options', 'trace'] filter_fields = ('created_by__username', 'tags__name', 'projects__id') permission_classes = (permissions.InMaintenance, permissions.ApiAuthOptional, permissions.CanEditOrReadOnly, permissions.ApplicationMemberOrReadOnly) serializer_class = ImageSerializer search_fields = ('id', 'name', 'versions__change_log', 'tags__name', 'tags__description', 'created_by__username', 'versions__machines__instance_source__provider__location') def get_queryset(self): request_user = self.request.user return Image.current_apps(request_user)
from core.models import Application as Image from api import permissions from api.v2.serializers.details import ImageSerializer from api.v2.views.base import AuthOptionalViewSet from api.v2.views.mixins import MultipleFieldLookup class ImageViewSet(MultipleFieldLookup, AuthOptionalViewSet): """ API endpoint that allows images to be viewed or edited. """ lookup_fields = ("id", "uuid") http_method_names = ['get', 'put', 'patch', 'head', 'options', 'trace'] filter_fields = ('created_by__username', 'tags__name', 'projects__id') permission_classes = (permissions.InMaintenance, permissions.ApiAuthOptional, permissions.CanEditOrReadOnly, permissions.ApplicationMemberOrReadOnly) serializer_class = ImageSerializer search_fields = ('id', 'name', 'versions__change_log', 'tags__name', 'tags__description', 'created_by__username') def get_queryset(self): request_user = self.request.user return Image.current_apps(request_user)
Set the wait time shorter than before.
package org.skywalking.apm.agent.core.remote; /** * @author wusheng */ public class GRPCStreamServiceStatus { private volatile boolean status; public GRPCStreamServiceStatus(boolean status) { this.status = status; } public boolean isStatus() { return status; } public void finished() { this.status = true; } /** * @param maxTimeout max wait time, milliseconds. */ public void wait4Finish(long maxTimeout) { long time = 0; while (status == false) { if (time > maxTimeout) { break; } try2Sleep(5); time += 5; } } /** * Try to sleep, and ignore the {@link InterruptedException} * * @param millis the length of time to sleep in milliseconds */ private void try2Sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } }
package org.skywalking.apm.agent.core.remote; /** * @author wusheng */ public class GRPCStreamServiceStatus { private volatile boolean status; public GRPCStreamServiceStatus(boolean status) { this.status = status; } public boolean isStatus() { return status; } public void finished() { this.status = true; } /** * * @param maxTimeout max wait time, milliseconds. */ public void wait4Finish(long maxTimeout) { long time = 0; while (status == false) { if (time > maxTimeout) { break; } try2Sleep(50); time += 50; } } /** * Try to sleep, and ignore the {@link InterruptedException} * * @param millis the length of time to sleep in milliseconds */ private void try2Sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } }
Tweak how Run handles checking if timeout occurred.
var Run = function(parent, op, befores, afters, timeout) { this.parent = parent; this.op = op; this.expects = []; this.ran = false; if (timeout) { this.timeout = timeout; } else if (defaultTimeout) { this.timeout = defaultTimeout } if (befores) this.befores = befores; if (afters) this.afters = afters; } Run.prototype.perform = function(callback) { var self = this; var runTimeout; if (self.timeout) { runTimeout = setTimeout(function() { self.ran = true; loop(0, self.expects.length, function(i, next) { enter(self.expects[i], next); }, function() { self.reset(); callback(); }); }, self.timeout); } self.op(function() { if (!self.ran) { if (runTimeout) { clearTimeout(runTimeout); } loop(0, self.expects.length, function(i, next) { enter(self.expects[i], next); }, function() { self.reset(); callback(); }); } else { console.error("Warning: run block completed after timed out."); } // self.ran = true; }); } Run.prototype.reset = function() { this.ran = false; }
var Run = function(parent, op, befores, afters, timeout) { this.parent = parent; this.op = op; this.expects = []; this.ran = false; if (timeout) { this.timeout = timeout; } else if (defaultTimeout) { this.timeout = defaultTimeout } if (befores) this.befores = befores; if (afters) this.afters = afters; } Run.prototype.perform = function(callback) { var self = this; var runTimeout; if (self.timeout) { runTimeout = setTimeout(function() { self.ran = true; loop(0, self.expects.length, function(i, next) { enter(self.expects[i], next); }, callback); }, self.timeout); } self.op(function() { if (!self.ran) { if (runTimeout) { clearTimeout(runTimeout); } loop(0, self.expects.length, function(i, next) { enter(self.expects[i], next); }, callback); } else { console.error("Warning: run block completed after timed out."); } // self.ran = true; }); }
Fix string format for week numbers < 10
#!/usr/bin/python import sys import gzip import datetime import tempfile import boto3 import logging logger = logging.getLogger() logger.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('[%(levelname)s] %(asctime)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) import listRecords import download def main(): dataset = 'ictrp-raw-{}-w{:02d}.xml.gz'.format(*datetime.datetime.today().isocalendar()) idlist = listRecords.allList() with tempfile.TemporaryFile() as tmpfile: with gzip.GzipFile('raw.xml.gz', 'w', 9, tmpfile) as outfile: failed = download.downloadRecords(idlist, outfile, True) logger.info("Failed (all attempts): {}".format(str(failed))) tmpfile.seek(0) # write to s3 s3 = boto3.resource('s3') object = s3.Bucket('ictrp-data').put_object(Key=dataset, Body=tmpfile) object.Acl().put(ACL='public-read') if __name__ == "__main__": main()
#!/usr/bin/python import sys import gzip import datetime import tempfile import boto3 import logging logger = logging.getLogger() logger.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('[%(levelname)s] %(asctime)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) import listRecords import download def main(): dataset = 'ictrp-raw-{}-w{}.xml.gz'.format(*datetime.datetime.today().isocalendar()) idlist = listRecords.allList() with tempfile.TemporaryFile() as tmpfile: with gzip.GzipFile('raw.xml.gz', 'w', 9, tmpfile) as outfile: failed = download.downloadRecords(idlist, outfile, True) logger.info("Failed (all attempts): {}".format(str(failed))) tmpfile.seek(0) # write to s3 s3 = boto3.resource('s3') object = s3.Bucket('ictrp-data').put_object(Key=dataset, Body=tmpfile) object.Acl().put(ACL='public-read') if __name__ == "__main__": main()
backend: Fix problem with regular files in search paths
"use strict"; const fs = require("fs-extra-promise"); const path = require("path"); const log = require("log"); const findDirsWithEntry = async (baseDir, entryFile = "index.js") => { const res = []; const dirContent = await fs.readdirAsync(baseDir); for (const dirName of dirContent) { const dirPath = path.join(baseDir, dirName); const entryPath = path.join(dirPath, entryFile); try { const dirStat = await fs.statAsync(dirPath); if (dirStat.isDirectory()) { await fs.accessAsync(entryPath, fs.constants.R_OK); res.push({ path: entryPath, name: dirName, dir: dirPath }); } } catch (error) { log.warn(`Path ${entryPath} isn't accessible, skipping...`, error); } } return res; }; module.exports = findDirsWithEntry;
"use strict"; const fs = require("fs-extra-promise"); const path = require("path"); const log = require("log"); const findDirsWithEntry = async (baseDir, entryFile = "index.js") => { const res = []; const dirContent = await fs.readdirAsync(baseDir); for (const dirName of dirContent) { const dirPath = path.join(baseDir, dirName); const entryPath = path.join(dirPath, entryFile); try { fs.accessAsync(entryPath, fs.constants.R_OK); res.push({ path: entryPath, name: dirName, dir: dirPath }); } catch (error) { log.warn(`Path ${entryPath} isn't readable, skipping...`, error); } } return res; }; module.exports = findDirsWithEntry;
Switch to a singleton NOOP. With proper variance, this can be used everywhere. Proper variance is useful in general. When you want to use it, define your service methods thusly: void detonateBombs (int targetId, Callback<? super String> onResult); Then you can pass Callback<String> or Callback<Object> to the service method in question. Java uses what is called "use site" variance declarations, which means that everyone that uses Callback has to repeat this "? super" boilerplate. Java loves boilerplate, so perhaps it's apropos. There is an alternative approach, called "declaration site" variance, which is used by Scala. It allows the Callback declaration to say that it is contravariant in type parameter T: trait Callback[-T] { def onSuccess (value :T) def onFailure (cause :Throwable) } The "-T" means that everywhere someone says they take Callback[T], they actually mean they take (the equivalent of) Callback[? super T]. Things "just work" for everyone who uses Callback and there is much rejoicing. If only we could write everything in Scala.
// // Nexus Core - a framework for developing distributed applications // http://github.com/threerings/nexus/blob/master/LICENSE package com.threerings.nexus.util; /** * Used to communicate asynchronous results. */ public interface Callback<T> { /** A callback that chains failure to the supplied delegate callback. */ public static abstract class Chain<T> implements Callback<T> { public Chain (Callback<?> onFailure) { _onFailure = onFailure; } public void onFailure (Throwable cause) { _onFailure.onFailure(cause); } protected Callback<?> _onFailure; } /** A callback that does nothing, including nothing in the event of failure. Don't use this if * doing so will result in the suppression of errors! */ public static final Callback<Object> NOOP = new Callback<Object>() { @Override public void onSuccess (Object result) {} // noop! @Override public void onFailure (Throwable cause) {} // noop! }; /** * Called when the asynchronous request succeeded, supplying its result. */ void onSuccess (T result); /** * Called when the asynchronous request failed, supplying a cause for failure. */ void onFailure (Throwable cause); }
// // Nexus Core - a framework for developing distributed applications // http://github.com/threerings/nexus/blob/master/LICENSE package com.threerings.nexus.util; /** * Used to communicate asynchronous results. */ public interface Callback<T> { /** A callback that chains failure to the supplied delegate callback. */ public static abstract class Chain<T> implements Callback<T> { public Chain (Callback<?> onFailure) { _onFailure = onFailure; } public void onFailure (Throwable cause) { _onFailure.onFailure(cause); } protected Callback<?> _onFailure; } public static class NoOp<T> implements Callback<T> { @Override public void onSuccess (T result) { // We're a No-Op - do nothing. } @Override public void onFailure (Throwable cause) { // We're a No-Op - do nothing. } } /** * Called when the asynchronous request succeeded, supplying its result. */ void onSuccess (T result); /** * Called when the asynchronous request failed, supplying a cause for failure. */ void onFailure (Throwable cause); }
Update the project URL since it’s no longer in the Kanboard namespace :(
<?php namespace Kanboard\Plugin\Matrix; use Kanboard\Core\Translator; use Kanboard\Core\Plugin\Base; /** * Matrix Plugin * * @package matrix * @author Andrej Shadura */ class Plugin extends Base { public function initialize() { $this->template->hook->attach('template:config:integrations', 'matrix:config/integration'); $this->template->hook->attach('template:project:integrations', 'matrix:project/integration'); $this->projectNotificationTypeModel->setType('matrix', t('Matrix'), '\Kanboard\Plugin\Matrix\Notification\Matrix'); } public function onStartup() { Translator::load($this->languageModel->getCurrentLanguage(), __DIR__.'/Locale'); } public function getPluginDescription() { return 'Receive notifications on Matrix'; } public function getPluginAuthor() { return 'Andrej Shadura'; } public function getPluginVersion() { return '1.0.0'; } public function getPluginHomepage() { return 'https://github.com/andrewshadura/kanboard-plugin-matrix'; } public function getCompatibleVersion() { return '>=1.0.37'; } }
<?php namespace Kanboard\Plugin\Matrix; use Kanboard\Core\Translator; use Kanboard\Core\Plugin\Base; /** * Matrix Plugin * * @package matrix * @author Andrej Shadura */ class Plugin extends Base { public function initialize() { $this->template->hook->attach('template:config:integrations', 'matrix:config/integration'); $this->template->hook->attach('template:project:integrations', 'matrix:project/integration'); $this->projectNotificationTypeModel->setType('matrix', t('Matrix'), '\Kanboard\Plugin\Matrix\Notification\Matrix'); } public function onStartup() { Translator::load($this->languageModel->getCurrentLanguage(), __DIR__.'/Locale'); } public function getPluginDescription() { return 'Receive notifications on Matrix'; } public function getPluginAuthor() { return 'Andrej Shadura'; } public function getPluginVersion() { return '1.0.0'; } public function getPluginHomepage() { return 'https://github.com/kanboard/plugin-matrix'; } public function getCompatibleVersion() { return '>=1.0.37'; } }
Fix issue with multiple lines
# -*- coding: utf-8 -*- # © 2004-2009 Tiny SPRL (<http://tiny.be>). # © 2015 Pedro M. Baeza # © 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import api, fields, models import openerp.addons.decimal_precision as dp class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.depends('discount') def _compute_amount(self): prices = {} for line in self: if line.discount: prices[line.id] = line.price_unit line.price_unit *= (1 - line.discount / 100.0) super(PurchaseOrderLine, self)._compute_amount() # restore prices for line in self: if line.discount: line.price_unit = prices[line.id] discount = fields.Float( string='Discount (%)', digits_compute=dp.get_precision('Discount')) _sql_constraints = [ ('discount_limit', 'CHECK (discount <= 100.0)', 'Discount must be lower than 100%.'), ]
# -*- coding: utf-8 -*- # © 2004-2009 Tiny SPRL (<http://tiny.be>). # © 2015 Pedro M. Baeza # © 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import api, fields, models import openerp.addons.decimal_precision as dp class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.depends('discount') def _compute_amount(self): prices = {} for line in self: if line.discount: prices[line.id] = line.price_unit line.price_unit *= (1 - line.discount / 100.0) super(PurchaseOrderLine, self)._compute_amount() # restore prices for line in self: if self.discount: line.price_unit = prices[line.id] discount = fields.Float( string='Discount (%)', digits_compute=dp.get_precision('Discount')) _sql_constraints = [ ('discount_limit', 'CHECK (discount <= 100.0)', 'Discount must be lower than 100%.'), ]
Revert accidentally changes test case
package com.maxmind.geoip; /* CityLookupTest.java */ import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class CityLookupIdxTest { private static final double DELTA = 1e-5; @Test public void testCityLookupIdx() throws IOException { LookupService cl = new LookupService( "src/test/resources/GeoIP/GeoIPCity.dat", LookupService.GEOIP_INDEX_CACHE); Location l1 = cl.getLocation("222.230.137.0"); assertEquals("JP", l1.countryCode); assertEquals("Japan", l1.countryName); assertEquals("40", l1.region); assertEquals("Tokyo", l1.city); assertEquals(35.6850, l1.latitude, DELTA); assertEquals(139.7510, l1.longitude, DELTA); assertEquals(0, l1.metro_code); assertEquals(0, l1.area_code); cl.close(); } }
package com.maxmind.geoip; /* CityLookupTest.java */ import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class CityLookupIdxTest { private static final double DELTA = 1e-5; @Test public void testCityLookupIdx() throws IOException { LookupService cl = new LookupService( "/usr/share/GeoIP/GeoIPCity.dat", LookupService.GEOIP_INDEX_CACHE); Location l1 = cl.getLocation("131.130.1.11"); // assertEquals("JP", l1.countryCode); // assertEquals("Japan", l1.countryName); // assertEquals("40", l1.region); assertEquals("Tokyo", l1.city); assertEquals(35.6850, l1.latitude, DELTA); assertEquals(139.7510, l1.longitude, DELTA); assertEquals(0, l1.metro_code); assertEquals(0, l1.area_code); cl.close(); } }
Fix missing next in context.
# -#- coding: utf-8 -#- from django.db import models from django.utils.translation import ugettext_lazy as _ from leonardo.module.web.models import Widget LOGIN_TYPE_CHOICES = ( (1, _("Admin")), (2, _("Public")), ) class UserLoginWidget(Widget): type = models.PositiveIntegerField(verbose_name=_( "type"), choices=LOGIN_TYPE_CHOICES, default=2) def get_context_data(self, request): context = super(UserLoginWidget, self).get_context_data(request) if 'next' in request.GET: context['next'] = request.GET['next'] else: context['next'] = request.path return context class Meta: abstract = True verbose_name = _("user login") verbose_name_plural = _("user logins")
# -#- coding: utf-8 -#- from django.db import models from django.utils.translation import ugettext_lazy as _ from leonardo.module.web.models import Widget LOGIN_TYPE_CHOICES = ( (1, _("Admin")), (2, _("Public")), ) class UserLoginWidget(Widget): type = models.PositiveIntegerField(verbose_name=_( "type"), choices=LOGIN_TYPE_CHOICES, default=2) def get_context_data(self, request): context = super(UserLoginWidget, self).get_context_data(request) if 'next' in request.GET: context['next'] = request.GET['next'] return context class Meta: abstract = True verbose_name = _("user login") verbose_name_plural = _("user logins")
Add entry_points to run executable pygraphc
from setuptools import setup setup(name='pygraphc', version='0.0.1', description='Event log clustering in Python', long_description='This package contains event log clustering method including non-graph and ' 'graph-based approaches.', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Security', ], keywords='log clustering graph anomaly', url='http://github.com/studiawan/pygraphc/', author='Hudan Studiawan', author_email='studiawan@gmail.com', license='MIT', packages=['pygraphc'], scripts=['scripts/pygraphc'], entry_points={ 'console_scripts': ['pygraphc=scripts.pygraphc:main'] }, install_requires=[ 'networkx', 'scikit-learn', 'nltk', 'Sphinx', 'numpydoc', 'TextBlob', ], include_package_data=True, zip_safe=False)
from setuptools import setup setup(name='pygraphc', version='0.0.1', description='Event log clustering in Python', long_description='This package contains event log clustering method including non-graph and ' 'graph-based approaches.', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Security', ], keywords='log clustering graph anomaly', url='http://github.com/studiawan/pygraphc/', author='Hudan Studiawan', author_email='studiawan@gmail.com', license='MIT', packages=['pygraphc'], scripts=['scripts/pygraphc'], install_requires=[ 'networkx', 'numpy', 'scipy', 'scikit-learn', 'nltk', 'Sphinx', 'numpydoc', 'TextBlob', ], include_package_data=True, zip_safe=False)
Add arguments for interarrival and service rates.
#!/usr/bin/env python # encoding: utf-8 import argparse import mm1 import sim import time ### Parse command line arguments parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script") parser.add_argument('sim_duration', metavar='simulation_duration', type=int, help='simulation duration in seconds') parser.add_argument('int_rate', metavar='interarrival_rate', type=int, help='mean packet interarrival rate in seconds') parser.add_argument('sr_rate', metavar='service_rate', type=int, help='mean packet service rate in seconds') parser.add_argument('--seed', dest='seed', default=int(round(time.time())), type=int, help='seed for the PRNG (default: current system timestamp)') args = parser.parse_args() sim_duration = args.sim_duration interarrival_rate = args.int_rate service_rate = args.sr_rate seed = args.seed ### Initialize # Create new simulation engine se = sim.SimulationEngine() # Seed default PRNG se.prng.seed = seed # Create MM1 specific event handler event_handler = mm1.MM1EventHandler() event_handler.interarrival_rate = interarrival_rate event_handler.service_rate = service_rate ### Simulate # Schedule finishing event se.stop(sim_duration) # Start simulating se.start()
#!/usr/bin/env python # encoding: utf-8 import argparse import mm1 import sim import time ### Parse command line arguments parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script") parser.add_argument('sim_duration', metavar='simulation_duration', type=int, help='simulation duration in seconds') parser.add_argument('--seed', dest='seed', default=int(round(time.time())), type=int, help='seed for the PRNG (default: current system timestamp)') args = parser.parse_args() sim_duration = args.sim_duration seed = args.seed ### Params # Mean interarrival rate of customers per second; # hence, 0.05 <=> 3 people/minute interarrival_rate = 0.05 # Mean service rate by the teller per second; # hence, 0.1 <=> 6 people/minute service_rate = 0.1 ### Initialize # Create new simulation engine se = sim.SimulationEngine() # Seed default PRNG se.prng.seed = seed # Create MM1 specific event handler event_handler = mm1.MM1EventHandler() event_handler.interarrival_rate = interarrival_rate event_handler.service_rate = service_rate ### Simulate # Schedule finishing event se.stop(sim_duration) # Start simulating se.start()
Use results instead of result in search part.
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details. 'use strict'; module.exports = function searchResultsTemplate(searchResultsPart, renderer, done) { var results = searchResultsPart.results; if (Array.isArray(results)) { renderer.startTag('ul', { 'class': 'search-results search-results-' + searchResultsPart.meta.name }); searchResultsPart.results.forEach(function renderResultEntry(entry) { renderer.startTag('li'); if (entry.url) { renderer.tag('a', {href: entry.url}, entry.title); } else { renderer.write(entry.title); } renderer.endTag(); }); renderer .endTag() .finally(done); } else { renderer.write(results).finally(done); } };
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details. 'use strict'; module.exports = function searchResultsTemplate(searchResultsPart, renderer, done) { var result = searchResultsPart.result; if (Array.isArray(result)) { renderer.startTag('ul', { 'class': 'search-results search-results-' + searchResultsPart.meta.name }); searchResultsPart.result.forEach(function renderResultEntry(entry) { renderer.startTag('li'); if (entry.url) { renderer.tag('a', {href: entry.url}, entry.title); } else { renderer.write(entry.title); } renderer.endTag(); }); renderer .endTag() .finally(done); } else { renderer.write(result).finally(done); } };
Add current date to generated HTML
import datetime import os now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") template_header = """<html> <head><title>Littlefield Charts</title></head> <body> <p>Data last collected: %s</p> <table>""" % now template_footer = """</table> <p><a href="production.csv">Download production data</a></p> <p><a href="rankings.csv">Download latest rankings</a></p> </body> </html>""" root = os.path.abspath(os.path.dirname(__file__)) os.chdir(root) # Just to make sure files = os.listdir(os.getcwd()) charts = [f for f in files if f.endswith('.png')] charts.sort() img_tags = [] for c in charts: img = "<tr><div style=\"text-align: center; background: #8EC5EF;\">%s</div><img src=\"%s\" /></tr>" % (c[:-4], c) img_tags.append(img) rows = '\n'.join(img_tags) template = "%s%s%s" % (template_header, rows, template_footer) with open('index.html', 'wb') as f: f.write(template)
import os template_header = """<html> <head><title>Littlefield Charts</title></head> <body> <table>""" template_footer = """</table> <p><a href="production.csv">Download production data</a></p> <p><a href="rankings.csv">Download latest rankings</a></p> </body> </html>""" root = os.path.abspath(os.path.dirname(__file__)) os.chdir(root) # Just to make sure files = os.listdir(os.getcwd()) charts = [f for f in files if f.endswith('.png')] charts.sort() img_tags = [] for c in charts: img = "<tr><div style=\"text-align: center; background: #8EC5EF;\">%s</div><img src=\"%s\" /></tr>" % (c[:-4], c) img_tags.append(img) rows = '\n'.join(img_tags) template = "%s%s%s" % (template_header, rows, template_footer) with open('index.html', 'wb') as f: f.write(template)
BAP-3243: Create chart view layer - CR changes
<?php namespace Oro\Bundle\ChartBundle\Model; use Oro\Bundle\ChartBundle\Model\Data\DataInterface; class ChartView { /** * @var \Twig_Environment */ protected $twig; /** * Chart template * * @var string */ protected $template; /** * Chart view data * * @var DataInterface */ protected $data; /** * Chart view variables * * @var array */ protected $vars; /** * @param \Twig_Environment $twig * @param DataInterface $data * @param string $template * @param array $vars Chart view vars */ public function __construct(\Twig_Environment $twig, $template, DataInterface $data, array $vars) { $this->twig = $twig; $this->template = $template; $this->data = $data; $this->vars = $vars; } /** * Render chart * * @return string */ public function render() { $context = $this->vars; $context['data'] = $this->data->toArray(); return $this->twig->render($this->template, $context); } }
<?php namespace Oro\Bundle\ChartBundle\Model; use Oro\Bundle\ChartBundle\Model\Data\DataInterface; class ChartView { /** * @var \Twig_Environment */ protected $twig; /** * Chart template * * @var string */ protected $template; /** * Chart view variables * * @var array */ protected $vars; /** * @param \Twig_Environment $twig * @param DataInterface $data * @param string $template * @param array $vars Chart view vars */ public function __construct(\Twig_Environment $twig, $template, DataInterface $data, array $vars) { $this->twig = $twig; $this->template = $template; $this->data = $data; $this->vars = $vars; } /** * Render chart * * @return string */ public function render() { $context = $this->vars; $context['data'] = $this->data->toArray(); return $this->twig->render($this->template, $context); } }
Rename current user const value name
package middleware import ( "github.com/gin-gonic/gin" oauth_service "github.com/torinos-io/api/service/oauth_service" user_store "github.com/torinos-io/api/store/user_store" "github.com/torinos-io/api/type/system" ) const ( currentUserContextName = "CurrentUser" ) // SetCurrentUser sets current authenticated user from authorization header func SetCurrentUser(appContext *system.AppContext) gin.HandlerFunc { return func(c *gin.Context) { h := c.GetHeader("Authorization") if h == "" { c.Next() return } userStore := user_store.New(appContext.MainDB) service := oauth_service.New(oauth_service.Context{ Config: appContext.Config, UserStore: userStore, }) user, err := service.FindByAuthToken(h) if err != nil { c.Next() return } c.Set(currentUserContextName, user) c.Next() } }
package middleware import ( "github.com/gin-gonic/gin" oauth_service "github.com/torinos-io/api/service/oauth_service" user_store "github.com/torinos-io/api/store/user_store" "github.com/torinos-io/api/type/system" ) const ( currentuser = "CurrentUser" ) // SetCurrentUser sets current authenticated user from authorization header func SetCurrentUser(appContext *system.AppContext) gin.HandlerFunc { return func(c *gin.Context) { h := c.GetHeader("Authorization") if h == "" { c.Next() return } userStore := user_store.New(appContext.MainDB) service := oauth_service.New(oauth_service.Context{ Config: appContext.Config, UserStore: userStore, }) user, err := service.FindByAuthToken(h) if err != nil { c.Next() return } c.Set(currentuser, user) c.Next() } }
Add "until" attribute to list handled by hook TaskWarrior 2.5.1 (and possibly earlier versions) does not shift the "until" attribute appropriately during recurrence. This hook provides a workaround for that. Fixes [#6](https://github.com/tbabej/task.shift-recurrence/issues/6).
#!/usr/bin/python import sys import os from tasklib import TaskWarrior time_attributes = ('wait', 'scheduled', 'until') def is_new_local_recurrence_child_task(task): # Do not affect tasks not spun by recurrence if not task['parent']: return False # Newly created recurrence tasks actually have # modified field copied from the parent, thus # older than entry field (until their ID is generated) if (task['modified'] - task['entry']).total_seconds() < 0: return True tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0]))) tw.overrides.update(dict(recurrence="no", hooks="no")) def hook_shift_recurrence(task): if is_new_local_recurrence_child_task(task): parent = tw.tasks.get(uuid=task['parent']['uuid']) parent_due_shift = task['due'] - parent['due'] for attr in time_attributes: if parent[attr]: task[attr] = parent[attr] + parent_due_shift
#!/usr/bin/python import sys import os from tasklib import TaskWarrior time_attributes = ('wait', 'scheduled') def is_new_local_recurrence_child_task(task): # Do not affect tasks not spun by recurrence if not task['parent']: return False # Newly created recurrence tasks actually have # modified field copied from the parent, thus # older than entry field (until their ID is generated) if (task['modified'] - task['entry']).total_seconds() < 0: return True tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0]))) tw.overrides.update(dict(recurrence="no", hooks="no")) def hook_shift_recurrence(task): if is_new_local_recurrence_child_task(task): parent = tw.tasks.get(uuid=task['parent']['uuid']) parent_due_shift = task['due'] - parent['due'] for attr in time_attributes: if parent[attr]: task[attr] = parent[attr] + parent_due_shift
Change assignment assertion in accessors' tests to more restrict
<?php namespace MageTest\Command; use Mage\Command\AbstractCommand; use MageTest\TestHelper\BaseTest; use PHPUnit_Framework_MockObject_MockObject; /** * Class AbstractCommandTest * @package MageTest\Command * @author Jakub Turek <ja@kubaturek.pl> * @coversDefaultClass Mage\Command\AbstractCommand */ class AbstractCommandTest extends BaseTest { /** * @var AbstractCommand|PHPUnit_Framework_MockObject_MockObject */ private $abstractCommand; /** * @before */ public function before() { $this->abstractCommand = $this->getMockForAbstractClass('Mage\Command\AbstractCommand'); } /** * @covers ::setConfig */ public function testSetConfig() { $configMock = $this->getMock('Mage\Config'); $this->abstractCommand->setConfig($configMock); $actual = $this->getPropertyValue($this->abstractCommand, 'config'); $this->assertSame($configMock, $actual); } /** * @covers ::getConfig */ public function testGetConfig() { $configMock = $this->getMock('Mage\Config'); $this->setPropertyValue($this->abstractCommand, 'config', $configMock); $actual = $this->abstractCommand->getConfig(); $this->assertSame($configMock, $actual); } }
<?php namespace MageTest\Command; use Mage\Command\AbstractCommand; use MageTest\TestHelper\BaseTest; use PHPUnit_Framework_MockObject_MockObject; /** * Class AbstractCommandTest * @package MageTest\Command * @author Jakub Turek <ja@kubaturek.pl> * @coversDefaultClass Mage\Command\AbstractCommand */ class AbstractCommandTest extends BaseTest { /** * @var AbstractCommand|PHPUnit_Framework_MockObject_MockObject */ private $abstractCommand; /** * @before */ public function before() { $this->abstractCommand = $this->getMockForAbstractClass('Mage\Command\AbstractCommand'); } /** * @covers ::setConfig */ public function testSetConfig() { $configMock = $this->getMock('Mage\Config'); $this->abstractCommand->setConfig($configMock); $actual = $this->getPropertyValue($this->abstractCommand, 'config'); $this->assertEquals($configMock, $actual); } /** * @covers ::getConfig */ public function testGetConfig() { $configMock = $this->getMock('Mage\Config'); $this->setPropertyValue($this->abstractCommand, 'config', $configMock); $actual = $this->abstractCommand->getConfig(); $this->assertEquals($configMock, $actual); } }
Check APP_ENGINE env var before using hard-coded path to Google AppEngine SDK.
#!/usr/bin/env python import argparse import optparse from os import getenv, path from os.path import expanduser import sys import unittest # Simple stand-alone test runner # - Runs independently of appengine runner # - So we need to find the GAE library # - Looks for tests as ./tests/test*.py # - Use --skipbasics to skip the most basic tests and run only tests/test_graphs*.py # # see https://developers.google.com/appengine/docs/python/tools/localunittesting # # Alt: python -m unittest discover -s tests/ -p 'test_*.py' (problem as needs GAE files) def main(sdk_path, test_path, args): sys.path.insert(0, sdk_path) # add AppEngine SDK to path import dev_appserver dev_appserver.fix_sys_path() print args, test_path if vars(args)["skipbasics"]: suite = unittest.loader.TestLoader().discover(test_path, pattern="test_graphs*.py") else: suite = unittest.loader.TestLoader().discover(test_path) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': sdk_path = getenv('APP_ENGINE', expanduser("~") + '/google-cloud-sdk/platform/google_appengine/') parser = argparse.ArgumentParser(description='Configurable testing of schema.org.') parser.add_argument('--skipbasics', action='store_true', help='Skip basic tests.') args = parser.parse_args() main(sdk_path, './tests/', args)
#!/usr/bin/env python import optparse import sys from os import path from os.path import expanduser import unittest import argparse # Simple stand-alone test runner # - Runs independently of appengine runner # - So we need to find the GAE library # - Looks for tests as ./tests/test*.py # - Use --skipbasics to skip the most basic tests and run only tests/test_graphs*.py # # see https://developers.google.com/appengine/docs/python/tools/localunittesting # # Alt: python -m unittest discover -s tests/ -p 'test_*.py' (problem as needs GAE files) def main(sdk_path, test_path, args): sys.path.insert(0, sdk_path) import dev_appserver dev_appserver.fix_sys_path() print args, test_path if vars(args)["skipbasics"]: suite = unittest.loader.TestLoader().discover(test_path, pattern="test_graphs*.py") else: suite = unittest.loader.TestLoader().discover(test_path) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Configurable testing of schema.org.') parser.add_argument('--skipbasics', action='store_true', help='Skip basic tests.') args = parser.parse_args() main(expanduser("~") + '/google-cloud-sdk/platform/google_appengine/', './tests/', args)
Fix db yargs hookup for bundle
const OS = require("os"); const serveCommand = require("./commands/serve"); const usage = "truffle db <sub-command> [options]" + OS.EOL + OS.EOL + " Available sub-commands: " + OS.EOL + OS.EOL + " serve \tStart the GraphQL server" + OS.EOL; const command = { command: "db", description: "Database interface commands", builder: function (yargs) { return yargs.command(serveCommand).demandCommand(); }, subCommands: { serve: { help: serveCommand.help, description: serveCommand.description } }, help: { usage, options: [] }, run: async function (args) { const [subCommand] = args._; switch (subCommand) { case "serve": await serveCommand.run(args); break; default: console.log(`Unknown command: ${subCommand}`); } } }; module.exports = command;
const OS = require("os"); const serveCommand = require("./commands/serve"); const usage = "truffle db <sub-command> [options]" + OS.EOL + OS.EOL + " Available sub-commands: " + OS.EOL + OS.EOL + " serve \tStart the GraphQL server" + OS.EOL; const command = { command: "db", description: "Database interface commands", builder: function (yargs) { return yargs.commandDir("commands").demandCommand(); }, subCommands: { serve: { help: serveCommand.help, description: serveCommand.description } }, help: { usage, options: [] }, run: async function (args) { const [subCommand] = args._; switch (subCommand) { case "serve": await serveCommand.run(args); break; default: console.log(`Unknown command: ${subCommand}`); } } }; module.exports = command;
MAINT: Remove superfluous test setup after zeit.cms got smarter
import zeit.cms.interfaces import zeit.cms.testing import zeit.content.dynamicfolder.testing class EditDynamicFolder(zeit.cms.testing.BrowserTestCase): layer = zeit.content.dynamicfolder.testing.DYNAMIC_LAYER def test_check_out_and_edit_folder(self): b = self.browser b.open('http://localhost/++skin++vivi/repository/dynamicfolder') b.getLink('Checkout').click() b.getControl( 'Configuration file').value = 'http://xml.zeit.de/testcontent' b.getControl('Apply').click() self.assertEllipsis('...Updated on...', b.contents) b.getLink('Checkin').click() self.assertIn('repository', b.url) folder = zeit.cms.interfaces.ICMSContent( 'http://xml.zeit.de/dynamicfolder') self.assertEqual( 'http://xml.zeit.de/testcontent', folder.config_file.uniqueId)
import zeit.cms.interfaces import zeit.cms.testing import zeit.content.dynamicfolder.testing class EditDynamicFolder(zeit.cms.testing.BrowserTestCase): layer = zeit.content.dynamicfolder.testing.DYNAMIC_LAYER def test_check_out_and_edit_folder(self): b = self.browser b.open('http://localhost/++skin++vivi/repository/dynamicfolder') b.getLink('Checkout').click() b.getControl( 'Configuration file').value = 'http://xml.zeit.de/testcontent' b.getControl('Apply').click() self.assertEllipsis('...Updated on...', b.contents) b.getLink('Checkin').click() self.assertIn('repository', b.url) with zeit.cms.testing.site(self.getRootFolder()): folder = zeit.cms.interfaces.ICMSContent( 'http://xml.zeit.de/dynamicfolder') self.assertEqual( 'http://xml.zeit.de/testcontent', folder.config_file.uniqueId)
Throw new error in order to test nightmare js setup
if(!window.jQuery) window.$ = window.Zepto = require('zepto-browserify').$; require('./components/polyfills.js')(); let warn = (msg) => { if (!window || !window.console) { return; } window.console.warn(msg); }; if (typeof Object.assign !== 'function') { require('object.assign/shim')(); } throw new Error('test!'); window.Storage = require('showcar-storage'); window.Pager = require('./components/pager.js'); require('showcar-icons'); const ctor = document.createElement('as24-tracking').constructor; if (ctor === HTMLElement || ctor === HTMLUnknownElement) { // only requiring showcar-tracking when it was not already included before require('showcar-tracking'); } require('./components/custom-dropdown.js'); $(_ => { require('./components/navigation.js'); require('./components/rotating-arrow.js')(); require('./components/sticky.js')(); require('./components/collapse.js')(); require('./components/scroll.js'); }); if (!window.notification) { window.notification = require('./components/notification.js'); } else { warn('window.notification is already registered.'); }
if(!window.jQuery) window.$ = window.Zepto = require('zepto-browserify').$; require('./components/polyfills.js')(); let warn = (msg) => { if (!window || !window.console) { return; } window.console.warn(msg); }; if (typeof Object.assign !== 'function') { require('object.assign/shim')(); } window.Storage = require('showcar-storage'); window.Pager = require('./components/pager.js'); require('showcar-icons'); const ctor = document.createElement('as24-tracking').constructor; if (ctor === HTMLElement || ctor === HTMLUnknownElement) { // only requiring showcar-tracking when it was not already included before require('showcar-tracking'); } require('./components/custom-dropdown.js'); $(_ => { require('./components/navigation.js'); require('./components/rotating-arrow.js')(); require('./components/sticky.js')(); require('./components/collapse.js')(); require('./components/scroll.js'); }); if (!window.notification) { window.notification = require('./components/notification.js'); } else { warn('window.notification is already registered.'); }
Update collection import to use new class
<?php namespace As3\Modlr\Api; use As3\Modlr\Metadata\EntityMetadata; use As3\Modlr\Models\Collections\Collection; use As3\Modlr\Models\Model; /** * Interface for serializing models in the implementing format. * * @author Jacob Bare <jacob.bare@gmail.com> */ interface SerializerInterface { /** * Serializes a Model object into the appropriate format. * * @param Model|null $model * @param AdapterInterface $adapter * @return string|array Depending on depth */ public function serialize(Model $model = null, AdapterInterface $adapter); /** * Serializes a Collection object into the appropriate format. * * @param Collection $collection * @param AdapterInterface $adapter * @return string|array Depending on depth */ public function serializeCollection(Collection $collection, AdapterInterface $adapter); /** * Serializes an array of Model objects into the appropriate format. * * @param Model[] $models * @param AdapterInterface $adapter * @return string|array Depending on depth */ public function serializeArray(array $models, AdapterInterface $adapter); /** * Gets a serialized error response. * * @return string */ public function serializeError($title, $detail, $httpCode); }
<?php namespace As3\Modlr\Api; use As3\Modlr\Metadata\EntityMetadata; use As3\Modlr\Models\Collection; use As3\Modlr\Models\Model; /** * Interface for serializing models in the implementing format. * * @author Jacob Bare <jacob.bare@gmail.com> */ interface SerializerInterface { /** * Serializes a Model object into the appropriate format. * * @param Model|null $model * @param AdapterInterface $adapter * @return string|array Depending on depth */ public function serialize(Model $model = null, AdapterInterface $adapter); /** * Serializes a Collection object into the appropriate format. * * @param Collection $collection * @param AdapterInterface $adapter * @return string|array Depending on depth */ public function serializeCollection(Collection $collection, AdapterInterface $adapter); /** * Serializes an array of Model objects into the appropriate format. * * @param Model[] $models * @param AdapterInterface $adapter * @return string|array Depending on depth */ public function serializeArray(array $models, AdapterInterface $adapter); /** * Gets a serialized error response. * * @return string */ public function serializeError($title, $detail, $httpCode); }
Change email address and home page.
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from setuptools import setup, Extension setup( name = 'python-ad', version = '0.9', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geertj@gmail.com', url = 'https://github.com/geertj/python-ad', license = 'MIT', classifiers = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python'], package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util'], install_requires = [ 'python-ldap', 'dnspython', 'ply' ], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])], test_suite = 'nose.collector' )
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from setuptools import setup, Extension setup( name = 'python-ad', version = '0.9', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://code.google.com/p/python-ad', license = 'MIT', classifiers = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python'], package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util'], install_requires = [ 'python-ldap', 'dnspython', 'ply' ], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])], test_suite = 'nose.collector' )
Check if user is banned in /actions API
import * as actionCore from '../core/action-core'; import {createJsonRoute, throwStatus} from '../util/express'; import {assert} from '../validation'; import * as banCore from '../core/ban-core'; import * as imageHttp from './image-http'; import * as throttleCore from '../core/throttle-core'; let postAction = createJsonRoute(function(req, res) { const action = assert(req.body, 'action'); if (!throttleCore.canDoAction(action.user, action.type)) { throwStatus(429, `Too many actions of type ${ action.type }`); } else if (banCore.isUserBanned(action.user)) { banCore.throwBannedError(); } let handleAction; if (action.type === 'IMAGE') { handleAction = imageHttp.postImage(req, res, action); } else { action.ip = req.ip; handleAction = actionCore.getActionType(action.type) .then(type => { if (type === null) { throwStatus(400, 'Action type ' + action.type + ' does not exist'); } }) .then(() => { return actionCore.createAction(action).then(rowsInserted => undefined); }); } return handleAction .then(() => throttleCore.executeAction(action.user, action.type)); }); export { postAction };
import * as actionCore from '../core/action-core'; import {createJsonRoute, throwStatus} from '../util/express'; import {assert} from '../validation'; import * as imageHttp from './image-http'; import * as throttleCore from '../core/throttle-core'; let postAction = createJsonRoute(function(req, res) { const action = assert(req.body, 'action'); if (!throttleCore.canDoAction(action.user, action.type)) { throwStatus(429, `Too many actions of type ${ action.type }`); } let handleAction; if (action.type === 'IMAGE') { handleAction = imageHttp.postImage(req, res, action); } else { action.ip = req.ip; handleAction = actionCore.getActionType(action.type) .then(type => { if (type === null) { throwStatus(400, 'Action type ' + action.type + ' does not exist'); } }) .then(() => { return actionCore.createAction(action).then(rowsInserted => undefined); }); } return handleAction .then(() => throttleCore.executeAction(action.user, action.type)); }); export { postAction };
Add missing confirmation dialog for hard reset Added the missing confirmation dialog for Reset->Hard action in History view. Bug: 319947 Change-Id: I1fab712e20a0087ce6f91903968416c24e3d902a Signed-off-by: Jens Baumgart <6d4d33e37bca550188034acaf6d86b3d82efd688@sap.com>
/******************************************************************************* * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.actions; import java.util.List; import org.eclipse.egit.core.op.IEGitOperation; import org.eclipse.egit.core.op.ResetOperation; import org.eclipse.egit.ui.UIText; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jgit.revwalk.RevCommit; /** * Hard reset to selected revision */ public class HardResetToRevisionAction extends AbstractRevCommitOperationAction { @Override protected IEGitOperation createOperation(final List<RevCommit> commits) { return new ResetOperation(getActiveRepository(), commits.get(0).getName(), ResetOperation.ResetType.HARD); } @Override protected String getJobName() { return UIText.HardResetToRevisionAction_hardReset; } @Override public void run(IAction act) { if (!MessageDialog.openQuestion(wp.getSite().getShell(), UIText.ResetTargetSelectionDialog_ResetQuestion, UIText.ResetTargetSelectionDialog_ResetConfirmQuestion)) return; super.run(act); } }
/******************************************************************************* * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.actions; import java.util.List; import org.eclipse.egit.core.op.IEGitOperation; import org.eclipse.egit.core.op.ResetOperation; import org.eclipse.egit.ui.UIText; import org.eclipse.jgit.revwalk.RevCommit; /** * Hard reset to selected revision */ public class HardResetToRevisionAction extends AbstractRevCommitOperationAction { @Override protected IEGitOperation createOperation(final List<RevCommit> commits) { return new ResetOperation(getActiveRepository(), commits.get(0).getName(), ResetOperation.ResetType.HARD); } @Override protected String getJobName() { return UIText.HardResetToRevisionAction_hardReset; } }
Fix relationship between question and poll.
<?php namespace VoyagerPolls\Models; use Illuminate\Database\Eloquent\Model; class PollQuestion extends Model { protected $table = 'voyager_poll_questions'; protected $fillable = ['poll_id', 'question', 'order']; protected $appends = ['answered']; public function answers(){ return $this->hasMany('VoyagerPolls\Models\PollAnswer', 'question_id')->orderBy('order', 'ASC'); } public function poll() { return $this->belongsTo('VoyagerPolls\Models\Poll', 'poll_id'); } public function totalVotes(){ $totalVotes = 0; foreach($this->answers as $answers){ $totalVotes += $answers->votes; } return $totalVotes; } public function getAnsweredAttribute(){ return false; } }
<?php namespace VoyagerPolls\Models; use Illuminate\Database\Eloquent\Model; class PollQuestion extends Model { protected $table = 'voyager_poll_questions'; protected $fillable = ['poll_id', 'question', 'order']; protected $appends = ['answered']; public function answers(){ return $this->hasMany('VoyagerPolls\Models\PollAnswer', 'question_id')->orderBy('order', 'ASC'); } public function totalVotes(){ $totalVotes = 0; foreach($this->answers as $answers){ $totalVotes += $answers->votes; } return $totalVotes; } public function getAnsweredAttribute(){ return false; } }
Update Requirements.name to Reqs enum
package edu.umn.csci5801.model; import java.util.List; /** * Created by Justin on 12/2/2014. */ public class GradReqCheck { private Reqs reqName; private boolean result; private Requirement details; public GradReqCheck() {} public GradReqCheck(Reqs n) { reqName = n; } public void setReqName(Reqs n) { reqName = n; } public void setResult(boolean ic) { result = ic; } public void setDetails(Requirement r) { details = r; } public Reqs getReqName() { return reqName; } public boolean getResult() { return result; } public Requirement getDetails() { return details; } public void testReq(Requirement requirement, List<CourseTaken> courseTakenList, List<CompletedMilestone> completedMilestoneList) { //DETERMINE WHETHER REQUIREMENT PASSED IN IS MET IN COURSETAKENLIST AND COMPLETEDMILESTONES //TODO: Logic for checking any given requirement switch (requirement.getName()) { //TODO: Fill in all the different case statements (one for each possible requirement name case BREADTH_REQUIREMENT_MS: } } }
package edu.umn.csci5801.model; import java.util.List; /** * Created by Justin on 12/2/2014. */ public class GradReqCheck { private String reqName; private boolean result; private Requirement details; public GradReqCheck() {} public GradReqCheck(String n) { reqName = n; } public void setReqName(String n) { reqName = n; } public void setResult(boolean ic) { result = ic; } public void setDetails(Requirement r) { details = r; } public String getReqName() { return reqName; } public boolean getResult() { return result; } public Requirement getDetails() { return details; } public void testReq(Requirement requirement, List<CourseTaken> courseTakenList, List<CompletedMilestone> completedMilestoneList) { //DETERMINE WHETHER REQUIREMENT PASSED IN IS MET IN COURSETAKENLIST AND COMPLETEDMILESTONES //TODO: Logic for checking any given requirement switch (requirement.getName()) { //TODO: Fill in all the different case statements (one for each possible requirement name case "BREADTH_REQUIREMENT_MS": } } }
Add alias and payload to GH's boilerplate
/* * Copyright 2013, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/eduardolundgren/blob/master/LICENSE.md * * @author Author <email@email.com> */ // -- Requires ----------------------------------------------------------------- var base = require('../base'), logger = require('../logger'); // -- Constructor -------------------------------------------------------------- function Hello(options) { this.options = options; } // -- Constants ---------------------------------------------------------------- Hello.DETAILS = { alias: 'he', description: 'Hello world example. Copy to start a new command.', options: { 'world': Boolean }, shorthands: { 'w': [ '--world' ] }, payload: function(payload, options) { options.world = true; } }; // -- Commands ----------------------------------------------------------------- Hello.prototype.run = function() { var instance = this, options = instance.options; if (options.world) { instance.world(); } }; Hello.prototype.world = function() { logger.log('hello world :)'); }; exports.Impl = Hello;
/* * Copyright 2013, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/eduardolundgren/blob/master/LICENSE.md * * @author Author <email@email.com> */ // -- Requires ----------------------------------------------------------------- var base = require('../base'), logger = require('../logger'); // -- Constructor -------------------------------------------------------------- function Hello(options) { this.options = options; } // -- Constants ---------------------------------------------------------------- Hello.DETAILS = { description: 'Hello world example. Copy to start a new command.', options: { 'world': Boolean }, shorthands: { 'w': [ '--world' ] } }; // -- Commands ----------------------------------------------------------------- Hello.prototype.run = function() { var instance = this, options = instance.options; instance.world(); }; Hello.prototype.world = function() { logger.log('hello world :)'); }; exports.Impl = Hello;
Fix NWjs bug not triggering process exit event Call process.exit() directly instead of using nwApp.quit(). Fixes gdbus child process not being terminated on exit.
import { get, inject, Service } from "ember"; import nwWindow, { toggleVisibility, toggleMaximized, toggleMinimized } from "nwjs/Window"; const { service } = inject; export default Service.extend({ modal: service(), settings: service(), streaming: service(), reload() { nwWindow.reloadIgnoringCache(); }, devTools() { nwWindow.showDevTools(); }, minimize() { let integration = get( this, "settings.gui_integration" ); let minimizetotray = get( this, "settings.gui_minimizetotray" ); // tray only or both with min2tray: just hide the window if ( integration === 2 || integration === 3 && minimizetotray ) { toggleVisibility(); } else { toggleMinimized(); } }, maximize() { toggleMaximized(); }, close() { const streams = get( this, "streaming.model" ).toArray(); if ( streams.length && streams.some( stream => !get( stream, "hasEnded" ) ) ) { get( this, "modal" ).openModal( "quit", this ); } else { this.quit(); } }, quit() { process.exit(); } });
import { get, inject, Service } from "ember"; import nwApp from "nwjs/App"; import nwWindow, { toggleVisibility, toggleMaximized, toggleMinimized } from "nwjs/Window"; const { service } = inject; export default Service.extend({ modal: service(), settings: service(), streaming: service(), reload() { nwWindow.reloadIgnoringCache(); }, devTools() { nwWindow.showDevTools(); }, minimize() { let integration = get( this, "settings.gui_integration" ); let minimizetotray = get( this, "settings.gui_minimizetotray" ); // tray only or both with min2tray: just hide the window if ( integration === 2 || integration === 3 && minimizetotray ) { toggleVisibility(); } else { toggleMinimized(); } }, maximize() { toggleMaximized(); }, close() { const streams = get( this, "streaming.model" ).toArray(); if ( streams.length && streams.some( stream => !get( stream, "hasEnded" ) ) ) { get( this, "modal" ).openModal( "quit", this ); } else { this.quit(); } }, quit() { nwApp.quit(); } });
Fix pathing for directory creation
#!/usr/bin/env node 'use strict'; var program = require('commander') , gulp = require('gulp') , chalk = require('chalk') , exec = require('exec') var strings = { create: 'Creating new project', install: 'Installing dependencies', complete: 'Done!' } function notify(message) { if (!program.quiet) console.log(chalk.green(message)) } function installDependencies(name) { notify(strings.install) exec('cd ' + name + ' && npm install', function () { notify(strings.complete) }) } function newProject(name) { notify(strings.create, name) gulp.src([__dirname + '/assets/**/*', __dirname + '/assets/.*']) .pipe(gulp.dest(process.cwd() + '/' + name)) .on('end', installDependencies.bind(this, name)) } program .version('0.0.0') .option('-q, --quiet', 'Hide logging information') program .command('new <name>') .description('scaffold out a new app in the current directory') .action(newProject) program.parse(process.argv);
#!/usr/bin/env node 'use strict'; var program = require('commander') , gulp = require('gulp') , chalk = require('chalk') , exec = require('exec') var strings = { create: 'Creating new project', install: 'Installing dependencies', complete: 'Done!' } function notify(message) { if (!program.quiet) console.log(chalk.green(message)) } function installDependencies(name) { notify(strings.install) exec('cd ' + name + ' && npm install', function () { notify(strings.complete) }) } function newProject(name) { notify(strings.create, name) gulp.src(['./assets/**/*', './assets/.*']) .pipe(gulp.dest(__dirname + '/' + name)) .on('end', installDependencies.bind(this, name)) } program .version('0.0.0') .option('-q, --quiet', 'Hide logging information') program .command('new <name>') .description('scaffold out a new app in the current directory') .action(newProject) program.parse(process.argv);
Rename `options` param to `config` to bring it inline with other plugins
import onBackspace from './utils/onBackspace'; // Block-Types to be handled will be stored here let types = []; const cleanupEmptyPlugin = (config = {}) => { types = config.types || []; return { handleKeyCommand(command, { getEditorState, setEditorState }) { const editorState = getEditorState(); let newEditorState = null; if (command.indexOf('backspace') === 0) { newEditorState = onBackspace(editorState, types); } if (newEditorState) { setEditorState(newEditorState); return true; } return false; }, }; }; export default cleanupEmptyPlugin; // Use this to add one type to the list export const cleanupType = item => types.push(item); // Use this to add multiple types to the list export const cleanupTypes = items => types.push(...items);
import onBackspace from './utils/onBackspace'; // Block-Types to be handled will be stored here let types = []; const cleanupEmptyPlugin = (options = {}) => { types = options.types || []; return { handleKeyCommand(command, { getEditorState, setEditorState }) { const editorState = getEditorState(); let newEditorState = null; if (command.indexOf('backspace') === 0) { newEditorState = onBackspace(editorState, types); } if (newEditorState) { setEditorState(newEditorState); return true; } return false; }, }; }; export default cleanupEmptyPlugin; // Use this to add one type to the list export const cleanupType = item => types.push(item); // Use this to add multiple types to the list export const cleanupTypes = items => types.push(...items);
Change main script name to nmcontrol.py
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /* * Copyright (C) 2012, Anthony Prieur & Daniel Oppenheim. All rights reserved. * * Original from SL4A modified to allow to embed Interpreter and scripts into an APK */ package info.namecoin.nmcontrolandroid.config; public class GlobalConstants { public static final String PYTHON_MAIN_SCRIPT_NAME = "nmcontrol.py"; public static final String PYTHON_PROJECT_ZIP_NAME = "my_python_project.zip"; public static final String PYTHON_ZIP_NAME = "python_27.zip"; public static final String PYTHON_EXTRAS_ZIP_NAME = "python_extras_27.zip"; public static final boolean IS_FOREGROUND_SERVICE = true; public static final String LOG_TAG = "PythonAPK"; }
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /* * Copyright (C) 2012, Anthony Prieur & Daniel Oppenheim. All rights reserved. * * Original from SL4A modified to allow to embed Interpreter and scripts into an APK */ package info.namecoin.nmcontrolandroid.config; public class GlobalConstants { public static final String PYTHON_MAIN_SCRIPT_NAME = "hello.py"; public static final String PYTHON_PROJECT_ZIP_NAME = "my_python_project.zip"; public static final String PYTHON_ZIP_NAME = "python_27.zip"; public static final String PYTHON_EXTRAS_ZIP_NAME = "python_extras_27.zip"; public static final boolean IS_FOREGROUND_SERVICE = true; public static final String LOG_TAG = "PythonAPK"; }
Add version contraints for sinon and chai
Package.describe({ summary: "Meteor unit testing framework for packages", name: "spacejamio:munit", version: "1.0.0", git: "https://github.com/spacejamio/meteor-munit.git" }); Package.onUse(function (api, where) { api.versionsFrom('0.9.0'); api.use(["coffeescript", "underscore"]); api.use(["tinytest","test-helpers"]); api.use(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]); api.imply(["tinytest","test-helpers"]); api.imply(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]); api.addFiles("namespaces.js"); api.addFiles("async_multi.js"); api.addFiles("Munit.coffee"); api.addFiles("Helpers.coffee"); api.addFiles("Describe.coffee"); api.export(['lvTestAsyncMulti']); api.export(['Munit', 'chai']); api.export(['describe', 'it', 'beforeAll', 'beforeEach', 'afterEach', 'afterAll']); }); Package.onTest(function(api) { api.use(["coffeescript", "spacejamio:munit"]); api.addFiles("tests/TestRunnerTest.coffee"); api.addFiles("tests/HelpersTest.coffee"); api.addFiles("tests/DescribeTest.coffee"); });
Package.describe({ summary: "Meteor unit testing framework for packages", name: "spacejamio:munit", version: "1.0.0", git: "https://github.com/spacejamio/meteor-munit.git" }); Package.onUse(function (api, where) { api.versionsFrom('0.9.0'); api.use(["coffeescript", "underscore"]); api.use(["tinytest","test-helpers"]); api.use(["spacejamio:chai","spacejamio:sinon"]); api.imply(["tinytest","test-helpers"]); api.imply(["spacejamio:chai","spacejamio:sinon"]); api.addFiles("namespaces.js"); api.addFiles("async_multi.js"); api.addFiles("Munit.coffee"); api.addFiles("Helpers.coffee"); api.addFiles("Describe.coffee"); api.export(['lvTestAsyncMulti']); api.export(['Munit', 'chai']); api.export(['describe', 'it', 'beforeAll', 'beforeEach', 'afterEach', 'afterAll']); }); Package.onTest(function(api) { api.use(["coffeescript", "spacejamio:munit"]); api.addFiles("tests/TestRunnerTest.coffee"); api.addFiles("tests/HelpersTest.coffee"); api.addFiles("tests/DescribeTest.coffee"); });
Remove postcss from webpack because it doesn't work
const { resolve } = require('path'); const webpack = require('webpack'); module.exports = { entry: [ 'react-hot-loader/patch', 'webpack-dev-server/client?http://localhost:9000', 'webpack/hot/only-dev-server', './index.js' ], output: { filename: 'bundle.js', path: resolve(__dirname, 'dist'), publicPath: '/' }, context: resolve(__dirname, 'src'), devtool: 'inline-source-map', devServer: { hot: true, contentBase: resolve(__dirname, 'dist'), publicPath: '/', port: 9000 }, module: { rules: [ { test: /\.js$/, use: [ 'babel-loader', ], exclude: /node_modules/ }, { test: /\.css$/, use: [ 'style-loader', 'css-loader?modules', ], }, ], }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin() ], };
const { resolve } = require('path'); const webpack = require('webpack'); module.exports = { entry: [ 'react-hot-loader/patch', 'webpack-dev-server/client?http://localhost:9000', 'webpack/hot/only-dev-server', './index.js' ], output: { filename: 'bundle.js', path: resolve(__dirname, 'dist'), publicPath: '/' }, context: resolve(__dirname, 'src'), devtool: 'inline-source-map', devServer: { hot: true, contentBase: resolve(__dirname, 'dist'), publicPath: '/', port: 9000 }, module: { rules: [ { test: /\.js$/, use: [ 'babel-loader', ], exclude: /node_modules/ }, { test: /\.css$/, use: [ 'style-loader', 'css-loader?modules', 'postcss-loader', ], }, ], }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin() ], };
Update for loop to be old-js compatible
'use strict'; var reshape = require('reshape') exports.name = 'reshape'; exports.inputFormats = ['reshape', 'html']; exports.outputFormat = 'html'; exports.renderAsync = function (str, options) { return new Promise(function (resolve, reject) { var plugins = [] if (Array.isArray(options.plugins)) { for (var i in options.plugins) { var plugin = options.plugins[i] plugins.push(require(plugin)()) } } else if (typeof options.plugins === 'object') { for (var key in options.plugins) { var settings = options.plugins[key] || {} plugins.push(require(key)(settings)) } } var modifiedOptions = options modifiedOptions.plugins = plugins // Process with Reshape. reshape(modifiedOptions) .process(str) .then(function (result) { resolve(result.output(options.locals)) }, reject) }) }
'use strict'; var reshape = require('reshape') exports.name = 'reshape'; exports.inputFormats = ['reshape', 'html']; exports.outputFormat = 'html'; exports.renderAsync = function (str, options) { return new Promise(function (resolve, reject) { var plugins = [] if (Array.isArray(options.plugins)) { for (var plugin of options.plugins) { plugins.push(require(plugin)()) } } else if (typeof options.plugins === 'object') { for (var key in options.plugins) { var settings = options.plugins[key] || {} plugins.push(require(key)(settings)) } } var modifiedOptions = options modifiedOptions.plugins = plugins // Process with Reshape. reshape(modifiedOptions) .process(str) .then(function (result) { resolve(result.output(options.locals)) }, reject) }) }
Indent and strip package metadata strings. The Python package metadata was not being correctly formatted due to the presence of unindented lines. I think setuptools should be responsible for this formatting, but it seems easier to just fix it here. With this change, it becomes possible for the standard pkg_resources parser to read the PKG-INFO metadata for this project.
#!/usr/bin/env python import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info < (2,5): raise NotImplementedError("Sorry, you need at least Python 2.5 or Python 3.x") import contexter with contexter.Contexter() as ctx: long_description = ' '.join(ctx << open('README.rst')).rstrip() setup(name='contexter', version=contexter.__version__, description=contexter.__doc__.replace('\n', '\n ').rstrip(), long_description=long_description, author=contexter.__author__, author_email='marc@gsites.de', url='https://bitbucket.org/defnull/contexter', py_modules=['contexter'], license='MIT', platforms = 'any', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
#!/usr/bin/env python import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info < (2,5): raise NotImplementedError("Sorry, you need at least Python 2.5 or Python 3.x") import contexter with contexter.Contexter() as ctx: long_description = ''.join(ctx << open('README.rst')) setup(name='contexter', version=contexter.__version__, description=contexter.__doc__, long_description=long_description, author=contexter.__author__, author_email='marc@gsites.de', url='https://bitbucket.org/defnull/contexter', py_modules=['contexter'], license='MIT', platforms = 'any', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Change endpoint for 2 other free services
import React from 'react'; const withCountry = component => class extends React.Component { static displayName = `withCountry(${component.displayName || component.name})`; constructor(props) { super(props); this.state = { country: 'US', }; } async componentDidMount() { try { const response = await fetch('//ipinfo.io/json'); const data = await response.json(); this.setState({country: data.country}); } catch (err) { // Failed to fetch can happen if the user has a blocker (ad, tracker...) window.trackJs.track(`Error when getting the country: ${err.message}`); // trying another server just to be sure try { const response = await fetch('//get.geojs.io/v1/ip/country.json'); const data = await response.json(); this.setState({country: data.country}); } catch (err2) { // giving up window.trackJs.track( `Error when getting the country: ${err2.message}`, ); } } } render() { const {country} = this.state; return React.createElement(component, { ...this.props, country, }); } }; export default withCountry;
import React from 'react'; const withCountry = component => class extends React.Component { static displayName = `withCountry(${component.displayName || component.name})`; constructor(props) { super(props); this.state = { country: 'US', }; } async componentDidMount() { try { const response = await fetch('//freegeoip.net/json/'); const data = await response.json(); this.setState({country: data.country_code}); } catch (err) { // Failed to fetch can happen if the user has a blocker (ad, tracker...) trackJs.track(`Error when getting the country: ${err.message}`); } } render() { const {country} = this.state; return React.createElement(component, { ...this.props, country, }); } }; export default withCountry;
fix: Fix wrong tested quote provider in Quote test
<?php namespace Monolol\Lolifiers; use Monolol\Referentials\MonologLevel; use Monolol\Lolifiers\Quote; use Monolol\Lolifiers\QuoteProviders; use Monolog\Logger; class QuoteTest extends \PHPUnit_Framework_TestCase { public function testHandling() { $this->assertTrue((new Quote(new QuoteProviders\EmptyQuoteProvider()))->isHandling(array())); } /** * @dataProvider providerTestQuote */ public function testQuote(QuoteProvider $provider, $logMessage) { $record = array('message' => $logMessage, 'datetime' => new \DateTime()); $lolifier = new Quote($provider); $lolilfiedRecord = $lolifier->lolify($record); $this->assertTrue(in_array($lolilfiedRecord['message'], $provider->getQuotes())); } public function providerTestQuote() { return array( 'Perceval' => array(new QuoteProviders\Kaamelott\Perceval(), 'Internal Burger Error'), 'Karadoc' => array(new QuoteProviders\Kaamelott\Karadoc(), 'Internal Pony Error'), 'Merlin' => array(new QuoteProviders\Kaamelott\Merlin(), 'Internal Unicorn Error'), 'Kadoc' => array(new QuoteProviders\Kaamelott\Kadoc(), 'Internal Rabbit Error'), ); } }
<?php namespace Monolol\Lolifiers; use Monolol\Referentials\MonologLevel; use Monolol\Lolifiers\Quote; use Monolol\Lolifiers\QuoteProviders; use Monolog\Logger; class QuoteTest extends \PHPUnit_Framework_TestCase { public function testHandling() { $this->assertTrue((new Quote(new QuoteProviders\EmptyQuoteProvider()))->isHandling(array())); } /** * @dataProvider providerTestQuote */ public function testQuote(QuoteProvider $provider, $logMessage) { $record = array('message' => $logMessage, 'datetime' => new \DateTime()); $lolifier = new Quote($provider); $lolilfiedRecord = $lolifier->lolify($record); $this->assertTrue(in_array($lolilfiedRecord['message'], $provider->getQuotes())); } public function providerTestQuote() { return array( 'Perceval' => array(new QuoteProviders\Kaamelott\Perceval(), 'Internal Burger Error'), 'Karadoc' => array(new QuoteProviders\Kaamelott\Karadoc(), 'Internal Pony Error'), 'Merlin' => array(new QuoteProviders\Kaamelott\Merlin(), 'Internal Unicorn Error'), 'Kadoc' => array(new QuoteProviders\Kaamelott\Merlin(), 'Internal Rabbit Error'), ); } }
Use enviroment variable for deployment
module.exports = function(grunt) { grunt.initConfig({ sshconfig: { 'onair.riplive.it': { host: 'onair.riplive.it', username: process.env.SSH_USER, password: process.env.SSH_PASSWORD, port : 5430 } }, sshexec: { deploy: { command: [ 'cd /var/www/riplive_instagram', 'git pull origin master', 'npm install', 'forever restartall', 'forever list' ].join(' && '), options: { config: 'onair.riplive.it' } } } }); grunt.loadNpmTasks('grunt-ssh'); grunt.registerTask('deploy', [ 'sshexec:deploy' ]); };
module.exports = function(grunt) { grunt.initConfig({ sshconfig: { 'onair.riplive.it': { host: 'onair.riplive.it', username: 'rip', password: 'rip_admin2013', port : 5430 } }, sshexec: { deploy: { command: [ 'cd /var/www/riplive_instagram', 'git pull origin master', 'npm install', 'forever restartall', 'forever list' ].join(' && '), options: { config: 'onair.riplive.it' } } } }); grunt.loadNpmTasks('grunt-ssh'); grunt.registerTask('deploy', [ 'sshexec:deploy' ]); };
[Glitch] Fix showing profile's featured tags on individual statuses Port bfafb114a2135b1f21ba7e6d54ee13e8da75b629 to glitch-soc Signed-off-by: Claire <82b964c50e9d1d222e48cf5046e6484a966a7b07@sitedethib.com>
import React from 'react'; import { Switch, Route, withRouter } from 'react-router-dom'; import { showTrends } from 'flavours/glitch/initial_state'; import Trends from 'flavours/glitch/features/getting_started/containers/trends_container'; import AccountNavigation from 'flavours/glitch/features/account/navigation'; const DefaultNavigation = () => ( <> {showTrends && ( <> <div className='flex-spacer' /> <Trends /> </> )} </> ); export default @withRouter class NavigationPortal extends React.PureComponent { render () { return ( <Switch> <Route path='/@:acct' exact component={AccountNavigation} /> <Route path='/@:acct/tagged/:tagged?' exact component={AccountNavigation} /> <Route path='/@:acct/with_replies' exact component={AccountNavigation} /> <Route path='/@:acct/followers' exact component={AccountNavigation} /> <Route path='/@:acct/following' exact component={AccountNavigation} /> <Route path='/@:acct/media' exact component={AccountNavigation} /> <Route component={DefaultNavigation} /> </Switch> ); } }
import React from 'react'; import { Switch, Route, withRouter } from 'react-router-dom'; import { showTrends } from 'flavours/glitch/initial_state'; import Trends from 'flavours/glitch/features/getting_started/containers/trends_container'; import AccountNavigation from 'flavours/glitch/features/account/navigation'; const DefaultNavigation = () => ( <> {showTrends && ( <> <div className='flex-spacer' /> <Trends /> </> )} </> ); export default @withRouter class NavigationPortal extends React.PureComponent { render () { return ( <Switch> <Route path='/@:acct/(tagged/:tagged?)?' component={AccountNavigation} /> <Route component={DefaultNavigation} /> </Switch> ); } }
Add incremental default settings merging
'use strict'; /* * Module for handling and saving various different user preferences */ angular.module('settings') .factory('settingsFactory', function ($localStorage, configFactory) { return { setInitialSettingsIfApplicable: function () { var initialSettings = configFactory.getValue('initialUserSettings'); if (!$localStorage.settings) { $localStorage.settings = {}; } $localStorage.settings = _.defaults($localStorage.settings, initialSettings); }, setSettings: function (settingOpt) { var keys = _.keys(settingOpt); var values = _.values(settingOpt); var i = 0; for (i = 0; i < values.length; i++) { $localStorage.settings[keys[i]] = values[i]; } }, getSetting: function (settingKey) { return $localStorage.settings[settingKey]; }, getAllSettings: function () { return $localStorage.settings; } }; });
'use strict'; /* * Module for handling and saving various different user preferences */ angular.module('settings') .factory('settingsFactory', function ($localStorage, configFactory) { return { setInitialSettingsIfApplicable: function () { if ($localStorage.settings) return; $localStorage.settings = configFactory.getValue('initialUserSettings'); }, setSettings: function (settingOpt) { var keys = _.keys(settingOpt); var values = _.values(settingOpt); var i = 0; for (i = 0; i < values.length; i++) { $localStorage.settings[keys[i]] = values[i]; } }, getSetting: function (settingKey) { return $localStorage.settings[settingKey]; }, getAllSettings: function () { return $localStorage.settings; } }; });
Fix heroku using wrong port
/** * ENVIRONMENT VARIABLES * TOKEN_LIFE: Number of seconds before a token expires * APP_TOKEN: Facebook app token * APP_ID: Facebook app ID * ADMIN_ID: Client ID for admin program * ADMIN_SECRET: Client secret for admin program */ // Dependencies var https = require('https') , fs = require('fs') , express = require('express') , app = express() , bodyParser = require('body-parser') , mongoose = require('mongoose') , passport = require('passport') , nodemailer = require('nodemailer') , path = require('path') , api = require('./api/app.js'); var port = process.env.PORT || (process.env.SSL ? 443 : 8080); app.use(bodyParser.urlencoded({ extended: true })); // Serve homepage app.use('/', express.static(path.join(__dirname, 'public'))); // REST API api.use(express, app, mongoose, passport, nodemailer); var serverStart = function() { console.log('Server started on port %d', port); }; if (process.env.NODE_ENV === 'production' || !process.env.SSL) { app.listen(port, serverStart); } else { // Load SSL Certificate var options = { key: fs.readFileSync('./sslcert/key.pem'), cert: fs.readFileSync('./sslcert/cert.pem') } https.createServer(options, app).listen(port, serverStart); }
/** * ENVIRONMENT VARIABLES * TOKEN_LIFE: Number of seconds before a token expires * APP_TOKEN: Facebook app token * APP_ID: Facebook app ID * ADMIN_ID: Client ID for admin program * ADMIN_SECRET: Client secret for admin program */ // Dependencies var https = require('https') , fs = require('fs') , express = require('express') , app = express() , bodyParser = require('body-parser') , mongoose = require('mongoose') , passport = require('passport') , nodemailer = require('nodemailer') , path = require('path') , api = require('./api/app.js'); var port = process.env.PORT || process.env.SSL ? 443 : 8080; app.use(bodyParser.urlencoded({ extended: true })); // Serve homepage app.use('/', express.static(path.join(__dirname, 'public'))); // REST API api.use(express, app, mongoose, passport, nodemailer); var serverStart = function() { console.log('Server started on port %d', port); }; if (process.env.NODE_ENV === 'production' || !process.env.SSL) { app.listen(port, serverStart); } else { // Load SSL Certificate var options = { key: fs.readFileSync('./sslcert/key.pem'), cert: fs.readFileSync('./sslcert/cert.pem') } https.createServer(options, app).listen(port, serverStart); }
Replace initial config for personal info.
module.exports = { siteMetadata: { title: `fmoliveira.dev`, description: `I'm a Freelance Software Engineer who loves writing clean and well-tested code. My favourite tech stack at the moment is React, TypeScript, Jest and Testing Library. Always hungry for learning and happy to help!`, author: `@fmoliveira`, }, plugins: [ `gatsby-plugin-typescript`, `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `fmoliveira.dev`, short_name: `fmoliveira`, start_url: `/`, background_color: `#20222e`, theme_color: `#20222e`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ `gatsby-plugin-typescript`, `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
Use dev settings for test.
var webpack = require("webpack"); var WebpackDevServer = require("webpack-dev-server"); var webpackConfig = require("./webpack.config"); var testConfig = require("../test/config/specs"); var artifacts = require("../test/artifacts"); var isDocker = require("is-docker"); var server; var SCREENSHOT_PATH = artifacts.pathSync("screenshots"); exports.config = { specs: [ './test/functional/index.js' ], exclude: [ ], maxInstances: 10, capabilities: [{ maxInstances: 5, browserName: 'chrome' }], sync: true, logLevel: 'verbose', coloredLogs: true, bail: 0, screenshotPath: SCREENSHOT_PATH, host: (isDocker() ? process.env.DOCKER_HOST : "127.0.0.1"), baseUrl: 'http://localhost', waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', // Because we don't know how long the initial build will take... timeout: 4*60*1000 }, onPrepare: function (config, capabilities) { var compiler = webpack(webpackConfig); server = new WebpackDevServer(compiler, {}); server.listen(testConfig.port); }, onComplete: function(exitCode) { server.close() } }
var webpack = require("webpack"); var WebpackDevServer = require("webpack-dev-server"); var webpackConfig = require("./webpack.production.config"); var testConfig = require("../test/config/specs"); var artifacts = require("../test/artifacts"); var isDocker = require("is-docker"); var server; var SCREENSHOT_PATH = artifacts.pathSync("screenshots"); exports.config = { specs: [ './test/functional/index.js' ], exclude: [ ], maxInstances: 10, capabilities: [{ maxInstances: 5, browserName: 'chrome' }], sync: true, logLevel: 'verbose', coloredLogs: true, bail: 0, screenshotPath: SCREENSHOT_PATH, host: (isDocker() ? process.env.DOCKER_HOST : "127.0.0.1"), baseUrl: 'http://localhost', waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', // Because we don't know how long the initial build will take... timeout: 4*60*1000 }, onPrepare: function (config, capabilities) { var compiler = webpack(webpackConfig); server = new WebpackDevServer(compiler, {}); server.listen(testConfig.port); }, onComplete: function(exitCode) { server.close() } }
Add missing files to package
from os import path from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(path.join(path.dirname(__file__), fname)).read() setup( name="pconf", version="0.5.1", author="Andras Maroy", author_email="andras@maroy.hu", description=("Hierarchical python configuration with files, environment variables, command-line arguments."), license="MIT", keywords="configuration hierarchical", url="https://github.com/andrasmaroy/pconf", packages=['pconf', 'pconf.store'], long_description=read('README.md'), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], install_requires=['pyyaml'], extras_require={ 'test': ['pytest', 'mock'], }, )
from os import path from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(path.join(path.dirname(__file__), fname)).read() setup( name="pconf", version="0.5.0", author="Andras Maroy", author_email="andras@maroy.hu", description=("Hierarchical python configuration with files, environment variables, command-line arguments."), license="MIT", keywords="configuration hierarchical", url="https://github.com/andrasmaroy/pconf", packages=['pconf', 'tests'], long_description=read('README.md'), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], install_requires=['pyyaml'], extras_require={ 'test': ['pytest', 'mock'], }, )
Make renderer polymorphically call updateEmptyListContent @bug W-3836575@ @rev trey.washington@
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ /* * These helper methods are in the renderer due to the many ways * that abstractList can be implemented. Since controller methods * can be overridden, and component creation can be dynamic, putting * the relevant helper method call in the renderer ensures that the * emptyListContent is handled no matter how the list is implemented. */ afterRender : function(component, helper){ this.superAfterRender(); helper.updateEmptyListContent(component); }, rerender : function(component){ this.superRerender(); var concreteCmp = component.getConcreteComponent(); if (concreteCmp.isDirty('v.items')) { concreteCmp.getDef().getHelper().updateEmptyListContent(component); } } })// eslint-disable-line semi
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ /* * These helper methods are in the renderer due to the many ways * that abstractList can be implemented. Since controller methods * can be overridden, and component creation can be dynamic, putting * the relevant helper method call in the renderer ensures that the * emptyListContent is handled no matter how the list is implemented. */ afterRender : function(component, helper){ this.superAfterRender(); helper.updateEmptyListContent(component); }, rerender : function(component, helper){ this.superRerender(); if (component.getConcreteComponent().isDirty('v.items')) { helper.updateEmptyListContent(component); } } })// eslint-disable-line semi
Replace singleton to bind for our main class in service provider
<?php namespace Edujugon\GoogleAds\Providers; use Edujugon\GoogleAds\Console\RefreshTokenCommand; use Edujugon\GoogleAds\GoogleAds; use Illuminate\Support\ServiceProvider; class GoogleAdsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php'; $this->publishes([ __DIR__.'/../Config/config.php' => $config_path, ], 'config'); } /** * Register the application services. * * @return void */ public function register() { // Console commands $this->commands([ RefreshTokenCommand::class, ]); $this->app->bind(GoogleAds::class, function ($app) { return new GoogleAds(); }); } }
<?php namespace Edujugon\GoogleAds\Providers; use Edujugon\GoogleAds\Console\RefreshTokenCommand; use Edujugon\GoogleAds\GoogleAds; use Illuminate\Support\ServiceProvider; class GoogleAdsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php'; $this->publishes([ __DIR__.'/../Config/config.php' => $config_path, ], 'config'); } /** * Register the application services. * * @return void */ public function register() { // Console commands $this->commands([ RefreshTokenCommand::class, ]); $this->app->singleton(GoogleAds::class, function ($app) { return new GoogleAds(); }); } }
Add support for WPA2 Enterprise Fixes #1.
'use strict'; var execFile = require('child_process').execFile; var wifiName = require('wifi-name'); function getPassword(ssid, cb) { var cmd = 'sudo'; var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid]; var ret; execFile(cmd, args, function (err, stdout) { if (err) { cb(err); return; } ret = /^\s*(?:psk|password)=(.+)\s*$/gm.exec(stdout); ret = ret && ret.length ? ret[1] : null; if (!ret) { cb(new Error('Could not get password')); return; } cb(null, ret); }); } module.exports = function (ssid, cb) { if (process.platform !== 'linux') { throw new Error('Only Linux systems are supported'); } if (ssid && typeof ssid !== 'function') { getPassword(ssid, cb); return; } else if (ssid && !cb) { cb = ssid; } wifiName(function (err, name) { if (err) { cb(err); return; } getPassword(name, cb); }); };
'use strict'; var execFile = require('child_process').execFile; var wifiName = require('wifi-name'); function getPassword(ssid, cb) { var cmd = 'sudo'; var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid]; var ret; execFile(cmd, args, function (err, stdout) { if (err) { cb(err); return; } ret = /^\s*psk=(.+)\s*$/gm.exec(stdout); ret = ret && ret.length ? ret[1] : null; if (!ret) { cb(new Error('Could not get password')); return; } cb(null, ret); }); } module.exports = function (ssid, cb) { if (process.platform !== 'linux') { throw new Error('Only Linux systems are supported'); } if (ssid && typeof ssid !== 'function') { getPassword(ssid, cb); return; } else if (ssid && !cb) { cb = ssid; } wifiName(function (err, name) { if (err) { cb(err); return; } getPassword(name, cb); }); };
Update redirect test to status 308
from .helpers import BaseApplicationTest, BaseAPIClientMixin class DataAPIClientMixin(BaseAPIClientMixin): data_api_client_patch_path = 'app.main.views.marketplace.data_api_client' class TestApplication(DataAPIClientMixin, BaseApplicationTest): def test_index(self): response = self.client.get('/') assert 200 == response.status_code assert len(self.data_api_client.find_frameworks.call_args_list) == 2 def test_404(self): response = self.client.get('/not-found') assert 404 == response.status_code def test_trailing_slashes(self): response = self.client.get('') assert 308 == response.status_code assert "http://localhost/" == response.location response = self.client.get('/trailing/') assert 301 == response.status_code assert "http://localhost/trailing" == response.location def test_trailing_slashes_with_query_parameters(self): response = self.client.get('/search/?q=r&s=t') assert 301 == response.status_code assert "http://localhost/search?q=r&s=t" == response.location def test_header_xframeoptions_set_to_deny(self): res = self.client.get('/') assert 200 == res.status_code assert 'DENY', res.headers['X-Frame-Options']
from .helpers import BaseApplicationTest, BaseAPIClientMixin class DataAPIClientMixin(BaseAPIClientMixin): data_api_client_patch_path = 'app.main.views.marketplace.data_api_client' class TestApplication(DataAPIClientMixin, BaseApplicationTest): def test_index(self): response = self.client.get('/') assert 200 == response.status_code assert len(self.data_api_client.find_frameworks.call_args_list) == 2 def test_404(self): response = self.client.get('/not-found') assert 404 == response.status_code def test_trailing_slashes(self): response = self.client.get('') assert 301 == response.status_code assert "http://localhost/" == response.location response = self.client.get('/trailing/') assert 301 == response.status_code assert "http://localhost/trailing" == response.location def test_trailing_slashes_with_query_parameters(self): response = self.client.get('/search/?q=r&s=t') assert 301 == response.status_code assert "http://localhost/search?q=r&s=t" == response.location def test_header_xframeoptions_set_to_deny(self): res = self.client.get('/') assert 200 == res.status_code assert 'DENY', res.headers['X-Frame-Options']
Add matches to annotated object
function annotateEngine(src, rules, ruleTypes, ruleMap) { var tokens = []; while(src) { // Pick rule var rule = ruleTypes.filter(function(ruleName, idx) { var regex = rules[ruleName]; return regex.exec(src); })[0]; // No matching rules if(!rule) { throw new Error('No rule found for: ' + src); } // Use rule to extract block var ruleRegex = rules[rule]; var block = ruleRegex.exec(src); // Get rule type var type = ruleMap[rule] || rule; // Get raw text var raw = block[0]; // Break out here to avoid infinite loops if(raw.length === 0) { break; } tokens.push({ type: ruleMap[rule] || rule, raw: raw, matches: block.slice(1), }); // Update source src = src.substring(raw.length); } return tokens; } module.exports = annotateEngine;
function annotateEngine(src, rules, ruleTypes, ruleMap) { var tokens = []; while(src) { // Pick rule var rule = ruleTypes.filter(function(ruleName, idx) { var regex = rules[ruleName]; return regex.exec(src); })[0]; // No matching rules if(!rule) { throw new Error('No rule found for: ' + src); } // Use rule to extract block var ruleRegex = rules[rule]; var block = ruleRegex.exec(src); // Get rule type var type = ruleMap[rule] || rule; // Get raw text var raw = block[0]; // Break out here to avoid infinite loops if(raw.length === 0) { break; } tokens.push({ type: ruleMap[rule] || rule, raw: raw, }); // Update source src = src.substring(raw.length); } return tokens; } module.exports = annotateEngine;
Move standard-minifiers self-test timeout *after* slow run.match.
import selftest, {Sandbox} from '../tool-testing/selftest.js'; selftest.define('standard-minifiers - CSS splitting', function (options) { const s = new Sandbox({ clients: options.clients }); s.createApp('myapp', 'minification-css-splitting'); s.cd('myapp'); s.testWithAllClients(function (run) { run.waitSecs(5); run.match('myapp'); run.match('proxy'); run.match('MongoDB'); run.match('your app'); run.match('running at'); run.match('localhost'); run.connectClient(); run.waitSecs(20); run.match('client connected'); run.match('the number of stylesheets: <2>'); run.match('the color of the tested 4097th property: <rgb(0, 128, 0)>'); s.append('client/lots-of-styles.main.styl', ` .class-4097 color: blue `); run.match('Client modified -- refreshing'); run.waitSecs(90); run.match('the number of stylesheets: <2>'); run.match('the color of the tested 4097th property: <rgb(0, 0, 255)>'); run.stop(); }, '--production'); });
import selftest, {Sandbox} from '../tool-testing/selftest.js'; selftest.define('standard-minifiers - CSS splitting', function (options) { const s = new Sandbox({ clients: options.clients }); s.createApp('myapp', 'minification-css-splitting'); s.cd('myapp'); s.testWithAllClients(function (run) { run.waitSecs(5); run.match('myapp'); run.match('proxy'); run.match('MongoDB'); run.match('your app'); run.match('running at'); run.match('localhost'); run.connectClient(); run.waitSecs(20); run.match('client connected'); run.match('the number of stylesheets: <2>'); run.match('the color of the tested 4097th property: <rgb(0, 128, 0)>'); s.append('client/lots-of-styles.main.styl', ` .class-4097 color: blue `); run.waitSecs(60); run.match('Client modified -- refreshing'); run.match('the number of stylesheets: <2>'); run.match('the color of the tested 4097th property: <rgb(0, 0, 255)>'); run.stop(); }, '--production'); });
Add compare method from com.thaiopensource.relaxng.output.common.
package com.thaiopensource.xml.util; public final class Name { final private String namespaceUri; final private String localName; final private int hc; public Name(String namespaceUri, String localName) { this.namespaceUri = namespaceUri; this.localName = localName; this.hc = namespaceUri.hashCode() ^ localName.hashCode(); } public String getNamespaceUri() { return namespaceUri; } public String getLocalName() { return localName; } public boolean equals(Object obj) { if (!(obj instanceof Name)) return false; Name other = (Name)obj; return (this.hc == other.hc && this.namespaceUri.equals(other.namespaceUri) && this.localName.equals(other.localName)); } public int hashCode() { return hc; } // We include this, but don't derive from Comparator<Name> to avoid a dependency on Java 5. static public int compare(Name n1, Name n2) { int ret = n1.namespaceUri.compareTo(n2.namespaceUri); if (ret != 0) return ret; return n1.localName.compareTo(n2.localName); } }
package com.thaiopensource.xml.util; public final class Name { final private String namespaceUri; final private String localName; final private int hc; public Name(String namespaceUri, String localName) { this.namespaceUri = namespaceUri; this.localName = localName; this.hc = namespaceUri.hashCode() ^ localName.hashCode(); } public String getNamespaceUri() { return namespaceUri; } public String getLocalName() { return localName; } public boolean equals(Object obj) { if (!(obj instanceof Name)) return false; Name other = (Name)obj; return (this.hc == other.hc && this.namespaceUri.equals(other.namespaceUri) && this.localName.equals(other.localName)); } public int hashCode() { return hc; } }
Move roles menu item into a submenu - 'organization' for conferences - 'advanced' for other event types
# This file is part of Indico. # Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from flask import session from indico.core import signals from indico.core.logger import Logger from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.menu import SideMenuItem logger = Logger.get('events.roles') @signals.menu.items.connect_via('event-management-sidemenu') def _sidemenu_items(sender, event, **kwargs): if event.can_manage(session.user): roles_section = 'organization' if event.type == 'conference' else 'advanced' return SideMenuItem('roles', _('Roles'), url_for('event_roles.manage', event), section=roles_section)
# This file is part of Indico. # Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from flask import session from indico.core import signals from indico.core.logger import Logger from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.menu import SideMenuItem logger = Logger.get('events.roles') @signals.menu.items.connect_via('event-management-sidemenu') def _sidemenu_items(sender, event, **kwargs): if event.can_manage(session.user): return SideMenuItem('roles', _('Roles'), url_for('event_roles.manage', event), 65, icon='medal')
Add context to error messages before printing them
package main import "log" const ( // outputRoot is the output directory // for the build artifacts. outputRoot = "dist" ) var ( // appName is the name of the // application to be built. appName string // appVersion is the version of // the application to be built. appVersion = "latest" ) func main() { var err error appName, err = currentFolderName() if err != nil { log.Printf("Error while getting folder name of current work directory: %v", err) return } appVersion, err = gitVersion() if err != nil { log.Printf("Error while getting version from Git: %v", err) return } config := NewConfig() err = config.Load() if err != nil { log.Printf("Error while loading config: %v", err) return } targetPlatforms, err := config.Targets.ToPlatforms() if err != nil { log.Printf("Error while converting targets from config to platforms: %v", err) return } err = runGoBuildChain(targetPlatforms) if err != nil { log.Printf("Error while running Go build chain: %v", err) return } err = archiveBuilds() if err != nil { log.Printf("Error while archiving builds: %v", err) return } }
package main import "log" const ( // outputRoot is the output directory // for the build artifacts. outputRoot = "dist" ) var ( // appName is the name of the // application to be built. appName string // appVersion is the version of // the application to be built. appVersion = "latest" ) func main() { var err error appName, err = currentFolderName() if err != nil { log.Println(err) return } appVersion, err = gitVersion() if err != nil { log.Println(err) return } config := NewConfig() err = config.Load() if err != nil { log.Println(err) return } targetPlatforms, err := config.Targets.ToPlatforms() if err != nil { log.Println(err) return } err = runGoBuildChain(targetPlatforms) if err != nil { log.Println(err) return } err = archiveBuilds() if err != nil { log.Println(err) return } }
Update use() function. Use local config
"use strict"; global.use = function (path) { if(path === 'config'){ return require.main.require('./' + path); }else{ return require('./' + path); } }; const Dominion = use('core/server'); const Message = use('core/messages'); const Server = new Dominion(); Server.addComponent(require('./components/sessions')); Server.addComponent(require('./components/permissions')); Server.addComponent(require('./components/accounts')); Server.addComponent(require('./components/tracking')); Server.addComponent(require('./components/logging')); Server.addComponent(require('./components/authorize')); Server.addComponent(require('./components/notifications')); Server.addComponent(require('./components/media')); Message.request.addInterceptor(function requestInterceptorLogConsole(){ console.log('-> Request interceptor to: ' + this.request.path); }); Message.response.addInterceptor(function responseInterceptorLogConsole(body){ console.log('<- Response interceptor from: ' + this.request.path); return body; }); Message.response.addInterceptor(function responseInterceptorAddServerNameHeader(body){ this.response.headers['Server'] = 'Dominion'; return body; }); module.exports = Server; //server.start(config);
"use strict"; global.use = function (path) { return require('./' + path); }; const Dominion = use('core/server'); const Message = use('core/messages'); const Server = new Dominion(); Server.addComponent(require('./components/sessions')); Server.addComponent(require('./components/permissions')); Server.addComponent(require('./components/accounts')); Server.addComponent(require('./components/tracking')); Server.addComponent(require('./components/logging')); Server.addComponent(require('./components/authorize')); Server.addComponent(require('./components/notifications')); Server.addComponent(require('./components/media')); Message.request.addInterceptor(function requestInterceptorLogConsole(){ console.log('-> Request interceptor to: ' + this.request.path); }); Message.response.addInterceptor(function responseInterceptorLogConsole(body){ console.log('<- Response interceptor from: ' + this.request.path); return body; }); Message.response.addInterceptor(function responseInterceptorAddServerNameHeader(body){ this.response.headers['Server'] = 'Dominion'; return body; }); module.exports = Server; //server.start(config);
Use absolute path on find packages
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages import os.path tests_require = [] setup( name='Mule', version='1.0', author='DISQUS', author_email='opensource@disqus.com', url='http://github.com/disqus/mule', description = 'Utilities for sharding test cases in BuildBot', packages=find_packages(os.path.dirname(__file__)), zip_safe=False, install_requires=[ 'unittest2', 'twisted', 'pyzmq', ], dependency_links=[], tests_require=tests_require, extras_require={'test': tests_require}, test_suite='mule.runtests.runtests', include_package_data=True, entry_points = { 'console_scripts': [ 'mule = mule.scripts.runner:main', ], }, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages tests_require = [] setup( name='Mule', version='1.0', author='DISQUS', author_email='opensource@disqus.com', url='http://github.com/disqus/mule', description = 'Utilities for sharding test cases in BuildBot', packages=find_packages(), zip_safe=False, install_requires=[ 'unittest2', 'twisted', 'pyzmq', ], dependency_links=[], tests_require=tests_require, extras_require={'test': tests_require}, test_suite='mule.runtests.runtests', include_package_data=True, entry_points = { 'console_scripts': [ 'mule = mule.scripts.runner:main', ], }, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
Remove wagtail_image from image resources
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'resource') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
:bug: Fix dirname deprecation when user config path is null
'use strict'; const fs = require('fs'); const os = require('os'); const path = require('path'); const Logger = require('../../lib/logger'); const configPath = typeof atom !== 'undefined' && atom.config.getUserConfigPath() ? path.join(path.dirname(atom.config.getUserConfigPath()), 'kite-config.json') : path.join(os.homedir(), '.kite', 'kite-config.json'); var config = null; try { Logger.verbose(`initializing localconfig from ${ configPath }...`); var str = fs.readFileSync(configPath, {encoding: 'utf8'}); config = JSON.parse(str); } catch (err) { config = {}; } function persist() { var str = JSON.stringify(config, null, 2); // serialize with whitespace for human readability fs.writeFile(configPath, str, 'utf8', (err) => { if (err) { Logger.error(`failed to persist localconfig to ${ configPath }`, err); } }); } // get gets a value from storage function get(key, fallback) { return key in config ? config[key] : fallback; } // set assigns a value to storage and asynchronously persists it to disk function set(key, value) { config[key] = value; persist(); // will write to disk asynchronously } module.exports = { get: get, set: set, };
'use strict'; const fs = require('fs'); const os = require('os'); const path = require('path'); const Logger = require('../../lib/logger'); const configPath = typeof atom !== 'undefined' ? path.join(path.dirname(atom.config.getUserConfigPath()), 'kite-config.json') : path.join(os.homedir(), '.kite', 'kite-config.json'); var config = null; try { Logger.verbose(`initializing localconfig from ${ configPath }...`); var str = fs.readFileSync(configPath, {encoding: 'utf8'}); config = JSON.parse(str); } catch (err) { config = {}; } function persist() { var str = JSON.stringify(config, null, 2); // serialize with whitespace for human readability fs.writeFile(configPath, str, 'utf8', (err) => { if (err) { Logger.error(`failed to persist localconfig to ${ configPath }`, err); } }); } // get gets a value from storage function get(key, fallback) { return key in config ? config[key] : fallback; } // set assigns a value to storage and asynchronously persists it to disk function set(key, value) { config[key] = value; persist(); // will write to disk asynchronously } module.exports = { get: get, set: set, };
Build a GraphQL response with errors reported
import {parse, Source} from 'graphql'; import {createSpecBuilderClass} from './base'; import {RepositoryBuilder} from './repository'; import {PullRequestBuilder} from './pr'; class SearchResultItemBuilder { static resolve() { return this; } constructor(...args) { this.args = args; this._value = null; } bePullRequest(block = () => {}) { const b = new PullRequestBuilder(...this.args); block(b); this._value = b.build(); } build() { return this._value; } } const SearchResultBuilder = createSpecBuilderClass('SearchResultItemConnection', { issueCount: {default: 0}, nodes: {linked: SearchResultItemBuilder, plural: true, singularName: 'node'}, }); const QueryBuilder = createSpecBuilderClass('Query', { repository: {linked: RepositoryBuilder}, search: {linked: SearchResultBuilder}, }); export function queryBuilder(...nodes) { return QueryBuilder.onFragmentQuery(nodes); } class RelayResponseBuilder extends QueryBuilder { static onOperation(op) { const doc = parse(new Source(op.text)); return this.onFullQuery(doc); } constructor(...args) { super(...args); this._errors = []; } addError(string) { this._errors.push(string); return this; } build() { if (this._errors.length > 0) { return {data: null, errors: this._errors}; } return {data: super.build()}; } } export function relayResponseBuilder(op) { return RelayResponseBuilder.onOperation(op); }
import {parse, Source} from 'graphql'; import {createSpecBuilderClass} from './base'; import {RepositoryBuilder} from './repository'; import {PullRequestBuilder} from './pr'; class SearchResultItemBuilder { static resolve() { return this; } constructor(...args) { this.args = args; this._value = null; } bePullRequest(block = () => {}) { const b = new PullRequestBuilder(...this.args); block(b); this._value = b.build(); } build() { return this._value; } } const SearchResultBuilder = createSpecBuilderClass('SearchResultItemConnection', { issueCount: {default: 0}, nodes: {linked: SearchResultItemBuilder, plural: true, singularName: 'node'}, }); const QueryBuilder = createSpecBuilderClass('Query', { repository: {linked: RepositoryBuilder}, search: {linked: SearchResultBuilder}, }); export function queryBuilder(...nodes) { return QueryBuilder.onFragmentQuery(nodes); } class RelayResponseBuilder extends QueryBuilder { static onOperation(op) { const doc = parse(new Source(op.text)); return this.onFullQuery(doc); } build() { return {data: super.build()}; } } export function relayResponseBuilder(op) { return RelayResponseBuilder.onOperation(op); }
Modify the hasDate function to check if an actual end date exists on the project as well
angular .module('app') .directive('projectQuickView', function() { return { restrict: 'E', replace: false, templateUrl: 'app/templates/partials/projectQuickView.html', link: function(scope, element, attrs) { scope.completed = attrs.completed; scope.hasDate = function() { return scope.item.end_date && scope.item.end_date !== null; }; scope.isContentFromOldSite = function(item) { return scope.item.end_date == "2012-10-20T04:00:00.000Z"; }; scope.completedStamp = function(item) { return scope.completed && !scope.isContentFromOldSite(item); }; } }; });
angular .module('app') .directive('projectQuickView', function() { return { restrict: 'E', replace: false, templateUrl: 'app/templates/partials/projectQuickView.html', link: function(scope, element, attrs) { scope.completed = attrs.completed; scope.hasDate = function() { return scope.item.end_date !== null; }; scope.isContentFromOldSite = function(item) { return scope.item.end_date == "2012-10-20T04:00:00.000Z"; }; scope.completedStamp = function(item) { return scope.completed && !scope.isContentFromOldSite(item); }; } }; });
Raise errors on incorrect library usage
package retry import ( "net/http" "time" "github.com/cenkalti/backoff/v4" "github.com/pkg/errors" ) // MaybeRetryRequest is an internal implementation detail of this module. It // shouldn't be used by users of the geoipupdate Go library. You can use the // RetryFor field of geoipupdate.Config if you'd like to retry failed requests // when using the library directly. func MaybeRetryRequest(c *http.Client, retryFor time.Duration, req *http.Request) (*http.Response, error) { if retryFor < 0 { return nil, errors.New("negative retry duration") } exp := backoff.NewExponentialBackOff() exp.MaxElapsedTime = retryFor var resp *http.Response err := backoff.Retry( func() error { var err error resp, err = c.Do(req) return errors.Wrap(err, "error performing http request") }, exp, ) return resp, err }
package retry import ( "net/http" "time" "github.com/cenkalti/backoff/v4" "github.com/pkg/errors" ) // MaybeRetryRequest is an internal implementation detail of this module. It // shouldn't be used by users of the geoipupdate Go library. You can use the // RetryFor field of geoipupdate.Config if you'd like to retry failed requests // when using the library directly. func MaybeRetryRequest(c *http.Client, retryFor time.Duration, req *http.Request) (*http.Response, error) { exp := backoff.NewExponentialBackOff() exp.MaxElapsedTime = retryFor var resp *http.Response err := backoff.Retry( func() error { var err error resp, err = c.Do(req) return errors.Wrap(err, "error performing http request") }, exp, ) return resp, err }
Remove functional property from component
function identity (x) { return x } module.exports = { name: 'AnimatedNumber', props: { number: Number, formatter: { type: Function, required: false, default: function () { return identity } } }, data: function () { return { display: this.number, interval: false } }, render: function (h) { return h('span', this.formatter(this.display)) }, watch: { number: function (val, old) { const $vm = this $vm.interval && clearInterval($vm.interval) let speed = 10 if (val < old) { speed = 4 } $vm.interval = setInterval(function () { if ($vm.display !== $vm.number) { const diff = ($vm.number - $vm.display) / speed $vm.display += diff >= 0 ? Math.ceil(diff) : Math.floor(diff) } else { clearInterval($vm.interval) } }, 20) } } }
function identity (x) { return x } module.exports = { name: 'AnimatedNumber', functional: true, props: { number: Number, formatter: { type: Function, required: false, default: function () { return identity } } }, data: function () { return { display: this.number, interval: false } }, render: function (h) { return h('span', this.formatter(this.display)) }, watch: { number: function (val, old) { const $vm = this $vm.interval && clearInterval($vm.interval) let speed = 10 if (val < old) { speed = 4 } $vm.interval = setInterval(function () { if ($vm.display !== $vm.number) { const diff = ($vm.number - $vm.display) / speed $vm.display += diff >= 0 ? Math.ceil(diff) : Math.floor(diff) } else { clearInterval($vm.interval) } }, 20) } } }
[FIX][11.0] Make debugger record a debug message instead of error when importing validate_email in partner_email_check
# Copyright 2019 Komit <https://komit-consulting.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import api, models, _ from odoo.exceptions import UserError _logger = logging.getLogger(__name__) try: from validate_email import validate_email except ImportError: _logger.debug('Cannot import "validate_email".') def validate_email(email): _logger.warning( 'Can not validate email, ' 'python dependency required "validate_email"') return True class ResPartner(models.Model): _inherit = 'res.partner' @api.constrains('email') def constrains_email(self): for rec in self.filtered("email"): self.email_check(rec.email) @api.model def email_check(self, email): if validate_email(email): return True raise UserError(_('Invalid e-mail!'))
# Copyright 2019 Komit <https://komit-consulting.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import api, models, _ from odoo.exceptions import UserError _logger = logging.getLogger(__name__) try: from validate_email import validate_email except ImportError: _logger.error('Cannot import "validate_email".') def validate_email(email): _logger.warning( 'Can not validate email, ' 'python dependency required "validate_email"') return True class ResPartner(models.Model): _inherit = 'res.partner' @api.constrains('email') def constrains_email(self): for rec in self.filtered("email"): self.email_check(rec.email) @api.model def email_check(self, email): if validate_email(email): return True raise UserError(_('Invalid e-mail!'))
Fix spelling of variable name.
/* * grunt-strip-comments * https://github.com/kkemple/grunt-strip-comments * * Copyright (c) 2013 Kurtis Kemple * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('comments', 'Remove comments from production code', function() { var multilineComment = /\/\*[\s\S]*?\*\//g; var singleLineComment = /\/\/.+/g; var options = this.options({ singleline: true, multiline: true }); this.files[0].src.forEach(function (file) { var contents = grunt.file.read(file); if ( options.multiline ) { contents = contents.replace(multilineComment, ''); } if ( options.singleline ) { contents = contents.replace(singleLineComment, ''); } grunt.file.write(file, contents); }); }); };
/* * grunt-strip-comments * https://github.com/kkemple/grunt-strip-comments * * Copyright (c) 2013 Kurtis Kemple * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('comments', 'Remove comments from production code', function() { var mulitlineComment = /\/\*[\s\S]*?\*\//g; var singleLineComment = /\/\/.+/g; var options = this.options({ singleline: true, multiline: true }); this.files[0].src.forEach(function (file) { var contents = grunt.file.read(file); if ( options.multiline ) { contents = contents.replace(mulitlineComment, ''); } if ( options.singleline ) { contents = contents.replace(singleLineComment, ''); } grunt.file.write(file, contents); }); }); };
Refactor how defer is constructed
var Stirrup = function(library) { if(typeof library !== 'object' && typeof library !== 'function') { throw 'You must provide Stirrup with a promise library'; } this.library = library; this.isNative = (typeof Promise === 'function' && Promise.toString().indexOf('[native code]') > -1); var constructor = this.getConstructor(); this.buildDefer(constructor); this.buildStaticFunctions(); return constructor; }; Stirrup.prototype.getConfig = function() { //@@config return config; }; Stirrup.prototype.getConstructor = function() { if(!this.isNative) { return this.getConfig().constructor ? this.library[this.getConfig().constructor] : this.library; } else { return this.library; } }; Stirrup.prototype.buildDefer = function(constructor) { var config = this.getConfig(); if(!this.isNative && config.defer) { this.defer = this.library[config.defer]; } else { //TODO: Promise inspection capability //https://github.com/petkaantonov/bluebird/blob/master/API.md#inspect---promiseinspection this.defer = function() { var fulfill, reject; var promise = new constuctor(function(f, r) { fulfill = f; reject = r; }); return { fulfill: fulfill, reject: reject, promise: promise } } } };
var Stirrup = function(library) { if(typeof library !== 'object' && typeof library !== 'function') { throw 'You must provide Stirrup with a promise library'; } this.library = library; this.isNative = (typeof Promise === 'function' && Promise.toString().indexOf('[native code]') > -1); this.buildDefer(); this.buildStaticFunctions(); return this.getConstructor(); }; Stirrup.prototype.getConfig = function() { //@@config return config; }; Stirrup.prototype.getConstructor = function() { if(!this.isNative) { return this.getConfig().constructor ? this.library[this.getConfig().constructor] : this.library; } else { return this.library; } }; Stirrup.prototype.buildDefer = function() { if(this.isNative) { //TODO: Promise inspection capability //https://github.com/petkaantonov/bluebird/blob/master/API.md#inspect---promiseinspection this.defer = function() { var fulfill, reject; var promise = new Promise(function(f, r) { fulfill = f; reject = r; }); return { fulfill: fulfill, reject: reject, promise: promise } } } else { this.defer = this.library.defer; } };
Set the priority to allow user changes
package net.trajano.ms.engine.jaxrs; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import io.vertx.core.json.Json; /** * This {@link ObjectMapper} sets up Jackson for some common defaults. This * utilizes Vert.x mapper to support their json objects in addition it will * prevent <code>null</code> from being put into a resulting JSON. * * @author Archimedes Trajano */ @Component @Provider @Priority(Priorities.ENTITY_CODER) public class CommonObjectMapper implements ContextResolver<ObjectMapper> { private static final ObjectMapper MAPPER; static { MAPPER = Json.mapper.copy(); MAPPER.setSerializationInclusion(Include.NON_NULL); } @Override public ObjectMapper getContext(final Class<?> clazz) { return MAPPER; } }
package net.trajano.ms.engine.jaxrs; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import io.vertx.core.json.Json; /** * This {@link ObjectMapper} sets up Jackson for some common defaults. This * utilizes Vert.x mapper to support their json objects in addition it will * prevent <code>null</code> from being put into a resulting JSON. * * @author Archimedes Trajano */ @Component @Provider public class CommonObjectMapper implements ContextResolver<ObjectMapper> { private static final ObjectMapper MAPPER; static { MAPPER = Json.mapper.copy(); MAPPER.setSerializationInclusion(Include.NON_NULL); } @Override public ObjectMapper getContext(final Class<?> clazz) { return MAPPER; } }
Fix missing newlines with Python3
import sys def expand(filename): for dir in ('.', '../common', '../anstests/'): try: f = open(dir + "/" + filename) except IOError: continue for line in f: line = line.replace('\r', '') if line.strip().startswith('#bye'): sys.exit(0) if line.strip().startswith('include '): expand(line.split()[1]) else: sys.stdout.write(line) sys.stdout.write('\n') return assert 0, filename + 'not found' if __name__ == '__main__': for a in sys.argv[1:]: expand(a)
import sys def expand(filename): for dir in ('.', '../common', '../anstests/'): try: f = open(dir + "/" + filename) except IOError: continue for line in f: line = line.replace('\r', '') if line.strip().startswith('#bye'): sys.exit(0) if line.strip().startswith('include '): expand(line.split()[1]) else: sys.stdout.write(line) print return assert 0, filename + 'not found' if __name__ == '__main__': for a in sys.argv[1:]: expand(a)
build: Enable classes transform for react-hot-loader interop.
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development'; const browsers = process.env.BROWSERSLIST; const targets = {}; if (browsers) { targets.browsers = browsers; } if (env === 'production') { targets.uglify = true; } const preset = { presets: [ ['env', { modules: false, loose: env === 'production', targets, // Force enable the classes transform, react-hot-loader doesn't // appear to work well with native classes + arrow functions in // transpiled class properties. include: ['transform-es2015-classes'] }], 'stage-2', 'react' ], plugins: [ 'transform-decorators-legacy', 'transform-export-extensions', ['transform-runtime', { polyfill: false }] ] }; if (env === 'development') { preset.plugins.push('react-hot-loader/babel'); } if (env === 'production') { preset.plugins.push( 'transform-react-constant-elements', 'transform-react-inline-elements', ['transform-react-remove-prop-types', { mode: 'wrap' }] ); } module.exports = preset;
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development'; const browsers = process.env.BROWSERSLIST; const targets = {}; if (browsers) { targets.browsers = browsers; } if (env === 'production') { targets.uglify = true; } const preset = { presets: [ ['env', { modules: false, targets }], 'stage-2', 'react' ], plugins: [ 'transform-decorators-legacy', 'transform-export-extensions', ['transform-runtime', { polyfill: false }] ] }; if (env === 'development') { preset.plugins.push('react-hot-loader/babel'); } if (env === 'production') { preset.plugins.push( 'transform-react-constant-elements', 'transform-react-inline-elements', ['transform-react-remove-prop-types', { mode: 'wrap' }] ); } module.exports = preset;
Update : extra_setup compiles code, and runs it into custom global context
from functools import wraps def extra_setup(setup_code): """Allows to setup some extra context to it's decorated function. As a convention, the bench decorated function should always handle *args and **kwargs. Kwargs will be updated with the extra context set by the decorator. Example: @extra_setup("l = [x for x in xrange(100)]") def bench_len(self, *args, **kwargs): print len(kwargs['l']) """ def decorator(func): # Exec extra setup code and put it in a local # context passed to function through kwargs. context = {} compiled_code = compile(setup_code, '<string>', 'exec') exec compiled_code in context @wraps(func) def decorated_function(*args, **kwargs): kwargs.update(context) return func(*args, **kwargs) return decorated_function return decorator
from functools import wraps def extra_setup(setup_code): """Allows to setup some extra context to it's decorated function. As a convention, the bench decorated function should always handle *args and **kwargs. Kwargs will be updated with the extra context set by the decorator. Example: @extra_setup("l = [x for x in xrange(100)]") def bench_len(self, *args, **kwargs): print len(kwargs['l']) """ def decorator(func): # Exec extra setup code and put it in a local # context passed to function through kwargs. context = {} exec setup_code in {}, context @wraps(func) def decorated_function(*args, **kwargs): kwargs.update(context) return func(*args, **kwargs) return decorated_function return decorator
Add more return types after fixing a typo in my script
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Authorization\Voter; use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Event\VoteEvent; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Decorates voter classes to send result events. * * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com> * * @internal */ class TraceableVoter implements VoterInterface { private $voter; private $eventDispatcher; public function __construct(VoterInterface $voter, EventDispatcherInterface $eventDispatcher) { $this->voter = $voter; $this->eventDispatcher = LegacyEventDispatcherProxy::decorate($eventDispatcher); } public function vote(TokenInterface $token, $subject, array $attributes): int { $result = $this->voter->vote($token, $subject, $attributes); $this->eventDispatcher->dispatch(new VoteEvent($this->voter, $subject, $attributes, $result), 'debug.security.authorization.vote'); return $result; } public function getDecoratedVoter(): VoterInterface { return $this->voter; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Authorization\Voter; use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Event\VoteEvent; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Decorates voter classes to send result events. * * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com> * * @internal */ class TraceableVoter implements VoterInterface { private $voter; private $eventDispatcher; public function __construct(VoterInterface $voter, EventDispatcherInterface $eventDispatcher) { $this->voter = $voter; $this->eventDispatcher = LegacyEventDispatcherProxy::decorate($eventDispatcher); } public function vote(TokenInterface $token, $subject, array $attributes) { $result = $this->voter->vote($token, $subject, $attributes); $this->eventDispatcher->dispatch(new VoteEvent($this->voter, $subject, $attributes, $result), 'debug.security.authorization.vote'); return $result; } public function getDecoratedVoter(): VoterInterface { return $this->voter; } }