text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Revert back to putting cursor at the end of selection after insertion
var vscode = require('vscode'); var loremIpsum = require('lorem-ipsum'); function activate(context) { var commands = [ vscode.commands.registerCommand('lorem-ipsum.line', generateLine), vscode.commands.registerCommand('lorem-ipsum.paragraph', generateParagraph), vscode.commands.registerCommand('lorem-ipsum.multipleParagraphs', generateMultipleParagraphs) ]; commands.forEach(function (command) { context.subscriptions.push(command); }); } function insertText(lorem) { var editor = vscode.window.activeTextEditor; editor.edit( edit => editor.selections.forEach( selection => { edit.delete(selection); edit.insert(selection.start, loremIpsum(lorem)); } ) ); } function generateLine() { insertText({ count: 1, units: 'sentences' }); } function generateParagraph() { insertText({ count: 1, units: 'paragraphs' }); } async function generateMultipleParagraphs() { const items = []; for (let i = 2; i <= 10; i++) { items.push(i.toString()); } const count = await vscode.window.showQuickPick(items, { placeHolder: 'How many paragraphs?' }); if (!count) { return; } insertText({ count: Number.parseInt(count), units: 'paragraphs' }); } exports.activate = activate;
var vscode = require('vscode'); var loremIpsum = require('lorem-ipsum'); function activate(context) { var commands = [ vscode.commands.registerCommand('lorem-ipsum.line', generateLine), vscode.commands.registerCommand('lorem-ipsum.paragraph', generateParagraph), vscode.commands.registerCommand('lorem-ipsum.multipleParagraphs', generateMultipleParagraphs) ]; commands.forEach(function (command) { context.subscriptions.push(command); }); } function insertText(lorem) { var editor = vscode.window.activeTextEditor; editor.edit(edit => editor.selections.forEach(v => edit.replace(v, loremIpsum(lorem)))); } function generateLine() { insertText({ count: 1, units: 'sentences' }); } function generateParagraph() { insertText({ count: 1, units: 'paragraphs' }); } async function generateMultipleParagraphs() { const items = []; for (let i = 2; i <= 10; i++) { items.push(i.toString()); } const count = await vscode.window.showQuickPick(items, { placeHolder: 'How many paragraphs?' }); if (!count) { return; } insertText({ count: Number.parseInt(count), units: 'paragraphs' }); } exports.activate = activate;
Add key to each message to get rid of annoying error message
import React, { Component } from 'react' import firebase, { reference, signIn } from '../firebase'; import Message from './Message'; const MessageContainer = ({messages}) => { const newMessage = messages.map((message, i, array) => { return ( <div key={message.firebaseId}> <div> <p className='time-stamp'>{message.time}</p> <p className='user-stamp'>{message.user}</p> </div> <p className='message-stamp'> {array[i].message} </p> </div> ) }) return ( <div > {newMessage} </div> ) } module.exports = MessageContainer;
import React, { Component } from 'react' import firebase, { reference, signIn } from '../firebase'; import Message from './Message'; const MessageContainer = ({messages}) => { const newMessage = messages.map((message, i, array) => { return ( <div key={messages.firebaseId}> <div> <p className='time-stamp'>{message.time}</p> <p className='user-stamp'>{message.user}</p> </div> <p className='message-stamp'> {array[i].message} </p> </div> ) }) return ( <div> {newMessage} </div> ) } module.exports = MessageContainer;
Fix wrong dev config logic
process.on('unhandledRejection', err => { throw err; }); const express = require('express'); const next = require('next'); const { createRouter } = require('soya-next/server/router'); const { soya } = require('soya-next/server/config'); // @remove-on-eject-begin const conf = require('../next.config'); // @remove-on-eject-end const host = soya.config.host || '0.0.0.0'; const port = soya.config.port || 3000; const dev = soya.config.dev ? soya.config.dev : process.env.NODE_ENV !== 'production'; const app = next({ dev, // @remove-on-eject-begin conf, // @remove-on-eject-end }); app.prepare() .then(() => { const server = express(); server.use(createRouter(app, soya.config)); server.listen(port, host, err => { if (err) { throw err; } // eslint-disable-next-line no-console console.log(`> Ready on ${host}:${port}`); }); }) .catch(ex => { // eslint-disable-next-line no-console console.error(ex.stack); process.exit(1); });
process.on('unhandledRejection', err => { throw err; }); const express = require('express'); const next = require('next'); const { createRouter } = require('soya-next/server/router'); const { soya } = require('soya-next/server/config'); // @remove-on-eject-begin const conf = require('../next.config'); // @remove-on-eject-end const host = soya.config.host || '0.0.0.0'; const port = soya.config.port || 3000; const dev = soya.config.dev || process.env.NODE_ENV !== 'production'; const app = next({ dev, // @remove-on-eject-begin conf, // @remove-on-eject-end }); app.prepare() .then(() => { const server = express(); server.use(createRouter(app, soya.config)); server.listen(port, host, err => { if (err) { throw err; } // eslint-disable-next-line no-console console.log(`> Ready on ${host}:${port}`); }); }) .catch(ex => { // eslint-disable-next-line no-console console.error(ex.stack); process.exit(1); });
Fix view for empty response
$(function () { $(document).on({ ajaxStart: function() { $('body').addClass("loading"); }, ajaxStop: function() { $('body').removeClass("loading"); } }) $( "#request_form" ).submit(function( event ) { event.preventDefault(); $('.results_container').slideUp( "slow"); $.post( "/call", { challenge_number: $("#challenge_number").val(), weeks: $("#weeks").val() }).done(function( data ) { $('.results_container .result').html(''); if (data) { $.each(data, function(key, value) { $('.results_container .results').append("<div class='result'>"+value+"</div>"); }); } else { $('.results_container .results').append("<div class='result'>None</div>"); } $('.results_container').slideDown( "slow"); }); }); });
$(function () { $(document).on({ ajaxStart: function() { $('body').addClass("loading"); }, ajaxStop: function() { $('body').removeClass("loading"); } }) $( "#request_form" ).submit(function( event ) { event.preventDefault(); $('.results_container').slideUp( "slow"); $.post( "/call", { challenge_number: $("#challenge_number").val(), weeks: $("#weeks").val() }).done(function( data ) { $('.results_container .result').html(''); $.each(data, function(key, value) { $('.results_container .results').append("<div class='result'>"+value+"</div>"); }); $('.results_container').slideDown( "slow"); }); }); });
Adjust parent filter on collections. Now top-level collections should specific 'top' as their parent instead of being null. This helps get rid of the problem of collections ending up being top-level when removed from their old parent
from django.shortcuts import render_to_response from django.template import RequestContext from registry.models import ResourceCollection from django.http import HttpResponse, HttpResponseBadRequest import json def browse(req): # Find all the collections that do not have parents top = ResourceCollection.objects.filter(parents="Top") # Find the closure (all children) for each top-level collection result = [ col.jsonClosure(req.user) for col in top ] collections = json.dumps(result) return render_to_response('repository/browse.jade', {'collections': collections}, context_instance=RequestContext(req)) def populateCollection(req, collectionId): # Find this collection try: col = ResourceCollection.objects.get(collection_id=collectionId) except ResourceCollection.DoesNotExist: return HttpResponseBadRequest('There is no collection with the given ID: %s' % collectionId) # Find the children for this collection result = col.jsonClosure(req.user) collections = json.dumps(result) return HttpResponse(collections, content_type="application/json")
from django.shortcuts import render_to_response from django.template import RequestContext from registry.models import ResourceCollection from django.http import HttpResponse, HttpResponseBadRequest import json def browse(req): # Find all the collections that do not have parents top = ResourceCollection.objects.filter(parents__isnull=True) # Find the closure (all children) for each top-level collection result = [ col.jsonClosure(req.user) for col in top ] collections = json.dumps(result) return render_to_response('repository/browse.jade', {'collections': collections}, context_instance=RequestContext(req)) def populateCollection(req, collectionId): # Find this collection try: col = ResourceCollection.objects.get(collection_id=collectionId) except ResourceCollection.DoesNotExist: return HttpResponseBadRequest('There is no collection with the given ID: %s' % collectionId) # Find the children for this collection result = col.jsonClosure(req.user) collections = json.dumps(result) return HttpResponse(collections, content_type="application/json")
Use typedef to define the type of GlobalWorkerOptions.
/* Copyright 2018 Mozilla Foundation * * 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. */ /** * @typedef {Object} GlobalWorkerOptionsType * @property {Worker | null} workerPort - Defines global port for worker * process. Overrides the `workerSrc` option. * @property {string} workerSrc - A string containing the path and filename * of the worker file. * * NOTE: The `workerSrc` option should always be set, in order to prevent any * issues when using the PDF.js library. */ /** @type {GlobalWorkerOptionsType} */ const GlobalWorkerOptions = Object.create(null); GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort; GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc; export { GlobalWorkerOptions };
/* Copyright 2018 Mozilla Foundation * * 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. */ const GlobalWorkerOptions = Object.create(null); /** * Defines global port for worker process. Overrides the `workerSrc` option. * @var {Object} */ GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort; /** * A string containing the path and filename of the worker file. * * NOTE: The `workerSrc` option should always be set, in order to prevent any * issues when using the PDF.js library. * @var {string} */ GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc; export { GlobalWorkerOptions };
Rename test class (sloppy cut n' paste job)
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import unittest from harness import MockRouter class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import unittest from harness import MockRouter class TestLog(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
Put parens in the right place
(function ($) { // http://davidwalsh.name/ways-css-javascript-interact function addCSSRule (sheet, selector, rules, index) { if (sheet.insertRule) { sheet.insertRule(selector + '{ ' + rules + ' }', index) } else { sheet.addRule(selector, rules, index) } } function heightOffset (elem) { return elem.offset().top || elem.outerHeight() } $.fn.sticky = function () { var elem = $(this), nextVisible = elem.siblings().first(':visible'), stuck = false, styleSheet = document.styleSheets[0] addCSSRule(styleSheet, '.stuck', 'position: fixed !important; top: 0 !important; z-index: 10') $(window).on('scroll', function () { if ($(this).scrollTop() > heightOffset(elem)) { if (stuck) return; elem.addClass('stuck') nextVisible.css('margin-top', elem.outerHeight()) stuck = true } else { elem.removeClass('stuck') nextVisible.css('margin-top', "") stuck = false } }) } })(jQuery)
(function ($) { // http://davidwalsh.name/ways-css-javascript-interact function addCSSRule (sheet, selector, rules, index) { if (sheet.insertRule) { sheet.insertRule(selector + '{ ' + rules + ' }', index) } else { sheet.addRule(selector, rules, index) } } function heightOffset (elem) { return elem.offset.top() || elem.outerHeight() } $.fn.sticky = function () { var elem = $(this), nextVisible = elem.siblings().first(':visible'), stuck = false, styleSheet = document.styleSheets[0] addCSSRule(styleSheet, '.stuck', 'position: fixed !important; top: 0 !important; z-index: 10') $(window).on('scroll', function () { if ($(this).scrollTop() > heightOffset(elem)) { if (stuck) return; elem.addClass('stuck') nextVisible.css('margin-top', elem.outerHeight()) stuck = true } else { elem.removeClass('stuck') nextVisible.css('margin-top', "") stuck = false } }) } })(jQuery)
[PLAT-2785] Format expanded null as empty string
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.web.server.push.analytics.formatting; import com.opengamma.engine.value.ValueSpecification; /** * Formats null values for display in the client. */ /* package */ class NullFormatter extends AbstractFormatter<Object> { /* package */ NullFormatter() { super(Object.class); addFormatter(new Formatter<Object>(Format.HISTORY) { @Override Object format(Object value, ValueSpecification valueSpec) { return null; } }); addFormatter(new Formatter<Object>(Format.EXPANDED) { @Override Object format(Object value, ValueSpecification valueSpec) { return ""; } }); } @Override public Object formatCell(Object value, ValueSpecification valueSpec) { return ""; } @Override public DataType getDataType() { return DataType.PRIMITIVE; } }
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.web.server.push.analytics.formatting; import com.opengamma.engine.value.ValueSpecification; /** * Formats null values for display in the client. */ /* package */ class NullFormatter extends AbstractFormatter<Object> { /* package */ NullFormatter() { super(Object.class); addFormatter(new Formatter<Object>(Format.HISTORY) { @Override Object format(Object value, ValueSpecification valueSpec) { return null; } }); addFormatter(new Formatter<Object>(Format.EXPANDED) { @Override Object format(Object value, ValueSpecification valueSpec) { return null; } }); } @Override public Object formatCell(Object value, ValueSpecification valueSpec) { return ""; } @Override public DataType getDataType() { return DataType.PRIMITIVE; } }
Fix behat context & fixtures after latest merges
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Currency\Context; /** * Interface to be implemented by the service providing the currently used * currency. * * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface CurrencyContextInterface { /** * Get the default currency. * * @return string */ public function getDefaultCurrency(); /** * Get the currently active currency. * * @return string */ public function getCurrency(); /** * Set the currently active currency. * * @param string $currency */ public function setCurrency($currency); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Currency\Context; use Sylius\Component\Model\CurrencyInterface; /** * Interface to be implemented by the service providing the currently used * currency. * * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface CurrencyContextInterface { /** * Get the default currency. * * @return CurrencyInterface */ public function getDefaultCurrency(); /** * Get the currently active currency. * * @return CurrencyInterface */ public function getCurrency(); /** * Set the currently active currency. * * @param CurrencyInterface $currency */ public function setCurrency($currency); }
Fix redirectValue for circular type
package funk import "reflect" func equal(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } return reflect.DeepEqual(expected, actual) } func sliceElem(rtype reflect.Type) reflect.Type { for { if rtype.Kind() != reflect.Slice && rtype.Kind() != reflect.Array { return rtype } rtype = rtype.Elem() } } func redirectValue(value reflect.Value) reflect.Value { for { if !value.IsValid() || value.Kind() != reflect.Ptr { return value } res := reflect.Indirect(value) // Test for a circular type. if res.Kind() == reflect.Ptr && value.Pointer() == res.Pointer() { return value } value = res } } func makeSlice(value reflect.Value, values ...int) reflect.Value { sliceType := sliceElem(value.Type()) size := value.Len() cap := size if len(values) > 0 { size = values[0] } if len(values) > 1 { cap = values[1] } return reflect.MakeSlice(reflect.SliceOf(sliceType), size, cap) }
package funk import "reflect" func equal(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } return reflect.DeepEqual(expected, actual) } func sliceElem(rtype reflect.Type) reflect.Type { if rtype.Kind() == reflect.Slice || rtype.Kind() == reflect.Array { return sliceElem(rtype.Elem()) } return rtype } func redirectValue(value reflect.Value) reflect.Value { for { if !value.IsValid() || value.Kind() != reflect.Ptr { return value } value = value.Elem() } } func makeSlice(value reflect.Value, values ...int) reflect.Value { sliceType := sliceElem(value.Type()) size := value.Len() cap := size if len(values) > 0 { size = values[0] } if len(values) > 1 { cap = values[1] } return reflect.MakeSlice(reflect.SliceOf(sliceType), size, cap) }
Test how much quicker deploys really are
import React from 'react' import { Link } from 'gatsby' import styled from 'styled-components' import Layout from '../components/structure/layout' const Section = styled.section` h2 { text-align: center; span { color: #23464c; } } h3 { display: flex; align-items: center; padding: 24px 16px; } h4 { text-align: center; } @media (min-width: 768px) { h3 { max-width: 320px; margin: 1rem auto; } } ` const NotFoundPage = () => ( <Layout> <Section> <h2 className="article-update-notification"> <span>💩 404 💩</span> <br /> <em>This page has been moved or no longer exists</em> </h2> <h4>👇 Check out all blog posts or the quick tips page 👇</h4> <Link to="/news/"> <h3 className="category fpv">Blog Posts</h3> </Link> <Link to="/quick-tips/"> <h3 className="category learning">Quick Tips</h3> </Link> </Section> </Layout> ) export default NotFoundPage
import React from 'react' import { Link } from 'gatsby' import styled from 'styled-components' import Layout from '../components/structure/layout' const Section = styled.section` h2 { text-align: center; span { color: #23464c; } } h3 { display: flex; align-items: center; padding: 24px 16px; } h4 { text-align: center; } @media (min-width: 768px) { h3 { max-width: 320px; margin: 1rem auto; } } ` const NotFoundPage = () => ( <Layout> <Section> <h2 className="article-update-notification"> <span>💩 404 💩</span> <br /> <em>This page has been moved or no longer exists.</em> </h2> <h4>👇 Check out all blog posts or the quick tips page 👇</h4> <Link to="/news/"> <h3 className="category fpv">Blog Posts</h3> </Link> <Link to="/quick-tips/"> <h3 className="category learning">Quick Tips</h3> </Link> </Section> </Layout> ) export default NotFoundPage
Improve custom scalar description test
<?php namespace Overblog\GraphQLBundle\Tests\Functional\Security; use Overblog\GraphQLBundle\Tests\Functional\TestCase; class CustomScalarTest extends TestCase { protected function setUp() { parent::setUp(); static::bootKernel(['test_case' => 'customScalar']); } public function testDateTimeTypeSerialize() { $query = '{ dateTime }'; $expected = [ 'dateTime' => '2016-11-28 12:00:00', ]; $this->assertGraphQL($query, $expected); } public function testDateTimeTypeParseValue() { $query = '{ dateTime(dateTime: "2016-01-18 23:00:00") }'; $expected = [ 'dateTime' => '2016-01-18 23:00:00', ]; $this->assertGraphQL($query, $expected); } public function testDateTimeTypeDescription() { $dateTimeType = static::$kernel->getContainer()->get('overblog_graphql.type_resolver')->resolve('DateTime'); $this->assertEquals('The DateTime type', $dateTimeType->description); } }
<?php namespace Overblog\GraphQLBundle\Tests\Functional\Security; use Overblog\GraphQLBundle\Tests\Functional\TestCase; class CustomScalarTest extends TestCase { protected function setUp() { parent::setUp(); static::bootKernel(['test_case' => 'customScalar']); } public function testDateTimeTypeSerialize() { $query = '{ dateTime }'; $expected = [ 'dateTime' => '2016-11-28 12:00:00', ]; $this->assertGraphQL($query, $expected); } public function testDateTimeTypeParseValue() { $query = '{ dateTime(dateTime: "2016-01-18 23:00:00") }'; $expected = [ 'dateTime' => '2016-01-18 23:00:00', ]; $this->assertGraphQL($query, $expected); } }
Make the data migration actually work
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage") for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): u = IngredientUsage(recipe=recipe, ingredient=ingredient, quantity=1) u.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_auto_20150919_1226'), ] operations = [ migrations.RunPython(change_to_usage), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage") for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): u = IngredientUsage(recipe=r, ingredient=i, quantity=1) u.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_auto_20150919_1226'), ] operations = [ migrations.RunPython(change_to_usage), ]
Upgrade libchromiumcontent to fix generating node.lib
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'aa87035cc012ce0d533bb56b947bca81a6e71b82' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e4b283c22236560fd289fe59c03e50adf39e7c4b' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
Fix the drop harvest event
package com.techern.minecraft.melonblockdrop; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s * * @since 1.0.0 */ public class MelonBlockHarvestEventHandler { /** * Called when harvesting any block * * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent} * * @since 1.0.0 */ @SubscribeEvent public void harvest(BlockEvent.HarvestDropsEvent event) { if (event.getState().getBlock().equals(Blocks.melon_block)) { //We're doing a melon block //First reset the drop list event.getDrops().clear(); //Then add the new drop event.getDrops().add(new ItemStack(Blocks.melon_block, 1)); } //Do nothing if not } }
package com.techern.minecraft.melonblockdrop; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s * * @since 1.0.0 */ public class MelonBlockHarvestEventHandler { /** * Called when harvesting any block * * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent} * * @since 1.0.0 */ @SubscribeEvent public void harvest(BlockEvent.HarvestDropsEvent event) { if (event.state.getBlock().equals(Blocks.melon_block)) { //We're doing a melon block //First reset the drop list event.drops.clear(); //Then add the new drop event.drops.add(new ItemStack(Blocks.melon_block, 1)); } //Do nothing if not } }
III-473: Remove useless, wrong class description
<?php /** * @file * Contains CultuurNet\UDB3\Event\Events\OrganizerUpdated. */ namespace CultuurNet\UDB3\Event\Events; use CultuurNet\UDB3\Event\EventEvent; class OrganizerUpdated extends EventEvent { use \CultuurNet\UDB3\OrganizerUpdatedTrait; /** * @param string $id * @param string $organizerId */ public function __construct($id, $organizerId) { parent::__construct($id); $this->organizerId = $organizerId; } /** * @return mixed The object instance */ public static function deserialize(array $data) { return new static($data['event_id'], $data['organizerId']); } }
<?php /** * @file * Contains CultuurNet\UDB3\Event\Events\OrganizerUpdated. */ namespace CultuurNet\UDB3\Event\Events; use CultuurNet\UDB3\Event\EventEvent; /** * Description of DescriptionUpdated */ class OrganizerUpdated extends EventEvent { use \CultuurNet\UDB3\OrganizerUpdatedTrait; /** * @param string $id * @param string $organizerId */ public function __construct($id, $organizerId) { parent::__construct($id); $this->organizerId = $organizerId; } /** * @return mixed The object instance */ public static function deserialize(array $data) { return new static($data['event_id'], $data['organizerId']); } }
Implement function to post by using michishiki API
michishiki.api = {}; michishiki.api.uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/'; michishiki.api.getPost = function(options) { var dfd = $.Deferred(); var api_uri = michishiki.api.uri + 'get_post.py'; var query_string = michishiki.api.utils.optionsToQueryString(options); $.getJSON(api_uri + query_string, function(json) { dfd.resolve(json); }); return dfd.promise(); }; michishiki.api.post = function(options) { var dfd = $.Deferred(); var api_url = michishiki.api.uri + 'post.py'; var query_string = michishiki.api.utils.optionsToQueryString(options); $.getJSON(api_uri + query_string, function(json) { dfd.resolve(json); }); return dfd.promise(); }; michishiki.api.utils = {}; michishiki.api.utils.optionsToQueryString = function(options) { var querys = []; for (var key in options) { var q = key + '=' + options[key]; querys.push(q); } return '?' + querys.join('&'); };
michishiki.api = {}; michishiki.api.uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/'; michishiki.api.getPost = function(options) { var dfd = $.Deferred(); var api_uri = michishiki.api.uri + 'get_post.py'; var query_string = michishiki.api.utils.optionsToQueryString(options); $.getJSON(api_uri + query_string, function(json) { dfd.resolve(json); }); return dfd.promise(); }; michishiki.api.post = function(options) { var api_url = michishiki.api.uri + 'post.py'; // }; michishiki.api.utils = {}; michishiki.api.utils.optionsToQueryString = function(options) { var querys = []; for (var key in options) { var q = key + '=' + options[key]; querys.push(q); } return '?' + querys.join('&'); };
Update concourse browser plugin for new version. Some of the markup has changed. In earlier versions, there was an element with an id of 'cli-downloads' that contained the download links in the lower left corner. With newer versions, this now also displays the concourse version, and as a result the markup has changed, and there's no longer an element with the relevant id. Instead, there's a container with a class of "lower-right-info" that contains all these details.
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementsByTagName("nav")[0]; element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementById("cli-downloads"); element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementsByTagName("nav")[0]; element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
SimonStewart: Convert the https test that we never run to use junit. git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@17194 07704840-8298-11de-bf8c-fd130f914ac9
/* Copyright 2012 Selenium committers Copyright 2012 Software Freedom Conservancy 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 com.thoughtworks.selenium.thirdparty; import com.thoughtworks.selenium.InternalSelenseTestBase; import org.junit.After; import org.junit.Test; public class YahooHttpsTest extends InternalSelenseTestBase { @After public void resetTimeout() { selenium.setTimeout("30000"); } @Test public void testYahoo() throws Exception { selenium.setTimeout("120000"); // this site has **two** HTTPS hosts (akamai and yahoo), so it's a good test of the new // multi-domain keystore support we just added selenium .open( "https://login11.marketingsolutions.yahoo.com/adui/signin/loadSignin.do?d=U2FsdGVkX1_evOPYuoCCKbeDENMTzoQ6O.oTzifl7TwsO8IqXh6duToE2tI2&p=11&s=21"); } }
/* Copyright 2012 Selenium committers Copyright 2012 Software Freedom Conservancy 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 com.thoughtworks.selenium.thirdparty; import com.thoughtworks.selenium.InternalSelenseTestBase; import org.testng.annotations.Test; public class YahooHttpsTest extends InternalSelenseTestBase { @Test(dataProvider = "system-properties") public void testYahoo() throws Exception { // this site has **two** HTTPS hosts (akamai and yahoo), so it's a good test of the new // multi-domain keystore support we just added selenium .open("https://login11.marketingsolutions.yahoo.com/adui/signin/loadSignin.do?d=U2FsdGVkX1_evOPYuoCCKbeDENMTzoQ6O.oTzifl7TwsO8IqXh6duToE2tI2&p=11&s=21"); } }
Add fail on invalid command to reload
'use babel'; 'use strict'; import Command from '../Command'; import now from 'performance-now'; export default class Reload extends Command { constructor(bot) { super(bot, { name: 'reload', description: 'Reload a command or all commands', aliases: ['r'], usage: '<prefix>reload [command]', extraHelp: `If a command name or alias is provided the specific command will be reloaded. Otherwise, all commands will be reloaded.`, group: 'base', permissions: ['ADMINISTRATOR'] }); } async action(message, args, mentions) // eslint-disable-line no-unused-vars { let start = now(); let command = this.bot.commands.findByNameOrAlias(args[0]); if (args[0] && !command) { message.channel.sendMessage(`Command "${args[0]}" could not be found.`) .then(response => { response.delete(5 * 1000); }); return; } if (command) this.bot.commandLoader.reloadCommand(command.name); else this.bot.commandLoader.loadCommands(); let end = now(); let name = args[0] ? this.bot.commands.findByNameOrAlias(args[0]).name : null; let text = name ? ` "${name}"` : 's'; message.channel.sendMessage(`Command${text} reloaded. (${(end - start).toFixed(3)} ms)`) .then(response => { response.delete(5 * 1000); }); } }
'use babel'; 'use strict'; import Command from '../Command'; import now from 'performance-now'; export default class Reload extends Command { constructor(bot) { super(bot, { name: 'reload', description: 'Reload a command or all commands', aliases: ['r'], usage: '<prefix>reload [command]', extraHelp: `If a command name or alias is provided the specific command will be reloaded. Otherwise, all commands will be reloaded.`, group: 'base', permissions: ['ADMINISTRATOR'] }); } async action(message, args, mentions) // eslint-disable-line no-unused-vars { let start = now(); if (args[0]) this.bot.commandLoader.reloadCommand(args[0]); else this.bot.commandLoader.loadCommands(); let end = now(); let name = args[0] ? this.bot.commands.findByNameOrAlias(args[0]).name : null; let text = name ? ` "${name}"` : 's'; message.channel.sendMessage(`Command${text} reloaded. (${(end - start).toFixed(3)} ms)`) .then(response => { response.delete(5 * 1000); }); } }
Correct DBC file path in hello world example.
#!/usr/bin/env python3 # # > python3 hello_world.py # Message: {'Temperature': 250.1, 'AverageRadius': 3.2, 'Enable': 'Enabled'} # Encoded: c001400000000000 # Decoded: {'Enable': 'Enabled', 'AverageRadius': 3.2, 'Temperature': 250.1} # from __future__ import print_function import os from binascii import hexlify import cantools SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) MOTOHAWK_PATH = os.path.join(SCRIPT_DIR, '..', 'tests', 'files', 'motohawk.dbc') database = cantools.db.load_file(MOTOHAWK_PATH) message = { 'Temperature': 250.1, 'AverageRadius': 3.2, 'Enable': 'Enabled' } encoded = database.encode_message('ExampleMessage', message) decoded = database.decode_message('ExampleMessage', encoded) print('Message:', message) print('Encoded:', hexlify(encoded).decode('ascii')) print('Decoded:', decoded)
#!/usr/bin/env python3 from __future__ import print_function import os from binascii import hexlify import cantools SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) MOTOHAWK_PATH = os.path.join(SCRIPT_DIR, '..', 'tests', 'files', 'motohawk.dbc') database = cantools.db.load_file('tests/files/motohawk.dbc') message = { 'Temperature': 250.1, 'AverageRadius': 3.2, 'Enable': 'Enabled' } encoded = database.encode_message('ExampleMessage', message) decoded = database.decode_message('ExampleMessage', encoded) print('Message:', message) print('Encoded:', hexlify(encoded).decode('ascii')) print('Decoded:', decoded)
Use logging to keep debug message
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Superbil' __version__ = '0.1.0' import shapefile import logging log = logging.getLogger() log.setLevel(logging.DEBUG) sf = shapefile.Reader("shapefiles/路網數值圖103年_西屯區道路路段") # 確認 shapeType 種類 if sf.shapeType is 3: log.debug("PolyLine") # srs = sf.shapeRecords() mapping = {} index = 0 for f in sf.fields: # 跳過第 0 個這個不是 field if index is not 0: key = f[0] mapping[key] = index index = index + 1 log.debug(mapping)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Superbil' __version__ = '0.1.0' import shapefile sf = shapefile.Reader("shapefiles/路網數值圖103年_西屯區道路路段") # 確認 shapeType 種類 if sf.shapeType is 3: print("PolyLine") # srs = sf.shapeRecords() mapping = {} index = 0 for f in sf.fields: # 跳過第 0 個這個不是 field if index is not 0: key = f[0] mapping[key] = index index = index + 1 print(mapping)
Disable printing error messages not in debug
import logging class DebugFilter(logging.Filter): def __init__(self, debug=None): self.debug = debug def filter(self, record): if self.debug: return True return False LOGGING = { 'version': 1, 'filters': { 'exc_filter': { '()': DebugFilter, 'debug': False } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'filters': ['exc_filter'] } }, 'loggers': { 'bamp': { 'level': 'DEBUG', 'handlers': ['console'] }, } }
import logging class ExceptionFilter(logging.Filter): def __init__(self, debug=None): self.debug = debug def filter(self, record): if self.debug: return True # clear exceptions when not in debug if record.levelname == 'ERROR' and record.exc_info: record.exc_info = None return True LOGGING = { 'version': 1, 'filters': { 'exc_filter': { '()': ExceptionFilter, 'debug': False } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'filters': ['exc_filter'] } }, 'loggers': { 'bamp': { 'level': 'DEBUG', 'handlers': ['console'] }, } }
Use the refactored timeline helpers for remaining time.
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange 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. """This module contains the templates which are used across the views.""" from soc.views.template import Template class Timeline(Template): """Timeline template. """ def context(self): rem_days, rem_hours, rem_mins = self.data.timeline.remainingTime() complete_percentage = self.data.timeline.completePercentage() stopwatch_percentage = self.data.timeline.stopwatchPercentage() return { 'remaining_days': rem_days, 'remaining_hours': rem_hours, 'remaining_minutes': rem_mins, 'complete_percentage': complete_percentage, 'stopwatch_percentage': stopwatch_percentage } def templatePath(self): return "v2/modules/gci/common_templates/_timeline.html"
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange 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. """This module contains the templates which are used across the views.""" from soc.views.template import Template class Timeline(Template): """Timeline template. """ def context(self): remaining = self.data.timeline.remainingTime() remaining_days = remaining.days remaining_hours = remaining.seconds / 3600 complete_percentage = self.data.timeline.completePercentage() stopwatch_percentage = self.data.timeline.stopwatchPercentage() return { 'remaining_days': remaining_days, 'remaining_hours': remaining_hours, 'complete_percentage': complete_percentage, 'stopwatch_percentage': stopwatch_percentage } def templatePath(self): return "v2/modules/gci/common_templates/_timeline.html"
Add newline at the end of file
app.controller('MyIndexController', ['$scope', function ($scope) { $scope.searchTable = false; $scope.files = []; $scope.searchFiles = []; $scope.instance = new Index(); $scope.showIndex = false; $scope.showSearch = false; $scope.indexData = {}; $scope.objKeys = Object.keys; $scope.readFile = (file) => { const reader = new FileReader(); reader.readAsText(file); const filename = file.name; reader.onload = (event) => { let content = event.target.result; $scope.alert = $scope.instance.validJson(filename, content); $scope.$apply(); } } $scope.getFile = () => { const file = document.getElementById('filePath').files[0]; $scope.filename = file.name; $scope.files.push(file.name); $scope.searchFiles.push(file.name); $scope.readFile(file); } $scope.createIndex = () => { $scope.showIndex = true; $scope.showSearch = false; $scope.indexData = $scope.instance.indexObject; } $scope.search = () => { $scope.showIndex = false; $scope.showSearch = true; const selectSearch = $scope.toSearch; const terms = document.getElementById("terms").value; const opt = document.getElementById("select"); const filename = opt.options[opt.selectedIndex].text; $scope.results = $scope.instance.searchIndex(filename, terms); } }]);
app.controller('MyIndexController', ['$scope', function ($scope) { $scope.searchTable = false; $scope.files = []; $scope.searchFiles = []; $scope.instance = new Index(); $scope.showIndex = false; $scope.showSearch = false; $scope.indexData = {}; $scope.objKeys = Object.keys; $scope.readFile = (file) => { const reader = new FileReader(); reader.readAsText(file); const filename = file.name; reader.onload = (event) => { let content = event.target.result; $scope.alert = $scope.instance.validJson(filename, content); $scope.$apply(); } } $scope.getFile = () => { const file = document.getElementById('filePath').files[0]; $scope.filename = file.name; $scope.files.push(file.name); $scope.searchFiles.push(file.name); $scope.readFile(file); } $scope.createIndex = () => { $scope.showIndex = true; $scope.showSearch = false; $scope.indexData = $scope.instance.indexObject; } $scope.search = () => { $scope.showIndex = false; $scope.showSearch = true; const selectSearch = $scope.toSearch; const terms = document.getElementById("terms").value; const opt = document.getElementById("select"); const filename = opt.options[opt.selectedIndex].text; $scope.results = $scope.instance.searchIndex(filename, terms); } }]);
Simplify the condition to check for a callable type
<?php declare(strict_types=1); use Booking\Domain\Operator\OperatorInterface; use Symfony\Component\DependencyInjection\ContainerInterface; final class DumbOperator implements OperatorInterface { public function __construct(ContainerInterface $container) { $this->container = $container; } public function __invoke(string $spec): Closure { return function (...$args) use ($spec) { $object = $this->container->get($spec); if (\is_callable($object)) { return $object(...$args); } return $object; }; } } return function (ContainerInterface $container): void { $container->autowire(DumbOperator::class, DumbOperator::class) ->setShared(true); $container->setAlias(OperatorInterface::class, DumbOperator::class); };
<?php declare(strict_types=1); use Booking\Domain\Operator\OperatorInterface; use Symfony\Component\DependencyInjection\ContainerInterface; final class DumbOperator implements OperatorInterface { public function __construct(ContainerInterface $container) { $this->container = $container; } public function __invoke(string $spec): Closure { return function (...$args) use ($spec) { $executable = $this->container->get($spec); if (\method_exists($executable, '__invoke')) { return ($executable)(...$args); } return $executable; }; } } return function (ContainerInterface $container): void { $container->autowire(DumbOperator::class, DumbOperator::class) ->setShared(true); $container->setAlias(OperatorInterface::class, DumbOperator::class); };
Use stderr.isTTY instead of stdout.isTTY
'use strict'; var EventEmitter = require('events').EventEmitter; var Console = require('./console'); var hostname = require('os').hostname(); var pid = process.pid; var emitter = new EventEmitter(); var _console = new Console(process.stderr); module.exports = factory; factory.on = function (event, listener) { emitter.on(event, listener); }; factory.removeListener = function (event, listener) { emitter.removeListener(event, listener); }; factory.setOutputStream = function (stream) { if (!stream) { _console = null; return; } _console = new Console(stream); }; function factory (componentName) { return new LoggingContext(componentName); } function LoggingContext(componentName) { this._name = componentName; } LoggingContext.prototype.chalk = require('chalk'); LoggingContext.prototype._write = function (level, message, data) { var payload = { component : this._name, time : new Date(), hostname : hostname, level : level, message : message, pid : pid, data : data }; emitter.emit('data', payload); if (_console) { _console.write(payload); } }; ['log', 'warn', 'info', 'error', 'debug'] .forEach(function (level) { LoggingContext.prototype[level] = function (message, metadata) { this._write(level, message, metadata); }; });
'use strict'; var EventEmitter = require('events').EventEmitter; var Console = require('./console'); var hostname = require('os').hostname(); var pid = process.pid; var emitter = new EventEmitter(); var _console = new Console(process.stdout); module.exports = factory; factory.on = function (event, listener) { emitter.on(event, listener); }; factory.removeListener = function (event, listener) { emitter.removeListener(event, listener); }; factory.setOutputStream = function (stream) { if (!stream) { _console = null; return; } _console = new Console(stream); }; function factory (componentName) { return new LoggingContext(componentName); } function LoggingContext(componentName) { this._name = componentName; } LoggingContext.prototype.chalk = require('chalk'); LoggingContext.prototype._write = function (level, message, data) { var payload = { component : this._name, time : new Date(), hostname : hostname, level : level, message : message, pid : pid, data : data }; emitter.emit('data', payload); if (_console) { _console.write(payload); } }; ['log', 'warn', 'info', 'error', 'debug'] .forEach(function (level) { LoggingContext.prototype[level] = function (message, metadata) { this._write(level, message, metadata); }; });
fix: Attach event listeners to streams after creation
import { SevenZipStream } from './stream.js' import { matchSymbolFileLine } from './parser.js' import { onSpawnError, onSubprocessError } from './onError.js' import { onSubprocessData } from './onData.js' /** * Add command * @param archive {String} Path to the archive * @param source {String|Array} Source to add * @param options {Object} An object of acceptable options to 7za bin. */ export function add (archive, source, options) { const opts = Object.assign({}, options) opts._commandArgs = ['a'] opts._commandArgs.push(archive, source) opts._parser = function (line) { console.log('add-parser: %s', line) // @TODO } return new SevenZipStream(opts) } export function test (archive, options) { const opts = Object.assign({}, options) opts._commandArgs = ['t'] opts._commandArgs.push(archive) opts._parser = matchSymbolFileLine const stream = new SevenZipStream(opts) // Handle events from child_process stream._childProcess.stdout.on('data', function (chunk) { onSubprocessData(stream, chunk) }) stream._childProcess.stderr.on('data', function (chunk) { onSubprocessError(stream, chunk) }) stream._childProcess.on('error', function (err) { onSpawnError(stream, err) }) return stream }
import { SevenZipStream } from './stream.js' /** * Add command * @param archive {String} Path to the archive * @param source {String|Array} Source to add * @param options {Object} An object of acceptable options to 7za bin. */ export function add (archive, source, options) { const opts = Object.assign({}, options) opts._commandArgs = ['a'] opts._commandArgs.push(archive, source) opts._parser = function (line) { console.log('add-parser: %s', line) // @TODO } return new SevenZipStream(opts) } export function test (archive, options) { const opts = Object.assign({}, options) opts._commandArgs = ['t'] opts._commandArgs.push(archive) opts._parser = function (line) { console.log('add-parser: %s', line) // @TODO } return new SevenZipStream(opts) }
Make the run_start goal build the project first.
/** * Copyright 2014 Google Inc. All Rights Reserved. */ package com.google.appengine.gcloudapp; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.util.ArrayList; /** * Starts the Gcloud App Engine development server and does not wait. * * @author Ludo * @goal run_start * @execute phase="package" * @threadSafe false */ public class GcloudAppAsyncStart extends GCloudAppRun { @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info(""); getLog().info("Gcloud SDK - Starting the Development Server"); getLog().info(""); if(application_directory == null) { application_directory = maven_project.getBuild().getDirectory() + "/" + maven_project.getBuild().getFinalName(); } File appDirFile = new File(application_directory); if(!appDirFile.exists()) { throw new MojoExecutionException("The application directory does not exist : " + application_directory); } if(!appDirFile.isDirectory()) { throw new MojoExecutionException("The application directory is not a directory : " + application_directory); } ArrayList<String> devAppServerCommand = getCommand(application_directory); startCommand(appDirFile, devAppServerCommand, WaitDirective.WAIT_SERVER_STARTED); } }
/** * Copyright 2014 Google Inc. All Rights Reserved. */ package com.google.appengine.gcloudapp; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.util.ArrayList; /** * Starts the Gcloud App Engine development server and does not wait. * * @author Ludo * @goal run_start * @execute phase="validate" * @threadSafe false */ public class GcloudAppAsyncStart extends GCloudAppRun { @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info(""); getLog().info("Gcloud SDK - Starting the Development Server"); getLog().info(""); if(application_directory == null) { application_directory = maven_project.getBuild().getDirectory() + "/" + maven_project.getBuild().getFinalName(); } File appDirFile = new File(application_directory); if(!appDirFile.exists()) { throw new MojoExecutionException("The application directory does not exist : " + application_directory); } if(!appDirFile.isDirectory()) { throw new MojoExecutionException("The application directory is not a directory : " + application_directory); } ArrayList<String> devAppServerCommand = getCommand(application_directory); startCommand(appDirFile, devAppServerCommand, WaitDirective.WAIT_SERVER_STARTED); } }
Move hackish clobbering to the script that calls the dartium annotated steps Also clean it up, we don't have any builders that starts with release I will remove this functionality from the dartium annotated step since it does not work correctly. This change allow us to use the normal chromium_utils function which we know work TBR=whesse Review URL: https://codereview.chromium.org/230683002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@262656 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') script = 'src/dartium_tools/buildbot_annotated_steps.py' chromium_utils.RunCommand([sys.executable, script]) # BIG HACK # Normal ninja clobbering does not work due to symlinks/python on windows # Full clobbering before building does not work since it will destroy # the ninja build files # So we basically clobber at the end here if chromium_utils.IsWindows() and 'full' in builder_name: chromium_utils.RemoveDirectory('src/out') return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') is_release_bot = builder_name.startswith('release') script = '' if is_release_bot: script = 'src/dartium_tools/buildbot_release_annotated_steps.py' else: script = 'src/dartium_tools/buildbot_annotated_steps.py' return chromium_utils.RunCommand([sys.executable, script]) if __name__ == '__main__': sys.exit(main())
Fix CSV download link to include content type
function prepareCSVLink() { var pokemonCells = document.getElementsByClassName('pokemonCell'); var csvString = 'Number, Name, Caught\n' for(var i = 0; i < pokemonCells.length; i++) { var pokemonCell = pokemonCells[i]; var number = pokemonCell.getElementsByClassName("pokemonCellNumber")[0].innerHTML; var name = pokemonCell.getElementsByClassName("pokemonCellName")[0].innerHTML; var caughtState = pokemonCell.className.split(/\s+/)[1]; csvString+=number; csvString+=', '; csvString+=name; csvString+=', '; csvString+=caughtState; csvString+='\n'; break; } var downloadLink = document.createElement("a"); var csvURI = 'data:text/csv;charset=utf-8,' + csvString; downloadLink.href = csvURI; downloadLink.download = 'dex.csv'; downloadLink.innerHTML = "Download as CSV (experimental)"; var container = document.getElementsByClassName("csvDownloadLinkContainer")[0]; container.appendChild(downloadLink); }
function prepareCSVLink() { var pokemonCells = document.getElementsByClassName('pokemonCell'); var csvString = 'Number, Name, Caught\n' for(var i = 0; i < pokemonCells.length; i++) { var pokemonCell = pokemonCells[i]; var number = pokemonCell.getElementsByClassName("pokemonCellNumber")[0].innerHTML; var name = pokemonCell.getElementsByClassName("pokemonCellName")[0].innerHTML; var caughtState = pokemonCell.className.split(/\s+/)[1]; csvString+=number; csvString+=', '; csvString+=name; csvString+=', '; csvString+=caughtState; csvString+='\n'; break; } var downloadLink = document.createElement("a"); var csvURI = 'data:text/csv;charset=utf-8,' + csvString; downloadLink.href = csvString; downloadLink.download = 'dex.csv'; downloadLink.innerHTML = "Download as CSV (experimental)"; var container = document.getElementsByClassName("csvDownloadLinkContainer")[0]; container.appendChild(downloadLink); }
Fix timestampable lifecycle callback issue
<?php namespace V3labs\DoctrineExtensions\ORM\Timestampable; use Datetime; trait Timestampable { protected $createdAt; protected $updatedAt; /** * @return DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * @return DateTime */ public function getUpdatedAt() { return $this->updatedAt; } public function setCreatedAt(DateTime $createdAt) { $this->createdAt = $createdAt; } public function setUpdatedAt(DateTime $updatedAt) { $this->updatedAt = $updatedAt; } public function updateTimestampableFields() { if (is_null($this->createdAt)) { $this->createdAt = new DateTime('now'); } $this->updatedAt = new DateTime('now'); } }
<?php namespace V3labs\DoctrineExtensions\ORM\Timestampable; use Datetime; trait Timestampable { protected $createdAt; protected $updatedAt; /** * @return DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * @return DateTime */ public function getUpdatedAt() { return $this->updatedAt; } public function setCreatedAt(DateTime $createdAt) { $this->createdAt = $createdAt; } public function setUpdatedAt(DateTime $updatedAt) { $this->updatedAt = $updatedAt; } protected function updateTimestampableFields() { if (is_null($this->createdAt)) { $this->createdAt = new DateTime('now'); } $this->updatedAt = new DateTime('now'); } }
refactor: Move code out of try block
const fs = require('./fs'); const util = require('./util'); /** * add subcommand */ module.exports = function* (file, filePath, config, passFilePath, passphrases) { const isRunSSHAdd = util.getSSHAddOption(config.config, file); try { // check authentication file existence yield fs.stat(filePath); } catch (e) { // if the authentication file is not found, do nothing. return; } // authentication file already exists if (isRunSSHAdd) { try { if (file in passphrases) { yield util.sshAdd( file, passphrases[file], config.config.ssh_add.options ); } else { // if file is not found in the pass file, do nothing. return; } } catch (e) { // if pass file is not found, do nothing. return; } } };
const fs = require('./fs'); const util = require('./util'); /** * add subcommand */ module.exports = function* (file, filePath, config, passFilePath, passphrases) { const isRunSSHAdd = util.getSSHAddOption(config.config, file); try { // check authentication file existence yield fs.stat(filePath); // authentification file already exists if (isRunSSHAdd) { try { if (file in passphrases) { yield util.sshAdd( file, passphrases[file], config.config.ssh_add.options ); } else { // if file is not found in the pass file, // do nothing. return; } } catch (e) { // if pass file is not found, do nothing. return; } } } catch (e) { // authentification file is not found // do nothing. } };
Add travis Chrome to karma hopefully ?
module.exports = function(config) { var detectBrowsers = { enabled: false, usePhantomJS: false }; // On Travis CI, we can only run in Firefox. if (process.env.TRAVIS) { config.browsers = ['Firefox', 'travisChrome']; } // If no browsers are specified, we enable `karma-detect-browsers` // this will detect all browsers that are available for testing if (!config.browsers.length) { detectBrowsers.enabled = true; } config.set({ basePath: '..', frameworks: ['qunit', 'detectBrowsers'], files: [ 'node_modules/sinon/pkg/sinon.js', 'node_modules/sinon/pkg/sinon-ie.js', 'node_modules/video.js/dist/video.js', 'node_modules/video.js/dist/video-js.css', 'node_modules/ogv/dist/ogv-support.js', 'node_modules/ogv/dist/ogv.js', 'test/dist/bundle.js' ], customLaunchers: { travisChrome: { base: 'Chrome', flags: ['--no-sandbox'] } }, detectBrowsers: detectBrowsers, reporters: ['dots'], port: 9876, colors: true, autoWatch: false, singleRun: true, concurrency: Infinity }); };
module.exports = function(config) { var detectBrowsers = { enabled: false, usePhantomJS: false }; // On Travis CI, we can only run in Firefox. if (process.env.TRAVIS) { config.browsers = ['Firefox']; } // If no browsers are specified, we enable `karma-detect-browsers` // this will detect all browsers that are available for testing if (!config.browsers.length) { detectBrowsers.enabled = true; } config.set({ basePath: '..', frameworks: ['qunit', 'detectBrowsers'], files: [ 'node_modules/sinon/pkg/sinon.js', 'node_modules/sinon/pkg/sinon-ie.js', 'node_modules/video.js/dist/video.js', 'node_modules/video.js/dist/video-js.css', 'node_modules/ogv/dist/ogv-support.js', 'node_modules/ogv/dist/ogv.js', 'test/dist/bundle.js' ], detectBrowsers: detectBrowsers, reporters: ['dots'], port: 9876, colors: true, autoWatch: false, singleRun: true, concurrency: Infinity }); };
Call `this._super.init` to avoid ember-cli deprecation This avoids the following deprecation warning: DEPRECATION: Overriding init without calling this._super is deprecated. Please call this._super.init && this._super.init.apply(this, arguments);
/* jshint node: true */ 'use strict'; var path = require('path'); var fs = require('fs'); var VersionChecker = require('ember-cli-version-checker'); module.exports = { name: 'ember-modal-dialog', init: function() { this._super.init && this._super.init.apply(this, arguments); var checker = new VersionChecker(this); if (!checker.for('ember-cli', 'npm').isAbove('0.2.6')) { console.warn("Warning: ember-modal-dialog requires ember-cli >= 0.2.6 " + "for support for the addon-templates tree, which allows " + "us to support various ember versions. Use an older " + "version of ember-modal-dialog if you are stuck on an " + "older ember-cli."); } }, treeForAddonTemplates: function treeForAddonTemplates (tree) { var checker = new VersionChecker(this); var dep = checker.for('ember', 'bower'); var baseTemplatesPath = path.join(this.root, 'addon/templates'); if (dep.lt('1.13.0-beta.1')) { return this.treeGenerator(path.join(baseTemplatesPath, 'lt-1-13')); } else { return this.treeGenerator(path.join(baseTemplatesPath, 'current')); } } };
/* jshint node: true */ 'use strict'; var path = require('path'); var fs = require('fs'); var VersionChecker = require('ember-cli-version-checker'); module.exports = { name: 'ember-modal-dialog', init: function() { var checker = new VersionChecker(this); if (!checker.for('ember-cli', 'npm').isAbove('0.2.6')) { console.warn("Warning: ember-modal-dialog requires ember-cli >= 0.2.6 " + "for support for the addon-templates tree, which allows " + "us to support various ember versions. Use an older " + "version of ember-modal-dialog if you are stuck on an " + "older ember-cli."); } }, treeForAddonTemplates: function treeForAddonTemplates (tree) { var checker = new VersionChecker(this); var dep = checker.for('ember', 'bower'); var baseTemplatesPath = path.join(this.root, 'addon/templates'); if (dep.lt('1.13.0-beta.1')) { return this.treeGenerator(path.join(baseTemplatesPath, 'lt-1-13')); } else { return this.treeGenerator(path.join(baseTemplatesPath, 'current')); } } };
Fix exception message formatting in Python3
# -*- coding: utf-8 -*- from gym import error, envs from gym.envs import registration from gym.envs.classic_control import cartpole def test_make(): env = envs.make('CartPole-v0') assert env.spec.id == 'CartPole-v0' assert isinstance(env, cartpole.CartPoleEnv) def test_spec(): spec = envs.spec('CartPole-v0') assert spec.id == 'CartPole-v0' def test_missing_lookup(): registry = registration.EnvRegistry() registry.register(id='Test-v0', entry_point=None) registry.register(id='Test-v15', entry_point=None) registry.register(id='Test-v9', entry_point=None) registry.register(id='Other-v100', entry_point=None) try: registry.spec('Test-v1') except error.UnregisteredEnv: pass else: assert False def test_malformed_lookup(): registry = registration.EnvRegistry() try: registry.spec(u'“Breakout-v0”') except error.Error as e: assert 'malformed environment ID' in '{}'.format(e), 'Unexpected message: {}'.format(e) else: assert False
# -*- coding: utf-8 -*- from gym import error, envs from gym.envs import registration from gym.envs.classic_control import cartpole def test_make(): env = envs.make('CartPole-v0') assert env.spec.id == 'CartPole-v0' assert isinstance(env, cartpole.CartPoleEnv) def test_spec(): spec = envs.spec('CartPole-v0') assert spec.id == 'CartPole-v0' def test_missing_lookup(): registry = registration.EnvRegistry() registry.register(id='Test-v0', entry_point=None) registry.register(id='Test-v15', entry_point=None) registry.register(id='Test-v9', entry_point=None) registry.register(id='Other-v100', entry_point=None) try: registry.spec('Test-v1') except error.UnregisteredEnv: pass else: assert False def test_malformed_lookup(): registry = registration.EnvRegistry() try: registry.spec(u'“Breakout-v0”') except error.Error as e: assert 'malformed environment ID' in e.message, 'Unexpected message: {}'.format(e) else: assert False
Move ansi_escape to generic function
# coding=utf-8 import re import os import sys # Regex for matching URLs # See https://mathiasbynens.be/demo/url-regex url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)") ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE) INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links') def escape_ansi(text): return ansi_escape_regex.sub("", text) def parse_stdin(): lines = [line.strip() for line in sys.stdin] print(os.linesep.join(lines).strip(), file=sys.stderr) return parse_input(os.linesep.join(lines)) def parse_input(text): matches = url_regex.findall(escape_ansi(text.strip())) return [result[0] for result in matches] def read_inputfile(): with open(INPUT_FILE) as f: return [l.strip() for l in f.readlines()] def main(): #If we are not being piped, exit if sys.stdin.isatty(): sys.exit(1) result = parse_stdin() for url in result: print(url) if __name__ == '__main__': main()
# coding=utf-8 import re import os import sys # Regex for matching URLs # See https://mathiasbynens.be/demo/url-regex url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)") ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE) INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links') def escape_ansi(text): return ansi_escape_regex.sub("", text) def parse_stdin(): stdin = [escape_ansi(line.strip()) for line in sys.stdin] print(os.linesep.join(stdin).strip(), file=sys.stderr) return parse_input(os.linesep.join(stdin)) def parse_input(text): matches = url_regex.findall(text.strip()) return [result[0] for result in matches] def read_inputfile(): with open(INPUT_FILE) as f: return [l.strip() for l in f.readlines()] def main(): #If we are not being piped, exit if sys.stdin.isatty(): sys.exit(1) result = parse_stdin() for url in result: print(url) if __name__ == '__main__': main()
Fix resultSet set and get functions
'use strict'; var noop = require('./noop'); var Records = require('./records'); module.exports = ResultSet; function ResultSet(resultset) { this._resultset = resultset; } ResultSet.prototype = { set: function (key, val) { this._resultset.setOption(key, val); return this; }, get: function (key) { return this._resultset.getOption(key); }, get size() { return this._resultset.size(); }, getRecords: function (index, counts, cb) { cb || (cb = noop); this._resultset.getRecords(index, counts, function (err, records) { if (err) { cb(err); return; } cb(null, new Records(records)); }); } };
'use strict'; var noop = require('./noop'); var Records = require('./records'); module.exports = ResultSet; function ResultSet(resultset) { this._resultset = resultset; } ResultSet.prototype = { set: function (key, val) { this._resultset.set(key, val); return this; }, get: function (key) { return this._resultset.get(key); }, get size() { return this._resultset.size(); }, getRecords: function (index, counts, cb) { cb || (cb = noop); this._resultset.getRecords(index, counts, function (err, records) { if (err) { cb(err); return; } cb(null, new Records(records)); }); } };
Add missing vendors to webpack
var webpack = require('webpack'); module.exports = { entry: { app: './src/js/app.jsx', vendors: ['react', 'react-dom', 'react-router', 'redux', 'redux-thunk', 'es6-promise-polyfill'] }, output: { path: './dist/js/', publicPath: '/js/', filename: 'app.js' }, module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'] } ], loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: '/node_modules/', query: { cacheDirectory: true, presets: ['react', 'es2015'] } } ] }, resolve: { extensions: ['', '.js', '.jsx'] }, devServer: { historyApiFallback: true }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, minimize: true }) ] };
var webpack = require('webpack'); module.exports = { entry: { app: './src/js/app.jsx', vendors: ['react', 'react-dom', 'es6-promise-polyfill'] }, output: { path: './dist/js/', publicPath: '/js/', filename: 'app.js' }, module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'] } ], loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: '/node_modules/', query: { cacheDirectory: true, presets: ['react', 'es2015'] } } ] }, resolve: { extensions: ['', '.js', '.jsx'] }, devServer: { historyApiFallback: true }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, minimize: true }) ] };
Add name property to compile error
/* * Grasspiler / errors.js * copyright (c) 2016 Susisu */ "use strict"; function endModule() { module.exports = Object.freeze({ ParseError, CompileError }); } class ParseError extends Error { constructor(message) { super(message); this.name = this.constructor.name; } } class CompileError extends Error { constructor(trace, message) { super(message); this.name = this.constructor.name; this.trace = trace; } addTrace(trace) { return new CompileError(trace.concat(this.trace), this.message); } toString() { const traceStr = this.trace.map(t => t.toString() + ":\n").join(""); return this.name + ": " + traceStr + this.message; } } endModule();
/* * Grasspiler / errors.js * copyright (c) 2016 Susisu */ "use strict"; function endModule() { module.exports = Object.freeze({ ParseError, CompileError }); } class ParseError extends Error { constructor(message) { super(message); this.name = this.constructor.name; } } class CompileError extends Error { constructor(trace, message) { super(message); this.trace = trace; } addTrace(trace) { return new CompileError(trace.concat(this.trace), this.message); } toString() { const traceStr = this.trace.map(t => t.toString() + ":\n").join(""); return traceStr + this.message; } } endModule();
Fix issue with error when the context object is not set
var _ = require('lodash'); exports.register = function (plugin, options, next) { var environment = process.env.NODE_ENV || 'development'; // Hook onto the 'onPostHandler' plugin.ext('onPostHandler', function (request, next) { // Get the response object var response = request.response; // Check to see if the response is a view if (response.variety === 'view') { if(_.isEmpty(response.source.context)){ response.source.context = {}; } if(_.isEmpty(response.source.context.assets)){ response.source.context.assets = {}; } response.source.context.assets = options[environment]; } return next(); }); return next(); }; exports.register.attributes = { pkg: require("./package.json") };
var _ = require('lodash'); exports.register = function (plugin, options, next) { var environment = process.env.NODE_ENV || 'development'; // Hook onto the 'onPostHandler' plugin.ext('onPostHandler', function (request, next) { // Get the response object var response = request.response; // Check to see if the response is a view if (response.variety === 'view') { if(_.isEmpty(response.source.context.assets)){ response.source.context.assets = {}; } response.source.context.assets = options[environment]; } return next(); }); return next(); }; exports.register.attributes = { pkg: require("./package.json") };
Add function that takes a Collection of beans and returns a Set of ids
package org.beanmaker.util; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class Ids { public static String getProtectionCodeFromParameterName(final String parameterName) { return getProtectionCodeFromParameterName(parameterName, "_"); } public static String getProtectionCodeFromParameterName(final String parameterName, final String separatorRegex) { final String[] elements = parameterName.split(separatorRegex); if (elements.length < 2) throw new IllegalArgumentException("Could not separate id/code from name based on regex: " + separatorRegex); return elements[elements.length - 1]; } public static long getIdFromParameterName(final String parameterName) { return Long.valueOf(getProtectionCodeFromParameterName(parameterName)); } public static long getIdFromParameterName(final String parameterName, final String separatorRegex) { return Long.valueOf(getProtectionCodeFromParameterName(parameterName, separatorRegex)); } public static Set<Long> getIdSet(final Collection<DbBeanInterface> beans) { final Set<Long> set = new HashSet<Long>(); for (DbBeanInterface bean: beans) set.add(bean.getId()); return set; } }
package org.beanmaker.util; public class Ids { public static String getProtectionCodeFromParameterName(final String parameterName) { return getProtectionCodeFromParameterName(parameterName, "_"); } public static String getProtectionCodeFromParameterName(final String parameterName, final String separatorRegex) { final String[] elements = parameterName.split(separatorRegex); if (elements.length < 2) throw new IllegalArgumentException("Could not separate id/code from name based on regex: " + separatorRegex); return elements[elements.length - 1]; } public static long getIdFromParameterName(final String parameterName) { return Long.valueOf(getProtectionCodeFromParameterName(parameterName)); } public static long getIdFromParameterName(final String parameterName, final String separatorRegex) { return Long.valueOf(getProtectionCodeFromParameterName(parameterName, separatorRegex)); } }
Use a generator instead of append
from django.conf import settings from django.core.mail import send_mass_mail from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from pigeon.notification import Notification def build_emails(notification): context = {'site': notification.site} for user in notification.users: message = render_to_string(notification.template_name, context) yield [ notification.subject, message, settings.DEFAULT_FROM_EMAIL, [user.email], ] def send_emails(notification): messages = build_emails(notification) send_mass_mail(messages) class AccountInactiveNotification(Notification): handlers = (send_emails,) template_name = 'user_deletion/email_notification.txt' subject = _('Re-activate your account') class AccountDeletedNotification(Notification): handlers = (send_emails,) template_name = 'user_deletion/email_deletion.txt' subject = _('Your account has been deleted')
from django.conf import settings from django.core.mail import send_mass_mail from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from pigeon.notification import Notification def send_emails(notification): messages = [] context = {'site': notification.site} for user in notification.users: message = render_to_string(notification.template_name, context) messages.append([ notification.subject, message, settings.DEFAULT_FROM_EMAIL, [user.email], ]) send_mass_mail(messages) class AccountInactiveNotification(Notification): handlers = (send_emails,) template_name = 'user_deletion/email_notification.txt' subject = _('Re-activate your account') class AccountDeletedNotification(Notification): handlers = (send_emails,) template_name = 'user_deletion/email_deletion.txt' subject = _('Your account has been deleted')
Fix imports when using the client on Solaris Previously the incorrect syntax had been used for inserting an item at the beginning of sys.path. Change-Id: I98a1451dd84619a0ba5f5be3dc4163509b867149 Addresses-Issue: Jira/AQUILON-1276 Reviewed-by: Gabor Gombas <3bb8c49439d9d044594e1c6967f991d0b4248a64@morganstanley.com>
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # 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. """ Suggested versions of external libraries, and the defaults for the binaries shipped. """ import sys import ms.version ms.version.addpkg('lxml', '2.3.2') if sys.platform == "sunos5": # ctypes is missing from the default Python build on Solaris, due to # http://bugs.python.org/issue2552. It is available as a separate package # though. ms.version.addpkg("ctypes", "1.0.2") # required to move the ctypes path before the core paths sys.path.insert(0, sys.path.pop())
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # 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. """ Suggested versions of external libraries, and the defaults for the binaries shipped. """ import sys import ms.version ms.version.addpkg('lxml', '2.3.2') if sys.platform == "sunos5": # ctypes is missing from the default Python build on Solaris, due to # http://bugs.python.org/issue2552. It is available as a separate package # though. ms.version.addpkg("ctypes", "1.0.2") # required to move the ctypes path before the core paths sys.path[0] = sys.path.pop()
Migrate employee field to timesheet only if it exists in time log
from __future__ import unicode_literals import frappe def execute(): if frappe.db.table_exists("Time Log") and "employee" in frappe.db.get_table_columns("Time Log"): timesheet = frappe.db.sql("""select tl.employee as employee, ts.name as name, tl.modified as modified, tl.modified_by as modified_by, tl.creation as creation, tl.owner as owner from `tabTimesheet` ts, `tabTimesheet Detail` tsd, `tabTime Log` tl where tsd.parent = ts.name and tl.from_time = tsd.from_time and tl.to_time = tsd.to_time and tl.hours = tsd.hours and tl.billing_rate = tsd.billing_rate and tsd.idx=1 and tl.docstatus < 2 and (ts.employee = '' or ts.employee is null)""", as_dict=1) for data in timesheet: ts_doc = frappe.get_doc('Timesheet', data.name) if len(ts_doc.time_logs) == 1: frappe.db.sql(""" update `tabTimesheet` set creation = %(creation)s, owner = %(owner)s, modified = %(modified)s, modified_by = %(modified_by)s, employee = %(employee)s where name = %(name)s""", data)
from __future__ import unicode_literals import frappe def execute(): if frappe.db.table_exists("Time Log"): timesheet = frappe.db.sql("""select tl.employee as employee, ts.name as name, tl.modified as modified, tl.modified_by as modified_by, tl.creation as creation, tl.owner as owner from `tabTimesheet` ts, `tabTimesheet Detail` tsd, `tabTime Log` tl where tsd.parent = ts.name and tl.from_time = tsd.from_time and tl.to_time = tsd.to_time and tl.hours = tsd.hours and tl.billing_rate = tsd.billing_rate and tsd.idx=1 and tl.docstatus < 2 and (ts.employee = '' or ts.employee is null)""", as_dict=1) for data in timesheet: ts_doc = frappe.get_doc('Timesheet', data.name) if len(ts_doc.time_logs) == 1: frappe.db.sql(""" update `tabTimesheet` set creation = %(creation)s, owner = %(owner)s, modified = %(modified)s, modified_by = %(modified_by)s, employee = %(employee)s where name = %(name)s""", data)
Fix php by making methods static
<?php class Cookbooks { public static function get() { $cookbooks = Cache::remember( 'cookbooks', 60, //60 minutes function () { $cookbooks = Chef::get('/cookbooks'); if (empty($cookbooks)) { return []; } $cookbooks = (array) $cookbooks; ksort($cookbooks); return $cookbooks; } ); return $cookbooks; } public static function create($name, $version) { $cookbook = new StdClass(); $cookbook->name = $name; $cookbook->version = $version; Chef::put("/cookbooks/$name/$version", $cookbook); } }
<?php class Cookbooks { public function get() { $cookbooks = Cache::remember( 'cookbooks', 60, //60 minutes function () { $cookbooks = Chef::get('/cookbooks'); if (empty($cookbooks)) { return []; } $cookbooks = (array) $cookbooks; ksort($cookbooks); return $cookbooks; } ); return $cookbooks; } public function create($name, $version) { $cookbook = new StdClass(); $cookbook->name = $name; $cookbook->version = $version; Chef::put("/cookbooks/$name/$version", $cookbook); } }
Handle wrong formatted input, added comments, some cosmetics
class Token(object): def __init__( self, line ): # Splits line tab-wise, writes the values in parameters entries = line.split('\t') if len(entries) == 4: self.form = entries[0].lower() self.gold_pos = entries[1] self.predicted_pos = entries [3] elif len(entries) > 4: print "\tInput file not in expected format: Too many columns" else: print "\tInput file not in expected format: Too many columns" def createFeatureVector(self, featvec, currentToken, previousToken, nextToken): # creates a sparse representation of the feature vector (featvec) self.sparseFeatvec = {} # The current token self.sparseFeatvec[featvec["current_form_"+currentToken.form]] = 1 # If exists, the previous token; else it is the initial token of the phrase if previousToken: self.sparseFeatvec[featvec["prev_form_"+previousToken.form]] = 1 else: self.sparseFeatvec[featvec["initial_token"]] = 1 # if exists, the next token if nextToken: self.sparseFeatvec[featvec["next_form_"+nextToken.form]] = 1 def sentences( filestream ): # A generator to read a file sentence-wise and generate a Token object for each line # A list of Token objects of every sentence is yielded sentence = [] for line in filestream: line = line.rstrip() if line: sentence.append(Token(line)) elif sentence: yield sentence sentence = [] if sentence: yield sentence
class Token(object): def __init__( self, line ): entries = line.split('\t') self.form = entries[0].lower() self.gold_pos = entries[1] self.predicted_pos = entries [3] def createFeatureVector(self, featvec, currentToken, previousToken, nextToken): self.sparseFeatvec = {} #if previousToken: self.sparseFeatvec[featvec["prev_pos_"+str(previousToken.gold_pos)]] = 1 self.sparseFeatvec[featvec["current_form_"+currentToken.form]] = 1 if previousToken: self.sparseFeatvec[featvec["prev_form_"+previousToken.form]] = 1 if nextToken: self.sparseFeatvec[featvec["next_form_"+nextToken.form]] = 1 if not previousToken: self.sparseFeatvec[featvec["initial_token"]] = 1 def sentences( filestream ): sentence = [] for line in filestream: line = line.rstrip() if line: sentence.append(Token(line)) elif sentence: yield sentence sentence = [] if sentence: yield sentence
Fix for PREFIX omission in S3 push
import os import pip import tempfile import subprocess import opentis.version BUCKET_NAME = 'openpathsampling.org' if not opentis.version.release: PREFIX = 'latest' else: PREFIX = opentis.version.short_version PREFIX = '' if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()): raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd') # The secret key is available as a secure environment variable # on travis-ci to push the build documentation to Amazon S3. with tempfile.NamedTemporaryFile('w') as f: f.write('''[default] access_key = {AWS_ACCESS_KEY_ID} secret_key = {AWS_SECRET_ACCESS_KEY} '''.format(**os.environ)) f.flush() template = ('s3cmd --config {config} ' 'sync docs/_build/ s3://{bucket}/{prefix}/') cmd = template.format( config=f.name, bucket=BUCKET_NAME, prefix=PREFIX) return_val = subprocess.call(cmd.split()) # Sync index file. template = ('s3cmd --config {config} ' 'sync devtools/ci/index.html s3://{bucket}/') cmd = template.format( config=f.name, bucket=BUCKET_NAME) return_val = subprocess.call(cmd.split())
import os import pip import tempfile import subprocess import opentis.version BUCKET_NAME = 'openpathsampling.org' if not opentis.version.release: PREFIX = 'latest' else: PREFIX = opentis.version.short_version PREFIX = '' if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()): raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd') # The secret key is available as a secure environment variable # on travis-ci to push the build documentation to Amazon S3. with tempfile.NamedTemporaryFile('w') as f: f.write('''[default] access_key = {AWS_ACCESS_KEY_ID} secret_key = {AWS_SECRET_ACCESS_KEY} '''.format(**os.environ)) f.flush() template = ('s3cmd --config {config} ' 'sync docs/_build/ s3://{bucket}/{prefix}/') cmd = template.format( config=f.name, bucket=BUCKET_NAME ) return_val = subprocess.call(cmd.split()) # Sync index file. template = ('s3cmd --config {config} ' 'sync devtools/ci/index.html s3://{bucket}/') cmd = template.format( config=f.name, bucket=BUCKET_NAME ) return_val = subprocess.call(cmd.split())
Use Inserted/Removed instead of Found/Lost
package org.irmacard.androidcardproxy.messages; public class ReaderMessage { public String type = null; public String name = null; public String id = null; public ReaderMessageArguments arguments = null; public static String TYPE_EVENT = "event"; public static String TYPE_COMMAND = "command"; public static String TYPE_RESPONSE = "response"; public static String NAME_COMMAND_AUTHPIN = "authorizeWithPin"; public static String NAME_COMMAND_TRANSMIT = "transmitCommandSet"; public static String NAME_COMMAND_SELECTAPPLET = "selectApplet"; public static String NAME_EVENT_CARDFOUND = "cardInserted"; public static String NAME_EVENT_CARDLOST = "cardRemoved"; public static String NAME_EVENT_CARDREADERFOUND = "cardReaderFound"; public static String NAME_EVENT_STATUSUPDATE = "statusUpdate"; public ReaderMessage(String type, String name) { this.type = type; this.name = name; } public ReaderMessage(String type, String name, String id) { this.type = type; this.name = name; this.id = id; } public ReaderMessage(String type, String name, String id, ReaderMessageArguments arguments) { this.type = type; this.name = name; this.id = id; this.arguments = arguments; } }
package org.irmacard.androidcardproxy.messages; public class ReaderMessage { public String type = null; public String name = null; public String id = null; public ReaderMessageArguments arguments = null; public static String TYPE_EVENT = "event"; public static String TYPE_COMMAND = "command"; public static String TYPE_RESPONSE = "response"; public static String NAME_COMMAND_AUTHPIN = "authorizeWithPin"; public static String NAME_COMMAND_TRANSMIT = "transmitCommandSet"; public static String NAME_COMMAND_SELECTAPPLET = "selectApplet"; public static String NAME_EVENT_CARDFOUND = "cardFound"; public static String NAME_EVENT_CARDLOST = "cardLost"; public static String NAME_EVENT_CARDREADERFOUND = "cardReaderFound"; public static String NAME_EVENT_STATUSUPDATE = "statusUpdate"; public ReaderMessage(String type, String name) { this.type = type; this.name = name; } public ReaderMessage(String type, String name, String id) { this.type = type; this.name = name; this.id = id; } public ReaderMessage(String type, String name, String id, ReaderMessageArguments arguments) { this.type = type; this.name = name; this.id = id; this.arguments = arguments; } }
[TASK] Replace Math.pow to improve performance
define(function () { var self = {}; self.distance = function distance(a, b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); }; self.distancePoint = function distancePoint(a, b) { return Math.sqrt(self.distance(a, b)); }; self.distanceLink = function distanceLink(p, a, b) { /* http://stackoverflow.com/questions/849211 */ var l2 = self.distance(a, b); if (l2 === 0) { return self.distance(p, a); } var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2; if (t < 0) { return self.distance(p, a); } else if (t > 1) { return self.distance(p, b); } return self.distancePoint(p, { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) }); }; return self; });
define(function () { var self = {}; self.distance = function distance(a, b) { return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2); }; self.distancePoint = function distancePoint(a, b) { return Math.sqrt(self.distance(a, b)); }; self.distanceLink = function distanceLink(p, a, b) { /* http://stackoverflow.com/questions/849211 */ var l2 = self.distance(a, b); if (l2 === 0) { return self.distance(p, a); } var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2; if (t < 0) { return self.distance(p, a); } else if (t > 1) { return self.distance(p, b); } return self.distancePoint(p, { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) }); }; return self; });
Solve Largest Palindrome Product for range of n is [1,6]
# Find the largest palindrome made from the product of two n-digit numbers. # Since the result could be very large, you should return the largest palindrome mod 1337. # Example: # Input: 2 # Output: 987 # Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 # Note: # The range of n is [1,8]. def largestPalindrome(n): """ :type n: int :rtype: int """ number = "" for x in range(n): number += "9" number = int(number) palindrome = 0 upper = number + 1 lower = 0 for x in range(upper, lower, -1): for i in range(upper, lower, -1): product = x * i if product < palindrome: break elif isPalindrome(product): palindrome = product upper = x lower = i break return palindrome % 1337 def isPalindrome(num): """ Return True is number is Palindrome, else return False """ if str(num) == str(num)[::-1]: return True return False n = 5 print(largestPalindrome(n))
# Find the largest palindrome made from the product of two n-digit numbers. # Since the result could be very large, you should return the largest palindrome mod 1337. # Example: # Input: 2 # Output: 987 # Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 # Note: # The range of n is [1,8]. def largestPalindrome(n): """ :type n: int :rtype: int """ number1 = "" number2 = "" for x in range(n): number1 += "9" number2 += "9" number1 = int(number1) number2 = int(number2) palindrome = 0 for x in range(number1 + 1): for i in range(number2 + 1): product = x * i if (str(product) == str(product)[::-1]) and product > palindrome: palindrome = product return palindrome % 1337 n = 2 print(largestPalindrome(n))
Fix bug that prevented showing the loading screen
import { Map } from 'immutable'; import LastLoginScreen from './last_login_screen'; import LoadingScreen from '../loading_screen'; import { ui, isConnectionEnabled } from '../index'; export function renderSSOScreens(m) { // TODO: loading pin check belongs here? if (m.getIn(["sso", "syncStatus"]) != "ok" || m.get("isLoadingPanePinned")) { return new LoadingScreen(); } if (!ui.rememberLastLogin(m)) return null; const { name, strategy } = lastUsedConnection(m); const skipped = m.getIn(["sso", "skipped"], false); return !skipped && isConnectionEnabled(m, name) ? new LastLoginScreen() : null; } export function lastUsedConnection(m) { // { name, strategy } return m.getIn(["sso", "lastUsedConnection"], Map()).toJS(); } export function lastUsedUsername(m) { return m.getIn(["sso", "lastUsedUsername"], ""); } export function skipSSOLogin(m) { return m.setIn(["sso", "skipped"], true); }
import { Map } from 'immutable'; import LastLoginScreen from './last_login_screen'; import LoadingScreen from '../loading_screen'; import { ui, isConnectionEnabled } from '../index'; export function renderSSOScreens(m) { if (!ui.rememberLastLogin(m)) return null; // TODO: loading pin check belongs here? if (m.getIn(["sso", "syncStatus"]) != "ok" || m.get("isLoadingPanePinned")) { return new LoadingScreen(); } const { name, strategy } = lastUsedConnection(m); const skipped = m.getIn(["sso", "skipped"], false); return !skipped && isConnectionEnabled(m, name) ? new LastLoginScreen() : null; } export function lastUsedConnection(m) { // { name, strategy } return m.getIn(["sso", "lastUsedConnection"], Map()).toJS(); } export function lastUsedUsername(m) { return m.getIn(["sso", "lastUsedUsername"], ""); } export function skipSSOLogin(m) { return m.setIn(["sso", "skipped"], true); }
Fix duplicated ? on query string
const omit = require('lodash/omit') const qs = require('qs') const oauth = require('../lib/oauth') exports.mergeQueryWithURL = (url, ...queryObjs) => { const [, urlWithoutQuery, queryStringFromURL] = (url || '').match(/([^?]+)[?]?(.*)/) || [] const queryFromURL = qs.parse(queryStringFromURL) const mergedQuery = Object.assign({}, ...queryObjs, queryFromURL) const mergedQueryString = qs.stringify(mergedQuery) || '' return `${urlWithoutQuery || ''}?${mergedQueryString}` } exports.getBaseCallbackURL = req => `${oauth.getCurrentHostURL(req)}/callback` exports.getCallbackURLWithQuery = (req, query = req.query) => { return exports.mergeQueryWithURL( exports.getBaseCallbackURL(req), omit(query, [ 'client_id', 'code', 'grant_type', 'redirect_uri', 'response_type', 'scope', ]) ) }
const omit = require('lodash/omit') const qs = require('qs') const oauth = require('../lib/oauth') exports.mergeQueryWithURL = (url, ...queryObjs) => { const [, urlWithoutQuery, queryStringFromURL] = (url || '').match(/([^?]+[?]?)(.*)/) || [] const queryFromURL = qs.parse(queryStringFromURL) const mergedQuery = Object.assign({}, ...queryObjs, queryFromURL) const mergedQueryString = qs.stringify(mergedQuery) || '' return `${urlWithoutQuery || ''}?${mergedQueryString}` } exports.getBaseCallbackURL = req => `${oauth.getCurrentHostURL(req)}/callback` exports.getCallbackURLWithQuery = (req, query = req.query) => { return exports.mergeQueryWithURL( exports.getBaseCallbackURL(req), omit(query, [ 'client_id', 'code', 'grant_type', 'redirect_uri', 'response_type', 'scope', ]) ) }
Change _oport and _iport to weakref for prevention of loop references
# -*- coding: utf-8 -*- import ioport import weakref class Connection(object): """ Connection class for IPFBlock Connection binding OPort and IPort of some IPFBlocks """ def __init__(self, oport, iport): # Check port compatibility and free of input port if ioport.is_connect_allowed(oport, iport): self._oport = weakref.ref(oport) self._iport = weakref.ref(iport) self._oport().increase_binded_count() self._iport().set_binded() else: raise ValueError("Can not create Connection with given ports") def __del__(self): self._oport().decrease_binded_count() self._iport().set_free() def contains_port(self, port): return self._iport() == port or self._oport() == port def process(self): """ Send value from output port to input port """ self._iport().pass_value(self._oport().get_value())
# -*- coding: utf-8 -*- import ioport class Connection(object): """ Connection class for IPFBlock Connection binding OPort and IPort of some IPFBlocks """ def __init__(self, oport, iport): # Check port compatibility and free of input port if ioport.is_connect_allowed(oport, iport): self._oport = oport self._iport = iport self._oport.increase_binded_count() self._iport.set_binded() else: raise ValueError("Can not create Connection with given ports") def __del__(self): self._oport.decrease_binded_count() self._iport.set_free() def contains_port(self, port): return self._iport == port or self._oport == port def process(self): """ Send value from output port to input port """ self._iport.pass_value(self._oport.get_value())
Change default output behaviour to output to STDIO
#!/usr/bin/env nodejs // Autoformatter for Turing const fs = require('fs'), argv = require('minimist')(process.argv.slice(2), {boolean:true}); var files = argv._; // Check for flags, and process them var flags = argv.flags || null; var format = require('./format.js')(flags); /** * Main procedure */ files.forEach(file => { fs.readFile(file, 'utf8', (err, data) => { var ext = (argv.e || argv.extension) || ""; var out = (argv.o || argv.out) || file + ext; if (err) throw err; data = format.format(data); if ((argv.e || argv.extension) || (argv.o || argv.out) || (argv.r || argv.replace)) { fs.writeFile(out, data, err => { if (err) throw err; console.log(out + " has been saved"); }); } else { console.log(data); } }); });
#!/usr/bin/env nodejs // Autoformatter for Turing const fs = require('fs'), argv = require('minimist')(process.argv.slice(2), {boolean:true}); var files = argv._; // Check for flags, and process them var flags = argv.flags || null; var format = require('./format.js')(flags); console.log(argv) /** * Main procedure */ files.forEach(file => { fs.readFile(file, 'utf8', (err, data) => { var ext = (argv.e || argv.extension) || ""; var out = (argv.o || argv.out) || file + ext; if (err) throw err; data = format.format(data); if (argv.s || argv.stdio) { console.log(data); } else { fs.writeFile(out, data, err => { if (err) throw err; console.log(out + " has been saved"); }); } }); });
Set docdown style to github. [ci skip]
#!/usr/bin/env node var _ = require('lodash'); var docdown = require('docdown'); var fs = require('fs'); var path = require('path'); var srcPath = path.join(__dirname, '../src'); var outPath = path.join(__dirname, '../docs'); // Define which files to scan var sourceFiles = [ 'tree.js', 'treenode.js', 'treenodes.js' ]; // Create output directory if (!fs.existsSync(outPath)) { fs.mkdirSync(outPath); } _.each(sourceFiles, function(sourceFile) { var markdown = docdown({ title: '', toc: 'categories', path: path.join(srcPath, sourceFile), style: 'github', url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile }); var docName = sourceFile.split('/').pop().replace('.js', '.md'); // Write file fs.writeFile(path.join(outPath, docName), markdown, function(err) { if (err) { console.log('Error writing to file:'); console.log(err); return; } console.log('Wrote output for ' + sourceFile); }); });
#!/usr/bin/env node var _ = require('lodash'); var docdown = require('docdown'); var fs = require('fs'); var path = require('path'); var srcPath = path.join(__dirname, '../src'); var outPath = path.join(__dirname, '../docs'); // Define which files to scan var sourceFiles = [ 'tree.js', 'treenode.js', 'treenodes.js' ]; // Create output directory if (!fs.existsSync(outPath)) { fs.mkdirSync(outPath); } _.each(sourceFiles, function(sourceFile) { var markdown = docdown({ title: '', toc: 'categories', path: path.join(srcPath, sourceFile), url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile }); var docName = sourceFile.split('/').pop().replace('.js', '.md'); // Write file fs.writeFile(path.join(outPath, docName), markdown, function(err) { if (err) { console.log('Error writing to file:'); console.log(err); return; } console.log('Wrote output for ' + sourceFile); }); });
Apply same rounding as Hive does when converting text to decimal
/* * 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 com.facebook.presto.hive; import com.facebook.presto.spi.type.DecimalType; import java.math.BigDecimal; import static com.facebook.presto.spi.type.Decimals.rescale; import static java.math.RoundingMode.HALF_UP; import static java.nio.charset.StandardCharsets.UTF_8; public final class HiveDecimalParser { private HiveDecimalParser() {} public static BigDecimal parseHiveDecimal(byte[] bytes, int start, int length, DecimalType columnType) { BigDecimal parsed = new BigDecimal(new String(bytes, start, length, UTF_8)); if (parsed.scale() > columnType.getScale()) { // Hive rounds HALF_UP too parsed = parsed.setScale(columnType.getScale(), HALF_UP); } return rescale(parsed, columnType); } }
/* * 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 com.facebook.presto.hive; import com.facebook.presto.spi.type.DecimalType; import java.math.BigDecimal; import static com.facebook.presto.spi.type.Decimals.rescale; import static java.nio.charset.StandardCharsets.UTF_8; public final class HiveDecimalParser { private HiveDecimalParser() {} public static BigDecimal parseHiveDecimal(byte[] bytes, int start, int length, DecimalType columnType) { return rescale(new BigDecimal(new String(bytes, start, length, UTF_8)), columnType); } }
Fix reserved field name setting
import sys from .base import Field class Reserved(Field): def __init__(self, *args, **kwargs): super(Reserved, self).__init__(*args, **kwargs) # Hack to add the reserved field to the class without # having to explicitly give it a (likely useless) name frame = sys._getframe(2) locals = frame.f_locals locals[self.get_available_name(locals.keys())] = self def get_available_name(self, locals): i = 0 while True: name = '_reserved_%s' % i if name not in locals: return name i += 1 def set_name(self, name): if hasattr(self, 'name'): raise TypeError('Reserved fields must not be given an attribute name') super(Reserved, self).set_name(name) def encode(self, value): return b'\x00' * self.size def decode(self, value): return None
import sys from .base import Field class Reserved(Field): def __init__(self, *args, **kwargs): super(Reserved, self).__init__(*args, **kwargs) # Hack to add the reserved field to the class without # having to explicitly give it a (likely useless) name frame = sys._getframe(2) locals = frame.f_locals locals[self.get_available_name(locals.keys())] = self def get_available_name(self, locals): i = 0 while True: name = '_reserved_%s' % i if name not in locals: return name i += 1 def set_name(self, name): if self.name: raise TypeError('Reserved fields must not be given an attribute name') super(Reserved, self).set_name(name) def encode(self, value): return b'\x00' * self.size def decode(self, value): return None
Mark dojango as 0.5.7 alpha
VERSION = (0, 5, 7, 'alpha', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
VERSION = (0, 5, 6, 'final', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
Fix ESLint error & onChange handler
import React, { Component } from 'react'; import { Line } from 'rc-progress'; import Form from 'shared/components/form/form'; import PropTypes from 'prop-types'; import FormSelect from 'shared/components/form/formSelect/formSelect'; import { MILSTATUS, BRANCH } from 'shared/constants/status'; import styles from './formComponents.css'; class MilitaryInfo extends Component { render() { return ( <Form className={styles.signup}> <h3>Progress = {this.props.percent}%</h3> <Line percent={this.props.percent} strokeWidth="4" strokeColor="green" /> <FormSelect id="militaryStatus" options={MILSTATUS} prompt="Current Military Status" onChange={e => this.props.update(e, e.target.value)} /> <FormSelect id="branch" options={BRANCH} prompt="Branch / Affiliation" onChange={e => this.props.update(e, e.target.value)} /> </Form> ); } } MilitaryInfo.propTypes = { update: PropTypes.func, percent: PropTypes.string }; MilitaryInfo.defaultProps = { update: null, percent: '0' }; export default MilitaryInfo;
import React, { Component } from 'react'; import { Line } from 'rc-progress'; import Form from 'shared/components/form/form'; import PropTypes from 'prop-types'; import FormSelect from 'shared/components/form/formSelect/formSelect'; import { MILSTATUS, BRANCH } from 'shared/constants/status'; import styles from './formComponents.css'; class MilitaryInfo extends Component { constructor(props) { super(props); } render() { return ( <Form className={styles.signup}> <h3>Progress = {this.props.percent}%</h3> <Line percent={this.props.percent} strokeWidth="4" strokeColor="green" /> <FormSelect id="militaryStatus" options={MILSTATUS} prompt="Current Military Status" onChange={e => this.onChange(e)} /> <FormSelect id="branch" options={BRANCH} prompt="Branch / Affiliation" onChange={e => this.props.update(e, e.target.value)} /> </Form> ); } } MilitaryInfo.propTypes = { update: PropTypes.func, percent: PropTypes.string }; MilitaryInfo.defaultProps = { update: null, percent: '0' }; export default MilitaryInfo;
Integrate with modified property, dupairs, of AnalyzedCFG
/** * Created by ChengFuLin on 2015/6/10. */ var factoryAnalyzedCFG = require('../../lib/dujs').factoryAnalyzedCFG, should = require('should'); describe('AnalyzedCFGFactory', function () { "use strict"; describe('Factory Method', function () { it('should support to create empty AnalyzedCFG', function () { var analyzedCFG = factoryAnalyzedCFG.create(); should.not.exist(analyzedCFG._testonly_._cfg); should.exist(analyzedCFG._testonly_._scopeWrappers); analyzedCFG._testonly_._scopeWrappers.length.should.eql(0); should.exist(analyzedCFG._testonly_._dupairs); analyzedCFG._testonly_._dupairs.size.should.eql(0); }); }); });
/** * Created by ChengFuLin on 2015/6/10. */ var factoryAnalyzedCFG = require('../../lib/dujs').factoryAnalyzedCFG, should = require('should'); describe('AnalyzedCFGFactory', function () { "use strict"; describe('Factory Method', function () { it('should support to create empty AnalyzedCFG', function () { var analyzedCFG = factoryAnalyzedCFG.create(); should.not.exist(analyzedCFG._testonly_._cfg); should.exist(analyzedCFG._testonly_._scopeWrappers); analyzedCFG._testonly_._scopeWrappers.length.should.eql(0); should.exist(analyzedCFG._testonly_._dupairs); analyzedCFG._testonly_._dupairs.length.should.eql(0); }); }); });
Allow matching nodes with a function
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
Fix my cats press on keyboard
package fr.free.nrw.commons.theme; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import fr.free.nrw.commons.R; public class BaseAppCompatActivity extends AppCompatActivity { boolean currentTheme; @Override protected void onCreate(Bundle savedInstanceState) { if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false)) { currentTheme = true; setTheme(R.style.DarkAppTheme); }else { currentTheme = false; setTheme(R.style.LightAppTheme); //default } super.onCreate(savedInstanceState); } @Override protected void onResume() { //Restart activity if theme is changed Log.d("deneme","onResume Base"); boolean newTheme = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false); if(currentTheme!=newTheme){ //is activity theme changed Intent intent = getIntent(); finish(); startActivity(intent); } super.onResume(); } }
package fr.free.nrw.commons.theme; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import fr.free.nrw.commons.R; public class BaseAppCompatActivity extends AppCompatActivity { boolean currentTheme; @Override protected void onCreate(Bundle savedInstanceState) { if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false)) { currentTheme = true;g setTheme(R.style.DarkAppTheme); }else { currentTheme = false; setTheme(R.style.LightAppTheme); //default } super.onCreate(savedInstanceState); } @Override protected void onResume() { //Restart activity if theme is changed Log.d("deneme","onResume Base"); boolean newTheme = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false); if(currentTheme!=newTheme){ //is activity theme changed Intent intent = getIntent(); finish(); startActivity(intent); } super.onResume(); } }
Add method to retrieve the DomainError as a dict.
# -*- coding: utf-8 -*- from flask import jsonify def register_error_handlers(app): app.register_error_handler(EntityNotFoundError, entity_not_found_handler) app.register_error_handler(InvalidInputError, invalid_input_handler) def entity_not_found_handler(e): return jsonify(e.as_dict()), 404 def invalid_input_handler(e): return jsonify(e.as_dict()), 400 class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details def as_dict(self): data = {} if self.message: data['message'] = self.message if self.details: data['details'] = self.details return data class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
# -*- coding: utf-8 -*- from flask import jsonify def register_error_handlers(app): app.register_error_handler(EntityNotFoundError, entity_not_found_handler) app.register_error_handler(InvalidInputError, invalid_input_handler) def entity_not_found_handler(e): return jsonify({'message': e.message}), 404 def invalid_input_handler(e): return jsonify({'message': e.message, 'details': e.details}), 400 class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
Modify Textfiled component to not change background to dark grey when it is disabled.
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachChangeAction( self.node(), self.identifier() ); }; self.registerAction('change', function() { self.setState('text-value', self.node().value); }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; }; self.disable = function() { self._enabled = false; self.node().readOnly = true; }; return self; }
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachChangeAction( self.node(), self.identifier() ); }; self.registerAction('change', function() { self.setState('text-value', self.node().value); }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; self.node().style.backgroundColor = (self.__previousBackgroundColor ? self.__previousBackgroundColor : '#fff'); }; self.disable = function() { self._enabled = false; self.node().readOnly = true; self.__previousBackgroundColor = self.node().style.backgroundColor; self.node().style.backgroundColor = '#ddd'; }; return self; }
Fix HTTPClientHandlerInterface in Laravel Config.
<?php return [ /* |-------------------------------------------------------------------------- | Telegram Bot API Access Token [REQUIRED] |-------------------------------------------------------------------------- | | Your Telegram's Bot Access Token. | Example: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 | | Refer for more details: | https://core.telegram.org/bots#botfather | */ 'bot_token' => env('TELEGRAM_BOT_TOKEN', 'YOUR-BOT-TOKEN'), /* |-------------------------------------------------------------------------- | Asynchronous Requests [Optional] |-------------------------------------------------------------------------- | | When set to True, All the requests would be made non-blocking (Async). | | Default: false | Possible Values: (Boolean) "true" OR "false" | */ 'async_requests' => env('TELEGRAM_ASYNC_REQUESTS', false), /* |-------------------------------------------------------------------------- | HTTP Client Handler [Optional] |-------------------------------------------------------------------------- | | If you'd like to use a custom HTTP Client Handler. | Should be an instance of \Irazasyed\Telegram\HttpClients\HttpClientInterface | | Default: GuzzlePHP | */ 'http_client_handler' => null, ];
<?php return [ /* |-------------------------------------------------------------------------- | Telegram Bot API Access Token [REQUIRED] |-------------------------------------------------------------------------- | | Your Telegram's Bot Access Token. | Example: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 | | Refer for more details: | https://core.telegram.org/bots#botfather | */ 'bot_token' => env('TELEGRAM_BOT_TOKEN', 'YOUR-BOT-TOKEN'), /* |-------------------------------------------------------------------------- | Asynchronous Requests [Optional] |-------------------------------------------------------------------------- | | When set to True, All the requests would be made non-blocking (Async). | | Default: false | Possible Values: (Boolean) "true" OR "false" | */ 'async_requests' => env('TELEGRAM_ASYNC_REQUESTS', false), /* |-------------------------------------------------------------------------- | HTTP Client Handler [Optional] |-------------------------------------------------------------------------- | | If you'd like to use a custom HTTP Client Handler. | Should be an instance of \Irazasyed\Telegram\HttpClients\TelegramHttpClientInterface | | Default: GuzzlePHP | */ 'http_client_handler' => null, ];
Fix issues with HTMLBars parser transition.
'use strict'; var assert = require('assert'); var _compile = require('htmlbars').compile; describe('Ember template compiler', function() { var astPlugins; function compile(template) { return _compile(template, { plugins: { ast: astPlugins } }); } beforeEach(function() { astPlugins = []; }); it('sanity: compiles templates', function() { var template = compile('<div></div>'); assert.ok(template, 'template is created'); }); it('sanity: loads plugins on the template compiler', function() { var instanceCount = 0; var NoopPlugin = function(){ instanceCount++; }; NoopPlugin.prototype.transform = function(ast) { return ast; }; astPlugins.push(NoopPlugin); compile('<div></div>'); assert.equal(instanceCount, 1, 'registered plugins are instantiated'); }); });
'use strict'; var assert = require('assert'); var buildTemplateCompiler = require('../helpers/template-compiler'); describe('Ember template compiler', function() { var templateCompiler; beforeEach(function() { templateCompiler = buildTemplateCompiler(); }); it('sanity: compiles templates', function() { var template = templateCompiler.precompile('<div></div>'); assert.ok(template, 'template is created from precompile'); }); it('sanity: loads plugins on the template compiler', function() { var instanceCount = 0; var NoopPlugin = function(){ instanceCount++; }; NoopPlugin.prototype.transform = function(ast) { return ast; }; templateCompiler.registerPlugin('ast', NoopPlugin); templateCompiler.precompile('<div></div>'); assert.equal(instanceCount, 1, 'registered plugins are instantiated'); }); });
Fix BERT -> bert in bert_tasks
import unittest from nose.tools import nottest from metal.mmtl.bert_tasks import create_tasks from metal.mmtl.metal_model import MetalModel from metal.mmtl.trainer import MultitaskTrainer @nottest class MMTLTest(unittest.TestCase): @classmethod def setUpClass(cls): task_names = [ "COLA", "SST2", "MNLI", "RTE", "WNLI", "QQP", "MRPC", "STSB", "QNLI", ] cls.tasks = create_tasks( task_names, max_datapoints=100, max_len=200, dl_kwargs={"batch_size": 8} ) def test_mmtl_training(self): model = MetalModel(self.tasks, verbose=False) trainer = MultitaskTrainer(verbose=False) trainer.train_model(model, self.tasks, n_epochs=1) if __name__ == "__main__": unittest.main()
import unittest from nose.tools import nottest from metal.mmtl.BERT_tasks import create_tasks from metal.mmtl.metal_model import MetalModel from metal.mmtl.trainer import MultitaskTrainer @nottest class MMTLTest(unittest.TestCase): @classmethod def setUpClass(cls): task_names = [ "COLA", "SST2", "MNLI", "RTE", "WNLI", "QQP", "MRPC", "STSB", "QNLI", ] cls.tasks = create_tasks( task_names, max_datapoints=100, max_len=200, dl_kwargs={"batch_size": 8} ) def test_mmtl_training(self): model = MetalModel(self.tasks, verbose=False) trainer = MultitaskTrainer(verbose=False) trainer.train_model(model, self.tasks, n_epochs=1) if __name__ == "__main__": unittest.main()
Remove old route that is no longer in user
const express = require('express') const users = require('../Controllers/userCtrl') const jwt = require('../Lib/jwt.js') const router = express.Router() const isAuthenticated = function(req, res, next) { const token = req.get("Authorization") const decoded = jwt.decode(token) if (typeof decoded === 'object') { console.log("token successfuly decoded: ", decoded) res.status(200) next() } else { console.log('ERROR, INCORRECT ACCESS TOKEN') res.status(400).end() } } router.use(isAuthenticated) router.route('/') .post(users.createUser) //add user router.route('/:userId') .get(users.getUser) //get user .put(users.updateUser) //update user information router.route('/:userId/saved') .get(users.getSavedPins) .post(users.createPin) //add new pin .delete(users.deletePin) //delete pin router.route('/:userId/created') .get(users.getCreatedPins) .delete(users.deleteSpot) //delete spot module.exports = router
const express = require('express') const users = require('../Controllers/userCtrl') const jwt = require('../Lib/jwt.js') const router = express.Router() const isAuthenticated = function(req, res, next) { const token = req.get("Authorization") const decoded = jwt.decode(token) if (typeof decoded === 'object') { console.log("token successfuly decoded: ", decoded) res.status(200) next() } else { console.log('ERROR, INCORRECT ACCESS TOKEN') res.status(400).end() } } router.use(isAuthenticated) router.route('/') .post(users.createUser) //add user router.route('/:userId') .get(users.getUser) //get user .put(users.updateUser) //update user information router.route('/:userId/saved') .get(users.getSavedPins) .post(users.createPin) //add new pin .delete(users.deletePin) //delete pin router.route('/:userId/created') .get(users.getCreatedPins) .post(users.createSpot) //add new spot .delete(users.deleteSpot) //delete spot module.exports = router
Simplify arguments passed to exec.
var gulp = require("gulp"); var CFG = require("./utils/config.js"); var $ = require("gulp-load-plugins")(); var exec = require("child_process").exec; var path = require("path"); var notify = require("./utils/notify-style-lint"); /** * style:lint * @see github.com/causes/scss-lint * @see rubygems.org/gems/scss-lint */ gulp.task("style:lint", function (callback) { var scsslintProcess = exec([ "bundle", "exec", "scss-lint", "--config", path.join(CFG.FILE.config.styleLint), path.join(CFG.DIR.src, CFG.DIR.style) ].join(" "), function(err, stdout, stderr) { $.util.log("[style:lint] stdout:", stdout); $.util.log("[style:lint] stderr: ", stderr); notify(stdout); if(null !== err) { $.util.log("[style:lint] err: ", err); } callback(); }); });
var gulp = require("gulp"); var CFG = require("./utils/config.js"); var $ = require("gulp-load-plugins")(); var exec = require("child_process").exec; var path = require("path"); var notify = require("./utils/notify-style-lint"); /** * style:lint * @see github.com/causes/scss-lint * @see rubygems.org/gems/scss-lint */ gulp.task("style:lint", function (callback) { var scsslintProcess = exec("bundle " + [ "exec", "scss-lint", "--config", path.join(CFG.FILE.config.styleLint), path.join(CFG.DIR.src, CFG.DIR.style) ].join(" "), function(err, stdout, stderr) { $.util.log("[style:lint] stdout:", stdout); $.util.log("[style:lint] stderr: ", stderr); notify(stdout); if(null !== err) { $.util.log("[style:lint] err: ", err); } callback(); }); });
Fix bug in legends magic.
var LegendFactory = require('../editor/layers/layer-content-views/legend/legend-factory'); var onChange = function (layerDefModel) { var styleModel = layerDefModel.styleModel; var canSuggestLegends = !LegendFactory.hasMigratedLegend(layerDefModel); var fill; var color; var size; if (!styleModel) return; if (!canSuggestLegends) return; LegendFactory.removeAllLegend(layerDefModel); fill = styleModel.get('fill'); if (!fill) return; color = fill.color; size = fill.size; if (size && size.attribute !== undefined) { LegendFactory.createLegend(layerDefModel, 'bubble'); } if (color && color.attribute !== undefined) { if (color.attribute_type && color.attribute_type === 'string') { LegendFactory.createLegend(layerDefModel, 'category'); } else { LegendFactory.createLegend(layerDefModel, 'choropleth'); } } }; module.exports = { track: function (layerDefModel) { layerDefModel.on('change:cartocss', onChange); layerDefModel.on('destroy', function () { layerDefModel.off('change:cartocss', onChange); }); } };
var LegendFactory = require('../editor/layers/layer-content-views/legend/legend-factory'); var onChange = function (layerDefModel) { var styleModel = layerDefModel.styleModel; var canSuggestLegends = LegendFactory.hasMigratedLegend(layerDefModel); var fill; var color; var size; if (!styleModel) return; if (!canSuggestLegends) return; LegendFactory.removeAllLegend(layerDefModel); fill = styleModel.get('fill'); color = fill.color; size = fill.size; if (size && size.attribute !== undefined) { LegendFactory.createLegend(layerDefModel, 'bubble'); } if (color && color.attribute !== undefined) { if (color.attribute_type && color.attribute_type === 'string') { LegendFactory.createLegend(layerDefModel, 'category'); } else { LegendFactory.createLegend(layerDefModel, 'choropleth'); } } }; module.exports = { track: function (layerDefModel) { layerDefModel.on('change:cartocss', onChange); layerDefModel.on('destroy', function () { layerDefModel.off('change:cartocss', onChange); }); } };
Disable WebSocket in 'ruby-runtime-opal' modular-module
if (typeof globalThis === 'undefined') { // define `globalThis` for IE self.globalThis = this; } self.importScripts('opal.min.js'); // disable network access self.importScripts = null; self.XMLHttpRequest = null; self.fetch = null; self.WebSocket = null; var Opal = self.Opal; var input = null; var output = ''; var error = ''; Opal.global.console.log = function(s) { output += s; }; Opal.global.console.warn = function(s) { error += s; }; Opal.STDIN.$read = function() { if (arguments.length !== 0) { throw 'read: not implemented'; } return (input !== null ? input : Opal.nil); }; self.addEventListener('message', function(event) { var data = event.data; input = data.input; output = ''; error = ''; try { Opal.eval(data.code); } catch (e) { self.postMessage({ output: null, error: null, exception: e.toString() || 'undefined exception', }); return; } self.postMessage({ output: output, error: error, exception: '', }); }, false);
if (typeof globalThis === 'undefined') { // define `globalThis` for IE self.globalThis = this; } self.importScripts('opal.min.js'); // disable network access self.importScripts = null; self.XMLHttpRequest = null; self.fetch = null; var Opal = self.Opal; var input = null; var output = ''; var error = ''; Opal.global.console.log = function(s) { output += s; }; Opal.global.console.warn = function(s) { error += s; }; Opal.STDIN.$read = function() { if (arguments.length !== 0) { throw 'read: not implemented'; } return (input !== null ? input : Opal.nil); }; self.addEventListener('message', function(event) { var data = event.data; input = data.input; output = ''; error = ''; try { Opal.eval(data.code); } catch (e) { self.postMessage({ output: null, error: null, exception: e.toString() || 'undefined exception', }); return; } self.postMessage({ output: output, error: error, exception: '', }); }, false);
Make object wrapper function idempotent
package com.btk5h.skriptmirror; import ch.njol.skript.registrations.Classes; import java.util.Arrays; public class ObjectWrapper { protected Object object; private ObjectWrapper(Object object) { this.object = object; } public static ObjectWrapper create(Object object) { if (object instanceof ObjectWrapper) { return (ObjectWrapper) object; } if (object.getClass().isArray()) { return new OfArray((Object[]) object); } return new ObjectWrapper(object); } public static Object wrapIfNecessary(Object returnedValue) { Class<?> returnedClass = returnedValue.getClass(); if (returnedClass.isArray()) { returnedValue = create(Util.boxPrimitiveArray(returnedValue)); } else if (Classes.getSuperClassInfo(returnedClass).getC() == Object.class) { returnedValue = create(returnedValue); } return returnedValue; } public Object get() { return object; } @Override public String toString() { return object.toString(); } public static class OfArray extends ObjectWrapper { private OfArray(Object[] object) { super(object); } @Override public Object[] get() { return (Object[]) object; } @Override public String toString() { return Arrays.deepToString(get()); } } }
package com.btk5h.skriptmirror; import ch.njol.skript.registrations.Classes; import java.util.Arrays; public class ObjectWrapper { protected Object object; private ObjectWrapper(Object object) { this.object = object; } public static ObjectWrapper create(Object object) { if (object.getClass().isArray()) { return new OfArray((Object[]) object); } return new ObjectWrapper(object); } public static Object wrapIfNecessary(Object returnedValue) { Class<?> returnedClass = returnedValue.getClass(); if (returnedClass.isArray()) { returnedValue = create(Util.boxPrimitiveArray(returnedValue)); } else if (Classes.getSuperClassInfo(returnedClass).getC() == Object.class) { returnedValue = create(returnedValue); } return returnedValue; } public Object get() { return object; } @Override public String toString() { return object.toString(); } public static class OfArray extends ObjectWrapper { private OfArray(Object[] object) { super(object); } @Override public Object[] get() { return (Object[]) object; } @Override public String toString() { return Arrays.deepToString(get()); } } }
Add `version` field in exports
'use strict'; const Engine = require('./Engine'); const PublicSelect = require('./public/PublicSelect'); const PublicApiOptions = require('./PublicApiOptions'); const Explainer = require('./Explainer'); class PublicApi { /** * * @param {PublicApiOptions} options */ constructor(options = new PublicApiOptions) { if (options instanceof PublicApiOptions) { this.options = options; } else { this.options = new PublicApiOptions(options); } this.engine = new Engine(); } /** * * @param {string} sql * @returns {PublicSelect} */ query(sql) { return new PublicSelect(this.engine.createQuery(sql, this.options), this.options.dataSourceResolvers); } explain(select) { const e = new Explainer(); return e.createExplain(select); } } PublicApi.DataSourceResolver = require('./DataSourceResolver'); PublicApi.exceptions = { JlException: require('./error/JlException'), SqlFunctionArgumentError: require('./error/SqlFunctionArgumentError'), SqlLogicError: require('./error/SqlLogicError'), SqlNotSupported: require('./error/SqlNotSupported'), JsonParsingError: require('./error/JsonParsingError'), DataSourceNotFound: require('./error/DataSourceNotFound') }; PublicApi.version = require('../package.json').version; module.exports = PublicApi;
'use strict'; const Engine = require('./Engine'); const PublicSelect = require('./public/PublicSelect'); const PublicApiOptions = require('./PublicApiOptions'); const Explainer = require('./Explainer'); class PublicApi { /** * * @param {PublicApiOptions} options */ constructor(options = new PublicApiOptions) { if (options instanceof PublicApiOptions) { this.options = options; } else { this.options = new PublicApiOptions(options); } this.engine = new Engine(); } /** * * @param {string} sql * @returns {PublicSelect} */ query(sql) { return new PublicSelect(this.engine.createQuery(sql, this.options), this.options.dataSourceResolvers); } explain(select) { const e = new Explainer(); return e.createExplain(select); } } PublicApi.DataSourceResolver = require('./DataSourceResolver'); PublicApi.exceptions = { JlException: require('./error/JlException'), SqlFunctionArgumentError: require('./error/SqlFunctionArgumentError'), SqlLogicError: require('./error/SqlLogicError'), SqlNotSupported: require('./error/SqlNotSupported'), JsonParsingError: require('./error/JsonParsingError'), DataSourceNotFound: require('./error/DataSourceNotFound') }; module.exports = PublicApi;
Remove geopandas - installing geos.dll and gdal is too painful on Windows/Anaconda
from setuptools import setup, find_packages setup( name = "biofloat", version = "0.3.2", packages = find_packages(), requires = ['Python (>=2.7)'], install_requires = [ 'beautifulsoup4>=4.4', 'coverage>=4', 'jupyter>=1.0.0', 'matplotlib', 'numpy>=1.10', 'pandas>=0.17', 'Pydap', 'requests>=2.8', 'seawater>=3.3', 'simpletable>=0.2', 'statsmodels>=0.6.1', 'xray>=0.6' ], scripts = ['scripts/load_biofloat_cache.py', 'scripts/woa_calibration.py'], # metadata for upload to PyPI author = "Mike McCann", author_email = "mccann@mbari.org", description = "Software for working with data from Bio-Argo floats", license = "MIT", keywords = "Oceanography Argo Bio-Argo drifting buoys floats", url = "https://github.com/biofloat/biofloat", )
from setuptools import setup, find_packages setup( name = "biofloat", version = "0.3.1", packages = find_packages(), requires = ['Python (>=2.7)'], install_requires = [ 'beautifulsoup4>=4.4', 'coverage>=4', 'geopandas>=0.1.1', 'jupyter>=1.0.0', 'matplotlib', 'numpy>=1.10', 'pandas>=0.17', 'Pydap', 'requests>=2.8', 'seawater>=3.3', 'simpletable>=0.2', 'statsmodels>=0.6.1', 'xray>=0.6' ], scripts = ['scripts/load_biofloat_cache.py', 'scripts/woa_calibration.py'], # metadata for upload to PyPI author = "Mike McCann", author_email = "mccann@mbari.org", description = "Software for working with data from Bio-Argo floats", license = "MIT", keywords = "Oceanography Argo Bio-Argo drifting buoys floats", url = "https://github.com/biofloat/biofloat", )
ENH: Allow web API parameters to be passed as POST parameters in addition to the normal GET parameters
<?php /*========================================================================= Program: CDash - Cross-Platform Dashboard System Module: $Id$ Language: PHP Date: $Date$ Version: $Revision$ Copyright (c) 2002 Kitware, Inc. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // To be able to access files in this CDash installation regardless // of getcwd() value: // $cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__))); set_include_path($cdashpath . PATH_SEPARATOR . get_include_path()); require_once("cdash/pdo.php"); // Add other api includes here require("api_coverage.php"); require("api_project.php"); require("api_build.php"); require("api_user.php"); if(!isset($_GET['method'])) { echo "Method should be set: method=..."; return; } $method = $_GET['method']; $classname = ucfirst($method).'API'; $class = new $classname; $class->Parameters = array_merge($_GET, $_POST); $results = $class->Run(); // Return json by default echo json_encode($results); ?>
<?php /*========================================================================= Program: CDash - Cross-Platform Dashboard System Module: $Id$ Language: PHP Date: $Date$ Version: $Revision$ Copyright (c) 2002 Kitware, Inc. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // To be able to access files in this CDash installation regardless // of getcwd() value: // $cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__))); set_include_path($cdashpath . PATH_SEPARATOR . get_include_path()); require_once("cdash/pdo.php"); // Add other api includes here require("api_coverage.php"); require("api_project.php"); require("api_build.php"); require("api_user.php"); if(!isset($_GET['method'])) { echo "Method should be set: method=..."; return; } $method = $_GET['method']; $classname = ucfirst($method).'API'; $class = new $classname; $class->Parameters = $_GET; $results = $class->Run(); // Return json by default echo json_encode($results); ?>
Replace texture after rendering sprinkler particle The original particle texture wasn't being bound again to the renderer, and so all particles would use the wrong texture while the sprinkler was active. This commit adds an overriding render method in LiquidSprayFX that sets the texture back after calling the original parent render method.
package com.infinityraider.agricraft.renderers.particles; //heavily inspired by the OpenBlocks sprinkler import com.infinityraider.agricraft.utility.BaseIcons; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class LiquidSprayFX extends AgriCraftFX { public LiquidSprayFX(World world, double x, double y, double z, float scale, float gravity, Vec3d vector) { super(world, x, y, z, scale, gravity, vector, new ResourceLocation("minecraft:textures/blocks/water_still.png")); this.particleMaxAge = 15; this.setSize(0.2f, 0.2f); } @Override public void renderParticle(VertexBuffer worldRenderer, Entity entity, float partialTicks, float f0, float f1, float f2, float f3, float f4) { Minecraft.getMinecraft().renderEngine.bindTexture(this.texture); super.renderParticle(worldRenderer, entity, partialTicks, f0, f1, f2, f3, f4); Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); } }
package com.infinityraider.agricraft.renderers.particles; //heavily inspired by the OpenBlocks sprinkler import com.infinityraider.agricraft.utility.BaseIcons; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class LiquidSprayFX extends AgriCraftFX { public LiquidSprayFX(World world, double x, double y, double z, float scale, float gravity, Vec3d vector) { super(world, x, y, z, scale, gravity, vector, new ResourceLocation("minecraft:textures/blocks/water_still.png")); this.particleMaxAge = 15; this.setSize(0.2f, 0.2f); } }
Add __TRANSFORMERS__ to special keys
var _ = require('underscore'); var async = require('async'); var config = require('./config'); var fs = require('fs'); var mkdirp = require('mkdirp'); var path = require('path'); var META_KEYS = ['__VERSION__', '__IN__', '__TRANSFORMERS__']; var pruneManifest = function (manifest) { return _.reduce(manifest, function (manifest, val, key) { if (_.include(META_KEYS, key)) { manifest[key] = val; } else if (val.targetPaths && val.hash) { manifest[key] = _.omit(val, 'buffer'); } return manifest; }, {}); }; module.exports = function (cb) { var manifestPath = config.get().manifestPath; if (!manifestPath) return cb(); async.series([ _.partial(mkdirp, path.dirname(manifestPath)), _.partial( fs.writeFile, manifestPath, JSON.stringify(pruneManifest(config.get().manifest)) ) ], cb); };
var _ = require('underscore'); var async = require('async'); var config = require('./config'); var fs = require('fs'); var mkdirp = require('mkdirp'); var path = require('path'); var pruneManifest = function (manifest) { return _.reduce(manifest, function (manifest, val, key) { if (key === '__VERSION__' || key === '__IN__') { manifest[key] = val; } else if (val.targetPaths && val.hash) { manifest[key] = _.omit(val, 'buffer'); } return manifest; }, {}); }; module.exports = function (cb) { var manifestPath = config.get().manifestPath; if (!manifestPath) return cb(); async.series([ _.partial(mkdirp, path.dirname(manifestPath)), _.partial( fs.writeFile, manifestPath, JSON.stringify(pruneManifest(config.get().manifest)) ) ], cb); };
Add comments to auth example
<?php namespace Tyrell; use Tonic\Resource, Tonic\Response, Tonic\UnauthorizedException; /** * Simple HTTP authentication example. * * The condition annotation @secure maps to the secure() method allowing us to easily * secure the mySecret() method with the given username and password * * @uri /secret */ class Secret extends Resource { /** * Resource method to handle GET request and return the secret only if the user * has the credentials specified in the @secure annotation. * * @method GET * @secure aUser aPassword * @return str */ function mySecret() { return 'My secret'; } /** * Condition method for the @secure annotation that checks the requests HTTP * authentication details against the username and password given in the annotation. * * @param str $username * @param str $password * @throws UnauthorizedException */ function secure($username, $password) { if ( isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] == $username && isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] == $password ) { return; } #return new Response(401, 'No entry', array('wwwAuthenticate' => 'Basic realm="My Realm"')); throw new UnauthorizedException('No entry'); } }
<?php namespace Tyrell; use Tonic\Resource, Tonic\Response, Tonic\UnauthorizedException; /** * Simple HTTP authentication example. * * The condition annotation @secure maps to the secure() method allowing us to easily * secure the mySecret() method with the given username and password * * @uri /secret */ class Secret extends Resource { /** * @method GET * @secure aUser aPassword */ function mySecret() { return 'My secret'; } function secure($username, $password) { if ( isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] == $username && isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] == $password ) { return; } #return new Response(401, 'No entry', array('wwwAuthenticate' => 'Basic realm="My Realm"')); throw new UnauthorizedException('No entry'); } }
Fix telegram plugin install requires
from setuptools import setup, find_packages version = '0.0.1' setup( name="alerta-telegram", version=version, description='Alerta plugin for Telegram', url='https://github.com/alerta/alerta-contrib', license='MIT', author='Nick Satterly', author_email='nick.satterly@theguardian.com', packages=find_packages(), py_modules=['alerta_telegram'], install_requires=[ 'telepot' ], include_package_data=True, zip_safe=True, entry_points={ 'alerta.plugins': [ 'telegram = alerta_telegram:TelegramBot' ] } )
from setuptools import setup, find_packages version = '0.0.1' setup( name="alerta-telegram", version=version, description='Alerta plugin for Telegram', url='https://github.com/alerta/alerta-contrib', license='MIT', author='Nick Satterly', author_email='nick.satterly@theguardian.com', packages=find_packages(), py_modules=['alerta_telegram'], install_requires=[ 'telebot' ], include_package_data=True, zip_safe=True, entry_points={ 'alerta.plugins': [ 'telegram = alerta_telegram:TelegramBot' ] } )
Use empty(). Add hasFailed() method
<?php namespace PHPCheckstyle\PHPCheckstyle; use PHPCheckstyle\Exception; use SeekableIterator; use SplDoublyLinkedList; /** * Result of running a check. */ class CheckResult { /** * Violations held against the file. * @var array */ protected $violations = array(); /** * Returns whether check succeeded. * @return bool */ public function hasSucceeded() { return empty($this->violations); } public function hasFailed() { return empty($this->violations) === FALSE; } /** * Return all of the violations on the file. * Violations are sorted on a line/column basis. * @return array */ public function getViolations() { return $this->violations; } public function addViolation(Violation $violation) { $this->violations[] = $violation; usort($this->violations, function(Violation $a, Violation $b) { if ($a->getLine() === $b->getLine()) { if ($a->getColumn() === $b->getColumn()) { return 0; } return ($a->getColumn() < $b->getColumn() ? -1 : 1); } return ($a->getLine() < $b->getLine() ? -1 : 1); }); } }
<?php namespace PHPCheckstyle\PHPCheckstyle; use PHPCheckstyle\Exception; use SeekableIterator; use SplDoublyLinkedList; /** * Result of running a check. */ class CheckResult { /** * Violations held against the file. * @var array */ protected $violations = array(); /** * Returns whether check succeeded. * @return bool */ public function hasSucceeded() { return count($this->violations) === 0; } /** * Return all of the violations on the file. * Violations are sorted on a line/column basis. * @return array */ public function getViolations() { return $this->violations; } public function addViolation(Violation $violation) { $this->violations[] = $violation; usort($this->violations, function(Violation $a, Violation $b) { if ($a->getLine() === $b->getLine()) { if ($a->getColumn() === $b->getColumn()) { return 0; } return ($a->getColumn() < $b->getColumn() ? -1 : 1); } return ($a->getLine() < $b->getLine() ? -1 : 1); }); } }
Fix unit test for DeprecationLogger #689 +review REVIEW-6216
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.internal.featurelifecycle; public class SimulatedDeprecationMessageLogger { public static final String DIRECT_CALL = "direct call"; public static final String INDIRECT_CALL = "indirect call"; public static final String INDIRECT_CALL_2 = "second-level indirect call"; public static DeprecatedFeatureUsage indirectlySecondLevel(String message) { return indirectly(message); } public static DeprecatedFeatureUsage indirectly(String message) { return nagUserWith(message); } public static DeprecatedFeatureUsage nagUserWith(String message) { return new DeprecatedFeatureUsage(message, SimulatedDeprecationMessageLogger.class).withStackTrace(); } }
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.internal.featurelifecycle; public class SimulatedDeprecationMessageLogger { public static final String DIRECT_CALL = "direct call"; public static final String INDIRECT_CALL = "indirect call"; public static final String INDIRECT_CALL_2 = "second-level indirect call"; public static DeprecatedFeatureUsage indirectlySecondLevel(String message) { return indirectly(message); } public static DeprecatedFeatureUsage indirectly(String message) { return nagUserWith(message); } public static DeprecatedFeatureUsage nagUserWith(String message) { return new DeprecatedFeatureUsage(message, SimulatedDeprecationMessageLogger.class); } }
Handle new AndroidManifest.xml location in cordova-android@^7.0.0
module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), path = ctx.requireCordovaModule('path'), xml = ctx.requireCordovaModule('cordova-common').xmlHelpers; //manifest path of cordova-android@7+ projects var manifestPath = path.join(ctx.opts.projectRoot, 'platforms/android/app/src/main/AndroidManifest.xml'); if (!fs.existsSync(manifestPath)) { //fall back to legacy manifest path manifestPath = path.join(ctx.opts.projectRoot, 'platforms/android/AndroidManifest.xml'); } var doc = xml.parseElementtreeSync(manifestPath); if (doc.getroot().tag !== 'manifest') { throw new Error(manifestPath + ' has incorrect root node name (expected "manifest")'); } //adds the tools namespace to the root node // doc.getroot().attrib['xmlns:tools'] = 'http://schemas.android.com/tools'; //add tools:replace in the application node doc.getroot().find('./application').attrib['android:name'] = 'android.support.multidex.MultiDexApplication'; //write the manifest file fs.writeFileSync(manifestPath, doc.write({indent: 4}), 'utf-8'); };
module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), path = ctx.requireCordovaModule('path'), xml = ctx.requireCordovaModule('cordova-common').xmlHelpers; var manifestPath = path.join(ctx.opts.projectRoot, 'platforms/android/AndroidManifest.xml'); var doc = xml.parseElementtreeSync(manifestPath); if (doc.getroot().tag !== 'manifest') { throw new Error(manifestPath + ' has incorrect root node name (expected "manifest")'); } //adds the tools namespace to the root node // doc.getroot().attrib['xmlns:tools'] = 'http://schemas.android.com/tools'; //add tools:replace in the application node doc.getroot().find('./application').attrib['android:name'] = 'android.support.multidex.MultiDexApplication'; //write the manifest file fs.writeFileSync(manifestPath, doc.write({indent: 4}), 'utf-8'); };
Break the build to test Hudson git-svn-id: ec6ef1d57ec0831ce4cbff3b75527511e63bfbe3@736933 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.jsecurity.util; BREAK BUILD /** * Interface implemented by components that can be named, such as via configuration, and wish to have that name * set once it has been configured. * * @author Les Hazlewood * @since 0.9 */ public interface Nameable { /** * Sets the (preferably application unique) name for this component. * @param name the preferably application unique name for this component. */ void setName(String name); }
/* * 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.jsecurity.util; /** * Interface implemented by components that can be named, such as via configuration, and wish to have that name * set once it has been configured. * * @author Les Hazlewood * @since 0.9 */ public interface Nameable { /** * Sets the (preferably application unique) name for this component. * @param name the preferably application unique name for this component. */ void setName(String name); }
Plugins: Make it easier to integrate commercial plugins.
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # 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. # """ Commercial plugins package. This may load code from places indicated by a heuristics. """ # Auto extend to a Nuitka commercial installation, by adding it to the package # path. That aims at making extending Nuitka with these plugins easier. import os if "NUITKA_COMMERCIAL" in os.environ: path = os.environ["NUITKA_COMMERCIAL"] for candidate in "nuitka/plugins/commercial", ".": candidate = os.path.join(path, candidate) if os.path.isdir(candidate) and os.path.isfile( os.path.join(candidate, "__init__.py") ): __path__.append(candidate)
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # 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. # """ Dummy file to make this directory a package. """
Support for stories without owners.
var _ = require('lodash'); exports.printSeparator = function (s) { console.log((new Array(51)).join(s || "-")); }; exports.printObject = function (object, indent) { function padRight(string, length) { return string + (new Array((length - string.length) + 1).join(" ")); } var indentPad = Array(indent).join(" ") || "", names = _.keys(object), longestName = names.reduce(function (currentLongestName, name) { return name.length > currentLongestName.length ? name : currentLongestName; }, ""); names.forEach(function (name) { console.log(indentPad + padRight(name + ": ", longestName.length + 2) + object[name]); }); }; exports.printStory = function (story, content) { exports.printSeparator("="); console.log(story.id.toString().cyan + " | " + "Phase: ".cyan + story.phase.name + (story.owner ? " | " + "Owner: ".cyan + story.owner.name : "")) exports.printSeparator("="); console.log(story.text[story.color]); exports.printSeparator(); if (content) { console.log(content); exports.printSeparator(); } if (story.blockedReason) { console.log(story.blockedReason.red); exports.printSeparator(); } };
var _ = require('lodash'); exports.printSeparator = function (s) { console.log((new Array(51)).join(s || "-")); }; exports.printObject = function (object, indent) { function padRight(string, length) { return string + (new Array((length - string.length) + 1).join(" ")); } var indentPad = Array(indent).join(" ") || "", names = _.keys(object), longestName = names.reduce(function (currentLongestName, name) { return name.length > currentLongestName.length ? name : currentLongestName; }, ""); names.forEach(function (name) { console.log(indentPad + padRight(name + ": ", longestName.length + 2) + object[name]); }); }; exports.printStory = function (story, content) { exports.printSeparator("="); console.log(story.id.toString().cyan + " | " + "Phase: ".cyan + story.phase.name + " | " + "Owner: ".cyan + story.owner.name) exports.printSeparator("="); console.log(story.text[story.color]); exports.printSeparator(); if (content) { console.log(content); exports.printSeparator(); } if (story.blockedReason) { console.log(story.blockedReason.red); exports.printSeparator(); } };
Switch port to 3000 so it can run without root priviledges. Use nginx if you want it on port 80
var express = require('express'); var fs = require('fs'); var url = require('url'); var app = express.createServer(); app.use(express.static(__dirname + '/public')); app.get('*', handleAnyRequest); app.post('*', handleAnyRequest); app.delete('*', handleAnyRequest); app.put('*', handleAnyRequest); var TEMPLATE_PATTERN = new RegExp(/{{.*}}/g); function handleAnyRequest(req, res){ reqUrl = url.parse(req.url); var file = 'json' + reqUrl.pathname + '_' + req.method.toLowerCase() + ".json"; console.log('Request: ' + file); // TODO allow proxying calls to real API (for calls that are already implemented) var data = readFileJson(file); res.send(data) } function readFileJson(file) { var data = fs.readFileSync(file, 'utf8'); data = data.replace(TEMPLATE_PATTERN, function(match) { // TODO: allow variables instead of templates like SERVER_BASE_URL // TODO: for templates, allow {{Template(1)}} to add variables that can be used in the template like: {{param[1]}} var templateFile = 'json/_templates/' + match.slice(2,-2) + ".json"; return JSON.stringify(readFileJson(templateFile)); } ); return JSON.parse(data); } app.listen(3000);
var express = require('express'); var fs = require('fs'); var url = require('url'); var app = express.createServer(); app.use(express.static(__dirname + '/public')); app.get('*', handleAnyRequest); app.post('*', handleAnyRequest); app.delete('*', handleAnyRequest); app.put('*', handleAnyRequest); var TEMPLATE_PATTERN = new RegExp(/{{.*}}/g); function handleAnyRequest(req, res){ reqUrl = url.parse(req.url); var file = 'json' + reqUrl.pathname + '_' + req.method.toLowerCase() + ".json"; console.log('Request: ' + file); // TODO allow proxying calls to real API (for calls that are already implemented) var data = readFileJson(file); res.send(data) } function readFileJson(file) { var data = fs.readFileSync(file, 'utf8'); data = data.replace(TEMPLATE_PATTERN, function(match) { // TODO: allow variables instead of templates like SERVER_BASE_URL // TODO: for templates, allow {{Template(1)}} to add variables that can be used in the template like: {{param[1]}} var templateFile = 'json/_templates/' + match.slice(2,-2) + ".json"; return JSON.stringify(readFileJson(templateFile)); } ); return JSON.parse(data); } app.listen(80);
Make tooltip enabling observe `popover` and `title`
import Ember from 'ember'; export default Ember.Mixin.create({ /** * Attribute bindings for mixin's component element * @property {array} attributeBindings */ attributeBindings: [ 'title' ], /** * Enables the tooltip functionality, based on a passed-in `title` attribute * @method enableTooltip */ enableTooltip: function () { var popoverContent = this.get( 'popover' ); var title = this.get( 'title' ); if ( popoverContent ) { this.set( 'data-toggle', 'popover' ); this.$().popover({ content: popoverContent, placement: 'top' }); } else if ( title ) { this.set( 'data-toggle', 'tooltip' ); this.$().tooltip(); } }.observes( 'popover', 'title' ).on( 'didInsertElement' ) });
import Ember from 'ember'; export default Ember.Mixin.create({ /** * Attribute bindings for mixin's component element * @property {array} attributeBindings */ attributeBindings: [ 'title' ], /** * Enables the tooltip functionality, based on a passed-in `title` attribute * @method enableTooltip */ enableTooltip: function () { var popoverContent = this.get( 'popover' ); var title = this.get( 'title' ); if ( popoverContent ) { this.set( 'data-toggle', 'popover' ); this.$().popover({ content: popoverContent, placement: 'top' }); } else if ( title ) { this.set( 'data-toggle', 'tooltip' ); this.$().tooltip(); } }.on( 'didInsertElement' ) });
Add height is not absoulte note
var WebPage = require('webpage'), System = require('system'), address = System.args[1], index = 0; // All the sizes to screenshot. // Note: PhantomJs uses the heights specified here as a min-height criteria var screenshots = [ {"dimensions" : [970,300], "filename": './screenshots/screenshot_l.png'}, {"dimensions" : [720,300], "filename": './screenshots/screenshot_m.png'}, {"dimensions" : [400,200], "filename": './screenshots/screenshot_s.png'} ]; var capturescreen = function(dimensions, filename){ var page = WebPage.create(); page.viewportSize = { width: dimensions[0], height: dimensions[1] }; page.open(address); page.onLoadFinished = setTimeout(function() { page.render(filename); page.close(); index++; // Give it a second before calling next. // Phantom runs into some sort of race condition without this setTimeout(nextPage, 1000); }, 3000); } var nextPage = function(){ if(!screenshots[index]){ phantom.exit(); } capturescreen(screenshots[index].dimensions, screenshots[index].filename); } nextPage();
var WebPage = require('webpage'); var System = require('system'); address = System.args[1]; var index = 0; var screenshots = [ {"dimensions" : [975,500], "filename": './screenshots/screenshot_l.png'}, {"dimensions" : [720,400], "filename": './screenshots/screenshot_m.png'}, {"dimensions" : [400,200], "filename": './screenshots/screenshot_s.png'} ]; var capturescreen = function(dimensions, filename){ var page = WebPage.create(); page.viewportSize = { width: dimensions[0], height: dimensions[1] }; page.open(address); page.onLoadFinished = setTimeout(function() { page.render(filename); page.close(); index++; // Give it a second before calling next. // Phantom runs into some sort of race condition without this setTimeout(nextPage, 1000); }, 3000); } var nextPage = function(){ if(!screenshots[index]){ phantom.exit(); } capturescreen(screenshots[index].dimensions, screenshots[index].filename); } nextPage();
Fix typo in test method name.
<?php // Copyright 2004-present Facebook. 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. namespace Facebook\WebDriver\Remote; class WebDriverCommandTest extends \PHPUnit_Framework_TestCase { public function testShouldSetOptionsUsingConstructor() { $command = new WebDriverCommand('session-id-123', 'bar-baz-name', array('foo' => 'bar')); $this->assertSame('session-id-123', $command->getSessionID()); $this->assertSame('bar-baz-name', $command->getName()); $this->assertSame(array('foo' => 'bar'), $command->getParameters()); } }
<?php // Copyright 2004-present Facebook. 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. namespace Facebook\WebDriver\Remote; class WebDriverCommandTest extends \PHPUnit_Framework_TestCase { public function testShouldSetOptionsUsingConstructot() { $command = new WebDriverCommand('session-id-123', 'bar-baz-name', array('foo' => 'bar')); $this->assertSame('session-id-123', $command->getSessionID()); $this->assertSame('bar-baz-name', $command->getName()); $this->assertSame(array('foo' => 'bar'), $command->getParameters()); } }
Add indent in json to improve debugging
import json from relay_api.core.relay import relay from relay_api.conf.config import relays def init_relays(): for r in relays: relays[r]["object"] = relay(relays[r]["gpio"]) relays[r]["state"] = relays[r]["object"].get_state() def get_all_relays(): relays_dict = __get_relay_dict() return json.dumps(relays_dict, indent=4) def get_relay(relay_name): if relay_name not in relays: return None relay_dict = __get_relay_dict(relay_name) return json.dumps(relay_dict, indent=4) def __get_relay_dict(relay_name=None): if relay_name: relay_dict = dict.copy(relays["relay_name"]) del(relay_dict["object"]) return relay_dict relays_dict = dict.copy(relays) for r in relays_dict: del(relays_dict[r]["object"]) return relays_dict
import json from relay_api.core.relay import relay from relay_api.conf.config import relays def init_relays(): for r in relays: relays[r]["object"] = relay(relays[r]["gpio"]) relays[r]["state"] = relays[r]["object"].get_state() def get_all_relays(): relays_dict = __get_relay_dict() return json.dumps(relays_dict) def get_relay(relay_name): if relay_name not in relays: return None relay_dict = __get_relay_dict(relay_name) return json.dumps(relay_dict) def __get_relay_dict(relay_name=None): if relay_name: relay_dict = dict.copy(relays["relay_name"]) del(relay_dict["object"]) return relay_dict relays_dict = dict.copy(relays) for r in relays_dict: del(relays_dict[r]["object"]) return relays_dict
Fix publicPath in to allow php artisan serve
<?php namespace App; use Illuminate\Foundation\Application as IlluminateApplication; use InvalidArgumentException; /** * Extends \Illuminate\Foundation\Application to override some defaults. */ class Application extends IlluminateApplication { /** * We have merged public path and base path. * * @return string */ public function publicPath() { return $this->basePath; } /** * Loads a revision'ed asset file, making use of gulp-rev * This is a copycat of L5's Elixir, but catered to our directory structure. * * @param string $file * * @return string */ public function rev($file) { static $manifest = null; if (is_null($manifest)) { $manifest = json_decode(file_get_contents($this->publicPath().'/public/build/rev-manifest.json'), true); } if (isset($manifest[$file])) { return "/public/build/{$manifest[$file]}"; } throw new InvalidArgumentException("File {$file} not defined in asset manifest."); } }
<?php namespace App; use Illuminate\Foundation\Application as IlluminateApplication; use InvalidArgumentException; /** * Extends \Illuminate\Foundation\Application to override some defaults. */ class Application extends IlluminateApplication { /** * Loads a revision'ed asset file, making use of gulp-rev * This is a copycat of L5's Elixir, but catered to our directory structure. * * @param string $file * * @return string */ public function rev($file) { static $manifest = null; if (is_null($manifest)) { $manifest = json_decode(file_get_contents($this->publicPath().'/build/rev-manifest.json'), true); } if (isset($manifest[$file])) { return "/public/build/{$manifest[$file]}"; } throw new InvalidArgumentException("File {$file} not defined in asset manifest."); } }
Add fuzz call for SBBreakpointLocation.GetAddress(). git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@141443 91177308-0d34-0410-b5e6-96231b3b80d8
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.GetAddress() obj.GetLoadAddress() obj.SetEnabled(True) obj.IsEnabled() obj.SetCondition("i >= 10") obj.GetCondition() obj.SetThreadID(0) obj.GetThreadID() obj.SetThreadIndex(0) obj.GetThreadIndex() obj.SetThreadName("worker thread") obj.GetThreadName() obj.SetQueueName("my queue") obj.GetQueueName() obj.IsResolved() obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose) breakpoint = obj.GetBreakpoint() # Do fuzz testing on the breakpoint obj, it should not crash lldb. import sb_breakpoint sb_breakpoint.fuzz_obj(breakpoint)
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.GetLoadAddress() obj.SetEnabled(True) obj.IsEnabled() obj.SetCondition("i >= 10") obj.GetCondition() obj.SetThreadID(0) obj.GetThreadID() obj.SetThreadIndex(0) obj.GetThreadIndex() obj.SetThreadName("worker thread") obj.GetThreadName() obj.SetQueueName("my queue") obj.GetQueueName() obj.IsResolved() obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose) breakpoint = obj.GetBreakpoint() # Do fuzz testing on the breakpoint obj, it should not crash lldb. import sb_breakpoint sb_breakpoint.fuzz_obj(breakpoint)
Fix expireChunkRanges test to actually work.
var FakeRedis = require('fakeredis'); var RedisCache = require('../../cache/RedisCache'); var ChunkTypes = require('../ChunkTypes'); var Promise = require('bluebird'); var expect = require('expect'); var expireChunkRanges = require('../expireChunkRanges'); var sinon = require('sinon'); describe('expireChunkRanges', function() { var cache = new RedisCache(FakeRedis.createClient()); var listName = 'list'; it('should call methods for all specified chunks', function() { var ranges = [[1, 3], 5]; var prefixes = ['a']; var mockCache = sinon.mock(cache); mockCache.expects('getChunkByID') .exactly(4).returns(Promise.resolve(['a'])); mockCache.expects('dropPrefixes') .exactly(4).returns(Promise.resolve()); mockCache.expects('dropPendingSubChunksByChunkID') .exactly(4).returns(Promise.resolve()); mockCache.expects('dropChunkByID') .exactly(4).returns(Promise.resolve()); return expireChunkRanges(cache, listName, ChunkTypes.ADD, ranges) .then(function() { mockCache.verify(); mockCache.restore(); }); }); });
var FakeRedis = require('fakeredis'); var RedisCache = require('../../cache/RedisCache'); var Promise = require('bluebird'); var expect = require('expect'); var updateAddChunkPrefixes = require('../updateAddChunkPrefixes'); var sinon = require('sinon'); describe('expireChunkRanges', function() { var cache = new RedisCache(FakeRedis.createClient()); var listName = 'list'; it('should call methods for all specified chunks', function() { var ranges = [[1, 3], 5]; var prefixes = ['a']; var mockCache = sinon.mock(cache); mockCache.expects('getChunkByID') .exactly(4).returns(Promise.resolve(['a'])); mockCache.expects('dropPrefixes') .exactly(4).returns(Promise.resolve()); mockCache.expects('dropPendingSubChunksByChunkID') .exactly(4).returns(Promise.resolve()); mockCache.expects('dropChunkByID') .exactly(4).returns(Promise.resolve()); }); });
FIX Only update member actions that have occurred for member objects that exist in the DB
<?php /** * * * @author <marcus@silverstripe.com.au> * @license BSD License http://www.silverstripe.org/bsd-license */ class MicroPostActivityFilter implements RequestFilter { /** * @var MicroBlogService */ public $microBlogService; public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model) { $actions = $this->microBlogService->getUserActions(); if ($actions && count($actions)) { $members = Member::get()->filter('ID', array_keys($actions)); foreach ($members as $member) { if ($member->exists()) { $member->LastPostView = SS_Datetime::now()->getValue(); $member->write(); } } } } public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model) { } }
<?php /** * * * @author <marcus@silverstripe.com.au> * @license BSD License http://www.silverstripe.org/bsd-license */ class MicroPostActivityFilter implements RequestFilter { /** * @var MicroBlogService */ public $microBlogService; public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model) { $actions = $this->microBlogService->getUserActions(); if ($actions && count($actions)) { $members = Member::get()->filter('ID', array_keys($actions)); foreach ($members as $member) { $member->LastPostView = SS_Datetime::now()->getValue(); $member->write(); } } } public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model) { } }
Fix federation provider example to load users file from it's own ClassLoader instead of Thread CL
package org.keycloak.examples.federation.properties; import org.keycloak.models.KeycloakSession; import org.keycloak.models.UserFederationProviderModel; import java.io.InputStream; import java.util.Properties; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory { public static final String PROVIDER_NAME = "classpath-properties"; @Override protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) { return new ClasspathPropertiesFederationProvider(session, model, props); } protected InputStream getPropertiesFileStream(String path) { InputStream is = getClass().getClassLoader().getResourceAsStream(path); if (is == null) { throw new IllegalStateException("Path not found for properties file"); } return is; } @Override public String getId() { return PROVIDER_NAME; } }
package org.keycloak.examples.federation.properties; import org.keycloak.models.KeycloakSession; import org.keycloak.models.UserFederationProviderModel; import java.io.InputStream; import java.util.Properties; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory { public static final String PROVIDER_NAME = "classpath-properties"; @Override protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) { return new ClasspathPropertiesFederationProvider(session, model, props); } protected InputStream getPropertiesFileStream(String path) { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); if (is == null) { throw new IllegalStateException("Path not found for properties file"); } return is; } @Override public String getId() { return PROVIDER_NAME; } }
Remove all rules if not included
<?php namespace Styde\Html; use Illuminate\Support\Facades\{Auth, Gate}; trait HandlesAccess { public $included = true; public function includeIf(bool $value = true) { $this->included = $value; if (! $this->included && isset($this->rules)) { $this->disableRules(); } return $this; } public function ifAuth() { return $this->includeIf(Auth::check()); } public function ifGuest() { return $this->includeIf(Auth::guest()); } public function ifCan($ability, $arguments = []) { if ($this->rules && ! Gate::allows($ability, $arguments)) { $this->rules = []; } return $this->includeIf(Gate::allows($ability, $arguments)); } public function ifCannot($ability, $arguments = []) { return $this->includeIf(Gate::denies($ability, $arguments)); } public function ifIs($role) { $user = Auth::user(); return $this->includeIf($user && $user->isA($role)); } }
<?php namespace Styde\Html; use Illuminate\Support\Facades\{Auth, Gate}; trait HandlesAccess { public $included = true; public function includeIf(bool $value = true) { $this->included = $value; return $this; } public function ifAuth() { return $this->includeIf(Auth::check()); } public function ifGuest() { return $this->includeIf(Auth::guest()); } public function ifCan($ability, $arguments = []) { return $this->includeIf(Gate::allows($ability, $arguments)); } public function ifCannot($ability, $arguments = []) { return $this->includeIf(Gate::denies($ability, $arguments)); } public function ifIs($role) { $user = Auth::user(); return $this->includeIf($user && $user->isA($role)); } }
Fix environment variable checks for removing container
import os, os.path import nose.tools as nose import biobox_cli.container as ctn def project_root(): return os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) def is_ci_server(): return "CIRCLECI" in os.environ.keys() def remove_container(container): if not is_ci_server(): ctn.remove(container) def assert_file_not_empty(file_): file_size = os.stat(file_).st_size nose.assert_not_equal(file_size, 0, "File should not be empty but is: {}".format(file_)) def assert_file_contents_equal(file_, contents): with open(file_, 'r') as f: nose.assert_equal(f.read(), contents)
import os, os.path import nose.tools as nose import biobox_cli.container as ctn def project_root(): return os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) def is_ci_server(): return "CI" in os.environ.keys() def remove_container(container): if not is_ci_server(): ctn.remove(container) def assert_file_not_empty(file_): file_size = os.stat(file_).st_size nose.assert_not_equal(file_size, 0, "File should not be empty but is: {}".format(file_)) def assert_file_contents_equal(file_, contents): with open(file_, 'r') as f: nose.assert_equal(f.read(), contents)
[KARAF-1313] Set group argument as required in cluster:group-create command git-svn-id: 23a5554d8b20ee894ad801d0a5fe136f33ef549e@1330248 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.cellar.shell.group; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; @Command(scope = "cluster", name = "group-create", description = "Create a cluster group.") public class GroupCreateCommand extends GroupSupport { @Argument(index = 0, name = "group", description = "The cluster group name.", required = true, multiValued = false) String group; @Override protected Object doExecute() throws Exception { return groupManager.createGroup(group); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.cellar.shell.group; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; @Command(scope = "cluster", name = "group-create", description = "Create a cluster group.") public class GroupCreateCommand extends GroupSupport { @Argument(index = 0, name = "group", description = "The cluster group name.", required = false, multiValued = false) String group; @Override protected Object doExecute() throws Exception { return groupManager.createGroup(group); } }