text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Check away status of the target, not user, of USERHOST
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class UserhostCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "UserhostCommand" core = True def userCommands(self): return [ ("USERHOST", 1, self) ] def parseParams(self, user, params, prefix, tags): if not params: user.sendSingleError("UserhostParams", irc.ERR_NEEDMOREPARAMS, "USERHOST", "Not enough parameters") return None return { "nicks": params[:5] } def execute(self, user, data): userHosts = [] for nick in data["nicks"]: if nick not in self.ircd.userNicks: continue targetUser = self.ircd.users[self.ircd.userNicks[nick]] output = targetUser.nick if self.ircd.runActionUntilValue("userhasoperpermission", targetUser, "", users=[targetUser]): output += "*" output += "=" if targetUser.metadataKeyExists("away"): output += "-" else: output += "+" output += "{}@{}".format(targetUser.ident, targetUser.host()) userHosts.append(output) user.sendMessage(irc.RPL_USERHOST, " ".join(userHosts)) return True userhostCmd = UserhostCommand()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class UserhostCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "UserhostCommand" core = True def userCommands(self): return [ ("USERHOST", 1, self) ] def parseParams(self, user, params, prefix, tags): if not params: user.sendSingleError("UserhostParams", irc.ERR_NEEDMOREPARAMS, "USERHOST", "Not enough parameters") return None return { "nicks": params[:5] } def execute(self, user, data): userHosts = [] for nick in data["nicks"]: if nick not in self.ircd.userNicks: continue targetUser = self.ircd.users[self.ircd.userNicks[nick]] output = targetUser.nick if self.ircd.runActionUntilValue("userhasoperpermission", targetUser, "", users=[targetUser]): output += "*" output += "=" if user.metadataKeyExists("away"): output += "-" else: output += "+" output += "{}@{}".format(targetUser.ident, targetUser.host()) userHosts.append(output) user.sendMessage(irc.RPL_USERHOST, " ".join(userHosts)) return True userhostCmd = UserhostCommand()
Add an RNG to each cog.
from collections import OrderedDict import threading import aiohttp import random from joku.bot import Jokusoramame class _CogMeta(type): def __prepare__(*args, **kwargs): # Use an OrderedDict for the class body. return OrderedDict() class Cog(metaclass=_CogMeta): def __init__(self, bot: Jokusoramame): self._bot = bot self.logger = self.bot.logger # A cog-local session that can be used. self.session = aiohttp.ClientSession() # A RNG that can be used by each cog. self.rng = random.SystemRandom() def __unload(self): self.session.close() @property def bot(self) -> 'Jokusoramame': """ :return: The bot instance associated with this cog. """ return self._bot @classmethod def setup(cls, bot: Jokusoramame): bot.add_cog(cls(bot))
from collections import OrderedDict import threading import aiohttp from joku.bot import Jokusoramame class _CogMeta(type): def __prepare__(*args, **kwargs): # Use an OrderedDict for the class body. return OrderedDict() class Cog(metaclass=_CogMeta): def __init__(self, bot: Jokusoramame): self._bot = bot self.logger = self.bot.logger # A cog-local session that can be used. self.session = aiohttp.ClientSession() def __unload(self): self.session.close() @property def bot(self) -> 'Jokusoramame': """ :return: The bot instance associated with this cog. """ return self._bot @classmethod def setup(cls, bot: Jokusoramame): bot.add_cog(cls(bot))
Adjust metrics test to set up/tear down database
""" :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest from ...conftest import database_recreated # To be overridden by test parametrization @pytest.fixture def config_overrides(): return {} @pytest.fixture def client(config_overrides, make_admin_app, db): app = make_admin_app(**config_overrides) with app.app_context(): with database_recreated(db): yield app.test_client() @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}]) def test_metrics(client): response = client.get('/metrics') assert response.status_code == 200 assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8' assert response.mimetype == 'text/plain' assert response.get_data(as_text=True) == ( 'users_enabled_count 0\n' 'users_disabled_count 0\n' 'users_suspended_count 0\n' 'users_deleted_count 0\n' 'users_total_count 0\n' ) @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}]) def test_disabled_metrics(client): response = client.get('/metrics') assert response.status_code == 404
""" :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ def test_metrics(make_admin_app): client = _get_test_client(make_admin_app, True) response = client.get('/metrics') assert response.status_code == 200 assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8' assert response.mimetype == 'text/plain' assert response.get_data(as_text=True) == ( 'users_enabled_count 0\n' 'users_disabled_count 0\n' 'users_suspended_count 0\n' 'users_deleted_count 0\n' 'users_total_count 0\n' ) def test_disabled_metrics(make_admin_app): client = _get_test_client(make_admin_app, False) response = client.get('/metrics') assert response.status_code == 404 def _get_test_client(make_admin_app, metrics_enabled): config_overrides = {'METRICS_ENABLED': metrics_enabled} app = make_admin_app(**config_overrides) return app.test_client()
:bug: Fix unnoticed deletion widget eslint errors
/** * Listeners for header */ import $ from 'jquery' import { version } from '../../../package.json' import { reload, erase } from '../game-util' /* eslint-disable no-alert */ const deleteFriendo = (friendo) => { if (!friendo) { alert('No Friendo DNA found!') } else if ($('#delete-check1').prop('checked') && $('#delete-check2').prop('checked')) { // handle deletion flavor text if (friendo.level >= 1) { alert(`"... ${friendo.owner}... goodbye..."`) } else { alert('You hear a cracking noise as the egg fades into nothingness.') } // delete friendo and refresh erase() reload() } } /* eslint-enable no-alert */ export default () => { $('#vernum').html(`[ v${version} ]`).attr('href', `https://github.com/mattdelsordo/friendo/releases/tag/v${version}`) $('#game-info-icon').mouseenter(() => { $('#game-info').css('visibility', 'visible') }) $('#header').mouseleave(() => { $('#game-info').css('visibility', 'hidden') }) $('#delete-btn').click(() => { deleteFriendo() }) } export const updateDelete = (friendo) => { $('#delete-btn').off('click').click(() => { deleteFriendo(friendo) }) }
/** * Listeners for header */ import $ from 'jquery' import { version } from '../../../package.json' import { reload, erase } from '../game-util' const deleteFriendo = (friendo) => { console.log('called') if (!friendo) { alert('No Friendo DNA found!') } else if ($('#delete-check1').prop('checked') && $('#delete-check2').prop('checked')) { // handle deletion flavor text if (friendo.level >= 1) { alert(`"... ${friendo.owner}... goodbye..."`) } else { alert('You hear a cracking noise as the egg fades into nothingness.') } // delete friendo and refresh erase() reload() } } export default () => { $('#vernum').html(`[ v${version} ]`).attr('href', `https://github.com/mattdelsordo/friendo/releases/tag/v${version}`) $('#game-info-icon').mouseenter(() => { $('#game-info').css('visibility', 'visible') }) $('#header').mouseleave(() => { $('#game-info').css('visibility', 'hidden') }) $('#delete-btn').click(() => { deleteFriendo() }) } export const updateDelete = (friendo) => { $('#delete-btn').off('click').click(() => { deleteFriendo(friendo) }) }
Change file type to .roamer
""" argh """ import tempfile import os from subprocess import call EDITOR = os.environ.get('EDITOR', 'vim') if EDITOR in ['vim', 'nvim']: EXTRA_EDITOR_COMMAND = '+set backupcopy=yes' else: EXTRA_EDITOR_COMMAND = None def file_editor(content): with tempfile.NamedTemporaryFile(suffix=".roamer") as temp: temp.write(content) temp.flush() if EXTRA_EDITOR_COMMAND: call([EDITOR, EXTRA_EDITOR_COMMAND, temp.name]) else: call([EDITOR, temp.name]) temp.seek(0) return temp.read()
""" argh """ import tempfile import os from subprocess import call EDITOR = os.environ.get('EDITOR', 'vim') if EDITOR in ['vim', 'nvim']: EXTRA_EDITOR_COMMAND = '+set backupcopy=yes' else: EXTRA_EDITOR_COMMAND = None def file_editor(content): with tempfile.NamedTemporaryFile(suffix=".tmp") as temp: temp.write(content) temp.flush() if EXTRA_EDITOR_COMMAND: call([EDITOR, EXTRA_EDITOR_COMMAND, temp.name]) else: call([EDITOR, temp.name]) temp.seek(0) return temp.read()
Fix links on member widget
<div class="team-member row_block-2"> <img src="<?= $photo_url ?>" class="team-member_photo"/> <div class="team-member_name"><?= $name ?></div> <div class="team-member_role"><?= $role ?></div> <div class="team-member_links"> <?php if($vk) {?> <a href="<?= $vk ?>" class="fa fa-vk team-member_link "></a> <?php } ?> <?php if($fb) {?> <a href="<?= $fb ?>" class="fa fa-facebook team-member_link "></a> <?php } ?> <?php if($email) {?> <a href="<?= $email ?>" class="fa fa-envelope team-member_link "></a> <?php } ?> <?php if($linked_in) {?> <a href="<?= $linked_in ?>" class="fa fa-linkedin team-member_link "></a> <?php } ?> </div> </div>
<div class="team-member row_block-2"> <img src="<?= $photo_url ?>" class="team-member_photo"/> <div class="team-member_name"><?= $name ?></div> <div class="team-member_role"><?= $role ?></div> <div class="team-member_links"> <?php if($vk) {?> <a href="<?= $vk ?>" class="fa fa-facebook team-member_link "></a> <?php } ?> <?php if($fb) {?> <a href="<?= $fb ?>" class="fa fa-vk team-member_link "></a> <?php } ?> <?php if($email) {?> <a href="<?= $email ?>" class="fa fa-envelope team-member_link "></a> <?php } ?> <?php if($linked_in) {?> <a href="<?= $linked_in ?>" class="fa fa-linkedin team-member_link "></a> <?php } ?> </div> </div>
Fix test by setting a large timeout This is needed as downloading and extracting Magento could take a while so I've just a large timeout. Improvements welcome
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('magento generator', function () { this.timeout(120000); beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('magento:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig', '.gitignore', 'package.json', 'bower.json' ]; helpers.mockPrompt(this.app, { 'magentoVersion': '1.8.0.0' }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('magento generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('magento:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig', '.gitignore', 'package.json', 'bower.json' ]; helpers.mockPrompt(this.app, { 'magentoVersion': '1.8.0.0' }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
Update to use US English
'use strict'; var helpers = require('../helpers'), yaml = require('js-yaml'), fs = require('fs'), path = require('path'); var properties = yaml.safeLoad(fs.readFileSync(path.join(__dirname, '../../data', 'properties.yml'), 'utf8')).split(' '); module.exports = { 'name': 'property-spelling', 'defaults': { 'extra-properties': [] }, 'detect': function (ast, parser) { var result = []; ast.traverseByType('property', function (node) { if (node.first().is('ident')) { var curProperty = node.first().content; if (curProperty.charAt(0) === '-') { curProperty = helpers.stripPrefix(curProperty); } if (properties.indexOf(curProperty) === -1 && parser.options['extra-properties'].indexOf(curProperty) === -1) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': node.start.line, 'column': node.start.column, 'message': 'Property `' + curProperty + '` appears to be spelled incorrectly', 'severity': parser.severity }); } } }); return result; } };
'use strict'; var helpers = require('../helpers'), yaml = require('js-yaml'), fs = require('fs'), path = require('path'); var properties = yaml.safeLoad(fs.readFileSync(path.join(__dirname, '../../data', 'properties.yml'), 'utf8')).split(' '); module.exports = { 'name': 'property-spelling', 'defaults': { 'extra-properties': [] }, 'detect': function (ast, parser) { var result = []; ast.traverseByType('property', function (node) { if (node.first().is('ident')) { var curProperty = node.first().content; if (curProperty.charAt(0) === '-') { curProperty = helpers.stripPrefix(curProperty); } if (properties.indexOf(curProperty) === -1 && parser.options['extra-properties'].indexOf(curProperty) === -1) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': node.start.line, 'column': node.start.column, 'message': 'Property `' + curProperty + '` appears to be spelt incorrectly', 'severity': parser.severity }); } } }); return result; } };
Fix lostpassword mail when password policy contains special chars.
<?php \OCP\Util::addScript('password_policy', 'password_policy_user'); $tpl = new OCP\Template('password_policy', 'password_policy_user'); echo str_replace('{link}', $_['link'], $l->t('Use the following link to reset your password: {link}')); ?> <?php if(\OCP\App::isEnabled('password_policy')){ p($l->t('The following password restrictions are currently in place:')); ?> <?php p('- '.$l->t('Length of password at least: %s', OC_Password_Policy::getMinLength())); ?> <?php if(OC_Password_Policy::getMixedCase()){ p('- '.$l->t('Password must contain upper and lower case characters')); } ?> <?php if(OC_Password_Policy::getNumbers()){ p('- '.$l->t('Password must contain numbers')); } ?> <?php if(OC_Password_Policy::getSpecialChars()){ print_unescaped('- '.$l->t('Password must contain following special characters: %s', OC_Password_Policy::getSpecialCharsList())); }} ?>
<?php \OCP\Util::addScript('password_policy', 'password_policy_user'); $tpl = new OCP\Template('password_policy', 'password_policy_user'); echo str_replace('{link}', $_['link'], $l->t('Use the following link to reset your password: {link}')); ?> <?php if(\OCP\App::isEnabled('password_policy')){ p($l->t('The following password restrictions are currently in place:')); ?> <?php p('- '.$l->t('Length of password at least: %s', OC_Password_Policy::getMinLength())); ?> <?php if(OC_Password_Policy::getMixedCase()){ p('- '.$l->t('Password must contain upper and lower case characters')); } ?> <?php if(OC_Password_Policy::getNumbers()){ p('- '.$l->t('Password must contain numbers')); } ?> <?php if(OC_Password_Policy::getSpecialChars()){ p('- '.$l->t('Password must contain following special characters: %s', OC_Password_Policy::getSpecialCharsList())); }} ?>
Use Chrome and not chromium
module.exports = { test_page: 'tests/index.html?hidepassed', disable_watching: true, launch_in_ci: [ 'Chrome' ], launch_in_dev: [ 'Chrome' ], browser_args: { Chrome: { ci: [ // --no-sandbox is needed when running Chrome inside a container process.env.CI ? '--no-sandbox' : null, '--headless', '--disable-gpu', '--disable-dev-shm-usage', '--disable-software-rasterizer', '--mute-audio', '--remote-debugging-port=0', '--window-size=1440,900' ].filter(Boolean) }, chromium: { mode: 'ci', browser_start_timeout: 10000, browser_disconnect_timeout: 10000, args: [ '--disable-gpu', '--auto-open-devtools-for-tabs', '--remote-debugging-port=9222', '--remote-debugging-address=0.0.0.0', '--no-sandbox', '--user-data-dir=/tmp', '--window-size=1440,900' ] } } };
module.exports = { test_page: 'tests/index.html?hidepassed', disable_watching: true, launch_in_ci: [ 'chromium' ], launch_in_dev: [ 'Chrome' ], browser_args: { Chrome: { ci: [ // --no-sandbox is needed when running Chrome inside a container process.env.CI ? '--no-sandbox' : null, '--headless', '--disable-gpu', '--disable-dev-shm-usage', '--disable-software-rasterizer', '--mute-audio', '--remote-debugging-port=0', '--window-size=1440,900' ].filter(Boolean) }, chromium: { mode: 'ci', browser_start_timeout: 10000, browser_disconnect_timeout: 10000, args: [ '--disable-gpu', '--auto-open-devtools-for-tabs', '--remote-debugging-port=9222', '--remote-debugging-address=0.0.0.0', '--no-sandbox', '--user-data-dir=/tmp', '--window-size=1440,900' ] } } };
Use the ChatColor from Bukkit instead of BungeeCord.
package com.herocc.bukkit.core.commands; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.herocc.bukkit.core.Core; public class CommandFakeblock implements CommandExecutor { private final Core plugin = Core.getPlugin(); @SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) { if (cmd.getName().equalsIgnoreCase("fakeblock")) { if (sender.hasPermission("core.head.get")) { Player player = (Player) sender; player.sendBlockChange(player.getLocation(), Material.WOOL, (byte) 0); sender.sendMessage("The block has changed!"); } else { sender.sendMessage(ChatColor.RED + "Sorry, You do not have permission to use this command!"); } } return false; } }
package com.herocc.bukkit.core.commands; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.herocc.bukkit.core.Core; import net.md_5.bungee.api.ChatColor; public class CommandFakeblock implements CommandExecutor { private final Core plugin = Core.getPlugin(); @SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) { if (cmd.getName().equalsIgnoreCase("fakeblock")) { if (sender.hasPermission("core.head.get")) { Player player = (Player) sender; player.sendBlockChange(player.getLocation(), Material.WOOL, (byte) 0); sender.sendMessage("The block has changed!"); } else { sender.sendMessage(ChatColor.RED + "Sorry, You do not have permission to use this command!"); } } return false; } }
Fix crash on login with broken bukkit dimensions list Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>
package me.nallar.collections; import java.util.Iterator; import me.nallar.tickthreading.Log; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; public class ListSet extends SynchronizedList { @Override public synchronized boolean add(final Object o) { if (o instanceof World) { World world = (World) o; WorldProvider provider = world.provider; if (provider == null) { Log.severe("Tried to add world " + world + " with null provider to bukkit dimensions.", new Throwable()); return false; } Iterator<World> iterator = this.iterator(); while (iterator.hasNext()) { World world_ = iterator.next(); if (world_ == world) { return false; } else if (world_.provider == null) { Log.severe("World " + world_ + " with null provider still in bukkit dimensions.", new Throwable()); iterator.remove(); } else if (provider.dimensionId == world_.provider.dimensionId) { Log.severe("Attempted to add " + Log.dumpWorld(world) + " to bukkit dimensions when " + Log.dumpWorld(world_) + " is already in it.", new Throwable()); return false; } } return super.add(o); } return !this.contains(o) && super.add(o); } }
package me.nallar.collections; import me.nallar.tickthreading.Log; import net.minecraft.world.World; public class ListSet extends SynchronizedList { @Override public synchronized boolean add(final Object o) { if (o instanceof World) { World world = (World) o; for (World world_ : (Iterable<World>) this) { if (world_ == world) { return false; } else if (world.provider.dimensionId == world_.provider.dimensionId) { Log.severe("Attempted to add " + Log.dumpWorld(world) + " to bukkit dimensions when " + Log.dumpWorld(world_) + " is already in it.", new Throwable()); return false; } } return super.add(o); } return !this.contains(o) && super.add(o); } }
Fix react native support for v0.47 on the proper file
package com.attehuhtakangas.navigationbar; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class NavigationBarPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new NavigationBarModule(reactContext)); return modules; } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package com.attehuhtakangas.navigationbar; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class NavigationBarPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new NavigationBarModule(reactContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Update logic solver to not use deprecated and removed API
Package.describe({ summary: "General satisfiability solver for logic problems", version: '2.0.8' }); Package.onUse(function (api) { api.export('Logic'); api.use('underscore'); api.addFiles(['minisat.js', 'minisat_wrapper.js', 'types.js', 'logic.js', 'optimize.js']); }); Package.onTest(function (api) { api.use(['tinytest', 'check', 'underscore']); api.use('logic-solver'); // logic-solver is totally meant for the client too, but not old // ones like IE 8, so we have to exclude it from our automated // testing. It needs a browser released in the last year (say) so // that Emscripten-compiled code runs reasonably. api.addFiles('logic_tests.js', 'server'); });
Package.describe({ summary: "General satisfiability solver for logic problems", version: '2.0.7' }); Package.on_use(function (api) { api.export('Logic'); api.use('underscore'); api.add_files(['minisat.js', 'minisat_wrapper.js', 'types.js', 'logic.js', 'optimize.js']); }); Package.on_test(function (api) { api.use(['tinytest', 'check', 'underscore']); api.use('logic-solver'); // logic-solver is totally meant for the client too, but not old // ones like IE 8, so we have to exclude it from our automated // testing. It needs a browser released in the last year (say) so // that Emscripten-compiled code runs reasonably. api.add_files('logic_tests.js', 'server'); });
Fix another broken file attachment field. There was one more admin field for file attachments that was using an old name. Now fixed.
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from reviewboard.attachments.models import FileAttachment from reviewboard.reviews.models import FileAttachmentComment class FileAttachmentAdmin(admin.ModelAdmin): list_display = ('file', 'caption', 'mimetype', 'review_request_id') list_display_links = ('file_attachment', 'caption') search_fields = ('caption', 'mimetype') def review_request_id(self, obj): return obj.review_request.get().id review_request_id.short_description = _('Review request ID') class FileAttachmentCommentAdmin(admin.ModelAdmin): list_display = ('text', 'file_attachment', 'review_request_id', 'timestamp') list_filter = ('timestamp',) search_fields = ('caption', 'file_attachment') raw_id_fields = ('file_attachment', 'reply_to') def review_request_id(self, obj): return obj.review.get().review_request.id review_request_id.short_description = _('Review request ID') admin.site.register(FileAttachment, FileAttachmentAdmin) admin.site.register(FileAttachmentComment, FileAttachmentCommentAdmin)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from reviewboard.attachments.models import FileAttachment from reviewboard.reviews.models import FileAttachmentComment class FileAttachmentAdmin(admin.ModelAdmin): list_display = ('file', 'caption', 'mimetype', 'review_request_id') list_display_links = ('file_attachment', 'caption') search_fields = ('caption', 'mimetype') def review_request_id(self, obj): return obj.review_request.get().id review_request_id.short_description = _('Review request ID') class FileAttachmentCommentAdmin(admin.ModelAdmin): list_display = ('text', 'file_attachment', 'review_request_id', 'timestamp') list_filter = ('timestamp',) search_fields = ('caption', 'file_attachment') raw_id_fields = ('file', 'reply_to') def review_request_id(self, obj): return obj.review.get().review_request.id review_request_id.short_description = _('Review request ID') admin.site.register(FileAttachment, FileAttachmentAdmin) admin.site.register(FileAttachmentComment, FileAttachmentCommentAdmin)
Remove node_modules folder for alpha.10.3
'use strict'; /** * Module dependencies */ // Node.js core. const path = require('path'); // Local dependencies. const packageJSON = require('../json/package.json.js'); const database = require('../json/database.json.js'); /** * Copy required files for the generated application */ module.exports = { moduleDir: path.resolve(__dirname, '..'), templatesDirectory: path.resolve(__dirname, '..', 'templates'), before: require('./before'), after: require('./after'), targets: { // Call the `admin` generator. '.': ['admin'], // Main package. 'package.json': { jsonfile: packageJSON }, 'config/environments/development/database.json': { jsonfile: database }, // Copy dot files. '.editorconfig': { copy: 'editorconfig' }, '.npmignore': { copy: 'npmignore' }, '.gitignore': { copy: 'gitignore' }, // Copy Markdown files with some information. 'README.md': { template: 'README.md' }, // Empty API directory. 'api': { folder: {} }, // Empty plugins directory. 'plugins': { folder: {} }, // Empty public directory. 'public': { folder: {} } } };
'use strict'; /** * Module dependencies */ // Node.js core. const path = require('path'); // Local dependencies. const packageJSON = require('../json/package.json.js'); const database = require('../json/database.json.js'); /** * Copy required files for the generated application */ module.exports = { moduleDir: path.resolve(__dirname, '..'), templatesDirectory: path.resolve(__dirname, '..', 'templates'), before: require('./before'), after: require('./after'), targets: { // Call the `admin` generator. '.': ['admin'], // Main package. 'package.json': { jsonfile: packageJSON }, 'config/environments/development/database.json': { jsonfile: database }, // Copy dot files. '.editorconfig': { copy: 'editorconfig' }, '.npmignore': { copy: 'npmignore' }, '.gitignore': { copy: 'gitignore' }, // Copy Markdown files with some information. 'README.md': { template: 'README.md' }, // Empty API directory. 'api': { folder: {} }, // Empty plugins directory. 'plugins': { folder: {} }, // Empty public directory. 'public': { folder: {} }, // Empty node_modules directory. 'node_modules': { folder: {} } } };
LUCENE-2858: Fix Javadoc warnings, still missing some text for new classes git-svn-id: 91ee4cdcf3981427d300d1134dd1ee7af9ec73f6@1238026 13f79535-47bb-0310-9956-ffa450edef68
package org.apache.solr.core; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.store.Directory; /** * Default IndexReaderFactory implementation. Returns a standard Lucene * {@link DirectoryReader}. * * @see DirectoryReader#open(Directory) */ public class StandardIndexReaderFactory extends IndexReaderFactory { @Override public DirectoryReader newReader(Directory indexDir) throws IOException { return DirectoryReader.open(indexDir, termInfosIndexDivisor); } }
package org.apache.solr.core; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.store.Directory; /** * Default IndexReaderFactory implementation. Returns a standard Lucene * IndexReader. * * @see IndexReader#open(Directory) */ public class StandardIndexReaderFactory extends IndexReaderFactory { @Override public DirectoryReader newReader(Directory indexDir) throws IOException { return DirectoryReader.open(indexDir, termInfosIndexDivisor); } }
Disable braekpad automatic registration while we figure out stuff Review URL: http://codereview.chromium.org/462022 git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@33686 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb)))
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') @atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb)))
Compress the highlight view in search results The highlights used a lot of space when placed in individual paragraph tags. Put all of them inside the paragraph. String-split on periods to avoid highlight labels such as “subject.raw.en”.
<div class="card"> <header class="header"> <a href="{{ action('StudyController@view', ['id' => $hit["_id"]]) }}"> <strong class="label">{{ Utils::getEn($hit["_source"]["title"]) }}</strong> </a> </header> <div class="content"> @if (array_key_exists("abstract", $hit["_source"])) <p>{{ str_limit(Utils::getEn($hit["_source"]["abstract"]), 150) }}</p> @endif @if(array_key_exists("highlight", $hit)) <p> @foreach($hit["highlight"] as $label => $highlight) @foreach(array_keys($highlight) as $key) <strong>{{ explode(".", $label)[0] }}</strong>: {!!$highlight[$key]!!} @endforeach @endforeach </p> @endif </div> <!-- /content --> </div>
<div class="card"> <header class="header"> <a href="{{ action('StudyController@view', ['id' => $hit["_id"]]) }}"> <strong class="label">{{ Utils::getEn($hit["_source"]["title"]) }}</strong> </a> </header> <div class="content"> @if (array_key_exists("abstract", $hit["_source"])) <p>{{ str_limit(Utils::getEn($hit["_source"]["abstract"]), 150) }}</p> @endif @if(array_key_exists("highlight", $hit)) @foreach($hit["highlight"] as $label => $highlight) <p> @foreach(array_keys($highlight) as $key) <strong>{{ $label }}</strong>: {!!$highlight[$key]!!} @endforeach </p> @endforeach @endif </div> <!-- /content --> </div>
Allow changing password when no password has been set
<?php class Boom_Controller_Cms_Profile extends Boom_Controller { public function action_view() { $v = new View('boom/account/profile', array( 'person' => $this->person, 'auth' => $this->auth, 'logs' => $this->person->get_recent_account_activity(), )); $this->response->body($v); } public function action_save() { extract($this->request->post()); $this->person->set('name', $name); if ($new_password) { if ( ! $this->person->password OR $this->auth->check_password($current_password)) { $this->person->set('password', $this->auth->hash($new_password)); } else { $this->response ->status(500) ->headers('Content-Type', 'application/json') ->body(json_encode(array('message' => 'Invalid password'))); } } $this->person->update(); } }
<?php class Boom_Controller_Cms_Profile extends Boom_Controller { public function action_view() { $v = new View('boom/account/profile', array( 'person' => $this->person, 'auth' => $this->auth, 'logs' => $this->person->get_recent_account_activity(), )); $this->response->body($v); } public function action_save() { extract($this->request->post()); $this->person->set('name', $name); if ($current_password AND $new_password) { if ($this->auth->check_password($current_password)) { $this->person->set('password', $this->auth->hash($new_password)); } else { $this->response ->status(500) ->headers('Content-Type', 'application/json') ->body(json_encode(array('message' => 'Invalid password'))); } } $this->person->update(); } }
Upgrade the development status to beta.
#!/usr/bin/env python3 # encoding: utf-8 try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='autoprop', version='0.0.0', author='Kale Kundert', author_email='kale@thekunderts.net', long_description=open('README.rst').read(), url='https://github.com/kalekundert/autoprop', license='MIT', py_modules=[ 'autoprop', ], keywords=[ 'property', 'properties', 'accessor', 'accessors', 'getter', 'setter' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries', ], )
#!/usr/bin/env python3 # encoding: utf-8 try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='autoprop', version='0.0.0', author='Kale Kundert', author_email='kale@thekunderts.net', long_description=open('README.rst').read(), url='https://github.com/kalekundert/autoprop', license='MIT', py_modules=[ 'autoprop', ], keywords=[ 'property', 'properties', 'accessor', 'accessors', 'getter', 'setter' ], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries', ], )
Add json true/false/none in python repl https://mobile.twitter.com/mitsuhiko/status/1229385843585974272/photo/2
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) try: import __builtin__ except ImportError: import builtins as __builtin__ __builtin__.true = True __builtin__.false = False __builtin__.null = None readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full # path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(path=historyPath): import readline readline.write_history_file(path) if os.path.exists(historyPath): readline.read_history_file(historyPath) readline.parse_and_bind("tab: complete") readline.parse_and_bind(r"\C-a: beginning-of-line") readline.parse_and_bind(r"\C-e: end-of-line") atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath # vim: ft=python
Test: Use destroy for test clean up
/* See license.txt for terms of usage */ "use strict"; const { exist, addNewLayer, removeLayer } = require("./common.js"); const { closeTab } = require("sdk/tabs/utils"); /** * Add layer and check that it's properly created. */ exports["test Add Layer"] = function(assert, done) { addNewLayer().then(config => { let popup = config.popup; let layer = config.layer; // Check the layer store. There should be one layer at this moment. assert.equal(popup.store.layers.length, 1, "There must be one layer"); // Check if the panel content displays new layer. let selector = "img.layerImage[data-id='" + layer.id + "']"; exist(popup, selector).then(result => { assert.ok(result.data.args, "The layer must exist in the popup panel"); // Clean up removeLayer(popup, layer.id).then(() => { config.popup.destroy().then(() => { closeTab(config.tab); done(); }); }); }); }); }; require("sdk/test").run(exports);
/* See license.txt for terms of usage */ "use strict"; const { exist, addNewLayer, removeLayer } = require("./common.js"); const { closeTab } = require("sdk/tabs/utils"); /** * Add layer and check that it's properly created. */ exports["test Add Layer"] = function(assert, done) { addNewLayer().then(config => { let popup = config.popup; let layer = config.layer; // Check the layer store. There should be one layer at this moment. assert.equal(popup.store.layers.length, 1, "There must be one layer"); // Check if the panel content displays new layer. let selector = "img.layerImage[data-id='" + layer.id + "']"; exist(popup, selector).then(result => { assert.ok(result.data.args, "The layer must exist in the popup panel"); // Clean up removeLayer(popup, layer.id).then(() => { config.popup.hide().then(() => { closeTab(config.tab); done(); }); }); }); }); }; require("sdk/test").run(exports);
Fix database connection in test
<?php namespace geotime\Test; use PHPUnit_Framework_TestCase; use geotime\models\Map; use geotime\Database; class MapTest extends \PHPUnit_Framework_TestCase { static function setUpBeforeClass() { Map::$log->info(__CLASS__." tests started"); } static function tearDownAfterClass() { Map::$log->info(__CLASS__." tests ended"); } protected function setUp() { Database::connect("geotime_test"); } public function testGenerateMap() { $date1Str = '2011-01-02'; $date2Str = '2013-07-15'; $imageFileName = 'testImage.svg'; $map = Map::generateAndSaveReferences($imageFileName, $date1Str, $date2Str); $this->assertNotNull($map); $this->assertEquals($imageFileName, $map->getFileName()); $territoriesWithPeriods = $map->getTerritoriesWithPeriods(); $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getStart()); $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getEnd()); } }
<?php namespace geotime\Test; use PHPUnit_Framework_TestCase; use geotime\models\Map; class MapTest extends \PHPUnit_Framework_TestCase { static function setUpBeforeClass() { Map::$log->info(__CLASS__." tests started"); } static function tearDownAfterClass() { Map::$log->info(__CLASS__." tests ended"); } public function testGenerateMap() { $date1Str = '2011-01-02'; $date2Str = '2013-07-15'; $imageFileName = 'testImage.svg'; $map = Map::generateAndSaveReferences($imageFileName, $date1Str, $date2Str); $this->assertNotNull($map); $this->assertEquals($imageFileName, $map->getFileName()); $territoriesWithPeriods = $map->getTerritoriesWithPeriods(); $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getStart()); $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getEnd()); } }
Make source nullable; Add soft deletes
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttendanceTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('attendance', function (Blueprint $table) { $table->increments('id'); $table->string('attendable_type'); $table->unsignedInteger('attendable_id'); $table->integer('gtid')->length(9)->nullable(); $table->string('source')->nullable(); $table->unsignedInteger('recorded_by')->nullable(); $table->timestamps(); $table->softDeletes(); $table->foreign('recorded_by')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('attendance'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttendanceTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('attendance', function (Blueprint $table) { $table->increments('id'); $table->string('attendable_type'); $table->unsignedInteger('attendable_id'); $table->integer('gtid')->length(9)->nullable(); $table->string('source'); $table->unsignedInteger('recorded_by')->nullable(); $table->timestamps(); $table->foreign('recorded_by')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('attendance'); } }
Fix failing test since switching to use bare dates and not full timestamps when appropriate
import unittest import bill_info import fixtures import datetime class BillHistory(unittest.TestCase): def test_normal_enacted_bill(self): history = fixtures.bill("hr3590-111")['history'] self.assertEqual(history['house_passage_result'], 'pass') self.assertEqual(self.to_date(history['house_passage_result_at']), "2010-03-21 22:48") self.assertEqual(history['senate_passage_result'], 'pass') self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24") self.assertEqual(history['vetoed'], False) self.assertEqual(history['awaiting_signature'], False) self.assertEqual(history['enacted'], True) self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23") def to_date(self, time): if isinstance(time, str): return time else: return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M")
import unittest import bill_info import fixtures import datetime class BillHistory(unittest.TestCase): def test_normal_enacted_bill(self): history = fixtures.bill("hr3590-111")['history'] self.assertEqual(history['house_passage_result'], 'pass') self.assertEqual(self.to_date(history['house_passage_result_at']), "2010-03-21 22:48") self.assertEqual(history['senate_passage_result'], 'pass') self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24 00:00") self.assertEqual(history['vetoed'], False) self.assertEqual(history['awaiting_signature'], False) self.assertEqual(history['enacted'], True) self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23 00:00") def to_date(self, time): return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M")
Add docstring on every entity
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) """ A group entity. Contains multiple natural persons with specific roles. From zero to two parents with 'first_parent' and 'second_parent' subroles. And an unlimited number of children. """ Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) """ The minimal legal entity on which a legislation might be applied. Represents a natural person. """ entities = [Household, Person]
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) entities = [Household, Person]
Add columns "editable" to role tables.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRolesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('slug')->unique(); $table->text('description')->nullable(); $table->boolean('enabled'); $table->boolean('editable'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('roles'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRolesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('slug')->unique(); $table->text('description')->nullable(); $table->boolean('enabled'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('roles'); } }
Add some PyPI tags to package
from setuptools import find_packages from setuptools import setup with open('requirements.txt') as fobj: install_requires = [line.strip() for line in fobj] with open('README.rst') as fobj: long_description = fobj.read() with open('version.txt') as fobj: version = fobj.read().strip() packages = find_packages(exclude=['tests*']) scripts = [ 'runserver.py', 'registerclient.py', ] setup( name='opwen_email_server', version=version, author='Clemens Wolff', author_email='clemens.wolff+pypi@gmail.com', packages=packages, url='https://github.com/ascoderu/opwen-cloudserver', license='Apache Software License', description='Email server for the Opwen project', long_description=long_description, scripts=scripts, include_package_data=True, install_requires=install_requires, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Topic :: Communications :: Email', ])
from setuptools import find_packages from setuptools import setup with open('requirements.txt') as fobj: install_requires = [line.strip() for line in fobj] with open('README.rst') as fobj: long_description = fobj.read() with open('version.txt') as fobj: version = fobj.read().strip() packages = find_packages(exclude=['tests*']) scripts = [ 'runserver.py', 'registerclient.py', ] setup( name='opwen_email_server', version=version, author='Clemens Wolff', author_email='clemens.wolff+pypi@gmail.com', packages=packages, url='https://github.com/ascoderu/opwen-cloudserver', license='License :: OSI Approved :: Apache Software License', description='Email server for the Opwen project', long_description=long_description, scripts=scripts, include_package_data=True, install_requires=install_requires)
fix: Call recreate in Array constructor
import Class from '../class'; import Matreshka from '../matreshka'; import instanceMembers from './_prototype'; import matreshkaError from '../_helpers/matreshkaerror'; import initMK from '../_core/init'; import staticMembers from './_staticmembers'; instanceMembers.extends = Matreshka; instanceMembers.constructor = function MatreshkaArray(length) { if (!(this instanceof MatreshkaArray)) { throw matreshkaError('common:call_class'); } const def = initMK(this); const { itemMediator } = def; // repeat the same logic as for native Array if (arguments.length === 1 && typeof length === 'number') { this.length = length; } else if(arguments.length) { this.recreate(arguments, { silent: true, dontRender: true }); } // return is used to make possible to chain super() calls return this; }; const MatreshkaArray = Class(instanceMembers, staticMembers); export default MatreshkaArray;
import Class from '../class'; import Matreshka from '../matreshka'; import instanceMembers from './_prototype'; import matreshkaError from '../_helpers/matreshkaerror'; import initMK from '../_core/init'; import staticMembers from './_staticmembers'; instanceMembers.extends = Matreshka; instanceMembers.constructor = function MatreshkaArray(length) { if (!(this instanceof MatreshkaArray)) { throw matreshkaError('common:call_class'); } const def = initMK(this); const { itemMediator } = def; // repeat the same logic as for native Array if (arguments.length === 1 && typeof length === 'number') { this.length = length; } else { nofn.forEach(arguments, (arg, index) => { this[index] = itemMediator ? itemMediator(arg, index) : arg; }); this.length = arguments.length; } // return is used to make possible to chain super() calls return this; }; const MatreshkaArray = Class(instanceMembers, staticMembers); export default MatreshkaArray;
Add lameCard() which returns true when both cards are less than 4
var stateProvider = require("./stateProvider"); module.exports = (function(){ //TODO: this.getBetAmount = function() { var bet = 500; //get bet amount //calculation and some calculation logic goes here return bet; }; this.getCheckAmount = function() { //TODO: //return stateProvider.getCheckAmount() return 10; }; return this; })(); function toNum(c) { switch (c) { case 'J': return 11; case 'Q': return 12; case 'K': return 13; case 'A': return 14; default: return c; } } function lameCards(cards) { if ( (toNum(cards[0].rank) < 4 || toNum(cards[1].rank) < 4) && cards[0].rank != cards[1].rank ) { return true } else { return false } }
var stateProvider = require("./stateProvider"); module.exports = (function(){ //TODO: this.getBetAmount = function() { var bet = 500; //get bet amount //calculation and some calculation logic goes here return bet; }; this.getCheckAmount = function() { //TODO: //return stateProvider.getCheckAmount() return 10; }; return this; })(); function toNum(c) { switch (c) { case 'J': return 11; case 'Q': return 12; case 'K': return 13; case 'A': return 14; default: return c; } }
Make sure to install gpx.xsd in data directory
#!/usr/bin/env python from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos, using GPS tracks or manually from a map", url="http://www.grendelman.net/wp/tag/taggert", license="Apache License version 2.0", # package_dir={'taggert': 'taggert'}, packages=['taggert'], scripts=['taggert_run'], package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg', 'data/gpx.xsd']}, data_files=[ ('glib-2.0/schemas', ['com.tinuzz.taggert.gschema.xml']), ('applications', ['taggert.desktop']), ('pixmaps', ['taggert/data/taggert.svg']), ], )
#!/usr/bin/env python from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos, using GPS tracks or manually from a map", url="http://www.grendelman.net/wp/tag/taggert", license="Apache License version 2.0", # package_dir={'taggert': 'taggert'}, packages=['taggert'], scripts=['taggert_run'], package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg']}, data_files=[ ('glib-2.0/schemas', ['com.tinuzz.taggert.gschema.xml']), ('applications', ['taggert.desktop']), ('pixmaps', ['taggert/data/taggert.svg']), ], )
Replace newline characters with break tags in output
/** * Copyright 2015 Cm_Star. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var fs = require('fs'); var path = require('path'); var jade = require('jade'); var CleanCSS = require('clean-css'); module.exports.render = function(template, style, info) { if (!template) template = fs.readFileSync(path.resolve(__dirname, '../template.jade')); if (!style) style = fs.readFileSync(path.resolve(__dirname, '../styles/lines.css')); info.__style = new CleanCSS().minify(style).styles; return jade.render(template, info).replace(/\\n/g, '<br>'); }
/** * Copyright 2015 Cm_Star. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var fs = require('fs'); var path = require('path'); var jade = require('jade'); var CleanCSS = require('clean-css'); module.exports.render = function(template, style, info) { if (!template) template = fs.readFileSync(path.resolve(__dirname, '../template.jade')); if (!style) style = fs.readFileSync(path.resolve(__dirname, '../styles/lines.css')); info.__style = new CleanCSS().minify(style).styles; return jade.render(template, info); }
Enable syntax highlighting with Markdown.
from markdown import markdown import docutils.core from docutils.writers.html4css1 import Writer as rst_html_writer class Renderer(object): extensions = [] @classmethod def render(cls, plain): return plain class Markdown(Renderer): extensions = ['markdown', 'mkd'] @classmethod def render(cls, plain): return markdown(plain, ['def_list', 'footnotes', 'codehilite']) class ReStructuredText(Renderer): extensions = ['rst'] @classmethod def render(cls, plain): w = rst_html_writer() return docutils.core.publish_parts(plain, writer=w)['body'] class Plain(Renderer): extensions = 'txt' @classmethod def render(cls, plain): return plain.replace('\n', '<br>') all = [Renderer, Plain, Markdown, ReStructuredText]
from markdown import markdown import docutils.core from docutils.writers.html4css1 import Writer as rst_html_writer class Renderer(object): extensions = [] @classmethod def render(cls, plain): return plain class Markdown(Renderer): extensions = ['markdown', 'mkd'] @classmethod def render(cls, plain): return markdown(plain, ['def_list', 'footnotes']) class ReStructuredText(Renderer): extensions = ['rst'] @classmethod def render(cls, plain): w = rst_html_writer() return docutils.core.publish_parts(plain, writer=w)['body'] class Plain(Renderer): extensions = 'txt' @classmethod def render(cls, plain): return plain.replace('\n', '<br>') all = [Renderer, Plain, Markdown, ReStructuredText]
Set ComboBox class default ID to wx.ID_ANY
# -*- coding: utf-8 -*- ## \package custom.combo # MIT licensing # See: LICENSE.txt import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): def __init__(self, parent, win_id=wx.ID_ANY, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator, name=wx.ComboBoxNameStr): OwnerDrawnComboBox.__init__(self, parent, win_id, value, pos, size, choices, style, validator, name) self.Default = self.GetLabel() self.Priority = [] ## Resets ComboBox to defaults def Reset(self): if not self.Count: self.SetValue(self.Default) return self.Value == self.Default return False
# -*- coding: utf-8 -*- ## \package custom.combo # MIT licensing # See: LICENSE.txt import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator, name=wx.ComboBoxNameStr): OwnerDrawnComboBox.__init__(self, parent, win_id, value, pos, size, choices, style, validator, name) self.Default = self.GetLabel() self.Priority = [] ## Resets ComboBox to defaults def Reset(self): if not self.Count: self.SetValue(self.Default) return self.Value == self.Default return False
Replace binary strings with normal strings in an older migration
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wagtailmenus', '0010_auto_20160201_1558'), ] operations = [ migrations.AlterField( model_name='flatmenuitem', name='url_append', field=models.CharField(help_text="Use this to optionally append a #hash or querystring to the above page's URL.", max_length=255, verbose_name='Append to URL', blank=True), ), migrations.AlterField( model_name='mainmenuitem', name='url_append', field=models.CharField(help_text="Use this to optionally append a #hash or querystring to the above page's URL.", max_length=255, verbose_name='Append to URL', blank=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wagtailmenus', '0010_auto_20160201_1558'), ] operations = [ migrations.AlterField( model_name='flatmenuitem', name='url_append', field=models.CharField(help_text=b"Use this to optionally append a #hash or querystring to the above page's URL.", max_length=255, verbose_name='Append to URL', blank=True), ), migrations.AlterField( model_name='mainmenuitem', name='url_append', field=models.CharField(help_text=b"Use this to optionally append a #hash or querystring to the above page's URL.", max_length=255, verbose_name='Append to URL', blank=True), ), ]
Add missing console_scripts entry point. Signed-off-by: Chris Larson <8cf06b7089d5169434d5def8b2d1c9c9c95f6e71@mvista.com>
from setuptools import setup, find_packages from os.path import join, dirname version = 0.1 short_description = "Git cherry pick tracking." long_description = open(join(dirname(__file__), "README.txt"), "r").read() setup(name = "git_origin", version = version, description = short_description, long_description = long_description, classifiers = [], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords = "", author = "Chris Larson", author_email = "clarson@kergoth.com", url = "", license = "GPL v2", packages = find_packages("src"), package_dir = {"": "src"}, namespace_packages = ["git_origin"], include_package_data = True, zip_safe = False, install_requires = [ "setuptools", "GitPython", ], entry_points = { "console_scripts": [ "git-origin = git_origin.cmd:origin", ], }, )
from setuptools import setup, find_packages from os.path import join, dirname version = 0.1 short_description = "Git cherry pick tracking." long_description = open(join(dirname(__file__), "README.txt"), "r").read() setup(name = "git_origin", version = version, description = short_description, long_description = long_description, classifiers = [], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords = "", author = "Chris Larson", author_email = "clarson@kergoth.com", url = "", license = "GPL v2", packages = find_packages("src"), package_dir = {"": "src"}, namespace_packages = ["git_origin"], include_package_data = True, zip_safe = False, install_requires = [ "setuptools", "GitPython", ], )
Fix translatability of validation messages when defined in custom settings
from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ from django_auth_policy import settings as dap_settings def password_min_length(value): if dap_settings.PASSWORD_MIN_LENGTH_TEXT is None: return if len(value) < dap_settings.PASSWORD_MIN_LENGTH: msg = _(dap_settings.PASSWORD_MIN_LENGTH_TEXT).format( length=dap_settings.PASSWORD_MIN_LENGTH) raise ValidationError(msg, code='password_min_length') def password_complexity(value): if not dap_settings.PASSWORD_COMPLEXITY: return pw_set = set(value) for rule in dap_settings.PASSWORD_COMPLEXITY: if not pw_set.intersection(rule['chars']): msg = _(dap_settings.PASSWORD_COMPLEXITY_TEXT).format( rule_text=_(rule['text'])) raise ValidationError(msg, 'password_complexity')
from django.core.exceptions import ValidationError from django_auth_policy import settings as dap_settings def password_min_length(value): if dap_settings.PASSWORD_MIN_LENGTH_TEXT is None: return if len(value) < dap_settings.PASSWORD_MIN_LENGTH: msg = dap_settings.PASSWORD_MIN_LENGTH_TEXT.format( length=dap_settings.PASSWORD_MIN_LENGTH) raise ValidationError(msg, code='password_min_length') def password_complexity(value): if not dap_settings.PASSWORD_COMPLEXITY: return pw_set = set(value) for rule in dap_settings.PASSWORD_COMPLEXITY: if not pw_set.intersection(rule['chars']): msg = dap_settings.PASSWORD_COMPLEXITY_TEXT.format( rule_text=rule['text']) raise ValidationError(msg, 'password_complexity')
Fix bug where empty viewer mock breaks stuff
var extend = require('extend') var Crocodoc, createViewer module.exports.mock = function (mocks) { mocks = mocks || {} Crocodoc = window.Crocodoc createViewer = Crocodoc.createViewer Crocodoc.addPlugin('expose-config', function (scope) { return { init: function () { scope.getConfig().api.getConfig = function () { return scope.getConfig() } } } }) Crocodoc.createViewer = function (el, conf) { conf = extend(true, {}, conf, { plugins: { 'expose-config': true } }) var viewer = createViewer(el, conf) Object.keys(mocks).forEach(function (method) { var orig = viewer[method] viewer[method] = mocks[method] viewer['_' + method] = orig }) return viewer } } module.exports.restore = function () { if (Crocodoc) { Crocodoc.createViewer = createViewer } }
var extend = require('extend') var Crocodoc, createViewer module.exports.mock = function (mocks) { Crocodoc = window.Crocodoc createViewer = Crocodoc.createViewer Crocodoc.addPlugin('expose-config', function (scope) { return { init: function () { scope.getConfig().api.getConfig = function () { return scope.getConfig() } } } }) Crocodoc.createViewer = function (el, conf) { conf = extend(true, {}, conf, { plugins: { 'expose-config': true } }) var viewer = createViewer(el, conf) Object.keys(mocks).forEach(function (method) { var orig = viewer[method] viewer[method] = mocks[method] viewer['_' + method] = orig }) return viewer } } module.exports.restore = function () { if (Crocodoc) { Crocodoc.createViewer = createViewer } }
Reorder the service buttons display.
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.template.defaultfilters import slugify from cbv import HOME_SERVICE_COOKIE, TemplateView from calebasse.ressources.models import Service APPLICATIONS = ( (u'Gestion des dossiers', 'dossiers'), (u'Agenda', 'agenda'), (u'Saisie des actes', 'actes'), (u'Facturation et décompte', 'facturation'), (u'Gestion des personnes', 'personnes'), (u'Gestion des ressources', 'ressources'), ) def redirect_to_homepage(request): service_name = request.COOKIES.get(HOME_SERVICE_COOKIE, 'cmpp').lower() return redirect('homepage', service=service_name) class Homepage(TemplateView): template_name='calebasse/homepage.html' def get_context_data(self, **kwargs): services = Service.objects.values_list('name', 'slug') services = sorted(services, key=lambda tup: tup[0]) ctx = super(Homepage, self).get_context_data(**kwargs) ctx.update({ 'applications': APPLICATIONS, 'services': services, 'service_name': self.service.name, }) return ctx homepage = Homepage.as_view()
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.template.defaultfilters import slugify from cbv import HOME_SERVICE_COOKIE, TemplateView from calebasse.ressources.models import Service APPLICATIONS = ( (u'Gestion des dossiers', 'dossiers'), (u'Agenda', 'agenda'), (u'Saisie des actes', 'actes'), (u'Facturation et décompte', 'facturation'), (u'Gestion des personnes', 'personnes'), (u'Gestion des ressources', 'ressources'), ) def redirect_to_homepage(request): service_name = request.COOKIES.get(HOME_SERVICE_COOKIE, 'cmpp').lower() return redirect('homepage', service=service_name) class Homepage(TemplateView): template_name='calebasse/homepage.html' def get_context_data(self, **kwargs): services = Service.objects.values_list('name', 'slug') ctx = super(Homepage, self).get_context_data(**kwargs) ctx.update({ 'applications': APPLICATIONS, 'services': services, 'service_name': self.service.name, }) return ctx homepage = Homepage.as_view()
Fix post factory returning arrays
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; }); $factory->define(App\Post::class, function (Faker\Generator $faker) { return [ 'title' => $faker->sentence(6, true), 'body' => $faker->paragraphs(4, true), ]; });
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; }); $factory->define(App\Post::class, function (Faker\Generator $faker) { return [ 'title' => $faker->words(4), 'body' => $faker->paragraphs(6), ]; });
Update profile API to accept either the request's username or username in the data field
package summa import ( "database/sql" _ "go-sqlite3" "strings" ) func apiProfile(db *sql.DB, req apiRequest, resp apiResponseData) apiError { username, _ := req.Data["username"].(string) if username == "" { username = req.Username } u, err := userFetch(db, username) if err != nil { return &internalServerError{"Could not fetch user", err} } resp["user"] = u return nil } func apiProfileUpdate(db *sql.DB, req apiRequest, resp apiResponseData) apiError { var u User name, _ := req.Data["displayName"].(string) email, _ := req.Data["email"].(string) u.Username = req.Username u.DisplayName = strings.TrimSpace(name) u.Email = strings.TrimSpace(email) if u.DisplayName == "" { return &conflictError{apiResponseData{"field": "displayName"}} } if u.Email == "" { return &conflictError{apiResponseData{"field": "email"}} } err := userUpdate(db, &u) if err != nil { return &internalServerError{"Could not update user", err} } return nil }
package summa import ( "database/sql" _ "go-sqlite3" "strings" ) func apiProfile(db *sql.DB, req apiRequest, resp apiResponseData) apiError { u, err := userFetch(db, req.Username) if err != nil { return &internalServerError{"Could not fetch user", err} } resp["user"] = u return nil } func apiProfileUpdate(db *sql.DB, req apiRequest, resp apiResponseData) apiError { var u User name, _ := req.Data["displayName"].(string) email, _ := req.Data["email"].(string) u.Username = req.Username u.DisplayName = strings.TrimSpace(name) u.Email = strings.TrimSpace(email) if u.DisplayName == "" { return &conflictError{apiResponseData{"field": "displayName"}} } if u.Email == "" { return &conflictError{apiResponseData{"field": "email"}} } err := userUpdate(db, &u) if err != nil { return &internalServerError{"Could not update user", err} } return nil }
Raise ConfigurationError error that causes server to fail and dump whole stacktrace
from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise ConfigurationError("Unknown store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise ConfigurationError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise CubesError("Unable to find store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise CubesError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
Clear lesson field on add.
Template.sectionAddLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find(".lesson-name").value; // Create temporary lesson object var lessonObject = {'name': lessonName}; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); if (!this.lessonIDs) { this.lessonIDs = []; } // Add lesson ID to array this.lessonIDs.push(lessonId); // Get course sections array from parent template var courseSections = Template.parentData().sections; // Get course ID from parent template var courseID = Template.parentData()._id; // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); // Clear the lesson name field $(".lesson-name").val(''); } });
Template.sectionAddLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find(".lesson-name").value; // Create temporary lesson object var lessonObject = {'name': lessonName}; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); if (!this.lessonIDs) { this.lessonIDs = []; } // Add lesson ID to array this.lessonIDs.push(lessonId); // Get course sections array from parent template var courseSections = Template.parentData().sections; // Get course ID from parent template var courseID = Template.parentData()._id; // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); } });
[4.1] Update pwb version to 4.1 The current development is more than just bugfixes and i18n/L10N updates Change-Id: I581bfa1ee49f91161d904227e1be338db8361819
# -*- coding: utf-8 -*- """Pywikibot metadata file.""" # # (C) Pywikibot team, 2020 # # Distributed under the terms of the MIT license. # __name__ = 'pywikibot' __version__ = '4.1.0.dev0' __description__ = 'Python MediaWiki Bot Framework' __maintainer__ = 'The Pywikibot team' __maintainer_email__ = 'pywikibot@lists.wikimedia.org' __license__ = 'MIT License' __url__ = 'https://www.mediawiki.org/wiki/Manual:Pywikibot' __download_url__ = 'https://pywikibot.toolforge.org/' __copyright__ = '(C) Pywikibot team, 2003-2020' __keywords__ = 'API bot client framework mediawiki pwb python pywiki ' \ 'pywikibase pywikibot pywikipedia pywikipediabot wiki ' \ 'wikibase wikidata wikimedia wikipedia'
# -*- coding: utf-8 -*- """Pywikibot metadata file.""" # # (C) Pywikibot team, 2020 # # Distributed under the terms of the MIT license. # __name__ = 'pywikibot' __version__ = '4.0.1.dev0' __description__ = 'Python MediaWiki Bot Framework' __maintainer__ = 'The Pywikibot team' __maintainer_email__ = 'pywikibot@lists.wikimedia.org' __license__ = 'MIT License' __url__ = 'https://www.mediawiki.org/wiki/Manual:Pywikibot' __download_url__ = 'https://pywikibot.toolforge.org/' __copyright__ = '(C) Pywikibot team, 2003-2020' __keywords__ = 'API bot client framework mediawiki pwb python pywiki ' \ 'pywikibase pywikibot pywikipedia pywikipediabot wiki ' \ 'wikibase wikidata wikimedia wikipedia'
Fix row breakage in other ajax done
$(function(){ $("#all-students-table").on("change", ".teacher-drop-down", updateTableFromDropDown); $("#all-students-table").on("submit", ".add-form, .remove-form", addStudent) }); var updateTableFromDropDown = function(){ var $that = $(this); var studentUrl = $that.parent().attr('action'); var selectedTeacherId = $that.val(); var url = studentUrl + "/teachers/" + selectedTeacherId; $.ajax({ method: "patch", url: url }) .done(conditionallyReplaceRow); } var addStudent = function(event){ event.preventDefault(); var $that = $(this); $.ajax({ url: $that.attr('action'), method: "patch" }) .done(conditionallyReplaceRow) } var conditionallyReplaceRow = function(data){ var IDOfRowToReplace = $(data).attr("id"); if ($("#all-students-table").parent().attr("id") != "teacher-profile-students-table") { $('#' + IDOfRowToReplace).replaceWith(data); } else { $('#' + IDOfRowToReplace).remove(); } }
$(function(){ $("#all-students-table").on("change", ".teacher-drop-down", updateTableFromDropDown); $("#all-students-table").on("submit", ".add-form, .remove-form", addStudent) }); var updateTableFromDropDown = function(){ var $that = $(this); var studentUrl = $that.parent().attr('action'); var selectedTeacherId = $that.val(); var url = studentUrl + "/teachers/" + selectedTeacherId; $.ajax({ method: "patch", url: url }) .done(function(data){ var IDOfRowToReplace = $(data).attr("id") $('#' + IDOfRowToReplace).replaceWith(data); }); } var addStudent = function(event){ event.preventDefault(); var $that = $(this); $.ajax({ url: $that.attr('action'), method: "patch" }) .done(function(data){ var IDOfRowToReplace = $(data).attr("id"); console.log($("#all-students-table").parent().attr("id")) if ($("#all-students-table").parent().attr("id") != "teacher-profile-students-table") { $('#' + IDOfRowToReplace).replaceWith(data); } else { $('#' + IDOfRowToReplace).remove(); } }) }
ENH: Allow web API parameters to be passed as POST parameters in addition to the normal GET parameters git-svn-id: 496ab2bd9c9a782235c11388890d59de1024c1f0@2808 91079597-3006-4846-9bd3-4f3fb3d139a7
<?php /*========================================================================= Program: CDash - Cross-Platform Dashboard System Module: $Id$ Language: PHP Date: $Date$ Version: $Revision$ Copyright (c) 2002 Kitware, Inc. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // To be able to access files in this CDash installation regardless // of getcwd() value: // $cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__))); set_include_path($cdashpath . PATH_SEPARATOR . get_include_path()); require_once("cdash/pdo.php"); // Add other api includes here require("api_coverage.php"); require("api_project.php"); require("api_build.php"); require("api_user.php"); if(!isset($_GET['method'])) { echo "Method should be set: method=..."; return; } $method = $_GET['method']; $classname = ucfirst($method).'API'; $class = new $classname; $class->Parameters = array_merge($_GET, $_POST); $results = $class->Run(); // Return json by default echo json_encode($results); ?>
<?php /*========================================================================= Program: CDash - Cross-Platform Dashboard System Module: $Id$ Language: PHP Date: $Date$ Version: $Revision$ Copyright (c) 2002 Kitware, Inc. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // To be able to access files in this CDash installation regardless // of getcwd() value: // $cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__))); set_include_path($cdashpath . PATH_SEPARATOR . get_include_path()); require_once("cdash/pdo.php"); // Add other api includes here require("api_coverage.php"); require("api_project.php"); require("api_build.php"); require("api_user.php"); if(!isset($_GET['method'])) { echo "Method should be set: method=..."; return; } $method = $_GET['method']; $classname = ucfirst($method).'API'; $class = new $classname; $class->Parameters = $_GET; $results = $class->Run(); // Return json by default echo json_encode($results); ?>
Fix typos in PDFium fetch config. - The extra comma at the end of the url string unintentionally turns the url into a list. - The project name should be "pdfium". Change-Id: I8944d59d06751716c512030145d29aac10cf13fd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3770290 Reviewed-by: Aravind Vasudevan <dbe94b625b74f03bb5e24a737a4f1e15753433de@google.com> Commit-Queue: Lei Zhang <79648d9aca10df37c1b962af0b65ebfac3e19883@chromium.org>
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import config_util # pylint: disable=import-error # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=no-init class PdfiumConfig(config_util.Config): """Basic Config class for pdfium.""" @staticmethod def fetch_spec(props): url = 'https://pdfium.googlesource.com/pdfium.git' solution = { 'name': 'pdfium', 'url': url, 'managed': False, 'custom_vars': {}, } if props.get('checkout_configuration'): solution['custom_vars']['checkout_configuration'] = props[ 'checkout_configuration'] spec = { 'solutions': [solution], } if props.get('target_os'): spec['target_os'] = props['target_os'].split(',') if props.get('target_os_only'): spec['target_os_only'] = props['target_os_only'] return { 'type': 'gclient_git', 'gclient_git_spec': spec, } @staticmethod def expected_root(_props): return 'pdfium' def main(argv=None): return PdfiumConfig().handle_args(argv) if __name__ == '__main__': sys.exit(main(sys.argv))
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import config_util # pylint: disable=import-error # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=no-init class PdfiumConfig(config_util.Config): """Basic Config class for pdfium.""" @staticmethod def fetch_spec(props): url = 'https://pdfium.googlesource.com/pdfium.git', solution = { 'name': 'src', 'url': url, 'managed': False, 'custom_vars': {}, } if props.get('checkout_configuration'): solution['custom_vars']['checkout_configuration'] = props[ 'checkout_configuration'] spec = { 'solutions': [solution], } if props.get('target_os'): spec['target_os'] = props['target_os'].split(',') if props.get('target_os_only'): spec['target_os_only'] = props['target_os_only'] return { 'type': 'gclient_git', 'gclient_git_spec': spec, } @staticmethod def expected_root(_props): return 'pdfium' def main(argv=None): return PdfiumConfig().handle_args(argv) if __name__ == '__main__': sys.exit(main(sys.argv))
Fix Docker image tag inconsistency after merge commits The image pushed is always given by `git rev-parse HEAD`, but the tag for the image requested from Docker was retrieved from git log. Merge commits were ignored by the latter. Now the tag is set to `git rev-parse HEAD` both on push and retrieve.
from setuptools import setup, find_packages import os import subprocess os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil") versionFile = "src/cactus/shared/version.py" if os.path.exists(versionFile): os.remove(versionFile) git_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip() with open(versionFile, 'w') as versionFH: versionFH.write("cactus_commit = '%s'" % git_commit) setup( name="progressiveCactus", version="1.0", author="Benedict Paten", package_dir = {'': 'src'}, packages=find_packages(where='src'), include_package_data=True, package_data={'cactus': ['*_config.xml']}, # We use the __file__ attribute so this package isn't zip_safe. zip_safe=False, install_requires=[ 'decorator', 'subprocess32', 'psutil', 'networkx==1.11'], entry_points={ 'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
from setuptools import setup, find_packages import os import subprocess os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil") versionFile = "src/cactus/shared/version.py" if os.path.exists(versionFile): os.remove(versionFile) git_commit = subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0] with open(versionFile, 'w') as versionFH: versionFH.write("cactus_commit = '%s'" % git_commit) setup( name="progressiveCactus", version="1.0", author="Benedict Paten", package_dir = {'': 'src'}, packages=find_packages(where='src'), include_package_data=True, package_data={'cactus': ['*_config.xml']}, # We use the __file__ attribute so this package isn't zip_safe. zip_safe=False, install_requires=[ 'decorator', 'subprocess32', 'psutil', 'networkx==1.11'], entry_points={ 'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
Make sure the widget is initialized only once (although the widget factory does something similar)
/** * Main mixin for the Bolt buic module. * * @mixin * @namespace Bolt.buic * * @param {Object} bolt - The Bolt module. * @param {Object} $ - jQuery. */ (function (bolt, $) { 'use strict'; /** * Bolt.buic mixin container. * * @private * @type {Object} */ var buic = {}; /** * Initializes the fields, optionally based on a context. * * @function init * @memberof Bolt.buic * @param context */ buic.init = function (context) { if (typeof context === 'undefined') { context = $(document.documentElement); } // Widgets initialisations $('[data-widget]', context).each(function () { $(this)[$(this).data('widget')]() .removeAttr('data-widget') .removeData('widget'); }); }; // Add placeholder for buic. bolt.buic = buic; })(Bolt || {}, jQuery);
/** * Main mixin for the Bolt buic module. * * @mixin * @namespace Bolt.buic * * @param {Object} bolt - The Bolt module. * @param {Object} $ - jQuery. */ (function (bolt, $) { 'use strict'; /** * Bolt.buic mixin container. * * @private * @type {Object} */ var buic = {}; /** * Initializes the fields, optionally based on a context. * * @function init * @memberof Bolt.buic * @param context */ buic.init = function (context) { if (typeof context === 'undefined') { context = $(document.documentElement); } // Widgets initialisations $('[data-widget]', context).each(function () { $(this)[$(this).data('widget')](); }); }; // Add placeholder for buic. bolt.buic = buic; })(Bolt || {}, jQuery);
Increment version for 0.0.2 release.
from setuptools import setup setup( name='twisted-hl7', version='0.0.2', author='John Paulett', author_email = 'john@paulett.org', url = 'http://twisted-hl7.readthedocs.org', license = 'BSD', platforms = ['POSIX', 'Windows'], keywords = ['HL7', 'Health Level 7', 'healthcare', 'health care', 'medical record', 'twisted'], classifiers = [ 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'Intended Audience :: Healthcare Industry', 'Topic :: Communications', 'Topic :: Scientific/Engineering :: Medical Science Apps.', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking' ], packages = ['twistedhl7'], install_requires = [ # require twisted, but allow client to require specific version 'twisted', 'hl7' ], )
from setuptools import setup setup( name='twisted-hl7', version='0.0.2dev', author='John Paulett', author_email = 'john@paulett.org', url = 'http://twisted-hl7.readthedocs.org', license = 'BSD', platforms = ['POSIX', 'Windows'], keywords = ['HL7', 'Health Level 7', 'healthcare', 'health care', 'medical record', 'twisted'], classifiers = [ 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'Intended Audience :: Healthcare Industry', 'Topic :: Communications', 'Topic :: Scientific/Engineering :: Medical Science Apps.', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking' ], packages = ['twistedhl7'], install_requires = [ # require twisted, but allow client to require specific version 'twisted', 'hl7' ], )
Remove old progress stuff before creating new. git-svn-id: aa6b683a0c3c4a7a7056638acacb3aaf04dd239a@3148 63c81c92-1a08-11de-87e6-23293a004a03
function initProgressMarkers() { $('.ProgressMarker').remove(); $('.ProgressLine').remove(); var $formPage = $('.FormPage'); var $progressMarkers = $('.Answer').map(function() { var $progressMarker = $("<div class='ProgressMarker'/>"); $progressMarker.addClass( $(this).hasClass('Answered') ? 'Answered' : 'Unanswered'); $progressMarker.css('top', $(this).position().top); $formPage.append($progressMarker); return $progressMarker; }); for (var i=1; i<$progressMarkers.length; i++) { var topMarkerY = $progressMarkers[i-1].position().top; var bottomMarkerY = $progressMarkers[i].position().top; var length = bottomMarkerY - topMarkerY; var isConnected = $progressMarkers[i-1].hasClass('Answered') && $progressMarkers[i].hasClass('Answered'); var $progressLine = $("<div class='ProgressLine'>|</div>"); $progressLine.addClass( isConnected ? 'Connected' : 'Disconnected'); $progressLine.css('top', topMarkerY); $progressLine.css('height', length); $formPage.append($progressLine); console.log(isConnected, length); } }
function initProgressMarkers() { var $formPage = $('.FormPage'); var $progressMarkers = $('.Answer').map(function() { var $progressMarker = $("<div class='ProgressMarker'/>"); $progressMarker.addClass( $(this).hasClass('Answered') ? 'Answered' : 'Unanswered'); $progressMarker.css('top', $(this).position().top); $formPage.append($progressMarker); return $progressMarker; }); for (var i=1; i<$progressMarkers.length; i++) { var topMarkerY = $progressMarkers[i-1].position().top; var bottomMarkerY = $progressMarkers[i].position().top; var length = bottomMarkerY - topMarkerY; var isConnected = $progressMarkers[i-1].hasClass('Answered') && $progressMarkers[i].hasClass('Answered'); var $progressLine = $("<div class='ProgressLine'>|</div>"); $progressLine.addClass( isConnected ? 'Connected' : 'Disconnected'); $progressLine.css('top', topMarkerY); $progressLine.css('height', length); $formPage.append($progressLine); console.log(isConnected, length); } }
Improve error message legibility on windows
'use strict'; var chalk = require( 'chalk' ); var table = require( 'text-table' ); /** * @param {Errors[]} errorsCollection */ module.exports = function( errorsCollection ) { var errorCount = 0; /** * Formatting every error set. */ var report = errorsCollection.map( function( errors ) { if ( ! errors.isEmpty() ) { errorCount += errors.getErrorCount(); var output = errors.getErrorList().map( function( error ) { return [ '', chalk.gray( error.line ), chalk.gray( error.column ), process.platform !== 'win32' ? chalk.blue( error.message ) : chalk.cyan( error.message ) ]; } ); return [ '', chalk.underline( errors.getFilename() ), table( output ), '' ].join('\n'); } return ''; }); if ( errorCount ) { // Output results console.log( report.join('') ); } else { console.log( 'No code style errors found.' ); } }; // Expose path to reporter so it can be configured in e.g. grunt-jscs-checker module.exports.path = __dirname;
'use strict'; var chalk = require( 'chalk' ); var table = require( 'text-table' ); /** * @param {Errors[]} errorsCollection */ module.exports = function( errorsCollection ) { var errorCount = 0; /** * Formatting every error set. */ var report = errorsCollection.map( function( errors ) { if ( ! errors.isEmpty() ) { errorCount += errors.getErrorCount(); var output = errors.getErrorList().map( function( error ) { return [ '', chalk.gray( error.line ), chalk.gray( error.column ), chalk.blue( error.message ) ]; } ); return [ '', chalk.underline( errors.getFilename() ), table( output ), '' ].join('\n'); } return ''; }); if ( errorCount ) { // Output results console.log( report.join('') ); } else { console.log( 'No code style errors found.' ); } }; // Expose path to reporter so it can be configured in e.g. grunt-jscs-checker module.exports.path = __dirname;
Replace deprecated auth class with alternatives
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gbif.ws.client.filter; import org.gbif.api.model.common.GbifUser; import org.gbif.api.model.common.GbifUserPrincipal; import java.security.Principal; import java.util.function.Supplier; import com.google.common.base.Strings; /** * A Principal provider providing the same principal every time. The principal to be provided can be * changed at any time. * * <p>Useful for testing ws-resources. */ public class SimplePrincipalProvider implements Supplier<Principal> { private GbifUserPrincipal current; public void setPrincipal(String username) { if (Strings.isNullOrEmpty(username)) { current = null; } else { GbifUser user = new GbifUser(); user.setUserName(username); current = new GbifUserPrincipal(user); } } @Override public Principal get() { return current; } }
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gbif.ws.client.filter; import org.gbif.api.model.common.User; import org.gbif.api.model.common.UserPrincipal; import java.security.Principal; import java.util.function.Supplier; import com.google.common.base.Strings; /** * A Principal provider providing the same principal every time. The principal to be provided can be * changed at any time. * * <p>Useful for testing ws-resources. */ public class SimplePrincipalProvider implements Supplier<Principal> { private UserPrincipal current; public void setPrincipal(String username) { if (Strings.isNullOrEmpty(username)) { current = null; } else { User user = new User(); user.setUserName(username); current = new UserPrincipal(user); } } @Override public Principal get() { return current; } }
Remove an unused require statement
'use strict'; var $ = require('jquery') , game = require('./game') , primus; console.log('connecting to server ...'); /* global Primus */ primus = Primus.connect(); primus.on('open', function() { console.log('connection established'); }); // event handler for when this client joins a room primus.on('client.joinRoom', function(roomId) { console.log('joined room', roomId); }); // event handler for initializing the client primus.on('client.init', function(config) { // remove the canvas if it was already created // this may happen if the server gets restarted mid-game $('canvas').remove(); // run the game game.run(primus, config); }); // event handler for when an error occurs primus.on('error', function error(err) { console.error('Something horrible has happened', err.stack); });
'use strict'; var $ = require('jquery') , io = require('socket.io-client') , game = require('./game') , primus; console.log('connecting to server ...'); /* global Primus */ primus = Primus.connect(); primus.on('open', function() { console.log('connection established'); }); // event handler for when this client joins a room primus.on('client.joinRoom', function(roomId) { console.log('joined room', roomId); }); // event handler for initializing the client primus.on('client.init', function(config) { // remove the canvas if it was already created // this may happen if the server gets restarted mid-game $('canvas').remove(); // run the game game.run(primus, config); }); // event handler for when an error occurs primus.on('error', function error(err) { console.error('Something horrible has happened', err.stack); });
Update Flask-WTF imports to >0.9.0-style
from flask.ext.wtf import Form from wtforms.fields import TextField, PasswordField, BooleanField from wtforms.validators import Required from models import User class LoginForm(Form): username = TextField('username', [Required()]) password = PasswordField('password', [Required()]) remember = BooleanField('remember') def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.user = None def validate(self): rv = Form.validate(self) if not rv: return False user = User.query.filter_by(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True
from flask.ext.wtf import Form, TextField, PasswordField, BooleanField, validators from models import User class LoginForm(Form): username = TextField('username', [validators.Required()]) password = PasswordField('password', [validators.Required()]) remember = BooleanField('remember') def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.user = None def validate(self): rv = Form.validate(self) if not rv: return False user = User.query.filter_by(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True
Use -s option before or after argument
#!/usr/bin/env node var fs = require('fs') var path = require('path') var argv = require('yargs') .boolean('s') .alias('s', 'silent') .describe('s', 'print empty string instead of erroring out') .argv var pkg = path.join(process.cwd(), 'package.json') var field = argv._[0] || 'name' fs.readFile(pkg, 'utf8', function(err, data) { if (err) { if (argv.s) process.stdout.write('') else throw new Error(err) } else { try { var p = JSON.parse(data) process.stdout.write(p[field]||'') } catch (e) { if (argv.s) process.stdout.write('') else throw new Error(e) } } })
#!/usr/bin/env node var fs = require('fs') var path = require('path') var argv = require('yargs') .alias('s', 'silent') .describe('s', 'print empty string instead of erroring out') .argv var pkg = path.join(process.cwd(), 'package.json') var field = argv._[0] || 'name' fs.readFile(pkg, 'utf8', function(err, data) { if (err) { if (argv.s) process.stdout.write('') else throw new Error(err) } else { try { var p = JSON.parse(data) process.stdout.write(p[field]||'') } catch (e) { if (argv.s) process.stdout.write('') else throw new Error(e) } } })
Make sure filename is a string.
from functools import wraps from logging import getLogger from os import getcwd, unlink from os.path import join, realpath, isfile from psutil import Process logger = getLogger(__name__) def one(f): @wraps(f) def decorator(): pid_file = realpath(join(getcwd(), '.pid')) if _is_running(pid_file): exit(0) _set_running(pid_file) try: f() finally: unlink(pid_file) return decorator def _is_running(): pass def _read_pid_file(filename): if not isfile(str(filename)): return None with open(filename, 'r') as f: pid, create_time = f.read().split(',') return Process(int(pid)) def _set_running(filename): p = Process() with open(filename, 'w') as f: f.write('{},{}'.format(p.pid, p.create_time())) def _unlink_pid_file(f): unlink(f)
from functools import wraps from logging import getLogger from os import getcwd, unlink from os.path import join, realpath, isfile from psutil import Process logger = getLogger(__name__) def one(f): @wraps(f) def decorator(): pid_file = realpath(join(getcwd(), '.pid')) if _is_running(pid_file): exit(0) _set_running(pid_file) try: f() finally: unlink(pid_file) return decorator def _is_running(): pass def _read_pid_file(filename): with open(filename, 'r') as f: pid, create_time = f.read().split(',') return Process(int(pid)) def _set_running(filename): p = Process() with open(filename, 'w') as f: f.write('{},{}'.format(p.pid, p.create_time())) def _unlink_pid_file(f): unlink(f)
Fix the typo in the test case ref #34
'use babel' import RandomTipPanel from '../lib/random-tip-panel' describe('RandomTipPanel', () => { let panel = null beforeEach(() => { panel = new RandomTipPanel('user-support-helper-test') panel.add('foo', 'bar') }) describe('when showForcedly is called', () => { it('shows the panel.', () => { panel.showForcedly() expect(panel.panel.isVisible()).toBe(true) }) }) describe('when the show-tips configuration is false', () => { it('does not show the panel.', () => { const currentValue = atom.config.get('user-support-helper-test.show-tips') atom.config.set('user-support-helper-test.show-tips', true) panel.show() expect(panel.panel.isVisible()).not.toBe(true) if (currentValue) { atom.config.set('user-support-helper-test.show-tips', currentValue) } else { atom.config.unset('user-support-helper-test.show-tips') } }) }) })
'use babel' import RandomTipPanel from '../lib/random-tip-panel' describe('RandomTipPanel', () => { let panel = null beforeEach(() => { panel = new RandomTipPanel('user-support-helper-test') panel.add('foo', 'bar') }) describe('when showForcedly is called', () => { it('shows the panel.', () => { panel.showForcedly() expect(panel.panel.isVisible()).toBe(true) }) }) describe('when the show-tips configuration is false', () => { it('does not show the panel.', () => { const currentValue = atom.config.get('user-support-helper-test.show-tips') atom.config.set('user-support-helper-test.show-tips', true) panel.show() expect(panel.panel.isVisible()).not.toBe(true) if (currentValue) { atom.config.set('user-support-helper-test.show-tips', currentValue) } else { atom.conig.removeKeyPath('user-support-helper-test.show-tips') } }) }) })
Add matplotlib to runtime dependencies.
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='claes@emt.uni-paderborn.de', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy', 'matplotlib' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], )
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='claes@emt.uni-paderborn.de', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], )
Add auto page refresh when starting/stopping
package main /* This could probably be smarter, but it'll do for now. */ const HTML_STOPPED = ` <html> <body> <p>The instances for this service are currently powered down.</p> <p><a href="%s">Click here</a> to start.</p> </body> </html>` const HTML_STARTING = ` <html> <script> setTimeout(function() { window.location.reload(1); }, 5000); </script> <body> <p>Your service is starting, please wait.</p> </body> </html>` const HTML_STOPPING = ` <html> <script> setTimeout(function() { window.location.reload(1); }, 5000); </script> <body> <p>The instances for this service are being powered down.</p> </body> </html>` const HTML_UNHEALTHY = ` <html> <body> <p>The instances for this service appear to be in an unhealthy or inconsistent state.</p> </body> </html>` const HTML_ERROR = ` <html> <body> <p>An error occured processing your request: %v</p> </body> </html>`
package main /* This could probably be smarter, but it'll do for now. */ const HTML_STOPPED = ` <html> <body> <p>The instances for this service are currently powered down.</p> <p><a href="%s">Click here</a> to start.</p> </body> </html>` const HTML_STARTING = ` <html> <body> <p>Your service is starting, please wait.</p> </body> </html>` const HTML_STOPPING = ` <html> <body> <p>The instances for this service are being powered down.</p> </body> </html>` const HTML_UNHEALTHY = ` <html> <body> <p>The instances for this service appear to be in an unhealthy or inconsistent state.</p> </body> </html>` const HTML_ERROR = ` <html> <body> <p>An error occured processing your request: %v</p> </body> </html>`
Build gulp task for generating css and js
var gulp = require('gulp'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var minifyCSS = require('gulp-minify-css'); var uglify = require('gulp-uglify'); var paths = { js: ['js/**.js'], sass: { src: ['css/sass/**.scss'], build: 'css/' } }; gulp.task('js', function() { gulp.src(paths.js) .pipe(uglify()) .pipe(concat('firstpr.js')) .pipe(gulp.dest('.')); }); gulp.task('sass', function () { gulp.src( paths.sass.src ) .pipe(sass()) .pipe(gulp.dest( paths.sass.build )) .pipe(minifyCSS({keepSpecialComments: 0})) .pipe(concat('firstpr.css')) .pipe(gulp.dest('.')); }); // Continuous build gulp.task('watch', function() { gulp.watch( paths.js, ['js']); gulp.watch( paths.sass.src, ['sass']); }); gulp.task('build', ['js', 'sass']); gulp.task('default', ['build', 'watch']);
var gulp = require('gulp'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var minifyCSS = require('gulp-minify-css'); var uglify = require('gulp-uglify'); var paths = { js: ['js/**.js'], sass: { src: ['css/sass/**.scss'], build: 'css/' } }; gulp.task('js', function() { gulp.src(paths.js) .pipe(uglify()) .pipe(concat('firstpr.js')) .pipe(gulp.dest('.')); }); gulp.task('sass', function () { gulp.src( paths.sass.src ) .pipe(sass()) .pipe(gulp.dest( paths.sass.build )) .pipe(minifyCSS({keepSpecialComments: 0})) .pipe(concat('firstpr.css')) .pipe(gulp.dest('.')); }); // Continuous build gulp.task('watch', function() { gulp.watch( paths.js, ['js']); gulp.watch( paths.sass.src, ['sass']); }); gulp.task('default', ['js', 'sass', 'watch']);
tests: Use unittest.mock to mock Windows Registry read.
import sys import unittest from unittest.mock import patch from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @patch.object(AtmelStudioGccToolchain, 'read_reg', return_value = 'DUMMY_PATH') def test_from_project(self, mock_method): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('DUMMY_PATH\\..\\Atmel Toolchain\\ARM GCC\\Native\\4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
import sys import unittest from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_from_project(self): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('C:\\Program Files (x86)\\Atmel\\Atmel Studio 6.2\\..\\Atmel Toolchain\\ARM GCC\\Native\\' '4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
Add log message when no scenario are found. git-svn-id: 1c3b30599278237804f5418c838e2a3e6391d478@825 df8dfae0-ecdd-0310-b8d8-a050f7ac8317
package org.jbehave.mojo; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * Mojo to run scenarios * * @author Mauro Talevi * @goal run-scenarios */ public class ScenarioRunnerMojo extends AbstractJBehaveMojo { /** * Scenario class names * * @parameter */ private List<String> scenarioClassNames; public void execute() throws MojoExecutionException, MojoFailureException { List<String> scenarios = scenarioClassNames; if (scenarios == null || scenarios.isEmpty()) { scenarios = findScenarioClassNames(); } if (scenarios.isEmpty()) { getLog().info("No scenarios to run."); } else { for (String scenario : scenarios) { try { getLog().info("Running scenario " + scenario); createScenarioClassLoader().newScenario(scenario).runUsingSteps(); } catch (Throwable e) { throw new MojoExecutionException("Failed to run scenario " + scenario, e); } } } } }
package org.jbehave.mojo; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * Mojo to run scenarios * * @author Mauro Talevi * @goal run-scenarios */ public class ScenarioRunnerMojo extends AbstractJBehaveMojo { /** * Scenario class names * * @parameter */ private List<String> scenarioClassNames; public void execute() throws MojoExecutionException, MojoFailureException { List<String> scenarios = scenarioClassNames; if ( scenarios == null || scenarios.isEmpty() ){ scenarios = findScenarioClassNames(); } for (String scenario : scenarios) { try { getLog().info("Running scenario "+scenario); createScenarioClassLoader().newScenario(scenario).runUsingSteps(); } catch (Throwable e) { throw new MojoExecutionException("Failed to run scenario " + scenario, e); } } } }
Fix subme/unsubme not seeing subscriptions
/* * Used to generate a list of roles that are both lower than the bot's role, and subscribed to feeds * Returns the feed source and the role list */ module.exports = (guild, rssList) => { let finalList = [] const botRole = guild.members.get(guild.client.user.id).highestRole for (var rssName in rssList) { let subscribersFound = [] const source = rssList[rssName] const subscribers = source.subscribers if (!Array.isArray(subscribers) || subscribers.length === 0) continue for (const subscriber of subscribers) { if (subscriber.type === 'role') { const role = guild.roles.get(subscriber.id) if (role.comparePositionTo(botRole) < 0) subscribersFound.push(role.id) } } if (subscribersFound.length !== 0) finalList.push({ source: rssList[rssName], roleList: subscribersFound }) } if (finalList.length === 0) return null return finalList }
/* * Used to generate a list of roles that are both lower than the bot's role, and subscribed to feeds * Returns the feed source and the role list */ module.exports = (guild, rssList) => { let finalList = [] const botRole = guild.members.get(guild.client.user.id).highestRole for (var rssName in rssList) { let subscribersFound = [] const keys = ['globalSubscriptions', 'filteredSubscriptions'] const source = rssList[rssName] for (const key of keys) { const subscriptions = source[key] if (!Array.isArray(subscriptions) || subscriptions.length === 0) continue for (const subscriber of subscriptions) { if (subscriber.type === 'role') { const role = guild.roles.get(subscriber.id) if (role.comparePositionTo(botRole) < 0) subscribersFound.push(role.id) } } } if (subscribersFound.length !== 0) finalList.push({ source: rssList[rssName], roleList: subscribersFound }) } if (finalList.length === 0) return null return finalList }
Update test to psr4autoload. Before it was testing ps0autoload due to copy pasting shit.
<?php include __DIR__ . '/../src/psr4autoload.php'; class Psr4AutoloaderTest extends PHPUnit_Framework_TestCase { public static function setupBeforeClass() { $content = "<?php namespace subdirnamespace1\subdirnamespace2; class TestClass { public static function testFunctionPleaseDelete() { return true; } } "; mkdir(__DIR__ . "/subdir1/", 0777, true); file_put_contents(__DIR__ . '/subdir1/TestClass.php', $content); } public function testAutoload() { \tunalaruan\psr\psr4autoload("subdirnamespace1\subdirnamespace2", __DIR__ . "/subdir1"); try { \subdirnamespace1\subdirnamespace2\TestClass::testFunctionPleaseDelete(); } catch (Exception $e) { $this->fail("Failure to autoload"); } $this->assertTrue(class_exists('subdirnamespace1\subdirnamespace2\TestClass')); } public static function tearDownAfterClass() { unlink(__DIR__ . '/subdir1/TestClass.php'); rmdir(__DIR__ . '/subdir1'); } }
<?php include __DIR__ . '/../src/psr4autoload.php'; class Psr4AutoloaderTest extends PHPUnit_Framework_TestCase { public static function setupBeforeClass() { $content = "<?php namespace sample1\sample2; class TestClass { public static function testFunctionPleaseDelete() { return true; } } "; file_put_contents(__DIR__ . '/TestClass.php', $content); } public function testAutoload() { tunalaruan\psr\psr0autoload(__DIR__); sample1\sample2\TestClass::testFunctionPleaseDelete(); $this->assertTrue(class_exists('sample1\sample2\TestClass')); } public static function tearDownAfterClass() { unlink(__DIR__ . '/TestClass.php'); } }
Use new locale registration APIs. https://github.com/flarum/core/commit/6e0bffe395265ed1d24b33987971eb5b6c97af40
<?php namespace Qia; use Flarum\Support\Extension as BaseExtension; use Illuminate\Events\Dispatcher; use Flarum\Events\RegisterLocales; class Extension extends BaseExtension { public function listen(Dispatcher $events) { $events->listen(RegisterLocales::class, function (RegisterLocales $event) { $event->addLocale('fr', 'Français'); $event->addJsFile('fr', __DIR__.'/../locale/core.js'); $event->addConfig('fr', __DIR__.'/../locale/core.php'); $event->addTranslations('fr', __DIR__.'/../locale/core.yml'); $event->addTranslations('fr', __DIR__.'/../locale/likes.yml'); $event->addTranslations('fr', __DIR__.'/../locale/lock.yml'); $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml'); $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml'); $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/tags.yml'); }); } }
<?php namespace Qia; use Flarum\Support\Extension as BaseExtension; use Illuminate\Events\Dispatcher; use Flarum\Events\RegisterLocales; class Extension extends BaseExtension { public function listen(Dispatcher $events) { $events->listen(RegisterLocales::class, function (RegisterLocales $event) { $event->manager->addLocale('fr', 'Français'); $event->manager->addJsFile('fr', __DIR__.'/../locale/core.js'); $event->manager->addConfig('fr', __DIR__.'/../locale/core.php'); $event->addTranslations('fr', __DIR__.'/../locale/core.yml'); $event->addTranslations('fr', __DIR__.'/../locale/likes.yml'); $event->addTranslations('fr', __DIR__.'/../locale/lock.yml'); $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml'); $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml'); $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/tags.yml'); }); } }
Fix deprecation warning for Github button on examples page
import React from 'react'; import {findDOMNode} from 'react-dom'; const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead'; const GitHubStarsButton = React.createClass({ componentDidMount() { const node = findDOMNode(this); node.dataset.style = window.innerWidth > 480 ? 'mega': null; }, render() { return ( <a aria-label={`Star ${AUTHOR_REPO} on GitHub`} className="github-button" data-count-aria-label="# stargazers on GitHub" data-count-href={`/${AUTHOR_REPO}/stargazers`} data-show-count={true} href={`https://github.com/${AUTHOR_REPO}`}> Star </a> ); }, }); export default GitHubStarsButton;
import React from 'react'; import {findDOMNode} from 'react-dom'; const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead'; const GitHubStarsButton = React.createClass({ componentDidMount() { const node = findDOMNode(this); node.dataset.style = window.innerWidth > 480 ? 'mega': null; }, render() { return ( <a aria-label={`Star ${AUTHOR_REPO} on GitHub`} className="github-button" data-count-api={`/repos/${AUTHOR_REPO}#stargazers_count`} data-count-aria-label="# stargazers on GitHub" data-count-href={`/${AUTHOR_REPO}/stargazers`} href={`https://github.com/${AUTHOR_REPO}`}> Star </a> ); }, }); export default GitHubStarsButton;
Add an `add` method to places repo.
"use strict"; import placeToEat from "application/domain/placeToEat"; export default function inMemoryPlacesRepo() { let places = [ placeToEat({ id: 100, name: "Thai House", cuisine: "Thai" }), placeToEat({ id: 101, name: "Pizza Plus", cuisine: "American" }), placeToEat({ id: 102, name: "Mura Sushi", cuisine: "Japanese" }) ]; let fetchAll = () => places; let findById = (id) => { let _place; places.some((place) => { if (place.id === id) { _place = place; return true; } }); return _place; }; let fetchRandom = () => { let min = 0; let max = places.length; let idx = Math.floor(Math.random() * (max - min) + min); return places[idx]; }; let add = (placeToEat) => { places.push(placeToEat); }; return { add, fetchAll, findById, fetchRandom }; }
"use strict"; import placeToEat from "application/domain/placeToEat"; export default function inMemoryPlacesRepo() { let places = [ placeToEat({ id: 100, name: "Thai House", cuisine: "Thai" }), placeToEat({ id: 101, name: "Pizza Plus", cuisine: "American" }), placeToEat({ id: 102, name: "Mura Sushi", cuisine: "Japanese" }) ]; let fetchAll = () => places; let findById = (id) => { let _place; places.some((place) => { if (place.id === id) { _place = place; return true; } }); return _place; }; let fetchRandom = () => { let min = 0; let max = places.length; let idx = Math.floor(Math.random() * (max - min) + min); return places[idx]; }; return { fetchAll, findById, fetchRandom }; }
Add in more unit tests. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com>
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage. outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) # Now open up the ISO with pyiso and check some things out. iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long. assert(iso.pvd.space_size == 24) # genisoimage always produces ISOs with 2048-byte sized logical blocks. assert(iso.pvd.log_block_size == 2048) # With no files, the path table should be exactly 10 bytes (just for the # root directory entry). assert(iso.pvd.path_tbl_size == 10) # The little endian version of the path table should start at extent 19. assert(iso.pvd.path_table_location_le == 19) # The big endian version of the path table should start at extent 21. assert(iso.pvd.path_table_location_be == 21)
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long assert(iso.pvd.space_size == 24) assert(iso.pvd.log_block_size == 2048) assert(iso.pvd.path_tbl_size == 10)
Make api file path OS safe
import base64 import json from os import path import sys sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__)))) api_file = 'my_api.json' _api_file = path.join(path.dirname(path.abspath(__file__)), api_file) with open(_api_file) as fin: cw_api_settings = json.load(fin) API_URL = cw_api_settings['API_URL'] _cid = cw_api_settings['COMPANYID'] _pubk = cw_api_settings['PUBLICKEY'] _privk = cw_api_settings['PRIVATEKEY'] basic_auth = base64.b64encode("{}+{}:{}".format(_cid, _pubk, _privk).encode('utf-8')) basic_auth = {'Authorization': 'Basic {}'.format(str(basic_auth, 'utf-8'))}
import base64 import json from os import path import sys sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__)))) api_file = 'my_api.json' _api_file = '{}\{}'.format(path.dirname(path.abspath(__file__)), api_file) with open(_api_file) as fin: cw_api_settings = json.load(fin) API_URL = cw_api_settings['API_URL'] _cid = cw_api_settings['COMPANYID'] _pubk = cw_api_settings['PUBLICKEY'] _privk = cw_api_settings['PRIVATEKEY'] basic_auth = base64.b64encode("{}+{}:{}".format(_cid, _pubk, _privk).encode('utf-8')) basic_auth = {'Authorization': 'Basic {}'.format(str(basic_auth, 'utf-8'))}
Update examples to match docs Use the interface defined in the docs in the examples scripts.
# coding: utf-8 import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') sys.exit(1) # Creating TsuruClient instance tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this user has access to for app in tsuru.apps.list(): print('App: {}'.format(app.name)) # Get information for one app app = tsuru.apps.get('my-awesome-app') print('{app.name}: {app.description}'.format(app=app)) # Update specific app tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
# coding: utf-8 import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN.') sys.exit(1) api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this token has access to for app in api.apps: print(app.name) # Update one specific app api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app app = App.get('my-awesome-app') print('%s: %s' % (app.name, app.description)) # List all services instances for app for service in app.services: print('Service: %s' % service.name)
Fix bug with cli scripts
<? define('E_REPORTING', E_ALL & ~E_NOTICE); error_reporting(E_REPORTING); ini_set('display_errors', 'On'); define('TIME_START', microtime(true)); define('ROOT', dirname(dirname(__FILE__))); define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config'); define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null)); define('PROJECT_ROOT', PROJECT ? dirname(ROOT).'/appers/'.PROJECT : null); define('PROJECTS_ROOT', dirname(ROOT).'/appers'); define('EXEC_PATH', dirname(__FILE__).'/exec.php'); require ROOT.'/lib/application/loader.php'; loader::init(); config::init(); if(config::get('restartWorkersOnChange')) { if(loader::isFilesChanged()) { bg::restartWorkers(); } }
<? define('E_REPORTING', E_ALL & ~E_NOTICE); error_reporting(E_REPORTING); ini_set('display_errors', 'On'); define('TIME_START', microtime(true)); define('ROOT', dirname(dirname(__FILE__))); define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config'); define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null)); define('PROJECT_ROOT', PROJECT ? dirname(ROOT).'/appers/'.PROJECT : null); define('PROJECTS_ROOT', dirname(ROOT).'/appers'); define('EXEC_PATH', __FILE__); require ROOT.'/lib/application/loader.php'; loader::init(); config::init(); if(config::get('restartWorkersOnChange')) { if(loader::isFilesChanged()) { bg::restartWorkers(); } }
Convert environment variable to string
#!/usr/bin/env python3 import os import time import json import requests import pyperclip API_KEY = os.environ.get('API_KEY') # API_KEY = "" def google_url_shorten(url): req_url = "https://www.googleapis.com/urlshortener/v1/url?" + str(API_KEY) payload = {'longUrl': url} headers = {'content-type': 'application/json'} r = requests.post(req_url, data=json.dumps(payload), headers=headers) resp = json.loads(r.text) return resp["id"] recent_value = "" while True: tmp_value = pyperclip.paste() if (tmp_value != recent_value and not tmp_value.startswith("https://goo.gl") and not tmp_value.startswith("https://git")): recent_value = tmp_value url = str(recent_value) if url.startswith("http://") or url.startswith("https://") or url.startswith("www."): pyperclip.copy(google_url_shorten(url)) time.sleep(0.5)
#!/usr/bin/env python3 import os import time import json import requests import pyperclip API_KEY = os.environ.get('API_KEY') # API_KEY = "" def google_url_shorten(url): req_url = "https://www.googleapis.com/urlshortener/v1/url?" + API_KEY payload = {'longUrl': url} headers = {'content-type': 'application/json'} r = requests.post(req_url, data=json.dumps(payload), headers=headers) resp = json.loads(r.text) return resp["id"] recent_value = "" while True: tmp_value = pyperclip.paste() if (tmp_value != recent_value and not tmp_value.startswith("https://goo.gl") and not tmp_value.startswith("https://git")): recent_value = tmp_value url = str(recent_value) if url.startswith("http://") or url.startswith("https://") or url.startswith("www."): pyperclip.copy(google_url_shorten(url)) time.sleep(0.5)
Change prediction lock time to two weeks
<?php namespace App\Service; use App\Entity\Award; use App\Entity\Config; use DateTime; use Doctrine\ORM\EntityManagerInterface; class PredictionService { /** @var EntityManagerInterface */ private $em; /** @var Config */ private $config; public function __construct(EntityManagerInterface $em, ConfigService $configService) { $this->em = $em; $this->config = $configService->getConfig(); } public function arePredictionsLocked() { if ($this->config->isReadOnly()) { return true; } if (!$this->config->getStreamTime()) { return false; } return new DateTime('+14 days') > $this->config->getStreamTime(); } public function areResultsAvailable() { return $this->config->isPagePublic('results'); } public function isAwardResultAvailable(Award $award) { return $this->areResultsAvailable(); } }
<?php namespace App\Service; use App\Entity\Award; use App\Entity\Config; use DateTime; use Doctrine\ORM\EntityManagerInterface; class PredictionService { /** @var EntityManagerInterface */ private $em; /** @var Config */ private $config; public function __construct(EntityManagerInterface $em, ConfigService $configService) { $this->em = $em; $this->config = $configService->getConfig(); } public function arePredictionsLocked() { if ($this->config->isReadOnly()) { return true; } if (!$this->config->getStreamTime()) { return false; } return new DateTime('+24 hours') > $this->config->getStreamTime(); } public function areResultsAvailable() { return $this->config->isPagePublic('results'); } public function isAwardResultAvailable(Award $award) { return $this->areResultsAvailable(); } }
Update the PyPI version to 7.0.7.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.7', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.6', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Fix timeline adjust not being able to load Windows files
#!/usr/bin/python from __future__ import print_function import argparse import re time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"") first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)") def adjust_lines(lines, adjust): for line in lines: match = re.match(time_re, line) if match: time = float(match.group(1)) + adjust print(re.sub(first_num_re, str(time), line, 1), end='') else: print(line, end='') def main(): parser = argparse.ArgumentParser( description="A utility to uniformly adjust times in an act timeline file") parser.add_argument('--file', required=True, type=argparse.FileType('r', encoding="utf8"), help="The timeline file to adjust times in") parser.add_argument('--adjust', required=True, type=float, help="The amount of time to adjust each entry by") args = parser.parse_args() adjust_lines(args.file, args.adjust) if __name__ == "__main__": main()
#!/usr/bin/python from __future__ import print_function import argparse import re time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"") first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)") def adjust_lines(lines, adjust): for line in lines: match = re.match(time_re, line) if match: time = float(match.group(1)) + adjust print(re.sub(first_num_re, str(time), line, 1), end='') else: print(line, end='') def main(): parser = argparse.ArgumentParser( description="A utility to uniformly adjust times in an act timeline file") parser.add_argument('--file', required=True, type=argparse.FileType('r', 0), help="The timeline file to adjust times in") parser.add_argument('--adjust', required=True, type=float, help="The amount of time to adjust each entry by") args = parser.parse_args() adjust_lines(args.file, args.adjust) if __name__ == "__main__": main()
Remove Fork Cms copyright comments.
<?php namespace Frontend\Modules\Instagram\Widgets; use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel; /** * This is the instagram feed widget * * @author Jesse Dobbelaere <jesse@dobbelae.re> */ class InstagramFeed extends FrontendBaseWidget { /** * Execute the extra * * @return void */ public function execute() { // call the parent parent::execute(); // load template $this->loadTemplate(); // parse $this->parse(); } /** * Parse the data into the template * * @return void */ private function parse() { // add css $this->header->addCSS('/src/Frontend/Modules/' . $this->getModule() . '/Layout/Css/Instagram.css'); // fetch instagram user $instagramUser = FrontendInstagramModel::get($this->data['id']); // pass user info to javascript $this->addJSData('user', $instagramUser); // parse user info in template $this->tpl->assign('user', $instagramUser); } }
<?php namespace Frontend\Modules\Instagram\Widgets; /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel; /** * This is the instagram feed widget * * @author Jesse Dobbelaere <jesse@dobbelae.re> */ class InstagramFeed extends FrontendBaseWidget { /** * Execute the extra * * @return void */ public function execute() { // call the parent parent::execute(); // load template $this->loadTemplate(); // parse $this->parse(); } /** * Parse the data into the template * * @return void */ private function parse() { // add css $this->header->addCSS('/src/Frontend/Modules/' . $this->getModule() . '/Layout/Css/Instagram.css'); // fetch instagram user $instagramUser = FrontendInstagramModel::get($this->data['id']); // pass user info to javascript $this->addJSData('user', $instagramUser); // parse user info in template $this->tpl->assign('user', $instagramUser); } }
Use `process.setMaxListeners(0)` for tests to avoid annoying warnings.
process.env.NODE_ENV = 'test'; process.setMaxListeners(process.env.MAX_LISTENERS || 0); require('sugar'); require('colors'); module.exports.chai = require('chai'); module.exports.chai.Assertion.includeStack = true; module.exports.chai.use(require('chai-http')); module.exports.async = require('async'); module.exports.debug = console.log; // module.exports.longjohn = require('longjohn'); // module.exports.longjohn.async_trace_limit = 3; // REVIEW: http://chaijs.com/plugins module.exports.flag = function(value, default_value) { if (typeof value === 'undefined') { return (default_value === undefined) ? false : default_value; } else { return (/^1|true$/i).test('' + value); // ...to avoid the boolean/truthy ghetto. } }; module.exports.API = function() { var app = function(req, res) { res.writeHeader(200, { 'content-type': 'application/json', 'x-powered-by': 'connect' }); res.end(JSON.stringify({hello: "world"})); }; var api = require('connect')(); api.use(require('../').apply(this, arguments)); api.use(app); return api; };
process.env.NODE_ENV = 'test'; require('sugar'); require('colors'); module.exports.chai = require('chai'); module.exports.chai.Assertion.includeStack = true; module.exports.chai.use(require('chai-http')); module.exports.async = require('async'); module.exports.debug = console.log; // module.exports.longjohn = require('longjohn'); // module.exports.longjohn.async_trace_limit = 3; // REVIEW: http://chaijs.com/plugins module.exports.flag = function(value, default_value) { if (typeof value === 'undefined') { return (default_value === undefined) ? false : default_value; } else { return (/^1|true$/i).test('' + value); // ...to avoid the boolean/truthy ghetto. } }; module.exports.API = function() { var app = function(req, res) { res.writeHeader(200, { 'content-type': 'application/json', 'x-powered-by': 'connect' }); res.end(JSON.stringify({hello: "world"})); }; var api = require('connect')(); api.use(require('../').apply(this, arguments)); api.use(app); return api; };
Add middleware check for existing data
from django.conf import settings from django import http from django.http import HttpResponseRedirect from pymongo.connection import Connection from pymongo.errors import ConnectionFailure class MongodbConnectionMiddleware(object): def process_request(self, request): try: connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT) if connection.is_locked: if connection.unlock(): # if db gets unlocked return None return HttpResponseRedirect('/?db_error=locked') else: #check if collection have any data db = connection[settings.CDR_MONGO_DB_NAME] collection = db[settings.CDR_MONGO_CDR_COMMON] doc = collection.find_one() if not doc: return http.HttpResponseForbidden('<h1>Error Import data</h1> Make sure you have existing data in your collections') else: return None except ConnectionFailure: return HttpResponseRedirect('/?db_error=closed')
from django.conf import settings from django.http import HttpResponseRedirect from pymongo.connection import Connection from pymongo.errors import ConnectionFailure class MongodbConnectionMiddleware(object): def process_request(self, request): try: connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT) if connection.is_locked: if connection.unlock(): # if db gets unlocked return None return HttpResponseRedirect('/?db_error=locked') else: return None except ConnectionFailure: return HttpResponseRedirect('/?db_error=closed')
Add caching to ligand statistics
from django.conf.urls import url from django.views.decorators.cache import cache_page from django.views.generic import TemplateView from ligand.views import * urlpatterns = [ url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'), url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'), url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'), url(r'^targets$',TargetDetails, name='ligand_target_detail'), url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'), url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'), url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'), url(r'^statistics', cache_page(3600*24*7)(LigandStatistics.as_view()), name='ligand_statistics') ]
from django.conf.urls import url from django.views.decorators.cache import cache_page from django.views.generic import TemplateView from ligand.views import * urlpatterns = [ url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'), url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'), url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'), url(r'^targets$',TargetDetails, name='ligand_target_detail'), url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'), url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'), url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'), url(r'^statistics', LigandStatistics.as_view(), name='ligand_statistics') ]
Expire messages in 1 hour.
var apn = require('apn'); function PushNotifier() { var options = { cert: '/home/pi/node/HomeSensor/Node/cert.pem', key: '/home/pi/node/HomeSensor/Node/key.pem', errorCallback: function(err, notif) { console.log('ERROR : ' + err + '\nNOTIFICATION : ' + notif); } }; var apnConnection = new apn.Connection(options); this.sendNotification = function (deviceToken,message,sound) { var isHex = /[a-fA-F0-9]{16}/; if (!isHex.test(deviceToken)) { console.log('No valid hexkey: '+deviceToken); return false; } var myDevice = new apn.Device(deviceToken); var notification = new apn.Notification(); notification.badge = 0; notification.sound = (sound) ? sound : "default"; notification.expiry = Math.floor(Date.now() / 1000) + 3600; //1 hour from now notification.alert = message; notification.payload = {}; apnConnection.pushNotification(notification, myDevice); console.log(myDevice); console.log('Notification "'+message+'" sent to: '+myDevice); //console.log(notification); } } module.exports = new PushNotifier;
var apn = require('apn'); function PushNotifier() { var options = { cert: '/home/pi/node/HomeSensor/Node/cert.pem', key: '/home/pi/node/HomeSensor/Node/key.pem', errorCallback: function(err, notif) { console.log('ERROR : ' + err + '\nNOTIFICATION : ' + notif); } }; var apnConnection = new apn.Connection(options); this.sendNotification = function (deviceToken,message,sound) { var isHex = /[a-fA-F0-9]{16}/; if (!isHex.test(deviceToken)) { console.log('No valid hexkey: '+deviceToken); return false; } var myDevice = new apn.Device(deviceToken); var notification = new apn.Notification(); notification.badge = 0; notification.sound = (sound) ? sound : "default"; notification.alert = message; notification.payload = {}; apnConnection.pushNotification(notification, myDevice); console.log(myDevice); console.log('Notification "'+message+'" sent to: '+myDevice); //console.log(notification); } } module.exports = new PushNotifier;
Update handleEditTrip to take prop tripData rather than rawTripData.
import React from 'react'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import Button from 'react-bootstrap/Button'; /** * {@link TripData} defined originally in `ViewTrips/trip.js`. */ /** * Component that opens the edit trip modal upon click. * * @property {Object} props These are the props for this component: * @property {string} props.tripId The document id associated with the trip. * @property {TripData} props.tripData The current trip document data. * @property {Function} props.handleEditTrip Event handler responsible for * displaying the edit trip modal. */ const EditTripButton = (props) => { return ( <Button type='button' variant='link' onClick={() => props.handleEditTrip(props.tripId, props.tripData)} > <FontAwesomeIcon icon='edit' className='fa-icon'/> </Button> ); } export default EditTripButton;
import React from 'react'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import Button from 'react-bootstrap/Button'; /** * {@link RawTripData} defined originally in `ViewTrips/save-trip-modal.js`. */ /** * Component that opens the edit trip modal upon click. * * @property {Object} props These are the props for this component: * @property {string} props.tripId The document id associated with the trip. * @property {RawTripData} props.tripFormData Re-package trip document * data to pass to SaveTripModal when filling out form input default values. * @property {Function} props.handleEditTrip Event handler responsible for * displaying the edit trip modal. */ const EditTripButton = (props) => { return ( <Button type='button' variant='link' onClick={() => props.handleEditTrip(props.tripId, props.formattedTripData)} > <FontAwesomeIcon icon='edit' className='fa-icon'/> </Button> ); } export default EditTripButton;
Drop support for naming Deck objects
import logging import random from .card import Card from .enums import GameTag, Zone from .utils import CardList class Deck(CardList): MAX_CARDS = 30 MAX_UNIQUE_CARDS = 2 MAX_UNIQUE_LEGENDARIES = 1 @classmethod def fromList(cls, cards, hero): return cls([Card(card) for card in cards], Card(hero)) def __init__(self, cards, hero): super().__init__(cards) self.hero = hero for card in cards: # Don't use .zone directly as it would double-fill the deck card.tags[GameTag.ZONE] = Zone.DECK def __repr__(self): return "<Deck(hero=%r, count=%i)>" % (self.hero, len(self)) def shuffle(self): logging.info("Shuffling %r..." % (self)) random.shuffle(self)
import logging import random from .card import Card from .enums import GameTag, Zone from .utils import CardList class Deck(CardList): MAX_CARDS = 30 MAX_UNIQUE_CARDS = 2 MAX_UNIQUE_LEGENDARIES = 1 @classmethod def fromList(cls, cards, hero): return cls([Card(card) for card in cards], Card(hero)) def __init__(self, cards, hero, name=None): super().__init__(cards) self.hero = hero if name is None: name = "Custom %s" % (hero) self.name = name for card in cards: # Don't use .zone directly as it would double-fill the deck card.tags[GameTag.ZONE] = Zone.DECK def __str__(self): return self.name def __repr__(self): return "<%s (%i cards)>" % (self.hero, len(self)) def shuffle(self): logging.info("Shuffling %r..." % (self)) random.shuffle(self)
Use format_html if it is available, fallback for dj 1.4
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import widgets from django.forms.util import flatatt from django.utils.safestring import mark_safe try: from django.utils.html import format_html except ImportError: def format_html(format_string, *args, **kwargs): return format_string.format(*args, **kwargs) class SelectMultipleField(widgets.SelectMultiple): """Multiple select widget ready for jQuery multiselect.js""" allow_multiple_selected = True def render(self, name, value, attrs=None, choices=()): rendered_attrs = {'class': 'select-multiple-field'} rendered_attrs.update(attrs) if value is None: value = [] final_attrs = self.build_attrs(rendered_attrs, name=name) # output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)] output = [format_html('<select multiple="multiple"{0}>', flatatt(final_attrs))] options = self.render_options(choices, value) if options: output.append(options) output.append('</select>') return mark_safe('\n'.join(output))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import widgets from django.forms.util import flatatt from django.utils.safestring import mark_safe class SelectMultipleField(widgets.SelectMultiple): """Multiple select widget ready for jQuery multiselect.js""" allow_multiple_selected = True def render(self, name, value, attrs=None, choices=()): rendered_attrs = {'class': 'select-multiple-field'} rendered_attrs.update(attrs) if value is None: value = [] final_attrs = self.build_attrs(rendered_attrs, name=name) # output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)] output = ['<select multiple="multiple"{0}>'.format(flatatt(final_attrs))] options = self.render_options(choices, value) if options: output.append(options) output.append('</select>') return mark_safe('\n'.join(output))
Use the same kdf for Insight Storage
var cryptoUtil = require('../util/crypto'); var InsightStorage = require('./InsightStorage'); var inherits = require('inherits'); function EncryptedInsightStorage(config) { InsightStorage.apply(this, [config]); } inherits(EncryptedInsightStorage, InsightStorage); EncryptedInsightStorage.prototype.getItem = function(name, callback) { var key = cryptoUtil.kdf(this.password + this.email); InsightStorage.prototype.getItem.apply(this, [name, function(err, body) { if (err) { return callback(err); } var decryptedJson = cryptoUtil.decrypt(key, body); if (!decryptedJson) { return callback('Internal Error'); } return callback(null, decryptedJson); } ]); }; EncryptedInsightStorage.prototype.setItem = function(name, value, callback) { var key = cryptoUtil.kdf(this.password + this.email); var record = cryptoUtil.encrypt(key, value); InsightStorage.prototype.setItem.apply(this, [name, record, callback]); }; EncryptedInsightStorage.prototype.removeItem = function(name, callback) { var key = cryptoUtil.kdf(this.password + this.email); InsightStorage.prototype.removeItem.apply(this, [name, callback]); }; module.exports = EncryptedInsightStorage;
var cryptoUtil = require('../util/crypto'); var InsightStorage = require('./InsightStorage'); var inherits = require('inherits'); function EncryptedInsightStorage(config) { InsightStorage.apply(this, [config]); } inherits(EncryptedInsightStorage, InsightStorage); EncryptedInsightStorage.prototype.getItem = function(name, callback) { var key = cryptoUtil.kdfbinary(this.password + this.email); InsightStorage.prototype.getItem.apply(this, [name, function(err, body) { if (err) { return callback(err); } var decryptedJson = cryptoUtil.decrypt(key, body); if (!decryptedJson) { return callback('Internal Error'); } return callback(null, decryptedJson); } ]); }; EncryptedInsightStorage.prototype.setItem = function(name, value, callback) { var key = cryptoUtil.kdfbinary(this.password + this.email); var record = cryptoUtil.encrypt(key, value); InsightStorage.prototype.setItem.apply(this, [name, record, callback]); }; EncryptedInsightStorage.prototype.removeItem = function(name, callback) { var key = cryptoUtil.kdfbinary(this.password + this.email); InsightStorage.prototype.removeItem.apply(this, [name, callback]); }; module.exports = EncryptedInsightStorage;
Convert arg to absolute url in SoftRedirect
<?php namespace BNETDocs\Controllers; use \BNETDocs\Models\RedirectSoft as RedirectSoftModel; use \CarlBennett\MVC\Libraries\Common; use \CarlBennett\MVC\Libraries\Controller; use \CarlBennett\MVC\Libraries\Router; use \CarlBennett\MVC\Libraries\View; class RedirectSoft extends Controller { public function &run(Router &$router, View &$view, array &$args) { $model = new RedirectSoftModel(); $model->location = Common::relativeUrlToAbsolute(array_shift($args)); $view->render($model); $model->_responseCode = 302; $model->_responseHeaders["Content-Type"] = $view->getMimeType(); $model->_responseHeaders["Location"] = $model->location; $model->_responseTTL = 0; return $model; } }
<?php namespace BNETDocs\Controllers; use \BNETDocs\Models\RedirectSoft as RedirectSoftModel; use \CarlBennett\MVC\Libraries\Controller; use \CarlBennett\MVC\Libraries\Router; use \CarlBennett\MVC\Libraries\View; class RedirectSoft extends Controller { public function &run(Router &$router, View &$view, array &$args) { $model = new RedirectSoftModel(); $model->location = array_shift($args); $view->render($model); $model->_responseCode = 302; $model->_responseHeaders["Content-Type"] = $view->getMimeType(); $model->_responseHeaders["Location"] = $model->location; $model->_responseTTL = 0; return $model; } }
Fix error message 'ChannelError: channel disconnected'
# encoding=utf-8 from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) self._producer = Producer(self._connection) self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable) except Exception: self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer') raise def errback(exc, interval): self._logger.info('Error: %r', exc, exc_info=1) self._logger.info('Retry in %s seconds.', interval) def publish(self, payload, routing_key=None, serializer=None): publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3) publish(payload, serializer=serializer, exchange=self._task_exchange, declare=[self._task_exchange], routing_key=routing_key)
# encoding=utf-8 from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) self._producer = Producer(self._connection) self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable) except Exception: self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer') raise def errback(exc, interval): self._logger.info('Error: %r', exc, exc_info=1) self._logger.info('Retry in %s seconds.', interval) def publish(self, payload, routing_key=None, serializer=None): publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3) publish(payload, serializer=serializer, exchange=self._task_exchange, declare=[self._task_exchange], routing_key=routing_key) self._connection.release()
Use square brackets instead of angle brackets in messages, as the latter are getting stripped out
import os import json import requests from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def process_slack_message(request): send_message( request.POST.get('user_name'), request.POST.get('text')) return HttpResponse() def send_message(user, text): api_user = os.environ['HABITICA_APIUSER'] api_key = os.environ['HABITICA_APIKEY'] group_id = os.environ['HABITICA_GROUPID'] habitica_url = 'https://habitica.com/api/v3/groups/%s/chat' % group_id headers = { 'x-api-user': api_user, 'x-api-key': api_key } data = { 'groupId': group_id, 'message': '[%s says] %s' % (user, text) } response = requests.post(habitica_url, headers=headers, data=data)
import os import json import requests from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def process_slack_message(request): send_message( request.POST.get('user_name'), request.POST.get('text')) return HttpResponse() def send_message(user, text): api_user = os.environ['HABITICA_APIUSER'] api_key = os.environ['HABITICA_APIKEY'] group_id = os.environ['HABITICA_GROUPID'] habitica_url = 'https://habitica.com/api/v3/groups/%s/chat' % group_id headers = { 'x-api-user': api_user, 'x-api-key': api_key } data = { 'groupId': group_id, 'message': '<%s says> %s' % (user, text) } response = requests.post(habitica_url, headers=headers, data=data)
[Python] Refactor rolling a spare in tests
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def _roll_many(self, n, pins): "Roll 'n' times a roll of 'pins' pins" for i in range(n): self.g.roll(pins) def _roll_spare(self): "Roll a spare" self.g.roll(5) self.g.roll(5) def test_gutter_game(self): self._roll_many(20, 0) self.assertEqual(0, self.g.score()) def test_all_ones(self): self._roll_many(20, 1) self.assertEqual(20, self.g.score()) def test_one_spare(self): self._roll_spare() self.g.roll(3) self._roll_many(17, 0) self.assertEqual(16, self.g.score()) if __name__ == '__main__': unittest.main()
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def _roll_many(self, n, pins): "Roll 'n' times a roll of 'pins' pins" for i in range(n): self.g.roll(pins) def test_gutter_game(self): self._roll_many(20, 0) self.assertEqual(0, self.g.score()) def test_all_ones(self): self._roll_many(20, 1) self.assertEqual(20, self.g.score()) def test_one_spare(self): self.g.roll(5) self.g.roll(5) self.g.roll(3) self._roll_many(17, 0) self.assertEqual(16, self.g.score()) if __name__ == '__main__': unittest.main()
Discard other messages when multiple are added Not sure whether this can also happen when multiple messages are actually sent
<?php declare(strict_types=1); namespace Room11\Jeeves\Chat\Message; class Factory { public function build(array $data): Message { $message = reset($data); if (isset($message['e'])) { return $this->buildEventMessage(reset($message['e'])); } return new Heartbeat($message); } private function buildEventMessage(array $message): Message { switch ($message['event_type']) { case 1: return new NewMessage($message); case 2: return new EditMessage($message); case 3: return new UserEnter($message); case 4: return new UserLeave($message); case 6: return new StarMessage($message); case 10: return new DeleteMessage($message); default: return new Unknown($message); } } }
<?php declare(strict_types=1); namespace Room11\Jeeves\Chat\Message; class Factory { public function build(array $data): Message { $message = reset($data); if (isset($message['e'])) { return $this->buildEventMessage($message['e'][0]); } return new Heartbeat($message); } private function buildEventMessage(array $message): Message { switch ($message['event_type']) { case 1: return new NewMessage($message); case 2: return new EditMessage($message); case 3: return new UserEnter($message); case 4: return new UserLeave($message); case 6: return new StarMessage($message); case 10: return new DeleteMessage($message); default: return new Unknown($message); } } }
Make block comment parsing less greedy.
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the JSON plugin linter class.""" import json import os.path import re from SublimeLinter.lint import Linter class JSON(Linter): """Provides an interface to json.loads().""" syntax = 'json' cmd = None regex = r'^(?P<message>.+):\s*line (?P<line>\d+) column (?P<col>\d+)' def run(self, cmd, code): """Attempt to parse code as JSON, return '' if it succeeds, the error message if it fails.""" # Ignore comments in .sublime-settings files. if os.path.splitext(self.filename)[1] == '.sublime-settings': code = re.sub(r'\s*//.*', '', code) # Line comments. code = re.sub(r'\s*/\*.*?\*/', '', code, flags=re.DOTALL) # Block comments. try: json.loads(code) return '' except ValueError as err: return str(err)
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the JSON plugin linter class.""" import json import os.path import re from SublimeLinter.lint import Linter class JSON(Linter): """Provides an interface to json.loads().""" syntax = 'json' cmd = None regex = r'^(?P<message>.+):\s*line (?P<line>\d+) column (?P<col>\d+)' def run(self, cmd, code): """Attempt to parse code as JSON, return '' if it succeeds, the error message if it fails.""" # Ignore comments in .sublime-settings files. if os.path.splitext(self.filename)[1] == '.sublime-settings': code = re.sub(r'\s*//.*', '', code) # Line comments. code = re.sub(r'\s*/\*.*\*/', '', code, flags=re.DOTALL) # Block comments. try: json.loads(code) return '' except ValueError as err: return str(err)
Fix tests after contract change broke them.
var NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; function getTransactionError(func) { return Promise.resolve().then(func) .then(function(txid) { var tx = web3.eth.getTransaction(txid); var txr = web3.eth.getTransactionReceipt(txid); if (txr.gasUsed === tx.gas) throw new Error("all gas used"); }) .catch(function(err) { return err; }); } contract("SpiceHours", function(accounts) { describe("balance", function() { it("should be zero in the beginning", function() { var contract = SpiceHours.deployed(); return contract.balance.call(accounts[0]).then(function(balance) { assert.equal(balance.valueOf(), 0, "balance should be zero"); }); }); }); });
var NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; function getTransactionError(func) { return Promise.resolve().then(func) .then(function(txid) { var tx = web3.eth.getTransaction(txid); var txr = web3.eth.getTransactionReceipt(txid); if (txr.gasUsed === tx.gas) throw new Error("all gas used"); }) .catch(function(err) { return err; }); } contract("SpiceHours", function(accounts) { describe("test", function() { it("should not throw an error for owner", function() { var contract = SpiceHours.deployed(); return getTransactionError(function() { return contract.test(); }).then(function(err) { assert.isUndefined(err, "owner should have access"); }); }); it("should throw an error for others", function() { var contract = SpiceHours.deployed(); return getTransactionError(function() { return contract.test({from: accounts[1]}); }).then(function(err) { assert.isDefined(err, "others should not have access"); }); }); }); });
Change onTick function cron jobs
// Cron.js - in api/services "use strict"; const CronJob = require('cron').CronJob; const _ = require('lodash'); const crons = []; module.exports = { start: () => { sails.config.scientilla.crons.forEach(cron => { crons.push(new CronJob(cron.time, onTick(cron), null, false, 'Europe/Rome')) }); crons.forEach(cron => cron.start()); }, stop: () => { crons.forEach(cron => cron.stop()); } }; function onTick(cron) { return async function () { if (!cron.enabled) { return; } sails.log.info('Cron ' + cron.name + ' started at ' + new Date().toISOString()); await GruntTaskRunner.run('cron:' + cron.name); sails.log.info('Cron ' + cron.name + ' finished at ' + new Date().toISOString()); } }
// Cron.js - in api/services "use strict"; const CronJob = require('cron').CronJob; const _ = require('lodash'); const crons = []; module.exports = { start: () => { sails.config.scientilla.crons.forEach(cron => crons.push(new CronJob(cron.time, async cron => { if (!cron.enabled) { return; } sails.log.info('Cron ' + cron.name + ' started at ' + new Date().toISOString()); await GruntTaskRunner.run('Cron:' + cron.name); sails.log.info('Cron ' + cron.name + ' finished at ' + new Date().toISOString()); }, null, false, 'Europe/Rome')) ); crons.forEach(cron => cron.start()); }, stop: () => { crons.forEach(cron => cron.stop()); } };
Change kibi to kilo format
<?php use pendalf89\filemanager\assets\FilemanagerAsset; use pendalf89\filemanager\Module; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model pendalf89\filemanager\models\Mediafile */ /* @var $dataProvider yii\data\ActiveDataProvider */ $bundle = FilemanagerAsset::register($this); ?> <?= Html::img($model->getDefaultThumbUrl($bundle->baseUrl)) ?> <ul class="detail"> <li><?= $model->type ?></li> <li><?= Yii::$app->formatter->asDatetime($model->getLastChanges()) ?></li> <?php Yii::$app->formatter->sizeFormatBase = 1000; ?> <li><?= Yii::$app->formatter->asShortSize($model->size, 0) ?></li> <li><?= Html::a(Module::t('main', 'Delete'), ['/filemanager/file/delete/', 'id' => $model->id], [ 'class' => 'text-danger', 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-id' => $model->id, 'role' => 'delete', ] ) ?></li> </ul> <div class="filename"> <?= $model->filename ?> </div>
<?php use pendalf89\filemanager\assets\FilemanagerAsset; use pendalf89\filemanager\Module; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model pendalf89\filemanager\models\Mediafile */ /* @var $dataProvider yii\data\ActiveDataProvider */ $bundle = FilemanagerAsset::register($this); ?> <?= Html::img($model->getDefaultThumbUrl($bundle->baseUrl)) ?> <ul class="detail"> <li><?= $model->type ?></li> <li><?= Yii::$app->formatter->asDatetime($model->getLastChanges()) ?></li> <li><?= Yii::$app->formatter->asShortSize($model->size, 0) ?></li> <li><?= Html::a(Module::t('main', 'Delete'), ['/filemanager/file/delete/', 'id' => $model->id], [ 'class' => 'text-danger', 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-id' => $model->id, 'role' => 'delete', ] ) ?></li> </ul> <div class="filename"> <?= $model->filename ?> </div>
Support queries in created browserHistory
/* global window document */ /* eslint "import/no-extraneous-dependencies": 0 */ import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import IsomorphicRelay from 'isomorphic-relay'; import IsomorphicRouter from 'isomorphic-relay-router'; import { match, Router } from 'react-router'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { createHistory, useQueries } from 'history'; import moment from 'moment'; import prefix from './prefix'; import routes from './routes'; import './scss/stylesheet.scss'; injectTapEventPlugin(); const browserHistory = useQueries(createHistory)(); const environment = new Relay.Environment(); environment.injectNetworkLayer(new Relay.DefaultNetworkLayer(`${prefix}/graphql`, { credentials: 'same-origin', })); IsomorphicRelay.injectPreparedData(environment, window.__INITIAL_STATE__); // Even if this site is written in english, we are mostly used to norwegian formats moment.locale('nb'); match({ routes, history: browserHistory }, (error, redirectLocation, renderProps) => { IsomorphicRouter.prepareInitialRender(environment, renderProps).then((props) => { ReactDOM.render(<Router {...props} />, document.getElementById('app')); }); });
/* global window document */ /* eslint "import/no-extraneous-dependencies": 0 */ import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import IsomorphicRelay from 'isomorphic-relay'; import IsomorphicRouter from 'isomorphic-relay-router'; import { match, Router } from 'react-router'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { createHistory } from 'history'; import moment from 'moment'; import prefix from './prefix'; import routes from './routes'; import './scss/stylesheet.scss'; injectTapEventPlugin(); const browserHistory = createHistory(); const environment = new Relay.Environment(); environment.injectNetworkLayer(new Relay.DefaultNetworkLayer(`${prefix}/graphql`, { credentials: 'same-origin', })); IsomorphicRelay.injectPreparedData(environment, window.__INITIAL_STATE__); // Even if this site is written in english, we are mostly used to norwegian formats moment.locale('nb'); match({ routes, history: browserHistory }, (error, redirectLocation, renderProps) => { IsomorphicRouter.prepareInitialRender(environment, renderProps).then((props) => { ReactDOM.render(<Router {...props} />, document.getElementById('app')); }); });
Make STORAGE_KEY work when using CookieStorage Unfortunately PHP will convert **dot**s into underscore when parsing cookie names! So we have to remove dots in our `STORAKE_KEY`s so that is possible to use a CookieStorage. [The full list of field-name characters that PHP converts to _](http://ca.php.net/manual/en/language.variables.external.php#81080) [A random blog post](http://harrybailey.com/2009/04/dots-arent-allowed-in-php-cookie-names/)
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Currency\Context; /** * Interface to be implemented by the service providing the currently used * currency. * * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface CurrencyContextInterface { // Key used to store the currency in storage. const STORAGE_KEY = '_sylius_currency'; /** * Get the default currency. * * @return string */ public function getDefaultCurrency(); /** * Get the currently active currency. * * @return string */ public function getCurrency(); /** * Set the currently active currency. * * @param string $currency */ public function setCurrency($currency); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Currency\Context; /** * Interface to be implemented by the service providing the currently used * currency. * * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface CurrencyContextInterface { // Key used to store the currency in storage. const STORAGE_KEY = '_sylius.currency'; /** * Get the default currency. * * @return string */ public function getDefaultCurrency(); /** * Get the currently active currency. * * @return string */ public function getCurrency(); /** * Set the currently active currency. * * @param string $currency */ public function setCurrency($currency); }
Fix resolving .jsx for 'indico/...' paths
/* 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/>. */ /* eslint-disable import/no-commonjs, import/unambiguous */ /* global module:false __dirname:false */ const path = require('path'); const nodeResolve = require('eslint-import-resolver-node').resolve; module.exports = { interfaceVersion: 2, resolve(source, file, config) { const rv = nodeResolve(source, file, config); if (rv.found) { return rv; } else if (source.startsWith('indico/')) { const realPath = path.join(__dirname, 'indico/web/client/js', source.substr(7)); return nodeResolve(realPath, file, config); } return {found: false}; } };
/* 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/>. */ /* eslint-disable import/no-commonjs, import/unambiguous */ /* global module:false __dirname:false */ const path = require('path'); const nodeResolve = require('eslint-import-resolver-node').resolve; module.exports = { interfaceVersion: 2, resolve(source, file, config) { const rv = nodeResolve(source, file, config); if (rv.found) { return rv; } else if (source.startsWith('indico/')) { const realPath = path.join(__dirname, 'indico/web/client/js', source.substr(7)); return nodeResolve(realPath, file); } return {found: false}; } };
Add more special characters to the sample project
/* * Copyright 2016 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.paranoid.sample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import io.michaelrocks.paranoid.Obfuscate; @Obfuscate public class MainActivity extends AppCompatActivity { private static final String QUESTION = "Q:\r\n%s"; private static final String ANSWER = "A:\r\n%s"; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); final TextView questionTextView = (TextView) findViewById(R.id.questionTextView); questionTextView.setText(String.format(QUESTION, "How does it work?")); final TextView answerTextView = (TextView) findViewById(R.id.answerTextView); answerTextView.setText(String.format(ANSWER, "It's magic! ¯\\_(ツ)_/¯")); } }
/* * Copyright 2016 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.paranoid.sample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import io.michaelrocks.paranoid.Obfuscate; @Obfuscate public class MainActivity extends AppCompatActivity { private static final String QUESTION = "Q:\r\n%s"; private static final String ANSWER = "A:\r\n%s"; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); final TextView questionTextView = (TextView) findViewById(R.id.questionTextView); questionTextView.setText(String.format(QUESTION, "Does it work?")); final TextView answerTextView = (TextView) findViewById(R.id.answerTextView); answerTextView.setText(String.format(ANSWER, "Sure it does!")); } }
Add option hideSourceMaps to hide source maps
const {readFileSync} = require('fs') const {resolve} = require('path') function createRequestDecorator (stats) { return (req, res, next) => { res.locals = res.locals || Object.create(null) res.locals.webpackClientStats = stats next && next() } } function serveAssets (router, options = {}) { if (typeof options === 'string') { options = {outputPath: options} } if (typeof arguments[2] === 'function') { options.requestDecorator = arguments[2] } const { hideSourceMaps = true, hideStats = true, outputPath, publicPath = '/', statsFilename = 'stats.json', serveStatic, requestDecorator = createRequestDecorator } = options const statsPath = resolve(outputPath, statsFilename) const stats = JSON.parse(readFileSync(statsPath, 'utf8')) const decorateRequest = requestDecorator(stats) const serve = serveStatic(outputPath) if (hideSourceMaps) { router.use(publicPath, (req, res, next) => { if (req.url.endsWith('.map')) { return res.sendStatus(403) } next() }) } if (hideStats) { router.use(publicPath + statsFilename, (req, res) => { res.sendStatus(403) }) } router.use(publicPath, serve) router.use(decorateRequest) } exports = module.exports = serveAssets.bind() exports.createRequestDecorator = createRequestDecorator exports.serveAssets = serveAssets
const {readFileSync} = require('fs') const {resolve} = require('path') function createRequestDecorator (stats) { return (req, res, next) => { res.locals = res.locals || Object.create(null) res.locals.webpackClientStats = stats next && next() } } function serveAssets (router, options = {}) { if (typeof options === 'string') { options = {outputPath: options} } if (typeof arguments[2] === 'function') { options.requestDecorator = arguments[2] } const { hideStats = true, outputPath, publicPath = '/', statsFilename = 'stats.json', serveStatic, requestDecorator = createRequestDecorator } = options const statsPath = resolve(outputPath, statsFilename) const stats = JSON.parse(readFileSync(statsPath, 'utf8')) const decorateRequest = requestDecorator(stats) const serve = serveStatic(outputPath) if (hideStats) { router.use(publicPath + statsFilename, (req, res) => { res.sendStatus(403) }) } router.use(publicPath, serve) router.use(decorateRequest) } exports = module.exports = serveAssets.bind() exports.createRequestDecorator = createRequestDecorator exports.serveAssets = serveAssets