text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change GetTransMemoryHandler to return multiple strings per TextFlow Also had to split TranslationMemoryGlossaryItem into SearchResultItem, TransMemoryResultItem and GlossaryResultItem and related UI classes. (Sorting of TM results still needs to account for multiple strings.) TransMemoryQuery.toString() shortens now query strings.
package org.zanata.util; import java.util.ArrayList; import java.util.List; /** * ShortStrings are meant for use in logging. They don't incur the cost of * shortening until toString() is called. This means they hold on to the entire * string, so don't bother keeping them around in memory for long. * * @author Sean Flanigan <a * href="mailto:sflaniga@redhat.com">sflaniga@redhat.com</a> * */ public class ShortString { static final int MAX_LENGTH = 66; private static final String ELLIPSIS = "…"; private String input; public ShortString(String input) { this.input = input; } @Override public String toString() { return input = shorten(input); } public static String shorten(String s) { if (s.length() <= MAX_LENGTH) return s; return s.substring(0, MAX_LENGTH - ELLIPSIS.length()) + ELLIPSIS; } /** * @param strings * @return */ public static String shorten(List<String> strings) { List<String> shortStrings = new ArrayList<String>(strings.size()); for (String s : strings) { shortStrings.add(shorten(s)); } return shortStrings.toString(); } }
package org.zanata.util; /** * ShortStrings are meant for use in logging. They don't incur the cost of * shortening until toString() is called. This means they hold on to the entire * string, so don't bother keeping them around in memory for long. * * @author Sean Flanigan <a * href="mailto:sflaniga@redhat.com">sflaniga@redhat.com</a> * */ public class ShortString { static final int MAX_LENGTH = 66; private static final String ELLIPSIS = "…"; private String input; public ShortString(String input) { this.input = input; } @Override public String toString() { return input = shorten(input); } public static String shorten(String s) { if (s.length() <= MAX_LENGTH) return s; return s.substring(0, MAX_LENGTH - ELLIPSIS.length()) + ELLIPSIS; } }
FIX Exceptions broken if no notifiers specified
<?php class HailApiException extends Exception { /** * A class list of notifiers to use. Must implement HailNotifier * @see HailNotifier * @var array */ private static $notifiers; protected $hailMessage = ''; public function __construct($message = "", $code = 0, Throwable $previous = NULL) { $notifiers = Config::inst()->get('HailApiException', 'notifiers'); if($notifiers) { foreach($notifiers as $notifier) { if(!class_exists($notifier)) { user_error("$notifier class does not exist"); } if(!class_implements('HailNotifier')) { user_error("$notifier must implement HailNotifier"); } $obj = new $notifier(); $obj->sendNotification($message); } } } }
<?php class HailApiException extends Exception { /** * A class list of notifiers to use. Must implement HailNotifier * @see HailNotifier * @var array */ private static $notifiers; protected $hailMessage = ''; public function __construct($message = "", $code = 0, Throwable $previous = NULL) { $notifiers = Config::inst()->get('HailApiException', 'notifiers'); foreach($notifiers as $notifier) { if(!class_exists($notifier)) { user_error("$notifier class does not exist"); } if(!class_implements('HailNotifier')) { user_error("$notifier must implement HailNotifier"); } $obj = new $notifier(); $obj->sendNotification($message); } } }
Add manual experiment that replaces a RGB image with grayscale
import pytest import imghdr from io import BytesIO from PIL import Image import zlib from pikepdf import Pdf, Object def test_jpeg(resources, outdir): pdf = Pdf.open(resources / 'congress.pdf') # If you are looking at this as example code, Im0 is not necessarily the # name of any image. pdfimage = pdf.pages[0].Resources.XObject['/Im0'] raw_bytes = pdfimage.read_raw_bytes() with pytest.raises(RuntimeError): pdfimage.read_bytes() assert imghdr.what('', h=raw_bytes) == 'jpeg' im = Image.open(BytesIO(raw_bytes)) assert im.size == (pdfimage.Width, pdfimage.Height) assert im.mode == 'RGB' def test_replace_jpeg(resources, outdir): pdf = Pdf.open(resources / 'congress.pdf') pdfimage = pdf.pages[0].Resources.XObject['/Im0'] raw_bytes = pdfimage.read_raw_bytes() im = Image.open(BytesIO(raw_bytes)) grayscale = im.convert('L') #newimage = Object.Stream(pdf, grayscale.tobytes()) pdfimage.write(zlib.compress(grayscale.tobytes()), Object.Name("/FlateDecode"), Object.Null()) pdfimage.ColorSpace = Object.Name('/DeviceGray') pdf.save(outdir / 'congress_gray.pdf')
import pytest import imghdr from io import BytesIO from PIL import Image from pikepdf import _qpdf as qpdf def test_jpeg(resources, outdir): pdf = qpdf.Pdf.open(resources / 'congress.pdf') # If you are looking at this as example code, Im0 is not necessarily the # name of any image. pdfimage = pdf.pages[0].Resources.XObject.Im0 raw_stream = pdf.pages[0].Resources.XObject.Im0.read_raw_stream() with pytest.raises(RuntimeError): pdf.pages[0].Resources.XObject.Im0.read_stream() assert imghdr.what('', h=raw_stream) == 'jpeg' im = Image.open(BytesIO(raw_stream)) assert im.size == (pdfimage.Width, pdfimage.Height) assert im.mode == 'RGB'
Add auto increment field to user's table
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { const TABLE = 'users'; /** * Run the migrations. * * @return void */ public function up() { Schema::create(static::TABLE, function (Blueprint $table) { $table->smallIncrements('id'); $table->string('name'); $table ->string('email') ->unique() ; $table->string('password'); $table->rememberToken(); $table->softDeletesTz(); $table->timestampsTz(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(static::TABLE); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { const TABLE = 'users'; /** * Run the migrations. * * @return void */ public function up() { Schema::create(static::TABLE, function (Blueprint $table) { $table->smallInteger('id'); $table->string('name'); $table ->string('email') ->unique() ; $table->string('password'); $table->rememberToken(); $table->softDeletesTz(); $table->timestampsTz(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(static::TABLE); } }
Use `!Array.isArray` since it makes more sense.
'use strict'; const os = require('os'); const debug = require('debug')('asset-resolver'); const resolver = require('./lib/resolver'); function any(promises) { return Promise.all( promises.map(promise => promise.then( val => { throw val; }, reason => reason ) ) ).then( reasons => { throw reasons; }, firstResolved => firstResolved ); } module.exports.getResource = function(file, options = {}) { const opts = { base: [process.cwd()], filter: () => true, ...options }; if (!Array.isArray(opts.base)) { opts.base = [opts.base]; } opts.base = resolver.glob([...opts.base]); const promises = (opts.base || []).map(base => { return resolver.getResource(base, file, opts); }); return any(promises).catch(error => { const msg = [ 'The file "' + file + '" could not be resolved because of:' ].concat(error.map(err => err.message)); debug(msg); return Promise.reject(new Error(msg.join(os.EOL))); }); };
'use strict'; const os = require('os'); const debug = require('debug')('asset-resolver'); const resolver = require('./lib/resolver'); function any(promises) { return Promise.all( promises.map(promise => promise.then( val => { throw val; }, reason => reason ) ) ).then( reasons => { throw reasons; }, firstResolved => firstResolved ); } module.exports.getResource = function(file, options = {}) { const opts = { base: [process.cwd()], filter: () => true, ...options }; if (typeof opts.base === 'string') { opts.base = [opts.base]; } opts.base = resolver.glob([...opts.base]); const promises = (opts.base || []).map(base => { return resolver.getResource(base, file, opts); }); return any(promises).catch(error => { const msg = [ 'The file "' + file + '" could not be resolved because of:' ].concat(error.map(err => err.message)); debug(msg); return Promise.reject(new Error(msg.join(os.EOL))); }); };
Remove `--jedify-lang` command line option
var through = require('through') , falafel = require('falafel') , unparse = require('escodegen').generate , util = require('util') , minimist = require('minimist') var defaultLang = process.env['JEDIFY_LANG'] || 'en' var re = /\.js$/ module.exports = function (file, options) { if (!re.test(file)) return through() options = options || {} var lang = options.lang || defaultLang var buf = [] , stream = through(write, end) return stream function write(chunk) { buf.push(chunk) } function end () { var output = buf.join('') try { output = falafel(output, function (node) { if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'requirePo') { var dir = new Function([], 'return ' + unparse(node.arguments[0]))() dir = util.format(dir, lang) node.update('require(' + JSON.stringify(dir) + ')') } }).toString() } catch (err) { this.emit('error', new Error(err.toString().replace('Error: ', '') + ' (' + file + ')')) } stream.queue(output) stream.queue(null) } }
var through = require('through') , falafel = require('falafel') , unparse = require('escodegen').generate , util = require('util') , minimist = require('minimist') var argv = minimist(process.argv.slice(2)) var defaultLang = argv['jedify-lang'] || process.env['JEDIFY_LANG'] || 'en' var re = /\.js$/ module.exports = function (file, options) { if (!re.test(file)) return through() options = options || {} var lang = options.lang || defaultLang; var buf = [] , stream = through(write, end) return stream function write(chunk) { buf.push(chunk) } function end () { var output = buf.join('') try { output = falafel(output, function (node) { if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'requirePo') { var dir = new Function([], 'return ' + unparse(node.arguments[0]))() dir = util.format(dir, lang) node.update('require(' + JSON.stringify(dir) + ')') } }).toString() } catch (err) { this.emit('error', new Error(err.toString().replace('Error: ', '') + ' (' + file + ')')) } stream.queue(output) stream.queue(null) } }
Call CraftRecipe Register Func on preInit
package jp.crafterkina.pipes.common; import jp.crafterkina.pipes.common.recipe.vanilla.CraftManager; import lombok.Getter; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.InstanceFactory; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import static jp.crafterkina.pipes.common.PipesCore.MOD_ID; @Mod(modid = MOD_ID) public enum PipesCore { INSTANCE; public static final String MOD_ID = "jp.crafterkina.pipes"; @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "jp.crafterkina.pipes.client.ClientProxy", serverSide = "jp.crafterkina.pipes.server.ServerProxy") @Getter private static CommonProxy proxy; @InstanceFactory public static PipesCore getInstance(){ return INSTANCE; } @EventHandler private void preInit(FMLPreInitializationEvent event){ CraftManager.INSTANCE.register(); } }
package jp.crafterkina.pipes.common; import lombok.Getter; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.InstanceFactory; import net.minecraftforge.fml.common.SidedProxy; import static jp.crafterkina.pipes.common.PipesCore.MOD_ID; @Mod(modid = MOD_ID) public enum PipesCore { INSTANCE; public static final String MOD_ID = "jp.crafterkina.pipes"; @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "jp.crafterkina.pipes.client.ClientProxy", serverSide = "jp.crafterkina.pipes.server.ServerProxy") @Getter private static CommonProxy proxy; @InstanceFactory public static PipesCore getInstance(){ return INSTANCE; } }
Move title below db connection to get questionnaire name
<?php class QuestionnairesController extends Controller { function view($token) { $this->Questionnaire = new Database(); $this->Questionnaire->query('SELECT * FROM questionnaires WHERE token = :token'); $this->Questionnaire->bind(':token', $token); $this->Questionnaire->execute(); $questionnaire = $this->Questionnaire->single(); if ($this->Questionnaire->rowCount() == 1) { $this->set('item', $questionnaire); } else { $this->set('error', __('missing-questionnaire')); } $this->Questionnaire->query('SELECT * FROM questions WHERE questionnaire_id = :questionnaire_id'); $this->Questionnaire->bind(':questionnaire_id', $questionnaire['id']); $this->Questionnaire->execute(); if ($this->Questionnaire->rowCount() >= 1) { $this->set('questions', $this->Questionnaire->resultSet()); } else { $this->set('error', __('missing-questions')); } $this->set('title', $questionnaire['name']); } }
<?php class QuestionnairesController extends Controller { function view($token) { $this->set('title','Questionnaire '.$token); $this->Questionnaire = new Database(); $this->Questionnaire->query('SELECT * FROM questionnaires WHERE token = :token'); $this->Questionnaire->bind(':token', $token); $this->Questionnaire->execute(); $questionnaire = $this->Questionnaire->single(); if ($this->Questionnaire->rowCount() == 1) { $this->set('item', $questionnaire); } else { $this->set('error', __('missing-questionnaire')); } $this->Questionnaire->query('SELECT * FROM questions WHERE questionnaire_id = :questionnaire_id'); $this->Questionnaire->bind(':questionnaire_id', $questionnaire['id']); $this->Questionnaire->execute(); if ($this->Questionnaire->rowCount() >= 1) { $this->set('questions', $this->Questionnaire->resultSet()); } else { $this->set('error', __('missing-questions')); } } }
Add empty state container class as utility
package info.u_team.u_team_core.util; import static net.minecraft.client.renderer.model.ModelBakery.STATE_CONTAINER_OVERRIDES; import java.util.*; import com.google.common.collect.*; import net.minecraft.block.*; import net.minecraft.state.StateContainer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.*; @OnlyIn(Dist.CLIENT) public class ModelUtil { static { if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) { final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>(); STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put); STATE_CONTAINER_OVERRIDES = mutableMap; } } public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) { STATE_CONTAINER_OVERRIDES.put(location, container); } public static class EmptyStateContainer extends StateContainer<Block, BlockState> { public EmptyStateContainer(Block block) { super(block, BlockState::new, new HashMap<>()); } @Override public ImmutableList<BlockState> getValidStates() { return getOwner().getStateContainer().getValidStates(); } } }
package info.u_team.u_team_core.util; import static net.minecraft.client.renderer.model.ModelBakery.STATE_CONTAINER_OVERRIDES; import java.util.*; import com.google.common.collect.ImmutableMap; import net.minecraft.block.*; import net.minecraft.state.StateContainer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.*; @OnlyIn(Dist.CLIENT) public class ModelUtil { static { if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) { final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>(); STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put); STATE_CONTAINER_OVERRIDES = mutableMap; } } public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) { STATE_CONTAINER_OVERRIDES.put(location, container); } }
Modify the author email address
#!/usr/bin/env python from distutils.core import setup packages = [ 'upho', 'upho.phonon', 'upho.harmonic', 'upho.analysis', 'upho.structure', 'upho.irreps', 'upho.qpoints', 'group', ] scripts = [ 'scripts/upho_weights', 'scripts/upho_sf', 'scripts/upho_qpoints', 'scripts/upho_fit', ] setup(name='upho', version='0.5.3', author="Yuji Ikeda", author_email="y.ikeda@mpie.de", packages=packages, scripts=scripts, install_requires=['numpy', 'h5py', 'phonopy'])
#!/usr/bin/env python from distutils.core import setup packages = [ 'upho', 'upho.phonon', 'upho.harmonic', 'upho.analysis', 'upho.structure', 'upho.irreps', 'upho.qpoints', 'group', ] scripts = [ 'scripts/upho_weights', 'scripts/upho_sf', 'scripts/upho_qpoints', 'scripts/upho_fit', ] setup(name='upho', version='0.5.3', author="Yuji Ikeda", author_email="ikeda.yuji.6m@kyoto-u.ac.jp", packages=packages, scripts=scripts, install_requires=['numpy', 'h5py', 'phonopy'])
Change maximum nested list level to 1
import { Map } from 'immutable'; import { DefaultDraftBlockRenderMap } from 'draft-js'; import { BLOCK_TYPE } from '../api/constants'; // Maximum level of nesting for unordered and ordered lists. export const MAX_LIST_NESTING = 1; // Frequency at which the save callback is triggered. export const STATE_SAVE_INTERVAL = 250; /** * Options / configuration methods for the editor. */ export default { getBlockRenderMap(BLOCK_TYPES = []) { const renderMap = {}; BLOCK_TYPES.filter(type => type.element) .forEach((type) => { renderMap[type.style] = { element: type.element }; }); return DefaultDraftBlockRenderMap.merge(Map(renderMap)); }, getBlockStyleFn(BLOCK_TYPES = []) { const blockClassNames = {}; BLOCK_TYPES.filter(type => type.className) .forEach((type) => { blockClassNames[type.style] = type.className; }); const blockStyleFn = (block) => { const type = block.getType(); return blockClassNames[type] || undefined; }; return blockStyleFn; }, };
import { Map } from 'immutable'; import { DefaultDraftBlockRenderMap } from 'draft-js'; import { BLOCK_TYPE } from '../api/constants'; // Maximum level of nesting for unordered and ordered lists. export const MAX_LIST_NESTING = 3; // Frequency at which the save callback is triggered. export const STATE_SAVE_INTERVAL = 250; /** * Options / configuration methods for the editor. */ export default { getBlockRenderMap(BLOCK_TYPES = []) { const renderMap = {}; BLOCK_TYPES.filter(type => type.element) .forEach((type) => { renderMap[type.style] = { element: type.element }; }); return DefaultDraftBlockRenderMap.merge(Map(renderMap)); }, getBlockStyleFn(BLOCK_TYPES = []) { const blockClassNames = {}; BLOCK_TYPES.filter(type => type.className) .forEach((type) => { blockClassNames[type.style] = type.className; }); const blockStyleFn = (block) => { const type = block.getType(); return blockClassNames[type] || undefined; }; return blockStyleFn; }, };
Add promise returning on sending
var util = require('util'); var extend = require('extend'); var Promise = require('bluebird'); var nodemailer = require('nodemailer'); var smtpTransport = require('nodemailer-smtp-transport'); var BaseMailer = require('./BaseMailer'); util.inherits(SMTPMailer, BaseMailer); /** * Create new mailer instance for sending via SMTP servers * @constructor */ function SMTPMailer() { BaseMailer.apply(this, arguments); this._setTransporter(nodemailer.createTransport(smtpTransport(this.getConfig().transporter))); } /** * Returns instantiated instance of nodemailer transporter * @returns {*} * @private */ SMTPMailer.prototype._getTransporter = function () { return this._transporter; }; /** * Set new instance of the nodemailer transporter * @param {Object} transporter New transporter instantiated with nodemailer.createTransport() * @returns {SMTPMailer} * @private */ SMTPMailer.prototype._setTransporter = function (transporter) { this._transporter = transporter; return this; }; /** * Send message * @param {Object} _config Configuration object for overriding default config * @returns {Promise} */ SMTPMailer.prototype.send = function (_config) { var config = extend({}, this.getConfig(), _config); return new Promise(function (resolve, reject) { this._getTransporter().sendMail(config, function (error, result) { return error ? reject(error) : resolve(result); }); }.bind(this)); }; module.exports = SMTPMailer;
var util = require('util'); var extend = require('extend'); var nodemailer = require('nodemailer'); var smtpTransport = require('nodemailer-smtp-transport'); var BaseMailer = require('./BaseMailer'); util.inherits(SMTPMailer, BaseMailer); /** * Create new mailer instance for sending via SMTP servers * @constructor */ function SMTPMailer() { BaseMailer.apply(this, arguments); this._setTransporter(nodemailer.createTransport(smtpTransport(this.getConfig().transporter))); } /** * Returns instantiated instance of nodemailer transporter * @returns {*} * @private */ SMTPMailer.prototype._getTransporter = function () { return this._transporter; }; /** * Set new instance of the nodemailer transporter * @param {Object} transporter New transporter instantiated with nodemailer.createTransport() * @returns {SMTPMailer} * @private */ SMTPMailer.prototype._setTransporter = function (transporter) { this._transporter = transporter; return this; }; /** * Send message * @param {Object} _config Configuration object for overriding default config * @returns {SMTPMailer} */ SMTPMailer.prototype.send = function (_config) { var config = extend({}, this.getConfig(), _config); this._getTransporter().sendMail(config); return this; }; module.exports = SMTPMailer;
Add Unit test for Tag Transformer
<?php namespace RCatlin\Blog\Tests\Serializer\Transformer\Entity; use RCatlin\Blog\Entity; use RCatlin\Blog\Serializer\Transformer\Entity\TagTransformer; use RCatlin\Blog\Tests\HasFaker; class TagTransformerTest extends \PHPUnit_Framework_TestCase { use HasFaker; public function testTransform() { $id = $this->getFaker()->randomNumber(); $name = $this->getFaker()->word; $tag = new Entity\Tag($name); $reflection = new \ReflectionObject($tag); $property = $reflection->getProperty('id'); $property->setAccessible(true); $property->setValue($tag, $id); $transformer = new TagTransformer(); $this->assertSame( [ 'id' => $id, 'name' => $name, ], $transformer->transform($tag) ); } }
<?php namespace RCatlin\Blog\Tests\Serializer\Transformer\Entity; use RCatlin\Blog\Entity; use RCatlin\Blog\Serializer\Transformer\Entity\TagTransformer; use RCatlin\Blog\Tests\HasFaker; class TagTransformerTest extends \PHPUnit_Framework_TestCase { use HasFaker; public function testTransform() { $id = $this->getFaker()->randomNumber(); $name = $this->getFaker()->word; $tag = new Entity\Tag($name); $reflection = new \ReflectionObject($tag); $property = $reflection->getProperty('id'); $property->setAccessible(true); $property->setValue($tag, $id); $transformer = new TagTransformer(); $this->assertSame( [ 'id' => $id, 'name' => $name, ], $transformer->transform($tag) ); } }
Fix matching in the filter I got it backwards :/
/** * This filtering plugin will allow matching of module names in either * form of 'Foo::Bar', or 'Foo-Bar'. * * Based on dataTables.filter.phoneNumber.js * * @summary Make Perl module names searchable * @name Perl module * @author Zak B. Elep * * @example * $(document).ready(function() { * $('#example').dataTable({ * columDefs: [ * { type: 'perlModule', target: 1 } * ] * }); * }); */ jQuery.fn.DataTable.ext.type.search.perlModule = function(data) { return !data ? '' : typeof data === 'string' ? data.replace(/::/g, '-') : data; };
/** * This filtering plugin will allow matching of module names in either * form of 'Foo::Bar', or 'Foo-Bar'. * * Based on dataTables.filter.phoneNumber.js * * @summary Make Perl module names searchable * @name Perl module * @author Zak B. Elep * * @example * $(document).ready(function() { * $('#example').dataTable({ * columDefs: [ * { type: 'perlModule', target: 1 } * ] * }); * }); */ jQuery.fn.DataTable.ext.type.search.perlModule = function(data) { return !data ? '' : typeof data === 'string' ? data + data.replace(/[ \-]/g, '::') : data; };
[api] Add options.stdin, clean up options logic.
var prefork = require('../build/Release/prefork').prefork, fs = require('fs'); module.exports = function (options) { options = options || {}; var infd = -1, outfd = -1, errfd = -1, customFds; if (options.stdin && typeof options.stdin === 'string') { infd = fs.openSync(options.stdin, 'r'); } if (options.stdout && typeof options.stdout === 'string') { outfd = fs.openSync(options.stdout, 'a'); } if (options.stderr && typeof options.stderr === 'string') { errfd = fs.openSync(options.stderr, 'a'); } else if (outfd) { errfd = outfd; } if (Array.isArray(options.customFds)) { customFds = options.customFds; } else { customFds = [ infd, outfd, errfd ]; } prefork(customFds); };
var prefork = require('../build/Release/prefork').prefork, fs = require('fs'); module.exports = function (options) { options = options || {}; var outfd, errfd; if (Array.isArray(options.customFds) && options.customFds.length < 3) { options.customFds.unshift(-1); } if (options.stdout && typeof options.stdout === 'string') { outfd = fs.openSync(options.stdout, 'a'); } if (options.stderr && typeof options.stderr === 'string') { errfd = fs.openSync(options.stderr, 'a'); } else if (outfd) { errfd = outfd; } if (outfd && errfd) { options.customFds = [ -1, outfd, errfd ]; } prefork(options); };
Fix result status chiclet links for new-style filter querystrings.
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor 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. # # Case Conductor 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 Case Conductor. If not, see <http://www.gnu.org/licenses/>. from django import template from django.core.urlresolvers import reverse from ..models import TestCycle, TestRun, TestRunIncludedTestCase register = template.Library() @register.filter def results_detail_url(obj): if isinstance(obj, TestCycle): return reverse("results_testruns") + "?filter-testCycle=%s" % obj.id elif isinstance(obj, TestRun): return reverse("results_testcases") + "?filter-testRun=%s" % obj.id elif isinstance(obj, TestRunIncludedTestCase): return reverse("results_testcase_detail", kwargs={"itc_id": obj.id}) return ""
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor 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. # # Case Conductor 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 Case Conductor. If not, see <http://www.gnu.org/licenses/>. from django import template from django.core.urlresolvers import reverse from ..models import TestCycle, TestRun, TestRunIncludedTestCase register = template.Library() @register.filter def results_detail_url(obj): if isinstance(obj, TestCycle): return reverse("results_testruns") + "?testCycle=%s" % obj.id elif isinstance(obj, TestRun): return reverse("results_testcases") + "?testRun=%s" % obj.id elif isinstance(obj, TestRunIncludedTestCase): return reverse("results_testcase_detail", kwargs={"itc_id": obj.id}) return ""
Test is loaded CSS is applied
# -*- coding: utf-8 -*- import unittest from .base import FunctionalTestCase from .pages import game class StylesheetTests(FunctionalTestCase): def test_color_css_loaded(self): self.story('Create a game') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) page.start_button.click() self.assertTrue(any('css/color.css' in s.get_attribute('href') for s in page.stylesheets)) def test_main_stylesheet_loaded(self): self.story('Load the start page') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) self.assertTrue(any('css/main.css' in s.get_attribute('href') for s in page.stylesheets)) # Test constant to see if css actually gets loaded self.assertEqual('rgb(55, 71, 79)', page.bank_cash.value_of_css_property('border-color'))
# -*- coding: utf-8 -*- import unittest from .base import FunctionalTestCase from .pages import game class StylesheetTests(FunctionalTestCase): def test_color_css_loaded(self): self.story('Create a game') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) page.start_button.click() self.assertTrue(any('css/color.css' in s.get_attribute('href') for s in page.stylesheets)) def test_main_stylesheet_loaded(self): self.story('Load the start page') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) self.assertTrue(any('css/main.css' in s.get_attribute('href') for s in page.stylesheets))
Use new landingPage attribute locations
import Ember from 'ember'; export default Ember.Component.extend({ downloadLatency: Ember.computed(function() { var rawLatency = this.get('model').get("landingPage").downloadLatency; return Math.round(rawLatency) }), bodyHasDoi: Ember.computed(function() { if (this.get('model').get("landingPage").bodyHasPid) { return "Yes"; } else { return "No"; } }), hasSchemaOrg: Ember.computed(function() { if (this.get('model').get("landingPage").hasSchemaOrg) { return "Yes"; } else { return "No"; } }), isStatusError: Ember.computed(function() { return this.get('model').get("landingPage").status != 200; }), hasHttpInfo: Ember.computed(function() { if (this.get('model').get("landingPage").status) { return true; } else { return false; } }), hasError: Ember.computed(function() { if (this.get('model').get("landingPage").error) { return true; } else { return false; } }), });
import Ember from 'ember'; export default Ember.Component.extend({ downloadLatency: Ember.computed(function() { var rawLatency = this.get('model').get("landingPage").result['downloadLatency']; return Math.round(rawLatency) }), bodyHasDoi: Ember.computed(function() { if (this.get('model').get("landingPage").result['bodyHasPid']) { return "Yes"; } else { return "No"; } }), hasSchemaOrg: Ember.computed(function() { if (this.get('model').get("landingPage").result['hasSchemaOrg']) { return "Yes"; } else { return "No"; } }), isStatusError: Ember.computed(function() { return this.get('model').get("landingPage").status != 200; }), hasHttpInfo: Ember.computed(function() { if (this.get('model').get("landingPage").status) { return true; } else { return false; } }), hasError: Ember.computed(function() { if (this.get('model').get("landingPage").result.error) { return true; } else { return false; } }), });
Bump tensorflow from 2.5.1 to 2.5.2 Bumps [tensorflow](https://github.com/tensorflow/tensorflow) from 2.5.1 to 2.5.2. - [Release notes](https://github.com/tensorflow/tensorflow/releases) - [Changelog](https://github.com/tensorflow/tensorflow/blob/master/RELEASE.md) - [Commits](https://github.com/tensorflow/tensorflow/compare/v2.5.1...v2.5.2) --- updated-dependencies: - dependency-name: tensorflow dependency-type: direct:production ... Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com>
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name="EQTransformer", author="S. Mostafa Mousavi", version="0.1.61", author_email="smousavi05@gmail.com", description="A python package for making and using attentive deep-learning models for earthquake signal detection and phase picking.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/smousavi05/EQTransformer", license="MIT", packages=find_packages(), keywords='Seismology, Earthquakes Detection, P&S Picking, Deep Learning, Attention Mechanism', install_requires=[ 'pytest', 'numpy==1.20.3', 'keyring>=15.1', 'pkginfo>=1.4.2', 'scipy==1.4.1', 'tensorflow==2.5.2', 'keras==2.3.1', 'matplotlib', 'pandas', 'tqdm==4.48.0', 'h5py==3.1.0', 'obspy', 'jupyter'], python_requires='>=3.6', )
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name="EQTransformer", author="S. Mostafa Mousavi", version="0.1.61", author_email="smousavi05@gmail.com", description="A python package for making and using attentive deep-learning models for earthquake signal detection and phase picking.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/smousavi05/EQTransformer", license="MIT", packages=find_packages(), keywords='Seismology, Earthquakes Detection, P&S Picking, Deep Learning, Attention Mechanism', install_requires=[ 'pytest', 'numpy==1.20.3', 'keyring>=15.1', 'pkginfo>=1.4.2', 'scipy==1.4.1', 'tensorflow==2.5.1', 'keras==2.3.1', 'matplotlib', 'pandas', 'tqdm==4.48.0', 'h5py==3.1.0', 'obspy', 'jupyter'], python_requires='>=3.6', )
Remove GuiBoard for spec where it doesn't belong
var JSChess = require('../js-chess.js'); var _ = require('lodash'); describe('Classic Chess', function() { it('everything', function() { var army1 = new JSChess.Army({ forwardDirection: 'down' }); var army2 = new JSChess.Army({ forwardDirection: 'up' }); var board = new JSChess.Board({ army1: army1, army2: army2 }); var player1 = { name: 'Player 1', army: army1 }; var player2 = { name: 'Player 2', army: army2 }; defendingPiece = new army1.Piece('king')(); board.addPiece({ piece: defendingPiece, location: { row: 0, col: 2 } }); attackingPiece = new army2.Piece('queen')(); board.addPiece({ piece: attackingPiece, location: { row: 7, col: 2 } }); expect(board.pieceUnderAttack({ piece: defendingPiece })).toBe(true); }); });
var JSChess = require('../js-chess.js'); var GuiBoard = require('../lib/gui_board.js'); var _ = require('lodash'); describe('Classic Chess', function() { it('everything', function() { var army1 = new JSChess.Army({ forwardDirection: 'down' }); var army2 = new JSChess.Army({ forwardDirection: 'up' }); var board = new JSChess.Board({ army1: army1, army2: army2 }); var player1 = { name: 'Player 1', army: army1 }; var player2 = { name: 'Player 2', army: army2 }; var guiBoard = new GuiBoard({ board: board, army1: player1.army, army2: player2.army }); defendingPiece = new army1.Piece('king')(); board.addPiece({ piece: defendingPiece, location: { row: 0, col: 2 } }); attackingPiece = new army2.Piece('queen')(); board.addPiece({ piece: attackingPiece, location: { row: 7, col: 2 } }); guiBoard.print(); expect(board.pieceUnderAttack({ piece: defendingPiece })).toBe(true); }); });
Move deprecation under use statements
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Twig\Form; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; @trigger_error(sprintf('The %s class is deprecated since version 3.4 and will be removed in 4.0. Use %s instead.', TwigRenderer::class, FormRenderer::class), E_USER_DEPRECATED); /** * @author Bernhard Schussek <bschussek@gmail.com> * * @deprecated since version 3.4, to be removed in 4.0. Use Symfony\Component\Form\FormRenderer instead. */ class TwigRenderer extends FormRenderer implements TwigRendererInterface { public function __construct(TwigRendererEngineInterface $engine, CsrfTokenManagerInterface $csrfTokenManager = null) { parent::__construct($engine, $csrfTokenManager); } /** * Returns the engine used by this renderer. * * @return TwigRendererEngineInterface The renderer engine */ public function getEngine() { return parent::getEngine(); } /** * {@inheritdoc} */ public function setEnvironment(Environment $environment) { $this->getEngine()->setEnvironment($environment); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Twig\Form; @trigger_error(sprintf('The %s class is deprecated since version 3.4 and will be removed in 4.0. Use %s instead.', TwigRenderer::class, FormRenderer::class), E_USER_DEPRECATED); use Symfony\Component\Form\FormRenderer; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Twig\Environment; /** * @author Bernhard Schussek <bschussek@gmail.com> * * @deprecated since version 3.4, to be removed in 4.0. Use Symfony\Component\Form\FormRenderer instead. */ class TwigRenderer extends FormRenderer implements TwigRendererInterface { public function __construct(TwigRendererEngineInterface $engine, CsrfTokenManagerInterface $csrfTokenManager = null) { parent::__construct($engine, $csrfTokenManager); } /** * Returns the engine used by this renderer. * * @return TwigRendererEngineInterface The renderer engine */ public function getEngine() { return parent::getEngine(); } /** * {@inheritdoc} */ public function setEnvironment(Environment $environment) { $this->getEngine()->setEnvironment($environment); } }
QS-935: Rename compare route to use definitive one as 'compare'
import { fetchAnswers, fetchQuestion, fetchComparedAnswers, postAnswer, postSkipQuestion } from '../utils/APIUtils'; export function getAnswers(url = `answers`){ return fetchAnswers(url); } export function getComparedAnswers(otherUserId, filters, url = `answers/compare/${otherUserId}?locale=es${filters.map(filter => '&'+filter+'=1')}`){ return fetchComparedAnswers(url); } export function getQuestion(questionId, url = `questions/${questionId}?locale=es`){ return fetchQuestion(url); } export function getNextQuestion(url = `questions/next?locale=es`){ return fetchQuestion(url); } export function answerQuestion(questionId, answerId, acceptedAnswers, rating, url = `answers`){ return postAnswer(url, questionId, answerId, acceptedAnswers, rating); } export function skipQuestion(questionId, url = `questions/${questionId}/skip`){ return postSkipQuestion(url); }
import { fetchAnswers, fetchQuestion, fetchComparedAnswers, postAnswer, postSkipQuestion } from '../utils/APIUtils'; export function getAnswers(url = `answers`){ return fetchAnswers(url); } export function getComparedAnswers(otherUserId, filters, url = `answers/compare-new/${otherUserId}?locale=es${filters.map(filter => '&'+filter+'=1')}`){ return fetchComparedAnswers(url); } export function getQuestion(questionId, url = `questions/${questionId}?locale=es`){ return fetchQuestion(url); } export function getNextQuestion(url = `questions/next?locale=es`){ return fetchQuestion(url); } export function answerQuestion(questionId, answerId, acceptedAnswers, rating, url = `answers`){ return postAnswer(url, questionId, answerId, acceptedAnswers, rating); } export function skipQuestion(questionId, url = `questions/${questionId}/skip`){ return postSkipQuestion(url); }
Include sender in message if echo is specified. Needs io object.
var read = require('fs').readFileSync; var client = require('khoros-client'); module.exports = function (io, server) { // Serve client js. if (server) { var clientSource = read(require.resolve('khoros-client/khoros.js'), 'utf-8'); server.on('request', function(req, res) { if (req.url == "/khoros/khoros.js") { res.writeHead(200, {"Content-Type": "text/plain"}); res.end(clientSource); } }); } // Return middleware. return function (socket, next) { socket.onevent = function (packet) { if(packet.type == 2) { var type = packet.data[0]; var data = packet.data[1]; switch(type) { case "khoros.join": console.log("New listener in room: " + data.khoros.room); socket.join(data.khoros.room); break; default: data.khoros.clientID = socket.client.id; if (data.khoros.echo) { // Send to all including sender io.in(data.khoros.room).emit(type, data); } else { // Send to all except sender socket.broadcast.to(data.khoros.room).emit(type, data); } break; } } } return next ? next() : null; } }
var read = require('fs').readFileSync; var client = require('khoros-client'); module.exports = function (server) { // Serve client js. if (server) { var clientSource = read(require.resolve('khoros-client/khoros.js'), 'utf-8'); server.on('request', function(req, res) { if (req.url == "/khoros/khoros.js") { res.writeHead(200, {"Content-Type": "text/plain"}); res.end(clientSource); } }); } // Return middleware. return function (socket, next) { socket.onevent = function (packet) { if(packet.type == 2) { var type = packet.data[0]; var data = packet.data[1]; switch(type) { case "khoros.join": console.log("New listener in room: " + data.khoros.room); socket.join(data.khoros.room); break; default: data.khoros.clientID = socket.client.id; socket.broadcast.to(data.khoros.room).emit(type, data); break; } } } return next ? next() : null; } }
Make slug unique and fix the max_length.
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.generic import GenericForeignKey from django.db import models from django.template.defaultfilters import slugify class Tag(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True, max_length=100) def __unicode__(self): return self.name def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.name) super(Tag, self).save(*args, **kwargs) class TaggedItem(models.Model): object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey() tag = models.ForeignKey(Tag, related_name="items") def __unicode__(self): return "%s tagged with %s" % (self.content_object, self.tag)
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.generic import GenericForeignKey from django.db import models from django.template.defaultfilters import slugify class Tag(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() def __unicode__(self): return self.name def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.name) super(Tag, self).save(*args, **kwargs) class TaggedItem(models.Model): object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey() tag = models.ForeignKey(Tag, related_name="items") def __unicode__(self): return "%s tagged with %s" % (self.content_object, self.tag)
Use process.exit once final callback is called
#!/usr/bin/env node var cdbExport = require('cartodb-export'); var fs = require('fs'); var program = require('commander'); var cartodb2leaflet = require('../index'); program .version('0.0.1') .usage('[options] url') .option('-d, --dir [directory]', 'Specify the output directory [.]', '.') .parse(process.argv); if (!program.args.length) { console.log('Please enter a url'); program.outputHelp(); process.exit(1); } fs.readFile('/dev/stdin', 'utf8', function (error, contents) { console.log(JSON.stringify(cartocss2leaflet(contents))); }); var url = program.args[0]; console.log('Saving visualization in ' + program.dir); cdbExport.exportVis(url, program.dir, function (err) { if (err) { console.error('Error while exporting visualization:', err); return; } console.log('Converting visualization to Leaflet'); cartodb2leaflet.toLeaflet(program.dir, program.dir, function (err) { if (err) { console.error('Error while converting visualization to Leaflet:', err); return; } console.log('Done converting visualization to Leaflet'); process.exit(0); }); });
#!/usr/bin/env node var cdbExport = require('cartodb-export'); var fs = require('fs'); var program = require('commander'); var cartodb2leaflet = require('../index'); program .version('0.0.1') .usage('[options] url') .option('-d, --dir [directory]', 'Specify the output directory [.]', '.') .parse(process.argv); if (!program.args.length) { console.log('Please enter a url'); program.outputHelp(); process.exit(1); } fs.readFile('/dev/stdin', 'utf8', function (error, contents) { console.log(JSON.stringify(cartocss2leaflet(contents))); }); var url = program.args[0]; console.log('Saving visualization in ' + program.dir); cdbExport.exportVis(url, program.dir, function (err) { if (err) { console.error('Error while exporting visualization:', err); return; } console.log('Converting visualization to Leaflet'); cartodb2leaflet.toLeaflet(program.dir, program.dir, function (err) { if (err) { console.error('Error while converting visualization to Leaflet:', err); return; } console.log('Done converting visualization to Leaflet'); }); });
Support negative numbers in qtcreator debugging
from dumper import * def qdump__FixedPoint(d, value): d.putNumChild(3) raw = [ value["v"]["s"][i].integer() for i in range( value["v"]["numWords"].integer() ) ] ss = value["v"]["storageSize"].integer() exp = [raw[i] * 2**(i * ss) for i in range(len(raw)) ] if raw[-1] >= 2**(ss-1): exp += [ -2**(ss * len(raw)) ] d.putValue(sum(exp) * 2**-value["fractionalWidth"].integer()) if d.isExpanded(): with Children(d): d.putSubItem("fractionalWidth", value["fractionalWidth"]) d.putSubItem("integerWidth", value["integerWidth"]) d.putSubItem("v", value["v"]) def qdump__MultiwordInteger(d, value): d.putNumChild(3) raw = [ value["s"][i].integer() for i in range( value["numWords"].integer() ) ] exp = [ raw[i] * 2**(i * value["storageSize"].integer()) for i in range(len(raw)) ] d.putValue(sum(exp)) if d.isExpanded(): with Children(d): d.putSubItem("numWords", value["numWords"]) d.putSubItem("storageSize", value["storageSize"]) d.putSubItem("s", value["s"])
from dumper import * def qdump__FixedPoint(d, value): d.putNumChild(3) raw = [ value["v"]["s"][i].integer() for i in range( value["v"]["numWords"].integer() ) ] ss = value["v"]["storageSize"].integer() exp = [raw[i] * 2**(i * ss) for i in range(len(raw)) ] d.putValue(sum(exp) * 2**-value["fractionalWidth"].integer()) if d.isExpanded(): with Children(d): d.putSubItem("fractionalWidth", value["fractionalWidth"]) d.putSubItem("integerWidth", value["integerWidth"]) d.putSubItem("v", value["v"]) def qdump__MultiwordInteger(d, value): d.putNumChild(3) raw = [ value["s"][i].integer() for i in range( value["numWords"].integer() ) ] exp = [ raw[i] * 2**(i * value["storageSize"].integer()) for i in range(len(raw)) ] d.putValue(sum(exp)) if d.isExpanded(): with Children(d): d.putSubItem("numWords", value["numWords"]) d.putSubItem("storageSize", value["storageSize"]) d.putSubItem("s", value["s"])
Swap to using submission prediction writer function
#!/usr/bin/env python import neukrill_net.utils as utils import neukrill_net.image_processing as image_processing import csv import pickle from sklearn.externals import joblib import numpy as np import glob import os def main(): settings = utils.Settings('settings.json') image_fname_dict = settings.image_fnames processing = lambda image: image_processing.resize_image(image, (48,48)) X, names = utils.load_data(image_fname_dict, processing=processing, verbose=True) clf = joblib.load('model.pkl') p = clf.predict_proba(X) utils.write_predictions('submission.csv', p, names, settings) if __name__ == '__main__': main()
#!/usr/bin/env python import neukrill_net.utils as utils import neukrill_net.image_processing as image_processing import csv import pickle from sklearn.externals import joblib import numpy as np import glob import os def main(): settings = utils.Settings('settings.json') image_fname_dict = settings.image_fnames processing = lambda image: image_processing.resize_image(image, (48,48)) X, names = utils.load_data(image_fname_dict, processing=processing, verbose=True) clf = joblib.load('model.pkl') p = clf.predict_proba(X) with open('submission.csv', 'w') as csv_out: out_writer = csv.writer(csv_out, delimiter=',') out_writer.writerow(['image'] + list(settings.classes)) for index in range(len(names)): out_writer.writerow([names[index]] + list(p[index,])) if __name__ == '__main__': main()
Revert "Remove name from organisation"
"""empty message Revision ID: 0093_data_gov_uk Revises: 0092_add_inbound_provider Create Date: 2017-06-05 16:15:17.744908 """ # revision identifiers, used by Alembic. revision = '0093_data_gov_uk' down_revision = '0092_add_inbound_provider' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc' def upgrade(): op.execute("""INSERT INTO organisation VALUES ( '{}', '', 'data_gov_uk_x2.png', '' )""".format(DATA_GOV_UK_ID)) def downgrade(): op.execute(""" DELETE FROM organisation WHERE "id" = '{}' """.format(DATA_GOV_UK_ID))
"""empty message Revision ID: 0093_data_gov_uk Revises: 0092_add_inbound_provider Create Date: 2017-06-05 16:15:17.744908 """ # revision identifiers, used by Alembic. revision = '0093_data_gov_uk' down_revision = '0092_add_inbound_provider' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc' def upgrade(): op.execute("""INSERT INTO organisation VALUES ( '{}', '', '', '' )""".format(DATA_GOV_UK_ID)) def downgrade(): op.execute(""" DELETE FROM organisation WHERE "id" = '{}' """.format(DATA_GOV_UK_ID))
Fix unchecked function call in thread datawriter
<?php class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread { protected function _getFields() { $fields = parent::_getFields(); $fields['xf_thread']['word_count'] = array( 'type' => self::TYPE_UNKNOWN, 'verification' => array('$this', '_verifyWordCount') ); return $fields; } public function rebuildDiscussionCounters($replyCount = false, $firstPostId = false, $lastPostId = false) { parent::rebuildDiscussionCounters($replyCount, $firstPostId, $lastPostId); if (SV_Utils_AddOn::addOnIsActive('sidaneThreadmarks', 1030002)) { $wordCount = $this->_getThreadModel()->countThreadmarkWordsInThread($this->get('thread_id')); $this->set('word_count', $wordCount); } } protected function _verifyWordCount($wordCount) { if (is_int($wordCount) || is_null($wordCount)) { return true; } return false; } }
<?php class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread { protected function _getFields() { $fields = parent::_getFields(); $fields['xf_thread']['word_count'] = array( 'type' => self::TYPE_UNKNOWN, 'verification' => array('$this', '_verifyWordCount') ); return $fields; } public function rebuildDiscussionCounters($replyCount = false, $firstPostId = false, $lastPostId = false) { parent::rebuildDiscussionCounters($replyCount, $firstPostId, $lastPostId); $wordCount = $this->_getThreadModel()->countThreadmarkWordsInThread($this->get('thread_id')); $this->set('word_count', $wordCount); } protected function _verifyWordCount($wordCount) { if (is_int($wordCount) || is_null($wordCount)) { return true; } return false; } }
Add missing serial version ID (default). git-svn-id: fb13a56e2874bbe7f090676f40e1dce4dcf67111@1572570 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.archivers; /** * Exception thrown by ArchiveStreamFactory if a format is * requested/detected that doesn't support streaming. * @since 1.8 */ public class StreamingNotSupportedException extends ArchiveException { private static final long serialVersionUID = 1L; private final String format; /** * Creates a new StreamingNotSupportedException. * @param format the format that has been requested/detected. */ public StreamingNotSupportedException(String format) { super("The " + format + " doesn't support streaming."); this.format = format; } /** * Returns the format that has been requested/detected. * @return the format that has been requested/detected. */ public String getFormat() { return format; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.archivers; /** * Exception thrown by ArchiveStreamFactory if a format is * requested/detected that doesn't support streaming. * @since 1.8 */ public class StreamingNotSupportedException extends ArchiveException { private final String format; /** * Creates a new StreamingNotSupportedException. * @param format the format that has been requested/detected. */ public StreamingNotSupportedException(String format) { super("The " + format + " doesn't support streaming."); this.format = format; } /** * Returns the format that has been requested/detected. * @return the format that has been requested/detected. */ public String getFormat() { return format; } }
Revert "[MOD] Comment unused class" This reverts commit b952175697c59a959ab694f04ef6e40924c6b2e4.
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. /* $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader); $loader->unregister(); $apcLoader->register(true); */ require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php //use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. /* $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader); $loader->unregister(); $apcLoader->register(true); */ require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Clean up modal when it goes away
/* Scat functionality */ "use strict"; class ScatUtils { htmlToElement (html) { let template= document.createElement('template'); template.innerHTML= html.trim(); return template.content.firstChild; } // Pop up a dialog dialog (from, name, data= {}) { let url= name; if (from.disabled) return false from.disabled= true fetch(url) .then(res => { if (!res.ok) { throw new Error('Network response was not ok.'); } res.text().then(text => { console.log("Loaded '" + url + "'."); let modal = this.htmlToElement(text); document.body.insertAdjacentElement('beforeend', modal); $(modal).modal(); $(modal).on('hidden.bs.modal', function(e) { $(this).remove(); }); from.disabled= false; }); }) .catch (error => { console.log('There has been a problem with your fetch operation: ', error.message); }); } } let scat= new ScatUtils();
/* Scat functionality */ "use strict"; class ScatUtils { htmlToElement (html) { let template= document.createElement('template'); template.innerHTML= html.trim(); return template.content.firstChild; } // Pop up a dialog dialog (from, name, data= {}) { let url= name; if (from.disabled) return false from.disabled= true fetch(url) .then(res => { if (!res.ok) { throw new Error('Network response was not ok.'); } res.text().then(text => { console.log("Loaded '" + url + "'."); let modal = this.htmlToElement(text); document.body.insertAdjacentElement('beforeend', modal); $(modal).modal(); from.disabled= false; }); }) .catch (error => { console.log('There has been a problem with your fetch operation: ', error.message); }); } } let scat= new ScatUtils();
Improve regex to detect commands by allowing multiple sections separated with a dash.
<?php namespace WP_CLI; /** * Class AutoloadSplitter. * * This class is used to provide the splitting logic to the * `wp-cli/autoload-splitter` Composer plugin. * * @package WP_CLI */ class AutoloadSplitter { /** * Check whether the current class should be split out into a separate * autoloader. * * Note: `class` in this context refers to all PHP autoloadable elements: * - classes * - interfaces * - traits * * @param string $class Fully qualified name of the current class. * @param string $code Path to the code file that declares the class. * * @return bool Whether to split out the class into a separate autoloader. */ public function __invoke( $class, $code ) { return 1 === preg_match( '/.*\/wp-cli\/\w*(?:-\w*)*-command\/.*/', $code ) || 1 === preg_match( '/.*\/php\/commands\/src\/.*/', $code ); } }
<?php namespace WP_CLI; /** * Class AutoloadSplitter. * * This class is used to provide the splitting logic to the * `wp-cli/autoload-splitter` Composer plugin. * * @package WP_CLI */ class AutoloadSplitter { /** * Check whether the current class should be split out into a separate * autoloader. * * Note: `class` in this context refers to all PHP autoloadable elements: * - classes * - interfaces * - traits * * @param string $class Fully qualified name of the current class. * @param string $code Path to the code file that declares the class. * * @return bool Whether to split out the class into a separate autoloader. */ public function __invoke( $class, $code ) { return 1 === preg_match( '/.*\/wp-cli\/\w*-command\/.*/', $code ) || 1 === preg_match( '/.*\/php\/commands\/src\/.*/', $code ); } }
Resolve method error as a standard GraphQL error
class DDPNetworkInterface { constructor({ connection, noRetry = true, method = '/graphql' } = {} ) { this.connection = connection; this.noRetry = noRetry; this.method = method; } query(request) { return new Promise((resolve, reject) => { this.connection.apply(this.method, [request], { noRetry: this.noRetry }, (error, data) => { if (error) { resolve({ errors: [error] }); } else { resolve(data); } }); }); } } export { DDPNetworkInterface };
class DDPNetworkInterface { constructor({ connection, noRetry = true, method = '/graphql' } = {} ) { this.connection = connection; this.noRetry = noRetry; this.method = method; } query(request) { return new Promise((resolve, reject) => { this.connection.apply(this.method, [request], { noRetry: this.noRetry }, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } } export { DDPNetworkInterface };
Add nullable to assist imports
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class FkPageGroups extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('page_groups', function (Blueprint $table) { $table->integer('page_contents_id') ->unsigned() ->nullable(); $table->foreign('page_contents_id') ->references('id') ->on('page_contents') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('page_contents', function (Blueprint $table) { $table->dropForeign('page_contents_id'); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class FkPageGroups extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('page_groups', function (Blueprint $table) { $table->integer('page_contents_id') ->unsigned(); $table->foreign('page_contents_id') ->references('id') ->on('page_contents') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('page_contents', function (Blueprint $table) { $table->dropForeign('page_contents_id'); }); } }
BE: Add Jinja filter to convert URL params to dict
# -*- coding: utf-8 -*- "Jinja custom filters" import re from urlparse import urlparse, parse_qs from cla_public.apps.base import base from babel.dates import format_datetime @base.app_template_filter() def datetime(dt, format='medium', locale='en_GB'): if format == 'full': format = "EEEE, d MMMM y 'at' HH:mm" elif format == 'medium': format = "EE, dd/MM/y 'at' h:mma" elif format == 'short': format = "dd/MM/y, h:mma" return format_datetime(dt, format, locale=locale) @base.app_template_filter() def url_to_human(value): return re.sub(r'(^https?://)|(/$)', '', value) @base.app_template_filter() def human_to_url(value): return re.sub(r'^((?!https?://).*)', r'http://\1', value) @base.app_template_filter() def query_to_dict(value, prop=None): result = parse_qs(urlparse(value).query) if prop: result = result[prop] return result
# -*- coding: utf-8 -*- "Jinja custom filters" import re from cla_public.apps.base import base from babel.dates import format_datetime @base.app_template_filter() def datetime(dt, format='medium', locale='en_GB'): if format == 'full': format = "EEEE, d MMMM y 'at' HH:mm" elif format == 'medium': format = "EE, dd/MM/y 'at' h:mma" elif format == 'short': format = "dd/MM/y, h:mma" return format_datetime(dt, format, locale=locale) @base.app_template_filter() def url_to_human(value): return re.sub(r'(^https?://)|(/$)', '', value) @base.app_template_filter() def human_to_url(value): return re.sub(r'^((?!https?://).*)', r'http://\1', value) @base.app_template_filter() def query_to_dict(value, prop=None): result = parse_qs(urlparse(value).query) if prop: result = result[prop] return result
Add check for wifi details
var wifiManager = require('../../lib/WifiManager'); var hb = require('handlebars'); var fs = require('fs'); const path = require('path'); var subApp = function(){ this.staticFolder = "assets"; this.setup = function(router, express){ router.get('/', function(req, res) { fs.readFile(path.join(__dirname, './index.html'), 'utf-8', function(error, source){ var template = hb.compile(source); res.send(template()) }); }); router.get('/accesspoints', function(req, res) { wifiManager.listAccessPoints(function(err, list){ res.json({accesspoints: list}); }); }); router.get('/status', function(req, res) { wifiManager.getStatus(function(err, status){ if(!err){ res.json(status); }else{ res.sendStatus(500); } }); }); router.post('/configure', function(req, res) { if(req.body && req.body.ssid && req.body.password){ wifiManager.joinAccessPoint(req.body.ssid, req.body.password); res.sendStatus(200); }else{ res.sendStatus(500); } }); } return this; } module.exports = subApp();
var wifiManager = require('../../lib/WifiManager'); var hb = require('handlebars'); var fs = require('fs'); const path = require('path'); var subApp = function(){ this.staticFolder = "assets"; this.setup = function(router, express){ router.get('/', function(req, res) { fs.readFile(path.join(__dirname, './index.html'), 'utf-8', function(error, source){ var template = hb.compile(source); res.send(template()) }); }); router.get('/accesspoints', function(req, res) { wifiManager.listAccessPoints(function(err, list){ res.json({accesspoints: list}); }); }); router.get('/status', function(req, res) { wifiManager.getStatus(function(err, status){ if(!err){ res.json(status); }else{ res.sendStatus(500); } }); }); router.post('/configure', function(req, res) { wifiManager.joinAccessPoint(req.body.ssid, req.body.password); res.sendStatus(200); }); } return this; } module.exports = subApp();
Clean out old validation stuff from Signup
var async = require( 'async' ); var Data = require( './data' ); var Output = require( './output' ); var utils = require( '../utils' ); exports.userSignup = function ( req, res ) { async.waterfall( [ function ( callback ) { req.checkBody( 'email', "Must be an email address" ).isEmail(); req.checkBody( 'password', "Field is required" ).notEmpty(); var errors = req.validationErrors(); if ( errors ) { return callback( errors ); } return callback( null, req.body ); }, function ( requestBody, callback ) { Data.createUser( req.body.email, req.body.password, callback ); }, function ( newUserData, callback ) { Output.forSignup( newUserData, callback ); } ], function ( err, outputData ) { if ( err ) { return utils.handleRouteError( err, res ); } return res.json( outputData, 201 ); } ); };
var async = require( 'async' ); var Validation = require( './validation' ); var Data = require( './data' ); var Output = require( './output' ); var utils = require( '../utils' ); var validationError = require( '../utils/error_messages' ).validationError; exports.userSignup = function ( req, res ) { async.waterfall( [ function ( callback ) { req.checkBody( 'email', "Must be an email address" ).isEmail(); req.checkBody( 'password', "Field is required" ).notEmpty(); var errors = req.validationErrors(); if ( errors ) { return callback( errors ); } return callback( null, req.body ); }, function ( requestBody, callback ) { Data.createUser( req.body.email, req.body.password, callback ); }, function ( newUserData, callback ) { Output.forSignup( newUserData, callback ); } ], function ( err, outputData ) { if ( err ) { return utils.handleRouteError( err, res ); } return res.json( outputData, 201 ); } ); };
Use \x00 instead of \u0000 for null character
#!/usr/bin/env node 'use strict'; function exec (command) { return require('child_process').execSync(command).toString(); } function luckyCommit (desiredString) { if (!/^[0-9a-f]{1,40}$/.test(desiredString)) { throw new TypeError('Invalid input provided. (If an input is provided, it must be a hex string.)'); } const lastCommit = exec('git cat-file commit head'); const previousDate = exec('git --no-pager show -s --oneline --format="%cd" head'); const previousMessage = exec('git --no-pager show -s --oneline --format="%B" head').slice(0, -2); let currentStr = lastCommit; let counter = 0; let whitespace = ''; do { whitespace = (++counter).toString(2).replace(/0/g, ' ').replace(/1/g, '\t'); const strWithNewMessage = lastCommit.slice(0, -1) + whitespace + '\n'; currentStr = 'commit ' + strWithNewMessage.length + '\x00' + strWithNewMessage; } while (!require('crypto').createHash('sha1').update(currentStr).digest('hex').startsWith(desiredString)) exec('GIT_COMMITTER_DATE="' + previousDate + '" git commit --amend --cleanup=verbatim -m \'' + previousMessage.replace(/'/g, "'\"'\"'") + whitespace + "'"); } luckyCommit(process.argv[2] || '0000000');
#!/usr/bin/env node 'use strict'; function exec (command) { return require('child_process').execSync(command).toString(); } function luckyCommit (desiredString) { if (!/^[0-9a-f]{1,40}$/.test(desiredString)) { throw new TypeError('Invalid input provided. (If an input is provided, it must be a hex string.)'); } const lastCommit = exec('git cat-file commit head'); const previousDate = exec('git --no-pager show -s --oneline --format="%cd" head'); const previousMessage = exec('git --no-pager show -s --oneline --format="%B" head').slice(0, -2); let currentStr = lastCommit; let counter = 0; let whitespace = ''; do { whitespace = (++counter).toString(2).replace(/0/g, ' ').replace(/1/g, '\t'); const strWithNewMessage = lastCommit.slice(0, -1) + whitespace + '\n'; currentStr = 'commit ' + strWithNewMessage.length + '\u0000' + strWithNewMessage; } while (!require('crypto').createHash('sha1').update(currentStr).digest('hex').startsWith(desiredString)) exec('GIT_COMMITTER_DATE="' + previousDate + '" git commit --amend --cleanup=verbatim -m \'' + previousMessage.replace(/'/g, "'\"'\"'") + whitespace + "'"); } luckyCommit(process.argv[2] || '0000000');
Add description to selectiongrid items
from wagtail.core import blocks from wagtail.core.blocks import RichTextBlock from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock from falmer.content.models.core import Page class GridItem(blocks.StructBlock): title = blocks.CharBlock(required=True) link = blocks.URLBlock() image = FalmerImageChooserBlock() description = RichTextBlock(required=False) class Meta: icon = 'item' class SelectionGridPage(Page): body = StreamField([ ('heading_hero', HeroImageBlock()), ('selection_grid', blocks.ListBlock(GridItem)), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='Promote'), ObjectList(Page.settings_panels, heading='Settings', classname="settings"), ]) type_fields = ( 'body', )
from wagtail.core import blocks from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock from falmer.content.models.core import Page class GridItem(blocks.StructBlock): title = blocks.CharBlock(required=True) link = blocks.URLBlock() image = FalmerImageChooserBlock() class Meta: icon = 'item' class SelectionGridPage(Page): parent_page_types = [] body = StreamField([ ('heading_hero', HeroImageBlock()), ('selection_grid', blocks.ListBlock(GridItem)), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='Promote'), ObjectList(Page.settings_panels, heading='Settings', classname="settings"), ]) type_fields = ( 'body', )
Use test helpers in FieldsHaveDescriptions tests
import { FieldsHaveDescriptions } from '../../src/rules/fields_have_descriptions'; import { expectFailsRule } from '../assertions'; describe('FieldsHaveDescriptions rule', () => { it('catches fields that have no description', () => { expectFailsRule( FieldsHaveDescriptions, ` type QueryRoot { withoutDescription: String withoutDescriptionAgain: String! # Description withDescription: String } schema { query: QueryRoot } `, [ { message: 'The field `QueryRoot.withoutDescription` is missing a description.', locations: [{ line: 3, column: 9 }], }, { message: 'The field `QueryRoot.withoutDescriptionAgain` is missing a description.', locations: [{ line: 4, column: 9 }], }, ] ); }); });
import assert from 'assert'; import { parse } from 'graphql'; import { validate } from 'graphql/validation'; import { buildASTSchema } from 'graphql/utilities/buildASTSchema'; import { FieldsHaveDescriptions } from '../../src/rules/fields_have_descriptions'; describe('FieldsHaveDescriptions rule', () => { it('catches fields that have no description', () => { const ast = parse(` type QueryRoot { withoutDescription: String withoutDescriptionAgain: String! # Description withDescription: String } schema { query: QueryRoot } `); const schema = buildASTSchema(ast); const errors = validate(schema, ast, [FieldsHaveDescriptions]); assert.equal(errors.length, 2); assert.equal(errors[0].ruleName, 'fields-have-descriptions'); assert.equal( errors[0].message, 'The field `QueryRoot.withoutDescription` is missing a description.' ); assert.deepEqual(errors[0].locations, [{ line: 3, column: 9 }]); assert.equal(errors[1].ruleName, 'fields-have-descriptions'); assert.equal( errors[1].message, 'The field `QueryRoot.withoutDescriptionAgain` is missing a description.' ); assert.deepEqual(errors[1].locations, [{ line: 4, column: 9 }]); }); });
Fix 'kilo' arg was missing'
(function( angular ) { 'use strict'; angular.module('angular-humanize', []). filter('humanizeFilesize', function () { return function ( input, kilo, decimals, decPoint, thousandsSep ) { if ( isNaN(parseInt(input)) ) { return input; } return humanize.filesize(parseInt(input, kilo || undefined, decimals || undefined, decPoint || undefined, thousandsSep || undefined)); }; }). filter('humanizeOrdinal', function () { return function ( input ) { if ( parseInt(input) !== input ) { return input; } return humanize.ordinal(input); }; }). filter('humanizeNaturalDay', function () { return function ( input ) { if ( parseInt(input) !== input ) { return input; } return humanize.naturalDay(input); }; }). filter('humanizeRelativeTime', function () { return function ( input ) { if ( parseInt(input) !== input ) { return input; } return humanize.relativeTime(input); }; }); }( angular ));
(function( angular ) { 'use strict'; angular.module('angular-humanize', []). filter('humanizeFilesize', function () { return function ( input, decimals, decPoint, thousandsSep ) { if ( isNaN(parseInt(input)) ) { return input; } return humanize.filesize(parseInt(input, decimals || 2, decPoint || '.', thousandsSep || ',')); }; }). filter('humanizeOrdinal', function () { return function ( input ) { if ( parseInt(input) !== input ) { return input; } return humanize.ordinal(input); }; }). filter('humanizeNaturalDay', function () { return function ( input ) { if ( parseInt(input) !== input ) { return input; } return humanize.naturalDay(input); }; }). filter('humanizeRelativeTime', function () { return function ( input ) { if ( parseInt(input) !== input ) { return input; } return humanize.relativeTime(input); }; }); }( angular ));
Add &nbsp; to header values to force a value
<?php $subject = $this->email->getHeaderValue('Subject', '<Empty Subject>'); $this->title($subject); ?> <h1 class="heading"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Outgoing emails - listing</a> &gt; <span class="sub"><?= $this->escape()->html($subject);?></span> </h1> <div class="email-headers"> <dl> <?php foreach ($this->email->getHeaders() as $header) { echo "<dt>", $this->escape()->html($header->getName()), "</dt>\r\n"; echo "<dd>&nbsp;", $this->escape()->html($header->getValue()), "</dd>\r\n"; } ?> </dl> <div class="back"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Back to email list</a> </div> </div> <p class="email-body"> <?php $html = $this->email->getHtmlContent(); if ($html !== null) { echo preg_replace('/.*?<body>(.*?)<\/body>.*?/ims', '$1', $html); } else { echo nl2br($this->escape()->html($this->email->getTextContent())); } ?> </p>
<?php $subject = $this->email->getHeaderValue('Subject', '<Empty Subject>'); $this->title($subject); ?> <h1 class="heading"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Outgoing emails - listing</a> &gt; <span class="sub"><?= $this->escape()->html($subject);?></span> </h1> <div class="email-headers"> <dl> <?php foreach ($this->email->getHeaders() as $header) { echo "<dt>", $this->escape()->html($header->getName()), "</dt>\r\n"; echo "<dd>", $this->escape()->html($header->getValue()), "</dd>\r\n"; } ?> </dl> <div class="back"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Back to email list</a> </div> </div> <p class="email-body"> <?php $html = $this->email->getHtmlContent(); if ($html !== null) { echo preg_replace('/.*?<body>(.*?)<\/body>.*?/ims', '$1', $html); } else { echo nl2br($this->escape()->html($this->email->getTextContent())); } ?> </p>
Fix a bug which causes that JPEG lossless images cannot be decompressed in Safari
"use strict"; (function (cornerstoneWADOImageLoader) { function decodeJPEGLossless(imageFrame, pixelData) { // check to make sure codec is loaded if(typeof jpeg === 'undefined' || typeof jpeg.lossless === 'undefined' || typeof jpeg.lossless.Decoder === 'undefined') { throw 'No JPEG Lossless decoder loaded'; } var byteOutput = imageFrame.bitsAllocated <= 8 ? 1 : 2; //console.time('jpeglossless'); var buffer = pixelData.buffer; var decoder = new jpeg.lossless.Decoder(); var decompressedData = decoder.decode(buffer, pixelData.byteOffset, pixelData.length, byteOutput); //console.timeEnd('jpeglossless'); if (imageFrame.pixelRepresentation === 0) { if (imageFrame.bitsAllocated === 16) { imageFrame.pixelData = new Uint16Array(decompressedData.buffer); return imageFrame; } else { // untested! imageFrame.pixelData = new Uint8Array(decompressedData.buffer); return imageFrame; } } else { imageFrame.pixelData = new Int16Array(decompressedData.buffer); return imageFrame; } } // module exports cornerstoneWADOImageLoader.decodeJPEGLossless = decodeJPEGLossless; }(cornerstoneWADOImageLoader));
"use strict"; (function (cornerstoneWADOImageLoader) { function decodeJPEGLossless(imageFrame, pixelData) { // check to make sure codec is loaded if(typeof jpeg === 'undefined' || typeof jpeg.lossless === 'undefined' || typeof jpeg.lossless.Decoder === 'undefined') { throw 'No JPEG Lossless decoder loaded'; } var byteOutput = imageFrame.bitsAllocated <= 8 ? 1 : 2; //console.time('jpeglossless'); var buffer = pixelData.buffer; var decoder = new jpeg.lossless.Decoder(); var decompressedData = decoder.decode(buffer, buffer.byteOffset, buffer.length, byteOutput); //console.timeEnd('jpeglossless'); if (imageFrame.pixelRepresentation === 0) { if (imageFrame.bitsAllocated === 16) { imageFrame.pixelData = new Uint16Array(decompressedData.buffer); return imageFrame; } else { // untested! imageFrame.pixelData = new Uint8Array(decompressedData.buffer); return imageFrame; } } else { imageFrame.pixelData = new Int16Array(decompressedData.buffer); return imageFrame; } } // module exports cornerstoneWADOImageLoader.decodeJPEGLossless = decodeJPEGLossless; }(cornerstoneWADOImageLoader));
Stop GA from sending extra requests
(function(){ var html = document.getElementsByTagName('html')[0]; var analytics_id = html.getAttribute('data-analytics-id'); var analytics_domain = html.getAttribute('data-analytics-domain'); var ngApp = html.getAttribute('ng-app'); if (analytics_id && analytics_domain) { (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', analytics_id, analytics_domain); ga('set', 'displayFeaturesTask', null); // non ng tracking if (!ngApp) { ga('send', 'pageview'); } } })();
(function(){ var html = document.getElementsByTagName('html')[0]; var analytics_id = html.getAttribute('data-analytics-id'); var analytics_domain = html.getAttribute('data-analytics-domain'); var ngApp = html.getAttribute('ng-app'); if (analytics_id && analytics_domain) { (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', analytics_id, analytics_domain); // non ng tracking if (!ngApp) { ga('send', 'pageview'); } } })();
Set DISABLE_EXTRACT_CSS in correct place
const genDefaultConfig = require('@storybook/vue/dist/server/config/defaults/webpack.config.js') const merge = require('webpack-merge') module.exports = (baseConfig, env) => { /* when building with storybook we do not want to extract css as we normally do in production */ process.env.DISABLE_EXTRACT_CSS = true const storybookConfig = genDefaultConfig(baseConfig, env) const quasarConfig = require('../build/webpack.dev.conf.js') const quasarBasePlugins = require('../build/webpack.base.conf.js').plugins // use Quasar config as default let mergedConfig = merge(quasarConfig, storybookConfig) // set Storybook entrypoint mergedConfig.entry = storybookConfig.entry // allow relative module resolution as used in Storybook mergedConfig.resolve.modules = storybookConfig.resolve.modules // only use Quasars loaders mergedConfig.module.rules = quasarConfig.module.rules // enable Storybook http server mergedConfig.plugins = storybookConfig.plugins // get Quasar's DefinePlugin and PostCSS settings mergedConfig.plugins.unshift(quasarBasePlugins[0], quasarBasePlugins[1]) return mergedConfig }
const genDefaultConfig = require('@storybook/vue/dist/server/config/defaults/webpack.config.js') const merge = require('webpack-merge') module.exports = (baseConfig, env) => { const storybookConfig = genDefaultConfig(baseConfig, env) const quasarConfig = require('../build/webpack.dev.conf.js') /* when building with storybook we do not want to extract css as we normally do in production */ process.env.DISABLE_EXTRACT_CSS = true const quasarBasePlugins = require('../build/webpack.base.conf.js').plugins // use Quasar config as default let mergedConfig = merge(quasarConfig, storybookConfig) // set Storybook entrypoint mergedConfig.entry = storybookConfig.entry // allow relative module resolution as used in Storybook mergedConfig.resolve.modules = storybookConfig.resolve.modules // only use Quasars loaders mergedConfig.module.rules = quasarConfig.module.rules // enable Storybook http server mergedConfig.plugins = storybookConfig.plugins // get Quasar's DefinePlugin and PostCSS settings mergedConfig.plugins.unshift(quasarBasePlugins[0], quasarBasePlugins[1]) return mergedConfig }
Change default name of User class to 'Nameless User'
/* jshint node:true */ var _ = require('underscore'); var uuid = require('node-uuid'); module.exports = (function() { function User(socketArg) { this.id = uuid.v4(); this._socket = socketArg; this.name = 'Nameless User'; } User.prototype = { message: function(name, arg) { this._socket.emit('message-' + name, arg); }, _serverMessage: function(name, arg) { this._socket.emit('cloak-' + name, arg); }, leaveRoom: function() { if (this.room !== undefined) { this.room.removeMember(this); } }, enterRoom: function(room) { room.addMember(this); }, getRoom: function() { return this.room; }, connected: function() { return this.disconnectedSince === null; }, _userData: function() { return { id: this.id, name: this.name }; } }; return User; })();
/* jshint node:true */ var _ = require('underscore'); var uuid = require('node-uuid'); module.exports = (function() { function User(socketArg) { this.id = uuid.v4(); this._socket = socketArg; this.name = 'Nameless Room'; } User.prototype = { message: function(name, arg) { this._socket.emit('message-' + name, arg); }, _serverMessage: function(name, arg) { this._socket.emit('cloak-' + name, arg); }, leaveRoom: function() { if (this.room !== undefined) { this.room.removeMember(this); } }, enterRoom: function(room) { room.addMember(this); }, getRoom: function() { return this.room; }, connected: function() { return this.disconnectedSince === null; }, _userData: function() { return { id: this.id, name: this.name }; } }; return User; })();
Allow overriding properties on the command line.
package org.sourceforge.uptodater; import java.util.*; public class ConfigData { private static final String DEFAULT_CONFIGURATION_NAME = "uptodater"; protected Map<String,String> configuration = new HashMap<String,String>(); public ConfigData() { addOverrideConfiguration(DEFAULT_CONFIGURATION_NAME); } public void addOverrideConfiguration(String configurationName) { try { ResourceBundle res = ResourceBundle.getBundle(configurationName); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); configuration.put(key, res.getString(key)); } } catch (MissingResourceException e) { //gulp } } public String get(final String propertyName, final String defaultValue) { String key = propertyName.trim(); if(System.getProperties().containsKey(propertyName)) { return System.getProperty(propertyName); } else if(configuration.containsKey(key)) { return configuration.get(key); } else { return defaultValue; } } }
package org.sourceforge.uptodater; import java.util.*; public class ConfigData { private static final String DEFAULT_CONFIGURATION_NAME = "uptodater"; protected Map<String,String> configuration = new HashMap<String,String>(); public ConfigData() { addOverrideConfiguration(DEFAULT_CONFIGURATION_NAME); } public void addOverrideConfiguration(String configurationName) { try { ResourceBundle res = ResourceBundle.getBundle(configurationName); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); configuration.put(key, res.getString(key)); } } catch (MissingResourceException e) { //gulp } } public String get(final String propertyName, final String defaultValue) { String key = propertyName.trim(); if(configuration.containsKey(key)) { return configuration.get(key); } else { return defaultValue; } } }
Add columns to polls table
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePollsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('polls', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('title'); $table->text('desc'); $table->timestamp('start')->nullable(); $table->timestamp('end')->nullable(); $table->string('status')->default('active'); $table->string('type')->default('once'); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('polls'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePollsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('polls', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('polls'); } }
Store timeoutId in local variable
/* * Author: CM */ (function($) { $.event.special.clickConfirmed = { bindType: "click", delegateType: "click", settings: { message: 'Please Confirm' }, handle: function(event) { var $this = $(this); var deactivateTimeout = null; var activateButton = function() { $this.addClass('confirmClick'); $this.attr('title', $.event.special.clickConfirmed.settings.message).tooltip({trigger: 'manual'}).tooltip('show'); deactivateTimeout = setTimeout(function() { deactivateButton(); }, 5000); setTimeout(function() { $(document).one('click.clickConfirmed', function(e) { if (!$this.length || e.target !== $this[0] && !$.contains($this[0], e.target)) { deactivateButton(); } }); }, 0); }; var deactivateButton = function() { $this.removeClass('confirmClick'); $this.removeAttr('title').tooltip('hide'); clearTimeout(deactivateTimeout); $(document).off('click.clickConfirmed'); }; if ($this.hasClass('confirmClick')) { deactivateButton(); return event.handleObj.handler.call(this, event); } activateButton(); return false; } }; })(jQuery);
/* * Author: CM */ (function($) { $.event.special.clickConfirmed = { bindType: "click", delegateType: "click", settings: { message: 'Please Confirm' }, handle: function(event) { var $this = $(this); var activateButton = function() { $this.addClass('confirmClick'); $this.attr('title', $.event.special.clickConfirmed.settings.message).tooltip({trigger: 'manual'}).tooltip('show'); $this.data('timeoutId', setTimeout(function() { deactivateButton(); }, 5000)); setTimeout(function() { $(document).one('click.clickConfirmed', function(e) { if (!$this.length || e.target !== $this[0] && !$.contains($this[0], e.target)) { deactivateButton(); } }); }, 0); }; var deactivateButton = function() { $this.removeClass('confirmClick'); $this.removeAttr('title').tooltip('hide'); clearTimeout($this.data('timeoutId')); $(document).off('click.clickConfirmed'); }; if ($this.hasClass('confirmClick')) { deactivateButton(); return event.handleObj.handler.call(this, event); } activateButton(); return false; } }; })(jQuery);
Set application/json content when JSONObject is used body
package io.myweb.api; import org.json.JSONObject; import java.io.InputStream; public class HttpResponse { private String mimeType; private Object body; private int statusCode; private long contentLength; private HttpResponse() {} public static HttpResponse create() { return new HttpResponse(); } public HttpResponse ok() { return withStatusCode(200); } public String getMimeType() { return mimeType; } public Object getBody() { return body; } public HttpResponse withMimeType(String mimeType) { this.mimeType = mimeType; return this; } public HttpResponse withMimeTypeFromFilename(String filename) { return withMimeType(MimeTypes.getMimeType(filename)); } public HttpResponse withStatusCode(int code) { this.statusCode = code; return this; } public HttpResponse withBody(String s) { this.body = s; return this; } public HttpResponse withBody(InputStream is) { this.body = is; return this; } public HttpResponse withBody(JSONObject jsonObject) { this.body = jsonObject; return withMimeType(MimeTypes.MIME_APPLICATION_JSON); } public HttpResponse withContentLength(long length) { this.contentLength = length; return this; } public int getStatusCode() { return statusCode; } public long getContentLength() { return contentLength; } }
package io.myweb.api; import org.json.JSONObject; import java.io.InputStream; public class HttpResponse { private String mimeType; private Object body; private int statusCode; private long contentLength; private HttpResponse() {} public static HttpResponse create() { return new HttpResponse(); } public HttpResponse ok() { return withStatusCode(200); } public String getMimeType() { return mimeType; } public Object getBody() { return body; } public HttpResponse withMimeType(String mimeType) { this.mimeType = mimeType; return this; } public HttpResponse withMimeTypeFromFilename(String filename) { return withMimeType(MimeTypes.getMimeType(filename)); } public HttpResponse withStatusCode(int code) { this.statusCode = code; return this; } public HttpResponse withBody(String s) { this.body = s; return this; } public HttpResponse withBody(InputStream is) { this.body = is; return this; } public HttpResponse withBody(JSONObject jsonObject) { this.body = jsonObject; return this; } public HttpResponse withContentLength(long length) { this.contentLength = length; return this; } public int getStatusCode() { return statusCode; } public long getContentLength() { return contentLength; } }
Update the delete the .env file before installing message
<?php namespace Anomaly\StreamsDistribution\Http\Controller; use Anomaly\Streams\Platform\Application\Application; use Anomaly\Streams\Platform\Http\Controller\PublicController; use Anomaly\StreamsDistribution\Form\InstallerFormBuilder; /** * Class InstallerController * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <hello@anomaly.is> * @author Ryan Thompson <ryan@anomaly.is> * @package Anomaly\StreamsDistribution\Http\Controller */ class InstallerController extends PublicController { /** * Create a new InstallerController instance. * * @param InstallerFormBuilder $form * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response */ public function index(InstallerFormBuilder $form, Application $application) { if ($application->isInstalled()) { throw new \Exception("Please delete the .env file before installing."); } return $form->render(); } /** * Show the complete page. * * @return \Illuminate\View\View */ public function complete() { return view('anomaly.distribution.streams::complete'); } }
<?php namespace Anomaly\StreamsDistribution\Http\Controller; use Anomaly\Streams\Platform\Application\Application; use Anomaly\Streams\Platform\Http\Controller\PublicController; use Anomaly\StreamsDistribution\Form\InstallerFormBuilder; /** * Class InstallerController * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <hello@anomaly.is> * @author Ryan Thompson <ryan@anomaly.is> * @package Anomaly\StreamsDistribution\Http\Controller */ class InstallerController extends PublicController { /** * Create a new InstallerController instance. * * @param InstallerFormBuilder $form * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response */ public function index(InstallerFormBuilder $form, Application $application) { if ($application->isInstalled()) { throw new \Exception("Please delete the config/distribution.php file before installing."); } return $form->render(); } /** * Show the complete page. * * @return \Illuminate\View\View */ public function complete() { return view('anomaly.distribution.streams::complete'); } }
Resolve issue with e.target.tagName throwing errors in the editor
module.exports = { id: 'tabBar', template: require('./index.html'), data: {}, attached: function () { var el = this.$el; var inputs = document.querySelectorAll('input, te'); function onFocus(e) { if (!e.target.tagName) return; var tagName = e.target.tagName.toLowerCase(); if (['input', 'textarea'].indexOf(tagName) <= -1) { return; } el.style.display = 'none'; } function onBlur() { el.style.display = 'block'; } document.addEventListener('focus', onFocus, true); document.addEventListener('blur', onBlur, true); } };
module.exports = { id: 'tabBar', template: require('./index.html'), data: {}, attached: function () { var el = this.$el; var inputs = document.querySelectorAll('input, te'); function onFocus(e) { var tagName = e.target.tagName.toLowerCase(); if (['input', 'textarea'].indexOf(tagName) <= -1) { return; } el.style.display = 'none'; } function onBlur() { el.style.display = 'block'; } document.addEventListener('focus', onFocus, true); document.addEventListener('blur', onBlur, true); } };
Fix "Array to string conversion" bug related to errorParams
<?php $this->data['header'] = $this->t('{userid:error:header}'); $this->data['head'] = <<<EOF <meta name="robots" content="noindex, nofollow" /> <meta name="googlebot" content="noarchive, nofollow" /> EOF; $this->includeAtTemplateBase('includes/header.php'); $translationParams = [ '%IDPNAME%' => $this->data['parameters']['%IDPNAME%'], ]; ?> <h2><?php echo $this->t('{userid:error:title}'); ?></h2> <?php echo ('<p>' . $this->t('{userid:error:descr_' . $this->data['errorCode'] . '}', $translationParams) . '</p>'); echo ( '<p><a href="' . htmlspecialchars($this->data['parameters']['%BASEDIR%'] . 'saml2/idp/initSLO.php?RelayState=' . urlencode($this->data['parameters']['%RESTARTURL%'])) . '">' . $this->t('{userid:error:retry}') . '</a></p>' ); ?> <?php $this->includeAtTemplateBase('includes/footer.php');
<?php $this->data['header'] = $this->t('{userid:error:header}'); $this->data['head'] = <<<EOF <meta name="robots" content="noindex, nofollow" /> <meta name="googlebot" content="noarchive, nofollow" /> EOF; $this->includeAtTemplateBase('includes/header.php'); ?> <h2><?php echo $this->t('{userid:error:title}'); ?></h2> <?php echo ('<p>' . $this->t('{userid:error:descr_' . $this->data['errorCode'] . '}', $this->data['parameters']) . '</p>'); echo ( '<p><a href="' . htmlspecialchars($this->data['parameters']['%BASEDIR%'] . 'saml2/idp/initSLO.php?RelayState=' . urlencode($this->data['parameters']['%RESTARTURL%'])) . '">' . $this->t('{userid:error:retry}') . '</a></p>' ); ?> <?php $this->includeAtTemplateBase('includes/footer.php');
Create assets dir in src
// paths map var path = { src: 'src', dest: 'build' }; // set configs for plugins global['config'] = { src: path.src, dest: path.dest, tests: { src: 'tests/**/*' }, zip: { name: 'build.zip', src: path.dest + '/**/*', dest: './' }, esformatter: { src: path.src + '/assets/js/**/*', dest: path.src + '/assets/js' }, js: { src: path.src + '/assets/js/**/*.js', dest: path.dest + '/assets/js' }, browserSync: { server: { baseDir: path.dest } }, images: { src: path.src + '/assets/images/**/*', dest: path.dest + '/assets/images' }, markup: { src: path.src + '/**/*.html', dest: path.dest }, compass: { src: path.src + '/assets/sass', dest: path.dest + '/assets/css' }, scssLint: { conf: path.src + '/../scss-lint.yml' }, preprocessor: { choice: 'sass', //sass or stylus src: path.src + '/assets/sass/**/*.scss', //dir of sass or stylus dest: path.dest + '/assets/css' //dir of css dest } };
// paths map var path = { src: 'src', dest: 'build' }; // set configs for plugins global['config'] = { src: path.src, dest: path.dest, tests: { src: path.src + '/js/tests/**/*' }, zip: { name: 'build.zip', src: path.dest + '/**/*', dest: './' }, esformatter: { src: path.src + '/js/**/*', dest: path.src + '/js' }, js: { src: path.src + '/js/**/*.js', dest: path.dest + '/assets/js' }, browserSync: { server: { baseDir: path.dest } }, images: { src: path.src + '/images/**/*', dest: path.dest + '/assets/images' }, markup: { src: path.src + '/**/*.html', dest: path.dest }, compass: { src: path.src + '/sass', dest: path.dest + '/assets/css' }, scssLint: { conf: path.src + '/../scss-lint.yml' }, preprocessor: { choice: 'sass', //sass or stylus src: path.src + '/sass/**/*.scss', //dir of sass or stylus dest: path.dest + '/assets/css' //dir of css dest } };
Allow throwable in stub renderer By only accepting Exception the Stub Exception renderer cannot handle syntax errors, type errors or undefined method errors.
<?php declare(strict_types=1); /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 3.5.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\TestSuite\Stub; use Throwable; /** * Test Exception Renderer. * * Use this class if you want to re-throw exceptions that would otherwise be * caught by the ErrorHandlerMiddleware. This is useful while debugging or * writing integration test cases. * * @see \Cake\TestSuite\IntegrationTestCase::disableErrorHandlerMiddleware() * @internal */ class TestExceptionRenderer { /** * Simply rethrow the given exception * * @param \Throwable $exception Exception. * @return void * @throws \Throwable $exception Rethrows the passed exception. */ public function __construct(Throwable $exception) { throw $exception; } }
<?php declare(strict_types=1); /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 3.5.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\TestSuite\Stub; use Exception; /** * Test Exception Renderer. * * Use this class if you want to re-throw exceptions that would otherwise be * caught by the ErrorHandlerMiddleware. This is useful while debugging or * writing integration test cases. * * @see \Cake\TestSuite\IntegrationTestCase::disableErrorHandlerMiddleware() * @internal */ class TestExceptionRenderer { /** * Simply rethrow the given exception * * @param \Exception $exception Exception. * @return void * @throws \Exception $exception Rethrows the passed exception. */ public function __construct(Exception $exception) { throw $exception; } }
Use format to properly format file for process_logdata_parser.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py '{}'".format(os.path.join(ulog_directory, file)))
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py "+ulog_directory+"/"+file)
Add Python 3.2 trove classifier
from setuptools import setup setup(name='covenant', version='0.1.0', description='Code contracts for Python 3', author='Kamil Kisiel', author_email='kamil@kamilkisiel.net', url='http://pypi.python.org/pypi/covenant', license="BSD License", packages=["covenant"], keywords="contract", platforms=["All"], install_requires=["decorator"], classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities'], )
from setuptools import setup setup(name='covenant', version='0.1.0', description='Code contracts for Python 3', author='Kamil Kisiel', author_email='kamil@kamilkisiel.net', url='http://pypi.python.org/pypi/covenant', license="BSD License", packages=["covenant"], keywords="contract", platforms=["All"], install_requires=["decorator"], classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities'], )
Validate request body get and set fields
package co.paystack.android.api.request; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.HashMap; /** * Created by i on 24/08/2016. */ public class ValidateRequestBody extends BaseRequestBody implements Serializable { public static final String FIELD_TRANS = "trans"; public static final String FIELD_TOKEN = "token"; @SerializedName(FIELD_TRANS) public String trans; @SerializedName(FIELD_TOKEN) public String token; public ValidateRequestBody() { } public String getTrans() { return trans; } public ValidateRequestBody setTrans(String trans) { this.trans = trans; return this; } public String getToken() { return token; } public ValidateRequestBody setToken(String token) { this.token = token; return this; } @Override public HashMap<String, String> getParamsHashMap() { HashMap<String, String> params = new HashMap<>(); params.put(FIELD_TRANS, getTrans()); params.put(FIELD_TOKEN, getToken()); return params; } }
package co.paystack.android.api.request; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.HashMap; /** * Created by i on 24/08/2016. */ public class ValidateRequestBody extends BaseRequestBody implements Serializable { public static final String FIELD_TRANS = "trans"; public static final String FIELD_TOKEN = "token"; @SerializedName(FIELD_TRANS) public String trans; @SerializedName(FIELD_TOKEN) public String token; public ValidateRequestBody() { } public ValidateRequestBody(String trans, String token) { this.trans = trans; this.token = token; } @Override public HashMap<String, String> getParamsHashMap() { HashMap<String, String> params = new HashMap<>(); params.put(FIELD_TRANS, trans); params.put(FIELD_TOKEN, token); return params; } }
Rename variables to avoid conflict.
'use strict'; const menu = require('../common/menu'); const banner = require('../common/banner'); const donate = require('../common/donate'); const microgrants = require('../common/microgrants'); const passport = require('passport'); /* A controller for the admin page. */ function controller(app) { app.get('/admin', passport.authenticate('basic', { session: false }), function (req, res) { banner(app).then(function(banner) { donate(app).then(function(donate) { microgrants(app).then(function(microgrants) { let data = { menu: menu(), showBanner: false, banner: banner, donate: donate, microgrants: microgrants }; res.render('admin/admin', data); }); }); }); }); } module.exports = controller;
'use strict'; const menu = require('../common/menu'); const banner = require('../common/banner'); const donate = require('../common/donate'); const microgrants = require('../common/microgrants'); const passport = require('passport'); /* A controller for the admin page. */ function controller(app) { app.get('/admin', passport.authenticate('basic', { session: false }), function (req, res) { banner(app).then(function(banner) { donate(app).then(function(donate) { microgrants(app).then(function(donate) { let data = { menu: menu(), showBanner: false, banner: banner, donate: donate, microgrants: microgrants }; res.render('admin/admin', data); }); }); }); }); } module.exports = controller;
Set text color to blue
import React, { Component } from 'react' import { theme } from '../../tools' class NotFind extends Component { render() { const styles = { notFind: { display: 'flex', flexDirection: 'column', alignItems: 'center', color: theme.blue, fontSize: '2em', }, header: { fontSize: '4em', } } return ( <div style={styles.notFind} className="notFind"> <h1 style={styles.header}>404</h1> <p>Page non trouvée</p> </div> ) } } export default NotFind
import React, { Component } from 'react' class NotFind extends Component { render() { const styles = { notFind: { display: 'flex', flexDirection: 'column', alignItems: 'center', color: '#ffffff', fontSize: '2em', position: 'absolute', top: '25%', right: 'calc(50% + -100px)', }, header: { fontSize: '4em', } } return ( <div style={styles.notFind} className="notFind"> <h1 style={styles.header}>404</h1> <p>Page non trouvée</p> </div> ) } } export default NotFind
Set the vk key hex routine correctly
# Import nacl libs import libnacl import libnacl.encode # Import python libs import datetime import binascii class BaseKey(object): ''' Include methods for key management convenience ''' def hex_sk(self): if hasattr(self, 'sk'): return libnacl.encode.hex_encode(self.sk) else: return '' def hex_pk(self): if hasattr(self, 'pk'): return libnacl.encode.hex_encode(self.pk) def hex_vk(self): if hasattr(self, 'vk'): return libnacl.encode.hex_encode(self.vk) def salsa_key(): ''' Generates a salsa2020 key ''' return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES) def time_nonce(): ''' Generates a safe nonce The nonce generated here is done by grabbing the 20 digit microsecond timestamp and appending 4 random chars ''' nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format( datetime.datetime.now(), binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8')) return nonce
# Import nacl libs import libnacl import libnacl.encode # Import python libs import datetime import binascii class BaseKey(object): ''' Include methods for key management convenience ''' def hex_sk(self): if hasattr(self, 'sk'): return libnacl.encode.hex_encode(self.sk) else: return '' def hex_pk(self): if hasattr(self, 'pk'): return libnacl.encode.hex_encode(self.pk) def hex_vk(self): if hasattr(self, 'pk'): return libnacl.encode.hex_encode(self.pk) def salsa_key(): ''' Generates a salsa2020 key ''' return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES) def time_nonce(): ''' Generates a safe nonce The nonce generated here is done by grabbing the 20 digit microsecond timestamp and appending 4 random chars ''' nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format( datetime.datetime.now(), binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8')) return nonce
Make cli spec runner work regardless of cur. dir
/* jshint node:true, strict:false */ var path = require('path'), requirejs = require('requirejs'), jasmine = (function () { var Jasmine = require('jasmine'); return new Jasmine({ projectBaseDir: path.resolve() }); }()), $ = (function () { var doc = require('jsdom').jsdom(), window = doc.parentWindow; return require('jquery')(window); }()), Backbone = require('backbone'), specs = [ '../spec/bbctrl-button.spec', '../spec/bbctrl-switch.spec', '../spec/bbctrl-text-field.spec' ]; Backbone.$ = $; requirejs.config({ nodeRequire: require, baseUrl: path.resolve(__dirname, '../lib'), paths: {} }); requirejs(specs, function () { jasmine.configureDefaultReporter({}); jasmine.env.execute(); });
/* jshint node:true, strict:false */ var requirejs = require('requirejs'), jasmine = (function () { var Jasmine = require('jasmine'); return new Jasmine({ projectBaseDir: require('path').resolve() }); }()), $ = (function () { var doc = require('jsdom').jsdom(), window = doc.parentWindow; return require('jquery')(window); }()), Backbone = require('backbone'), specs = [ 'spec/bbctrl-button.spec.js', 'spec/bbctrl-switch.spec.js', 'spec/bbctrl-text-field.spec.js' ]; Backbone.$ = $; requirejs.config({ nodeRequire: require, baseUrl: 'lib', paths: {} }); requirejs(specs, function () { jasmine.configureDefaultReporter({}); jasmine.env.execute(); });
Fix bug with SQLAlchemy, change TEXT to STRING
from app import db class Sprinkler(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(25)) status = db.Column(db.String(25)) flow = db.Column(db.Integer) moisture = db.Column(db.Integer) def __init__(self, name, status, flow, moisture): self.name = name self.status = status self.flow = flow self.moisture = moisture def __repr__(self): return '<Sprinkler#%r %r, Status=%r>' % (self.id, self.name, self.status) def turn_on(self): self.status = 'ON' db.session.commit() def turn_off(self): self.status = 'OFF' db.session.commit()
from app import db class Sprinkler(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text(25)) status = db.Column(db.Text(25)) flow = db.Column(db.Integer) moisture = db.Column(db.Integer) def __init__(self, name, status, flow, moisture): self.name = name self.status = status self.flow = flow self.moisture = moisture def __repr__(self): return '<Sprinkler#%r %r, Status=%r>' % (self.id, self.name, self.status) def turn_on(self): self.status = 'ON' db.session.commit() def turn_off(self): self.status = 'OFF' db.session.commit()
Use tracks 1-3 instead of 0-2, to make room for reserved track
from s4ils import * s = Session() with s[INIT]: s.engine = c.Engine() | s s.fm = s.engine.new_module(rv.m.Fm) | s s.engine.output << s.fm | s s.track1 = s.engine.track(1) s.track2 = s.engine.track(2) s.track3 = s.engine.track(3) with s[0, 0]: s.note1 = s.fm.note_on(n.C4) | s.track1 | s with s[1, 0]: s.note2 = s.fm.note_on(n.E4) | s.track2 | s with s[2, 0]: s.note3 = s.fm.note_on(n.G4) | s.track3 | s with s[4, 0]: s.note1.off() | s s.note2.off() | s s.note3.off() | s if __name__ == '__main__': play(s) input()
from s4ils import * s = Session() with s[INIT]: s.engine = c.Engine() | s s.fm = s.engine.new_module(rv.m.Fm) | s s.engine.output << s.fm | s s.track1 = s.engine.track(0) s.track2 = s.engine.track(1) s.track3 = s.engine.track(2) with s[0, 0]: s.note1 = s.fm.note_on(n.C4) | s.track1 | s with s[1, 0]: s.note2 = s.fm.note_on(n.E4) | s.track2 | s with s[2, 0]: s.note3 = s.fm.note_on(n.G4) | s.track3 | s with s[4, 0]: s.note1.off() | s s.note2.off() | s s.note3.off() | s if __name__ == '__main__': play(s) input()
Move the construction of user credentials into parseUrl(), and only construct username and password if they're undefined (which is currently the case with phantomjs.
import Ember from "ember"; // We create an anchor since that is, afaik, the easiest way to parse a url in javascript function parseUrl(url) { let a = document.createElement('a'); a.href = url; a.hostWithoutPort = a.host.substring(0, a.host.lastIndexOf(':')); // Remove port // Workaround for HTMLAnchorElement not properly parsing username and password in phantomjs. if(!a.username && !a.password) { let credentials = url.substring(a.protocol.length + 2, url.lastIndexOf('@' + a.hostWithoutPort)).split(':'); a.username = credentials[0]; a.password = credentials[1]; } return a; } export default Ember.Controller.extend({ actions: { setDrainFromDatabase(database) { let connectionUrl = database.get('connectionUrl'); let a = parseUrl(connectionUrl); let model = this.get('model'); model.set('drainHost', a.hostWithoutPort); model.set('drainPort', a.port); model.set('drainUsername', a.username); model.set('drainPassword', a.password); }}, isSyslogDrain: Ember.computed("model.drainType", function() { return this.get("model.drainType") === "syslog_tls_tcp"; }) });
import Ember from "ember"; // We create an anchor since that is, afaik, the easiest way to parse a url in javascript function parseUrl(url) { let a = document.createElement('a'); a.href = url; return a; } export default Ember.Controller.extend({ actions: { setDrainFromDatabase(database) { let connectionUrl = database.get('connectionUrl'); let a = parseUrl(connectionUrl); let hostWithoutPort = a.host.substring(0, a.host.lastIndexOf(':')); // Remove port let credentials = connectionUrl.substring(a.protocol.length + 2, connectionUrl.lastIndexOf('@' + hostWithoutPort)).split(':'); let userName = credentials[0]; let password = credentials[1]; let model = this.get('model'); model.set('drainHost', hostWithoutPort); model.set('drainPort', a.port); model.set('drainUsername', userName); model.set('drainPassword', password); }}, isSyslogDrain: Ember.computed("model.drainType", function() { return this.get("model.drainType") === "syslog_tls_tcp"; }) });
Fix whoopsie in single quotes vs double quotes example
<?php require_once __DIR__.'/../vendor/autoload.php'; abstract class AbstractTest implements \mre\PHPench\TestInterface { protected $test; function setUp($arrSize) { } } class TestSingleQuotes extends AbstractTest { public function execute() { $test = 'hello' . 'this' . 'is' . 'a' . 'test'; } } class TestDoubleQuotes extends AbstractTest { public function execute() { $test = "hello" . "this" . "is" . "a" . "test"; } } // Create a new benchmark instance $phpench = new mre\PHPench(new \mre\PHPench\Aggregator\MedianAggregator); $output = new \mre\PHPench\Output\GnuPlotOutput('test4.png', 1024, 768); $output->setTitle('Compare single quote and double quote strings'); $phpench->setOutput($output); // Add your test to the instance $phpench->addTest(new TestSingleQuotes, 'single_quotes'); $phpench->addTest(new TestDoubleQuotes, 'double_quotes'); // Run the benchmark and plot the results in realtime. // With the second parameter you can specify // the start, end and step for each call $phpench->setInput(range(1,pow(2,16), 1024)); $phpench->setRepetitions(4); $phpench->run(True);
<?php require_once __DIR__.'/../vendor/autoload.php'; abstract class AbstractTest implements \mre\PHPench\TestInterface { protected $test; function setUp($arrSize) { } } class TestSingleQuotes extends AbstractTest { public function execute() { $test = 'hello' . 'this' . 'is' . 'a' . 'test'; } } class TestDoubleQuotes extends AbstractTest { public function execute() { $test = 'hello' . 'this' . 'is' . 'a' . 'test'; } } // Create a new benchmark instance $phpench = new mre\PHPench(new \mre\PHPench\Aggregator\MedianAggregator); $output = new \mre\PHPench\Output\GnuPlotOutput('test4.png', 1024, 768); $output->setTitle('Compare single quote and double quote strings'); $phpench->setOutput($output); // Add your test to the instance $phpench->addTest(new TestSingleQuotes, 'single_quotes'); $phpench->addTest(new TestDoubleQuotes, 'double_quotes'); // Run the benchmark and plot the results in realtime. // With the second parameter you can specify // the start, end and step for each call $phpench->setInput(range(1,pow(2,16), 1024)); $phpench->setRepetitions(4); $phpench->run(True);
Change package name to use hyphen
#! /usr/bin/env python from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from csdms.dakota import __version__, plugin_script setup(name='csdms-dakota', version=__version__, author='Mark Piper', author_email='mark.piper@colorado.edu', license='MIT', description='Python API for Dakota', long_description=open('README.md').read(), namespace_packages=['csdms'], packages=find_packages(exclude=['*.tests']), entry_points={ 'console_scripts': [ plugin_script + ' = csdms.dakota.run_plugin:main' ] } )
#! /usr/bin/env python from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from csdms.dakota import __version__, plugin_script package_name = 'csdms.dakota' setup(name=package_name, version=__version__, author='Mark Piper', author_email='mark.piper@colorado.edu', license='MIT', description='Python API for Dakota', long_description=open('README.md').read(), namespace_packages=['csdms'], packages=find_packages(exclude=['*.tests']), entry_points={ 'console_scripts': [ plugin_script + ' = ' + package_name + '.run_plugin:main' ] } )
Resolve namespace-level identifiers in the enclosing namespace.
<?php namespace Phortress; use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\Class_; /** * Namespace Continuation Environments: these are continuation of namespaces * for the purposes of variable declarations. When defining namespace-visible * identifiers, e.g constants or functions, this sets it on the actual * namespace. */ class NamespaceContinuationEnvironment extends NamespaceEnvironment { public function createNamespace($namespaceName) { $this->getNamespaceEnvironment()->createNamespace($namespaceName); } public function createClass(Class_ $class) { return $this->getNamespaceEnvironment()->createClass($class); } public function createFunction(Stmt $function) { return $this->getNamespaceEnvironment()->createFunction($function); } public function resolveFunction($functionName) { return $this->getNamespaceEnvironment()->resolveFunction($functionName); } public function resolveClass($className) { return $this->getNamespaceEnvironment()->resolveClass($className); } public function resolveNamespace($namespaceName) { return $this->getNamespaceEnvironment()->resolveNamespace($namespaceName); } public function resolveConstant($constantName) { return $this->getNamespaceEnvironment()->resolveConstant($constantName); } /** * Gets the namespace environment for this environment. This is a shorthand * for defining functions and constants. * * @return NamespaceEnvironment */ private function getNamespaceEnvironment() { $parent = $this->getParent(); while ($parent && get_class($parent) === '\Phortress\NamespaceContinuationEnvironment') { $parent = $parent->getParent(); } assert($parent, 'NamespaceContinuationEnvironments must be enclosed by a ' . 'NamespaceEnvironment'); return $parent; } }
<?php namespace Phortress; use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\Class_; /** * Namespace Continuation Environments: these are continuation of namespaces * for the purposes of variable declarations. When defining namespace-visible * identifiers, e.g constants or functions, this sets it on the actual * namespace. */ class NamespaceContinuationEnvironment extends NamespaceEnvironment { public function createNamespace($namespaceName) { $this->getNamespaceEnvironment()->createNamespace($namespaceName); } public function createClass(Class_ $class) { return $this->getNamespaceEnvironment()->createClass($class); } public function createFunction(Stmt $function) { return $this->getNamespaceEnvironment()->createFunction($function); } /** * Gets the namespace environment for this environment. This is a shorthand * for defining functions and constants. * * @return NamespaceEnvironment */ private function getNamespaceEnvironment() { $parent = $this->getParent(); while ($parent && get_class($parent) === '\Phortress\NamespaceContinuationEnvironment') { $parent = $parent->getParent(); } assert($parent, 'NamespaceContinuationEnvironments must be enclosed by a ' . 'NamespaceEnvironment'); return $parent; } }
Initialize $_SERVER['SERVER_NAME'] with null when PHP_SAPI is cli
<?php Event::add_before('system.ready', current(Event::get('system.ready')), 'multisite_fetch_appname'); function multisite_fetch_appname() { (PHP_SAPI == 'cli') AND $_SERVER['SERVER_NAME'] = Null; // Fetch application name preg_match('/^(.*)\.[^.]++\.[^.]++$/', $_SERVER['SERVER_NAME'], $appname); $appname = isset($appname[1]) ? $appname[1] : Kohana::config('arag.master_appname'); if ($appname == Kohana::config('arag.master_appname') || in_array($appname, Kohana::config('arag.master_appaliases')) || in_array('.*', Kohana::config('arag.master_appaliases'))) { define('MASTERAPP', TRUE); define('APPNAME', Kohana::config('arag.master_appname')); define('APPALIAS', $appname); } else { define('MASTERAPP', FALSE); define('APPNAME', $appname); } }
<?php Event::add_before('system.ready', current(Event::get('system.ready')), 'multisite_fetch_appname'); function multisite_fetch_appname() { // Fetch application name preg_match('/^(.*)\.[^.]++\.[^.]++$/', $_SERVER['SERVER_NAME'], $appname); $appname = isset($appname[1]) ? $appname[1] : Kohana::config('arag.master_appname'); if ($appname == Kohana::config('arag.master_appname') || in_array($appname, Kohana::config('arag.master_appaliases')) || in_array('.*', Kohana::config('arag.master_appaliases'))) { define('MASTERAPP', TRUE); define('APPNAME', Kohana::config('arag.master_appname')); define('APPALIAS', $appname); } else { define('MASTERAPP', FALSE); define('APPNAME', $appname); } }
Fix asset `checksAfterTimeOut`, use valid global instance of `wTools`
require( 'wTesting' ); // const _ = require( 'wTools' ); const _ = _globals_.testing.wTools; _.include( 'wConsequence' ); // function routine1( test ) { test.description = 'description1'; console.log( 'v0' ); test.identical( 1, 1 ); test.description = 'description2'; _.time.out( 2000 ); _.time.out( 1000, () => { console.log( 'v1' ); test.identical( 1, 1 ); test.equivalent( 1, 1 ); test.true( true ); test.ge( 5, 0 ); console.log( 'v2' ); }); return _.time.out( 2000 ); } routine1.timeOut = 100; // function routine2( test ) { test.description = 'description1'; console.log( 'v3' ); test.identical( 1, 1 ); return _.time.out( 2000, () => { }) } routine2.timeOut = 10000; // var Self1 = { name : 'ChecksAfterTimeOutAsset', tests : { routine1, routine2, } } // Self1 = wTestSuite( Self1 ); if( typeof module !== 'undefined' && !module.parent ) wTester.test( Self1.name );
require( 'wTesting' ); const _ = require( 'wTools' ); _.include( 'wConsequence' ); // function routine1( test ) { test.description = 'description1'; console.log( 'v0' ); test.identical( 1, 1 ); test.description = 'description2'; _.time.out( 2000 ); _.time.out( 1000, () => { console.log( 'v1' ); test.identical( 1, 1 ); test.equivalent( 1, 1 ); test.true( true ); test.ge( 5, 0 ); console.log( 'v2' ); }); return _.time.out( 2000 ); } routine1.timeOut = 100; // function routine2( test ) { test.description = 'description1'; console.log( 'v3' ); test.identical( 1, 1 ); return _.time.out( 2000, () => { }) } routine2.timeOut = 10000; // var Self1 = { name : 'ChecksAfterTimeOutAsset', tests : { routine1, routine2, } } // Self1 = wTestSuite( Self1 ); if( typeof module !== 'undefined' && !module.parent ) wTester.test( Self1.name );
Revert "updated MongoDB connection url" This reverts commit ff376619996ac5a04489440932dbbe2b2b0ffa43.
var mongoose = require('mongoose'); var mongoUrl; if (process.env.NODE_ENV === 'production') { mongoUrl = process.env.OPENSHIFT_MONGODB_DB_URL + 'elixir'; mongoUrl = 'mongodb://' + process.env.MONGODB_USER + ':' + process.env.MONGODB_PASSWORD + '@' + process.env.MONGODB_IP + ':' + process.env.MONGODB_PORT + '/' + process.env.MONGODB_DATABASE; } else { mongoUrl = 'mongodb://localhost:27017/elixir'; } mongoose.connect(mongoUrl); mongoose.connection.on('connected', function () { console.log('Mongoose default connection open to ' + mongoUrl); }); mongoose.connection.on('error',function (err) { console.log('Mongoose default connection error: ' + err); }); mongoose.connection.on('disconnected', function () { console.log('Mongoose default connection disconnected'); }); process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Mongoose default connection disconnected through app termination'); process.exit(0); }); });
var mongoose = require('mongoose'); var mongoUrl; if (process.env.NODE_ENV === 'production') { mongoUrl = process.env.OPENSHIFT_MONGODB_DB_URL + 'elixir'; mongoUrl = 'mongodb://' + process.env.MONGODB_USER + ':' + process.env.MONGODB_PASSWORD + '@' + process.env.MONGODB_IP + ':' + process.env.MONGODB_PORT + '/' + process.env.MONGODB_DATABASE +'?authSource=admin'; } else { mongoUrl = 'mongodb://localhost:27017/elixir'; } mongoose.connect(mongoUrl); mongoose.connection.on('connected', function () { console.log('Mongoose default connection open to ' + mongoUrl); }); mongoose.connection.on('error',function (err) { console.log('Mongoose default connection error: ' + err); }); mongoose.connection.on('disconnected', function () { console.log('Mongoose default connection disconnected'); }); process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Mongoose default connection disconnected through app termination'); process.exit(0); }); });
Fix bad namespace in @covers
<?php declare(strict_types=1); namespace unit\Formatters; use Mihaeu\PhpDependencies\DependencyHelper; use Mihaeu\PhpDependencies\Formatters\DotFormatter; /** * @covers Mihaeu\PhpDependencies\Formatters\DotFormatter */ class DotFormatterTest extends \PHPUnit_Framework_TestCase { public function testFormatsSimpleDependencies() { $expected = 'digraph generated_by_dePHPend {'.PHP_EOL ."\tA -> B".PHP_EOL ."\tA -> D".PHP_EOL ."\tC -> D".PHP_EOL .'}' ; $this->assertEquals($expected, (new DotFormatter())->format(DependencyHelper::map(' A --> B C --> D A --> D '))); } }
<?php declare(strict_types=1); namespace unit\Formatters; use Mihaeu\PhpDependencies\DependencyHelper; use Mihaeu\PhpDependencies\Formatters\DotFormatter; /** * @covers unit\Formatters\DotFormatter */ class DotFormatterTest extends \PHPUnit_Framework_TestCase { public function testFormatsSimpleDependencies() { $expected = 'digraph generated_by_dePHPend {'.PHP_EOL ."\tA -> B".PHP_EOL ."\tA -> D".PHP_EOL ."\tC -> D".PHP_EOL .'}' ; $this->assertEquals($expected, (new DotFormatter())->format(DependencyHelper::map(' A --> B C --> D A --> D '))); } }
Fix styles of new message notification
(function($){ var $bar; window.xeNotifyMessage = function(text, count){ $bar = $('div.message.info'); if(!$bar.length) { $bar = jQuery('<div class="message info"></div>').hide().css({ 'position' : 'absolute', 'opacity' : 0.7, 'z-index' : 10000, }).appendTo(document.body); } text = text.replace('%d', count); var link = jQuery('<a></a>'); link.attr("href", current_url.setQuery('module','').setQuery('act','dispCommunicationNewMessage')); //link.attr("onclick", "popopen(this.href, 'popup');xeNotifyMessageClose(); return false;"); link.text(text); var para = jQuery('<p></p>'); para.append(link).appendTo($bar); $bar.show().animate({top:0}); }; window.xeNotifyMessageClose = function(){ setTimeout(function(){ $bar.slideUp(); }, 2000); }; })(jQuery);
(function($){ var $bar; window.xeNotifyMessage = function(text, count){ $bar = $('div.message.info'); if(!$bar.length) { $bar = $('<div class="message info" />') .hide() .css({ 'position' : 'absolute', 'z-index' : '100', }) .prependTo(document.body); } text = text.replace('%d', count); $bar.html('<p><a href="'+current_url.setQuery('module','').setQuery('act','dispCommunicationNewMessage')+'" onclick="popopen(this.href, \'popup\');xeNotifyMessageClose(); return false;">'+text+'</a></p>').height(); $bar.show().animate({top:0}); }; window.xeNotifyMessageClose = function(){ setTimeout(function(){ $bar.slideUp(); }, 2000); }; })(jQuery);
Use function to get defaultValue for slack channel IDs on Canvas model Using a non-primitive is deprecated, since the values are shared.
import DS from 'ember-data'; import Ember from 'ember'; const { attr, belongsTo, hasMany } = DS; const { computed, get } = Ember; export default DS.Model.extend({ blocks: attr(), isTemplate: attr(), nativeVersion: attr(), slackChannelIds: attr({ defaultValue: _ => [] }), type: attr(), version: attr(), team: belongsTo('team', { async: true }), template: belongsTo('canvas', { async: true }), pulseEvents: hasMany('pulseEvent', { async: true }), editedAt: attr('date'), insertedAt: attr('date'), updatedAt: attr('date'), creator: belongsTo('user', { async: true }), firstContentBlock: computed('blocks.[]', 'blocks.@each.blocks', 'blocks.@each.content', function() { const firstContentBlock = this.get('blocks.1'); if (!firstContentBlock) return null; return get(firstContentBlock, 'blocks.firstObject') || firstContentBlock; }), summary: computed('firstContentBlock.content', function() { return (this.get('firstContentBlock.content') || '').slice(0, 140) || 'No content'; }), title: computed('blocks.firstObject.content', function() { return this.get('blocks.firstObject.content') || 'Untitled'; }) });
import DS from 'ember-data'; import Ember from 'ember'; const { attr, belongsTo, hasMany } = DS; const { computed, get } = Ember; export default DS.Model.extend({ blocks: attr(), isTemplate: attr(), nativeVersion: attr(), slackChannelIds: attr({ defaultValue: [] }), type: attr(), version: attr(), team: belongsTo('team', { async: true }), template: belongsTo('canvas', { async: true }), pulseEvents: hasMany('pulseEvent', { async: true }), editedAt: attr('date'), insertedAt: attr('date'), updatedAt: attr('date'), creator: belongsTo('user', { async: true }), firstContentBlock: computed('blocks.[]', 'blocks.@each.blocks', 'blocks.@each.content', function() { const firstContentBlock = this.get('blocks.1'); if (!firstContentBlock) return null; return get(firstContentBlock, 'blocks.firstObject') || firstContentBlock; }), summary: computed('firstContentBlock.content', function() { return (this.get('firstContentBlock.content') || '').slice(0, 140) || 'No content'; }), title: computed('blocks.firstObject.content', function() { return this.get('blocks.firstObject.content') || 'Untitled'; }) });
Fix album art retrieved from Spotify Remove double quotes around image URL retrieved from Spotify by slicing one character more from left and one character more from right. Also, remove redundant code and null errors to console when element is not found. Signed-off-by: Tomas Slusny <71c4488fd0941e24cd13e3ad13ef1eb0a5fe5168@gmail.com>
var config = { supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, playStateClass: 'playing', nextSelector: '#next', previousSelector: '#previous' } if (document.querySelector('#app-player')) { // Old Player config.artworkImageSelector = '#cover-art .sp-image-img'; config.frameSelector = '#app-player'; config.playStateSelector = '#play-pause'; config.playPauseSelector = '#play-pause'; config.titleSelector = '#track-name'; config.artistSelector = '#track-artist'; } else { // New Player config.artworkImageSelector = '#large-cover-image'; config.frameSelector = '#main'; config.playStateSelector = '#play'; config.playPauseSelector = '#pause'; config.titleSelector = '.caption .track'; config.artistSelector = '.caption .artist'; } controller = new BasicController(config); controller.override('getAlbumArt', function() { var img = this.doc().querySelector(this.artworkImageSelector); return img && img.style.backgroundImage.slice(5, -2); });
if (!!document.querySelector('#app-player')) { // Old Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#app-player', playStateSelector: '#play-pause', playStateClass: 'playing', playPauseSelector: '#play-pause', nextSelector: '#next', previousSelector: '#previous', titleSelector: '#track-name', artistSelector: '#track-artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1); }); } else { // New Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#main', playStateSelector: '#play', playStateClass: 'playing', playPauseSelector: '#play', nextSelector: '#next', previousSelector: '#previous', titleSelector: '.caption .track', artistSelector: '.caption .artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1); }); }
Fix issue while installation via pip Signed-off-by: Lehner Florian <34c6fceca75e456f25e7e99531e2425c6c1de443@der-flo.net>
# Copyright 2016 Florian Lehner. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() setup( name='panonoctl', version='0.3', py_modules=['panonoctl'], packages=find_packages(), long_description=readme, include_package_data=True, description = 'Python API to interact with the PANONO 360-camera', author = 'Florian Lehner', author_email = 'dev@der-flo.net', url = 'https://github.com/florianl/panonoctl/', download_url = 'https://github.com/florianl/panonoctl/archive/master.tar.gz', keywords = ['Panono', 'API '], install_requires=['websocket', 'simplejson', 'socket', 'struct'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers' ], license = 'Apache License 2.0' )
# Copyright 2016 Florian Lehner. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. from setuptools import setup, find_packages setup( name='panonoctl', version='0.3', py_modules=['panonoctl'], packages=find_packages(), long_description=open('README.md').read(), include_package_data=True, description = 'Python API to interact with the PANONO 360-camera', author = 'Florian Lehner', author_email = 'dev@der-flo.net', url = 'https://github.com/florianl/panonoctl/', download_url = 'https://github.com/florianl/panonoctl/archive/master.tar.gz', keywords = ['Panono', 'API '], install_requires=['websocket', 'simplejson', 'socket', 'struct'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers' ], license = 'Apache License 2.0' )
Disable the default 'help' subcommand
package main import ( "fmt" "github.com/codegangsta/cli" "os" ) func main() { app := cli.NewApp() app.Name = "docker-inject" app.Usage = "Copy files/directories from hosts to running Docker containers" app.Version = "0.0.0" app.HideHelp = true app.Flags = []cli.Flag{ cli.HelpFlag, } app.Action = func(c *cli.Context) { inj, err := newInjector(os.Stderr, c.Args()) if err != nil { fmt.Fprintf(os.Stderr, "%s: %s\n", app.Name, err) cli.ShowAppHelp(c) os.Exit(1) } if err := inj.run(); err != nil { fmt.Fprintf(os.Stderr, "%s: %s\n", app.Name, err) cli.ShowAppHelp(c) os.Exit(1) } } app.Run(os.Args) }
package main import ( "fmt" "github.com/codegangsta/cli" "os" ) func main() { app := cli.NewApp() app.Name = "docker-inject" app.Usage = "Copy files/directories from hosts to running Docker containers" app.Version = "0.0.0" app.Action = func(c *cli.Context) { inj, err := newInjector(os.Stderr, c.Args()) if err != nil { fmt.Fprintf(os.Stderr, "%s: %s\n", app.Name, err) cli.ShowAppHelp(c) os.Exit(1) } if err := inj.run(); err != nil { fmt.Fprintf(os.Stderr, "%s: %s\n", app.Name, err) cli.ShowAppHelp(c) os.Exit(1) } } app.Run(os.Args) }
Change desc to clearly advertise that this is a library to work with Google Cloud Endpoints
#!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description='Google Cloud Endpoints Proto Datastore Library', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), url='https://github.com/GoogleCloudPlatform/endpoints-proto-datastore', license='Apache', author='Danny Hermes', author_email='daniel.j.hermes@gmail.com', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python' ], packages=setuptools.find_packages(exclude=['examples*', 'docs*']), )
#!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description='Endpoints Proto Datastore API', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), url='https://github.com/GoogleCloudPlatform/endpoints-proto-datastore', license='Apache', author='Danny Hermes', author_email='daniel.j.hermes@gmail.com', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python' ], packages=setuptools.find_packages(exclude=['examples*', 'docs*']), )
Remove commented code [ci skip].
"""From http://stackoverflow.com/a/12260597/400691""" import sys from django.conf import settings settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbarray', 'HOST': 'localhost' } }, INSTALLED_APPS=('dbarray.tests',), ) try: from django.test.runner import DiscoverRunner except ImportError: # Fallback for django < 1.6 from discover_runner import DiscoverRunner test_runner = DiscoverRunner(verbosity=1) failures = test_runner.run_tests(['dbarray']) if failures: sys.exit(1)
"""From http://stackoverflow.com/a/12260597/400691""" import sys from django.conf import settings settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbarray', 'HOST': 'localhost' } }, INSTALLED_APPS=( 'dbarray.tests', # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.admin', ), ) try: from django.test.runner import DiscoverRunner except ImportError: # Fallback for django < 1.6 from discover_runner import DiscoverRunner test_runner = DiscoverRunner(verbosity=1) failures = test_runner.run_tests(['dbarray']) if failures: sys.exit(1)
Fix broken toggle - broken adjacent selector
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import Icon from '../icon/Icon'; const label = (key) => { const I18N = { on: c('Toggle button').t`On`, off: c('Toggle button').t`Off` }; return ( <span className="pm-toggle-label-text"> <Icon name={key} alt={I18N[key]} className="pm-toggle-label-img" /> </span> ); }; const Toggle = (props) => { return ( <> <input {...props} type="checkbox" className="pm-toggle-checkbox" /> <label htmlFor={props.id} className="pm-toggle-label"> {label('on')} {label('off')} </label> </> ); }; Toggle.propTypes = { id: PropTypes.string.isRequired, checked: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired }; Toggle.defaultProps = { id: 'toggle', checked: false }; export default Toggle;
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import Checkbox from '../input/Checkbox'; import Icon from '../icon/Icon'; const label = (key) => { const I18N = { on: c('Toggle button').t`On`, off: c('Toggle button').t`Off` }; return ( <span className="pm-toggle-label-text"> <Icon name={key} alt={I18N[key]} className="pm-toggle-label-img" /> </span> ); }; const Toggle = ({ id, checked, onChange }) => { return ( <> <Checkbox id={id} checked={checked} className="pm-toggle-checkbox" onChange={onChange} /> <label htmlFor={id} className="pm-toggle-label"> {label('on')} {label('off')} </label> </> ); }; Toggle.propTypes = { id: PropTypes.string.isRequired, checked: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired }; Toggle.defaultProps = { id: 'toggle', checked: false }; export default Toggle;
Document the handling of nil.
package alice import "net/http" // A constructor for a piece of middleware. // Most middleware use this constructor out of the box, // so in most cases you can just pass somepackage.New type Constructor func(http.Handler) http.Handler type Chain struct { constructors []Constructor } // Creates a new chain, memorizing the given middleware constructors func New(constructors ...Constructor) Chain { c := Chain{} c.constructors = append(c.constructors, constructors...) return c } // Chains the middleware and returns the final http.Handler // New(m1, m2, m3).Then(h) // is equivalent to: // m1(m2(m3(h))) // When the request comes in, it will be passed to m1, then m2, then m3 // and finally, the given handler // (assuming every middleware calls the following one) // // Then() treats nil as http.DefaultServeMux. func (c Chain) Then(h http.Handler) http.Handler { var final http.Handler if h != nil { final = h } else { final = http.DefaultServeMux } for i := len(c.constructors) - 1; i >= 0; i-- { final = c.constructors[i](final) } return final }
package alice import "net/http" // A constructor for a piece of middleware. // Most middleware use this constructor out of the box, // so in most cases you can just pass somepackage.New type Constructor func(http.Handler) http.Handler type Chain struct { constructors []Constructor } // Creates a new chain, memorizing the given middleware constructors func New(constructors ...Constructor) Chain { c := Chain{} c.constructors = append(c.constructors, constructors...) return c } // Chains the middleware and returns the final http.Handler // New(m1, m2, m3).Then(h) // is equivalent to: // m1(m2(m3(h))) // When the request comes in, it will be passed to m1, then m2, then m3 // and finally, the given handler // (assuming every middleware calls the following one) func (c Chain) Then(h http.Handler) http.Handler { var final http.Handler if h != nil { final = h } else { final = http.DefaultServeMux } for i := len(c.constructors) - 1; i >= 0; i-- { final = c.constructors[i](final) } return final }
Split attrs, cattrs versions for py36, py37
# -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages # noqa: H301 NAME = "looker_sdk" VERSION = "0.1.3b20" REQUIRES = [ "requests >= 2.22", # Python 3.6 "attrs >= 18.2.0;python_version<'3.7'", "cattrs < 1.1.0;python_version<'3.7'", "python-dateutil;python_version<'3.7'", # Python 3.7+ "attrs >= 20.1.0;python_version>='3.7'", "cattrs >= 1.1.0;python_version>='3.7'", "typing-extensions;python_version<'3.8'", ] setup( author="Looker Data Sciences, Inc.", author_email="support@looker.com", description="Looker API 3.1", install_requires=REQUIRES, license="MIT", long_description=open("README.rst").read(), long_description_content_type="text/x-rst", keywords=["Looker", "Looker API", "looker_sdk", "Looker API 3.1"], name=NAME, package_data={"looker_sdk": ["py.typed", "looker_sdk/looker-sample.ini"]}, packages=find_packages(), python_requires=">=3.6, <3.9", url="https://pypi.python.org/pypi/looker_sdk", version=VERSION, )
# -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages # noqa: H301 NAME = "looker_sdk" VERSION = "0.1.3b20" REQUIRES = [ "requests >= 2.22", "attrs >= 20.1.0", "cattrs >= 1.0.0", "python-dateutil;python_version<'3.7'", "typing-extensions;python_version<'3.8'", ] setup( author="Looker Data Sciences, Inc.", author_email="support@looker.com", description="Looker API 3.1", install_requires=REQUIRES, license="MIT", long_description=open("README.rst").read(), long_description_content_type="text/x-rst", keywords=["Looker", "Looker API", "looker_sdk", "Looker API 3.1"], name=NAME, package_data={"looker_sdk": ["py.typed", "looker_sdk/looker-sample.ini"]}, packages=find_packages(), python_requires=">=3.6, <3.9", url="https://pypi.python.org/pypi/looker_sdk", version=VERSION, )
Add Python 3 as Programming Language Show support for Python 3 by adding classifier on setup.py
from setuptools import setup, find_packages requirements = ['pycryptodome>=3.7.0'] setup( name="ziggeo", version="2.15", description="Ziggeo SDK for python", long_description="Ziggeo API (https://ziggeo.com) allows you to integrate video recording and playback with only two lines of code in your site, service or app. This is the Python Server SDK repository.", url="http://github.com/Ziggeo/ZiggeoPythonSdk", license="Apache 2.0", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], keywords=("Ziggeo video-upload"), packages=["."], package_dir={'ziggeo': '.'}, install_requires=requirements, author="Ziggeo", author_email="support@ziggeo.com" )
from setuptools import setup, find_packages requirements = ['pycryptodome>=3.7.0'] setup( name="ziggeo", version="2.15", description="Ziggeo SDK for python", long_description="Ziggeo API (https://ziggeo.com) allows you to integrate video recording and playback with only two lines of code in your site, service or app. This is the Python Server SDK repository.", url="http://github.com/Ziggeo/ZiggeoPythonSdk", license="Apache 2.0", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2.7", ], keywords=("Ziggeo video-upload"), packages=["."], package_dir={'ziggeo': '.'}, install_requires=requirements, author="Ziggeo", author_email="support@ziggeo.com" )
Use ES6 export syntax in App
import React from 'react'; import {Decorator as Cerebral} from 'cerebral-view-react'; import NewTodoForm from '../NewTodo'; import TodosList from '../List'; import TodosFooter from '../Footer'; import visibleTodos from '../../modules/List/computed/visibleTodos.js'; @Cerebral({ todos: ['app', 'list', 'todos'], isLoading: ['app', 'list', 'todos', 'isLoading'], isSaving: ['app', 'new', 'isSaving'], visibleTodos, }) class App extends React.Component { render() { return ( <div id="todoapp-wrapper"> <section className="todoapp"> <header className="header"> <h1>todos</h1> <NewTodoForm /> </header> {this.props.visibleTodos.length ? <TodosList /> : null} {Object.keys(this.props.todos).length ? <TodosFooter /> : null} </section> <footer className="info"> <p>Double-click to edit a todo</p> </footer> </div> ); } } export default App;
import React from 'react'; import {Decorator as Cerebral} from 'cerebral-view-react'; import NewTodoForm from '../NewTodo'; import TodosList from '../List'; import TodosFooter from '../Footer'; import visibleTodos from '../../modules/List/computed/visibleTodos.js'; @Cerebral({ todos: ['app', 'list', 'todos'], isLoading: ['app', 'list', 'todos', 'isLoading'], isSaving: ['app', 'new', 'isSaving'], visibleTodos, }) class App extends React.Component { render() { return ( <div id="todoapp-wrapper"> <section className="todoapp"> <header className="header"> <h1>todos</h1> <NewTodoForm /> </header> {this.props.visibleTodos.length ? <TodosList /> : null} {Object.keys(this.props.todos).length ? <TodosFooter /> : null} </section> <footer className="info"> <p>Double-click to edit a todo</p> </footer> </div> ); } } module.exports = App;
Add tests for no \t and ' in index.html Closes #82
var assert = require("assert"); var fs = require("fs"); var html5Lint = require("html5-lint"); var _html = ""; describe("index.html", function() { before(function() { _html = fs.readFileSync("index.html", "utf8"); }); it("should have valid HTML", function(done) { html5Lint(_html, function(err, results) { for (var m in results.messages) { var msg = results.messages[m]; var type = msg.type; // error, warning, or info var message = msg.message; var lineNumber = msg.lastLine; console.log("HTML5 Lint [%s]: %s %s (line %s)", type, message, lineNumber); assert.notStrictEqual(type, "error", message + ", see line " + lineNumber + " in index.html"); } done(); }); }); it("should not contain tab characters", function() { assert.strictEqual(-1, _html.indexOf("\t"), "Please remove any tab indents from index.html"); }); it("should not contain single quote characters", function() { assert.strictEqual(-1, _html.indexOf("'"), "Please remove any single quote characters from index.html"); }); });
var assert = require("assert"); var fs = require("fs"); var html5Lint = require("html5-lint"); describe("Splash Page", function() { it("should have valid HTML", function(done) { fs.readFile("index.html", "utf8", function(err, html) { assert.ok(!err); html5Lint(html, function(err, results) { for (var m in results.messages) { var msg = results.messages[m]; var type = msg.type; // error or warning var message = msg.message; console.log("HTML5 Lint [%s]: %s %s (line %s)", type, message, msg, msg.lastLine); assert.notStrictEqual(type, "error", message + ", see line " + msg.lastLine + " in index.html"); } done(); }); }); }); });
Change label for saving bookmark button
<?php /** * Copyright (c) 2011 Marvin Thomas Rabe <mrabe@marvinrabe.de> * Copyright (c) 2011 Arthur Schiwon <blizzz@arthur-schiwon.de> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ ?> <input type="hidden" id="bookmarkFilterTag" value="<?php if(isset($_GET['tag'])) echo htmlentities($_GET['tag']); ?>" /> <div id="controls"> <input type="hidden" id="bookmark_add_id" value="0" /> <input type="text" id="bookmark_add_url" placeholder="<?php echo $l->t('Address'); ?>" class="bookmarks_input" /> <input type="text" id="bookmark_add_title" placeholder="<?php echo $l->t('Title'); ?>" class="bookmarks_input" /> <input type="text" id="bookmark_add_tags" placeholder="<?php echo $l->t('Tags'); ?>" class="bookmarks_input" /> <input type="submit" value="<?php echo $l->t('Save bookmark'); ?>" id="bookmark_add_submit" /> </div> <div class="bookmarks_list"> </div> <div id="firstrun" style="display: none;"> <?php echo $l->t('You have no bookmarks'); require_once(OC::$APPSROOT . '/apps/bookmarks/templates/bookmarklet.php'); createBookmarklet(); ?> </div>
<?php /** * Copyright (c) 2011 Marvin Thomas Rabe <mrabe@marvinrabe.de> * Copyright (c) 2011 Arthur Schiwon <blizzz@arthur-schiwon.de> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ ?> <input type="hidden" id="bookmarkFilterTag" value="<?php if(isset($_GET['tag'])) echo htmlentities($_GET['tag']); ?>" /> <div id="controls"> <input type="hidden" id="bookmark_add_id" value="0" /> <input type="text" id="bookmark_add_url" placeholder="<?php echo $l->t('Address'); ?>" class="bookmarks_input" /> <input type="text" id="bookmark_add_title" placeholder="<?php echo $l->t('Title'); ?>" class="bookmarks_input" /> <input type="text" id="bookmark_add_tags" placeholder="<?php echo $l->t('Tags'); ?>" class="bookmarks_input" /> <input type="submit" value="<?php echo $l->t('Add bookmark'); ?>" id="bookmark_add_submit" /> </div> <div class="bookmarks_list"> </div> <div id="firstrun" style="display: none;"> <?php echo $l->t('You have no bookmarks'); require_once(OC::$APPSROOT . '/apps/bookmarks/templates/bookmarklet.php'); createBookmarklet(); ?> </div>
Add player name from props
import React, {Component} from 'react'; import {Table} from 'react-bootstrap'; import {connect} from 'react-redux'; import _ from 'lodash'; class UsersTable extends Component { render() { return ( <div className="tbl-scroll"> <Table responsive striped> <tbody> <tr> <th> {this.props.heading} </th> </tr> {_.union([this.props.currentUser], this.props.users) .map(_.startCase).sort().map((x) => _renderUserRow(x))} </tbody> </Table> </div> ); } } function _renderUserRow(data) { return ( <tr key={data}> <td>{data}</td> </tr> ) } function mapStateToProps(state) { return { users: state.users, currentUser: state.game.playerName, }; } export default connect(mapStateToProps)(UsersTable);
import React, {Component} from 'react'; import {Table} from 'react-bootstrap'; import {connect} from 'react-redux'; import _ from 'lodash'; class UsersTable extends Component { render() { return ( <div className="tbl-scroll"> <Table responsive striped> <tbody> <tr> <th> {this.props.heading} </th> </tr> {_.union(this.props.playerName, this.props.users) .map(_.startCase).sort().map((x) => _renderUserRow(x))} </tbody> </Table> </div> ); } } function _renderUserRow(data) { return ( <tr key={data}> <td>{data}</td> </tr> ) } function mapStateToProps(state) { return { users: state.users, playerName: state.game.playerName, }; } export default connect(mapStateToProps)(UsersTable);
Fix test on python 3.3
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) self.assertEqual(tags[1].slug, "tortilla-chips") self.assertEqual(tags[0].slug, "salsa")
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) self.assertEqual(tags[1].name, "tortilla chips") self.assertEqual(tags[1].slug, "tortilla-chips") self.assertEqual(tags[0].name, " salsa") self.assertEqual(tags[0].slug, "salsa")
Disable unreliable local client test
describe("local client", function() { var fs = require("fs-extra"); var setup = require("../controllers/setup"); global.test.blog(); // Sets up a temporary tmp folder and cleans it up after global.test.tmp(); // This causes an error xit("handles new file when setting up", function(done) { fs.outputFileSync(this.tmp + "/" + "hello.txt", "Hello World!"); setup(this.blog.id, this.tmp, function(err) { done(); }); }); it("handles existing file when setting up", function(done) { fs.outputFileSync(this.blogDirectory + "/" + "hello.txt", "Hello World!"); fs.outputFileSync(this.tmp + "/" + "hello.txt", "Hello World!"); setup(this.blog.id, this.tmp, function(err) { done(); }); }); it("handles removed file when setting up", function(done) { fs.outputFileSync(this.blogDirectory + "/" + "hello.txt", "Hello World!"); setup(this.blog.id, this.tmp, function(err) { done(); }); }); });
describe("local client", function() { var fs = require("fs-extra"); var setup = require("../controllers/setup"); global.test.blog(); // Sets up a temporary tmp folder and cleans it up after global.test.tmp(); it("handles new file when setting up", function(done) { fs.outputFileSync(this.tmp + "/" + "hello.txt", "Hello World!"); setup(this.blog.id, this.tmp, function(err) { done(); }); }); it("handles existing file when setting up", function(done) { fs.outputFileSync(this.blogDirectory + "/" + "hello.txt", "Hello World!"); fs.outputFileSync(this.tmp + "/" + "hello.txt", "Hello World!"); setup(this.blog.id, this.tmp, function(err) { done(); }); }); it("handles removed file when setting up", function(done) { fs.outputFileSync(this.blogDirectory + "/" + "hello.txt", "Hello World!"); setup(this.blog.id, this.tmp, function(err) { done(); }); }); });
Update dsub version to 0.4.2 PiperOrigin-RevId: 337172014
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.2'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.2.dev0'
Make UsersResource reusable for LDAP
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from .users import RolesResource, UsersResource from .services import UsersService, DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from .users import RolesResource, UsersResource from .services import DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
TST: Test sqlite and mongoquery variations.
import os import tempfile import shutil import tzlocal import pytest import portable_mds.mongoquery.mds import portable_mds.sqlite.mds variations = [portable_mds.mongoquery.mds, portable_mds.sqlite.mds] @pytest.fixture(params=variations, scope='function') def mds_all(request): '''Provide a function level scoped FileStore instance talking to temporary database on localhost:27017 with both v0 and v1. ''' tempdirname = tempfile.mkdtemp() mds = request.param.MDS({'directory': tempdirname, 'timezone': tzlocal.get_localzone().zone}, version=1) filenames = ['run_starts.json', 'run_stops.json', 'event_descriptors.json', 'events.json'] for fn in filenames: with open(os.path.join(tempdirname, fn), 'w') as f: f.write('[]') def delete_dm(): shutil.rmtree(tempdirname) request.addfinalizer(delete_dm) return mds
import os import tempfile import shutil import tzlocal import pytest from ..mongoquery.mds import MDS @pytest.fixture(params=[1], scope='function') def mds_all(request): '''Provide a function level scoped FileStore instance talking to temporary database on localhost:27017 with both v0 and v1. ''' ver = request.param tempdirname = tempfile.mkdtemp() mds = MDS({'directory': tempdirname, 'timezone': tzlocal.get_localzone().zone}, version=ver) filenames = ['run_starts.json', 'run_stops.json', 'event_descriptors.json', 'events.json'] for fn in filenames: with open(os.path.join(tempdirname, fn), 'w') as f: f.write('[]') def delete_dm(): shutil.rmtree(tempdirname) request.addfinalizer(delete_dm) return mds
Clean up code for JsHint
/*global console, require, module*/ (function () { "use strict"; // Establish the root object, `window` in the browser, or `global` on the server. var root, Instructor, setup, isNode; root = this; // Create a reference to this Instructor = function (fString) { var self = this; self.fRef = new root.Firebase(fString); self.create = function (func, validators) { console.log('piepie', func.toString()); }; return self.create; }; setup = function (isNode) { if (isNode) { root.Firebase = require('firebase'); } else if (!root.Firebase) { console.log("Please include Firebase.js"); } }; isNode = false; // Export the Instruce object for **CommonJS**, with backwards-compatibility // for the old `require()` API. If we're not in CommonJS, add `_` to the // global object. if (typeof module !== 'undefined' && module.exports) { module.exports = Instructor; isNode = true; } else { root.Instructor = Instructor; } setup(isNode); }());
(function () { // Establish the root object, `window` in the browser, or `global` on the server. var root = this; // Create a reference to this var Instructor = function (fString) { var self = this; self._fRef = new root.Firebase(fString); self._create = function (func, validators) { console.log('piepie', func.toString()); } return self._create; }; var setup = function (isNode) { if (isNode) { root.Firebase = require('firebase'); }else{ // Import script tag } }; var isNode = false; // Export the Instruce object for **CommonJS**, with backwards-compatibility // for the old `require()` API. If we're not in CommonJS, add `_` to the // global object. if (typeof module !== 'undefined' && module.exports) { module.exports = Instructor; isNode = true; } else { root.Instructor = Instructor; } setup(isNode); })();
Add 'public' field to ActionAdmin list display
from django.contrib import admin from actstream import models # Use django-generic-admin widgets if available try: from genericadmin.admin import GenericAdminModelAdmin as ModelAdmin except ImportError: ModelAdmin = admin.ModelAdmin class ActionAdmin(ModelAdmin): date_hierarchy = 'timestamp' list_display = ('__str__', 'actor', 'verb', 'target', 'public') list_editable = ('verb',) list_filter = ('timestamp',) raw_id_fields = ('actor_content_type', 'target_content_type', 'action_object_content_type') class FollowAdmin(ModelAdmin): list_display = ('__str__', 'user', 'follow_object', 'actor_only', 'started') list_editable = ('user',) list_filter = ('user', 'started',) raw_id_fields = ('user', 'content_type') admin.site.register(models.Action, ActionAdmin) admin.site.register(models.Follow, FollowAdmin)
from django.contrib import admin from actstream import models # Use django-generic-admin widgets if available try: from genericadmin.admin import GenericAdminModelAdmin as ModelAdmin except ImportError: ModelAdmin = admin.ModelAdmin class ActionAdmin(ModelAdmin): date_hierarchy = 'timestamp' list_display = ('__str__', 'actor', 'verb', 'target') list_editable = ('verb',) list_filter = ('timestamp',) raw_id_fields = ('actor_content_type', 'target_content_type', 'action_object_content_type') class FollowAdmin(ModelAdmin): list_display = ('__str__', 'user', 'follow_object', 'actor_only', 'started') list_editable = ('user',) list_filter = ('user', 'started',) raw_id_fields = ('user', 'content_type') admin.site.register(models.Action, ActionAdmin) admin.site.register(models.Follow, FollowAdmin)
Change to headless chrome in CI
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], customLaunchers: { ChromeNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] } } }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], customLaunchers: { ChromeNoSandbox: { base: 'Chrome', flags: ['--no-sandbox'] } } }); };
Support testscenarios by default in BaseTestCase This allows one to use the scenario framework easily from any test class. Change-Id: Ie736138fe2d1e1d38f225547dde54df3f4b21032
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg import testscenarios from solum.openstack.common import test class BaseTestCase(testscenarios.WithScenarios, test.BaseTestCase): """Test base class.""" def setUp(self): super(BaseTestCase, self).setUp() self.addCleanup(cfg.CONF.reset)
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg from solum.openstack.common import test class BaseTestCase(test.BaseTestCase): """Test base class.""" def setUp(self): super(BaseTestCase, self).setUp() self.addCleanup(cfg.CONF.reset)
Create project API responses the projects list
'use strict'; // External Modules ----------------------------------------------------- const express = require('express'); // My own Modules ------------------------------------------------------ const Project = require('../database/projects/project.model'); // Definitions --------------------------------------------------------- const router = express.Router(); // APIs ---------------------------------------------------------------- router.post('/create', (req, res, next) => { Project.addProject(req.body, (err, project) => { if(err) { res.json({success: false, msg: 'Falla al crear proyecto'}); } else { Project.getProjects(req.body.masterId, (err, projects) => { res.json({ success: true, msg: 'Proyecto creado correctamente', projects: projects }); }); } }); }); router.post('/delete', (req, res, next) => { Project.delete(req.body.projectId, err => { if(err) { res.json({success: false, msg: 'Falla al eliminar proyecto'}); } else { Project.getProjects(req.body.masterId, (err, projects) => { res.json({ success: true, msg: 'Proyecto eliminado correctamente', projects: projects }); }); } }); }); module.exports = router;
'use strict'; // External Modules ----------------------------------------------------- const express = require('express'); // My own Modules ------------------------------------------------------ const Project = require('../database/projects/project.model'); // Definitions --------------------------------------------------------- const router = express.Router(); // APIs ---------------------------------------------------------------- router.post('/create', (req, res, next) => { Project.addProject(req.body, (err, project) => { if(err) { res.json({success: false, msg: 'Falla al crear proyecto'}); } else { res.json({success: true, msg: 'Proyecto creado correctamente'}); } }); }); router.post('/delete', (req, res, next) => { Project.delete(req.body.projectId, err => { if(err) { res.json({success: false, msg: 'Falla al eliminar proyecto'}); } else { Project.getProjects(req.body.masterId, (err, projects) => { res.json({ success: true, msg: 'Proyecto eliminado correctamente', projects: projects }); }); } }); }); module.exports = router;
Add @RestController to default server config
/** * Copyright 2015 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * 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.zipkin.server; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ ZipkinServerConfiguration.class, ZipkinQueryApiV1.class }) public @interface EnableZipkinServer { }
/** * Copyright 2015 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * 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.zipkin.server; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ ZipkinServerConfiguration.class }) public @interface EnableZipkinServer { }
Add an error call back param This allows you to set an onError callback function in case the map doesn't load correctly.
export const GoogleApi = function(opts) { opts = opts || {}; if (!opts.hasOwnProperty('apiKey')) { throw new Error('You must pass an apiKey to use GoogleApi'); } const apiKey = opts.apiKey; const libraries = opts.libraries || ['places']; const client = opts.client; const URL = opts.url || 'https://maps.googleapis.com/maps/api/js'; const googleVersion = opts.version || '3.31'; let script = null; let google = (typeof window !== 'undefined' && window.google) || null; let loading = false; let channel = null; let language = opts.language; let region = opts.region || null; let onLoadEvents = []; const url = () => { let url = URL; let params = { key: apiKey, callback: 'CALLBACK_NAME', libraries: libraries.join(','), client: client, v: googleVersion, channel: channel, language: language, region: region, onError: 'ERROR_FUNCTION' }; let paramStr = Object.keys(params) .filter(k => !!params[k]) .map(k => `${k}=${params[k]}`) .join('&'); return `${url}?${paramStr}`; }; return url(); }; export default GoogleApi;
export const GoogleApi = function(opts) { opts = opts || {}; if (!opts.hasOwnProperty('apiKey')) { throw new Error('You must pass an apiKey to use GoogleApi'); } const apiKey = opts.apiKey; const libraries = opts.libraries || ['places']; const client = opts.client; const URL = opts.url || 'https://maps.googleapis.com/maps/api/js'; const googleVersion = opts.version || '3.31'; let script = null; let google = (typeof window !== 'undefined' && window.google) || null; let loading = false; let channel = null; let language = opts.language; let region = opts.region || null; let onLoadEvents = []; const url = () => { let url = URL; let params = { key: apiKey, callback: 'CALLBACK_NAME', libraries: libraries.join(','), client: client, v: googleVersion, channel: channel, language: language, region: region }; let paramStr = Object.keys(params) .filter(k => !!params[k]) .map(k => `${k}=${params[k]}`) .join('&'); return `${url}?${paramStr}`; }; return url(); }; export default GoogleApi;