text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use callbacks to ensure save is completed before returning a result
var express = require("express"), mongoose = require("mongoose"), app = express(); mongoose.connect("mongodb://localhost/test", function (err) { if (!err) { console.log("Connected to MongoDB"); } else { console.error(err); } }); app.get("/", function (req, res) { res.send("Hey buddy!"); }); var Thing = require("./model"); app.get("/:name", function (req, res) { Thing.find({ name: req.params.name }, function (err, t) { if (t.length < 1) { var thing = new Thing(); thing.name = req.params.name; thing.save(function(err) { if (err) { res.send(500); } else { res.send("Created a new thing with name " + thing.name); } }); } else { res.send(t); } }); }); app.listen(3000);
var express = require("express"), mongoose = require("mongoose"), app = express(); mongoose.connect("mongodb://localhost/test", function (err) { if (!err) { console.log("Connected to MongoDB"); } else { console.error(err); } }); app.get("/", function (req, res) { res.send("Hey buddy!"); }); var Thing = require("./model"); app.get("/:name", function (req, res) { Thing.find({ name: req.params.name }, function (err, t) { if (t.length < 1) { var thing = new Thing(); thing.name = req.params.name; thing.save(); res.send("Created a new thing with name " + thing.name); } else { res.send(t); } }); }); app.listen(3000);
Add get textures method for items
package com.infinityraider.infinitylib.item; import com.infinityraider.infinitylib.render.item.IItemRenderingHandler; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.List; public interface ICustomRenderedItem<I extends Item> { /** * Gets called to create the IBlockRenderingHandler instance to render this block with * @return a new IItemRenderingHandler object for this block */ @SideOnly(Side.CLIENT) IItemRenderingHandler<I> getRenderer(); /** * Gets a list of all textures necessary to render this item, * returned textures will be stitched to the atlas * @return list of textures */ @SideOnly(Side.CLIENT) List<ResourceLocation> getTextures(); /** * Gets an array of ResourceLocations used for the model of this block, all block states for this block will use this as key in the model registry * @return a unique ModelResourceLocation for this block */ @SideOnly(Side.CLIENT) ModelResourceLocation getItemModelResourceLocation(); }
package com.infinityraider.infinitylib.item; import com.infinityraider.infinitylib.render.item.IItemRenderingHandler; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public interface ICustomRenderedItem<I extends Item> { /** * Gets called to create the IBlockRenderingHandler instance to render this block with * @return a new IItemRenderingHandler object for this block */ @SideOnly(Side.CLIENT) IItemRenderingHandler<I> getRenderer(); /** * Gets an array of ResourceLocations used for the model of this block, all block states for this block will use this as key in the model registry * @return a unique ModelResourceLocation for this block */ @SideOnly(Side.CLIENT) ModelResourceLocation getItemModelResourceLocation(); }
Add country field to release serializer.
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): cdid = serializers.StringRelatedField( read_only=True ) class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'cdid') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments')
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): cdid = serializers.StringRelatedField( read_only=True ) class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'cdid') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year', 'local', 'compilation', 'female', 'tracks', 'comments')
Fix the wrong test access setup and teardown.
<?php namespace ProcessWire\GraphQL\Test; use PHPUnit\Framework\TestCase; use ProcessWire\GraphQL\Utils; use ProcessWire\GraphQL\Schema; abstract class GraphqlTestCase extends TestCase { public static $defaultConfig; public static function setUpBeforeClass() { self::$defaultConfig = Utils::module()->data(); $self = static::class; if (method_exists($self, 'setupAccess')) { $self::setupAccess(); } } public static function tearDownAfterClass() { $self = static::class; if (method_exists($self, 'teardownAccess')) { $self::teardownAccess(); } Utils::module()->setArray(self::$defaultConfig); } public static function execute($payload = null, $variables = null) { Schema::build(); return Utils::module()->executeGraphQL($payload, $variables); } }
<?php namespace ProcessWire\GraphQL\Test; use PHPUnit\Framework\TestCase; use ProcessWire\GraphQL\Utils; use ProcessWire\GraphQL\Schema; abstract class GraphqlTestCase extends TestCase { public static $defaultConfig; public static function setUpBeforeClass() { $self = static::class; if (method_exists($self, 'setupAccess')) { $self::setupAccess(); } self::$defaultConfig = Utils::module()->data(); } public static function tearDownAfterClass() { Utils::module()->setArray(self::$defaultConfig); $self = static::class; if (method_exists($self, 'teardownAccess')) { $self::teardownAccess(); } } public static function execute($payload = null, $variables = null) { Schema::build(); return Utils::module()->executeGraphQL($payload, $variables); } }
Fix documentFormatter comment about jsPDF
import documentFormatter from 'src/logic/documentPackager/documentFormatter'; import base64OfSimplePdf from './reference/base64OfSimplePdf'; describe('DocumentFormatter', () => { it('should returns the same data for \'html viewMode\'', () => { const viewMode = 'html'; const inputData = '<div>This is a HTML content</div>'; const outputData = documentFormatter.format(inputData, viewMode); expect(outputData).to.equal('<div>This is a HTML content</div>'); }); it('should returns a pdfBlob for \'pages viewMode\'', (done) => { const expectedOutput = base64OfSimplePdf; const inputData = '<div>This is a HTML content</div>'; const thatPromise = documentFormatter.getPdfBlob(inputData); thatPromise.then((outputData) => { // jsPDF does not give deterministic outputData // around 5 characters will always be different in the output // therefore, an approximation method to use content length for // testing is used. expect(outputData.length).to.equal(expectedOutput.length); done(); }).catch((error) => { done(error); }); }); });
import documentFormatter from 'src/logic/documentPackager/documentFormatter'; import base64OfSimplePdf from './reference/base64OfSimplePdf'; describe('DocumentFormatter', () => { it('should returns the same data for \'html viewMode\'', () => { const viewMode = 'html'; const inputData = '<div>This is a HTML content</div>'; const outputData = documentFormatter.format(inputData, viewMode); expect(outputData).to.equal('<div>This is a HTML content</div>'); }); it('should returns a pdfBlob for \'pages viewMode\'', (done) => { const expectedOutput = base64OfSimplePdf; const inputData = '<div>This is a HTML content</div>'; const thatPromise = documentFormatter.getPdfBlob(inputData); thatPromise.then((outputData) => { // pdfJS does not give deterministic outputData // around 5 characters will always be different in the output // therefore, an approximation method to use content length for // testing is used. expect(outputData.length).to.equal(expectedOutput.length); done(); }).catch((error) => { done(error); }); }); });
Reformat VCS tests; need updated unit test values!
# Licensed under an MIT open source license - see LICENSE ''' Test functions for VCS ''' import pytest import numpy as np import numpy.testing as npt from ..statistics import VCS, VCS_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances def test_VCS_method(): tester = VCS(dataset1["cube"]).run() npt.assert_allclose(tester.ps1D, computed_data['vcs_val']) npt.assert_allclose(tester.slope, computed_data['vcs_slopes_val']) def test_VCS_distance(): tester_dist = \ VCS_Distance(dataset1["cube"], dataset2["cube"]) tester_dist = tester_dist.distance_metric() npt.assert_almost_equal(tester_dist.distance, computed_distances['vcs_distance']) # Add tests for: VCS changing the spectral width, pixel and spectral units,
# Licensed under an MIT open source license - see LICENSE ''' Test functions for VCS ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import VCS, VCS_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testVCS(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_VCS_method(self): self.tester = VCS(dataset1["cube"]).run() npt.assert_allclose(self.tester.ps1D, computed_data['vcs_val']) def test_VCS_distance(self): self.tester_dist = \ VCS_Distance(dataset1["cube"], dataset2["cube"]) self.tester_dist = self.tester_dist.distance_metric() npt.assert_almost_equal(self.tester_dist.distance, computed_distances['vcs_distance'])
Add transformations property to projects.
""" Project :Authors: Berend Klein Haneveld """ class Project(object): """ Project holds the basic information of a project for RegistrationShop """ def __init__(self, title=None, fixedData=None, movingData=None, isReference=None): super(Project, self).__init__() self.title = title self.fixedData = fixedData self.movingData = movingData self.isReference = isReference self.folder = None self.resultData = None self.fixedSettings = None self.movingSettings = None self.multiSettings = None self.transformations = None def __eq__(self, other): if not isinstance(other, Project): return False return (self.title == other.title and self.fixedData == other.fixedData and self.movingData == other.movingData and self.isReference == other.isReference) def __ne__(self, other): return not self.__eq__(other)
""" Project :Authors: Berend Klein Haneveld """ class Project(object): """ Project holds the basic information of a project for RegistrationShop """ def __init__(self, title=None, fixedData=None, movingData=None, isReference=None): super(Project, self).__init__() self.title = title self.fixedData = fixedData self.movingData = movingData self.isReference = isReference self.folder = None self.resultData = None self.fixedSettings = None self.movingSettings = None self.multiSettings = None def __eq__(self, other): if not isinstance(other, Project): return False return (self.title == other.title and self.fixedData == other.fixedData and self.movingData == other.movingData and self.isReference == other.isReference) def __ne__(self, other): return not self.__eq__(other)
Include line number in unhandled token exception. git-svn-id: 2eebe84b5b32eb059849d530d3c549d0da009da8@114348 cb919951-1609-0410-8833-993d306c94f7
/** * File: AbstractObjectFactory.java * * Author: David Hay (dhay@localmatters.com) * Creation Date: Apr 21, 2010 * Creation Time: 10:46:54 AM * * Copyright 2010 Local Matters, Inc. * All Rights Reserved * * Last checkin: * $Author$ * $Revision$ * $Date$ */ package org.lesscss4j.factory; import org.antlr.runtime.tree.Tree; import org.lesscss4j.parser.LessCssParser; import static org.lesscss4j.parser.LessCssLexer.*; public abstract class AbstractObjectFactory<T> implements ObjectFactory<T> { protected String formatNode(String prefix, Tree node) { return String.format("%s [%d=%s] %d:%d - %s", prefix, node.getType(), LessCssParser.tokenNames[node.getType()], node.getLine(), node.getCharPositionInLine(), node.toString()); } protected void handleUnexpectedChild(String prefix, Tree child) { int type = child.getType(); if (type != WS && type != EOF) { throw new IllegalStateException(formatNode(prefix, child)); } } }
/** * File: AbstractObjectFactory.java * * Author: David Hay (dhay@localmatters.com) * Creation Date: Apr 21, 2010 * Creation Time: 10:46:54 AM * * Copyright 2010 Local Matters, Inc. * All Rights Reserved * * Last checkin: * $Author$ * $Revision$ * $Date$ */ package org.lesscss4j.factory; import org.antlr.runtime.tree.Tree; import org.lesscss4j.parser.LessCssParser; import static org.lesscss4j.parser.LessCssLexer.*; public abstract class AbstractObjectFactory<T> implements ObjectFactory<T> { protected String formatNode(String prefix, Tree node) { return String.format("%s [%d=%s] %s", prefix, node.getType(), LessCssParser.tokenNames[node.getType()], node.toString()); } protected void handleUnexpectedChild(String prefix, Tree child) { int type = child.getType(); if (type != WS && type != EOF) { throw new IllegalStateException(formatNode(prefix, child)); } } }
Tidy gulp screenshots import directives
'use strict'; import debug from 'gulp-debug'; import gulp from 'gulp'; // import phantom from 'phantomjs2'; // import phantom from 'phantomjs'; import plumber from 'gulp-plumber'; import webshot from 'gulp-webshot'; import config from './_config.babel.js'; import reportError from './_report-error.babel.js'; let sourceFiles = config.files.source.markup; gulp.task('screenshots', () => { return gulp.src(sourceFiles) .pipe(plumber({ errorHandler: reportError })) .pipe(debug({ title: 'screenshots:' })) .pipe(webshot({ phantomPath: phantom.path, dest: config.path.destination.screenshots, root: config.path.source.base })) .pipe(plumber.stop()) .on('error', reportError); }); gulp.task('screenshots:watch', function() { gulp.watch(sourceFiles, ['screenshots']); });
'use strict'; import debug from 'gulp-debug'; import gulp from 'gulp'; // import phantom from 'phantomjs2'; import phantom from 'phantomjs'; import plumber from 'gulp-plumber'; import webshot from 'gulp-webshot'; import config from './_config.babel.js'; import reportError from './_report-error.babel.js'; let sourceFiles = config.files.source.markup; gulp.task('screenshots', () => { return gulp.src(sourceFiles) .pipe(plumber({ errorHandler: reportError })) .pipe(debug({ title: 'screenshots:' })) .pipe(webshot({ phantomPath: phantom.path, dest: config.path.destination.screenshots, root: config.path.source.base })) .pipe(plumber.stop()) .on('error', reportError); }); gulp.task('screenshots:watch', function() { gulp.watch(sourceFiles, ['screenshots']); });
Add revertUnchanged command, because it's not uncommon.
/*jshint node:true*/ "use strict"; var exec = require("child_process").exec; function runCommand(command, args, done) { if(typeof args === "function") { done = args; args = ""; } exec("p4 " + command + " " + (args || ""), function(err, stdOut, stdErr) { if(err) return done(err); if(stdErr) return done(new Error(stdErr)); done(null, stdOut); }); } function edit(path, done) { runCommand("edit", path, done); } function add(path, done) { runCommand("add", path, done); } function smartEdit(path, done) { edit(path, function(err) { if(!err) return done(); add(path, done); }); } function revertUnchanged(path, done) { runCommand("revert", "-a", done); } exports.edit = edit; exports.add = add; exports.smartEdit = smartEdit; exports.run = runCommand; exports.revertUnchanged = revertUnchanged;
/*jshint node:true*/ "use strict"; var exec = require("child_process").exec; function runCommand(command, args, done) { if(typeof args === "function") { done = args; args = ""; } exec("p4 " + command + " " + (args || ""), function(err, stdOut, stdErr) { if(err) return done(err); if(stdErr) return done(new Error(stdErr)); done(null, stdOut); }); } function edit(path, done) { runCommand("edit", path, done); } function add(path, done) { runCommand("add", path, done); } function smartEdit(path, done) { edit(path, function(err) { if(!err) return done(); add(path, done); }); } exports.edit = edit; exports.add = add; exports.smartEdit = smartEdit; exports.run = runCommand;
Add UIHint.SELECT to NumericaContraint's supported hints
package org.sagebionetworks.bridge.models.surveys; import java.util.EnumSet; public class NumericalConstraints extends Constraints { private Unit unit; private Double minValue; private Double maxValue; private Double step; public NumericalConstraints() { setSupportedHints(EnumSet.of(UIHint.NUMBERFIELD, UIHint.SLIDER, UIHint.SELECT)); } public Unit getUnit() { return unit; } public void setUnit(Unit unit) { this.unit = unit; } public Double getMinValue() { return minValue; } public void setMinValue(Double minValue) { this.minValue = minValue; } public Double getMaxValue() { return maxValue; } public void setMaxValue(Double maxValue) { this.maxValue = maxValue; } public Double getStep() { return step; } public void setStep(Double step) { this.step = step; } }
package org.sagebionetworks.bridge.models.surveys; import java.util.EnumSet; public class NumericalConstraints extends Constraints { private Unit unit; private Double minValue; private Double maxValue; private Double step; public NumericalConstraints() { setSupportedHints(EnumSet.of(UIHint.NUMBERFIELD, UIHint.SLIDER)); } public Unit getUnit() { return unit; } public void setUnit(Unit unit) { this.unit = unit; } public Double getMinValue() { return minValue; } public void setMinValue(Double minValue) { this.minValue = minValue; } public Double getMaxValue() { return maxValue; } public void setMaxValue(Double maxValue) { this.maxValue = maxValue; } public Double getStep() { return step; } public void setStep(Double step) { this.step = step; } }
Views: Reset book status and start/finish dates on add form
BookShelf.BookAdd = function(params) { return $.extend(BookShelf.BookForm(params), { resetBook: function() { this.book.title(""); this.book.author(""); this.book.status(params.status); this.book.startDate(new Date()); this.book.finishDate(new Date()); }, save: function() { BookShelf.db.books.add(this.getBook()); BookShelf.app.back(); }, cancel: function() { BookShelf.app.back(); }, viewShowing: function() { this.resetBook(); } }); return viewModel; };
BookShelf.BookAdd = function(params) { return $.extend(BookShelf.BookForm(params), { resetBook: function() { this.book.title(""); this.book.author(""); }, save: function() { BookShelf.db.books.add(this.getBook()); BookShelf.app.back(); }, cancel: function() { BookShelf.app.back(); }, viewShowing: function() { this.resetBook(); } }); return viewModel; };
Use for-loop instead of while+iterator
package mib.microservice.commons.kafka; import kafka.consumer.KafkaStream; import kafka.message.MessageAndMetadata; import mib.microservice.commons.events.IEventConsumer; import mib.microservice.commons.events.base.EventBase; public class Consumer<K, V extends EventBase<?>> implements Runnable { private KafkaStream<K, V> stream; private IEventConsumer<K, V> command; public Consumer(KafkaStream<K, V> stream, IEventConsumer<K, V> command) { this.stream = stream; this.command = command; } @Override public void run() { for (MessageAndMetadata<K, V> msg : this.stream) { System.out.println("p" + msg.partition() + " @" + msg.offset()); this.command.execute(msg.key(), msg.message()); } } }
package mib.microservice.commons.kafka; import mib.microservice.commons.events.IEventConsumer; import mib.microservice.commons.events.base.EventBase; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import kafka.message.MessageAndMetadata; public class Consumer<K, V extends EventBase<?>> implements Runnable { private KafkaStream<K, V> stream; private IEventConsumer<K, V> command; public Consumer(KafkaStream<K, V> stream, IEventConsumer<K, V> command) { this.stream = stream; this.command = command; } @Override public void run() { ConsumerIterator<K, V> it = this.stream.iterator(); while (it.hasNext()) { MessageAndMetadata<K, V> msg = it.next(); System.out.println("p" + msg.partition() + " @" + msg.offset()); this.command.execute(msg.key(), msg.message()); } } }
Add 'createdAt' column to users table
exports.up = knex => ( knex.schema /** * Users table * * Contains info on all users in the system */ .createTableIfNotExists('users', (table) => { table.increments('id').primary(); table.timestamp('createdAt').defaultTo(knex.fn.now()); table.enum('scope', ['admin', 'user']).notNullable(); table.text('email').notNullable().unique(); table.text('description'); table.binary('image'); }) /** * Define a separate table for storing user secrets (such as password hashes). * * The rationale is: * - Have to explicitly join/query password table to access secrets * - Don't have to filter out secrets in every 'users' table query * * => Harder to accidentally leak out user secrets * * You may want to store other user secrets in this table as well. */ .createTableIfNotExists('secrets', (table) => { table.integer('ownerId').references('id').inTable('users').primary(); table.text('password').notNullable(); }) ); exports.down = knex => ( knex.schema .dropTableIfExists('users') .dropTableIfExists('secrets') );
exports.up = knex => ( knex.schema /** * Users table * * Contains info on all users in the system */ .createTableIfNotExists('users', (table) => { table.increments('id').primary(); table.enum('scope', ['admin', 'user']).notNullable(); table.text('email').notNullable().unique(); table.text('description'); table.binary('image'); }) /** * Define a separate table for storing user secrets (such as password hashes). * * The rationale is: * - Have to explicitly join/query password table to access secrets * - Don't have to filter out secrets in every 'users' table query * * => Harder to accidentally leak out user secrets * * You may want to store other user secrets in this table as well. */ .createTableIfNotExists('secrets', (table) => { table.integer('ownerId').references('id').inTable('users').primary(); table.text('password').notNullable(); }) ); exports.down = knex => ( knex.schema .dropTableIfExists('users') .dropTableIfExists('secrets') );
Fix translation failing on github
<?php namespace Backend\Modules\ContentBlocks\Tests\Action; use Backend\Core\Tests\BackendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; class IndexTest extends BackendWebTestCase { public function testAuthenticationIsNeeded(Client $client): void { self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index'); } public function testIndexHasNoItems(Client $client): void { $this->login($client); self::assertPageLoadedCorrectly( $client, '/private/en/content_blocks/index', [ 'There are no content blocks yet.', 'Add content block', ] ); } }
<?php namespace Backend\Modules\ContentBlocks\Tests\Action; use Backend\Core\Tests\BackendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; class IndexTest extends BackendWebTestCase { public function testAuthenticationIsNeeded(Client $client): void { self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index'); } public function testIndexHasNoItems(Client $client): void { $this->login($client); self::assertPageLoadedCorrectly( $client, '/private/en/content_blocks/index', [ 'There are no content blocks yet.', 'Add content block', 'Add a content block', ] ); } }
Allow passing of command line arguments to tcpdump
package main import ( "fmt" "log" "os" "time" "strings" "autotcpdump/parser" "autotcpdump/executer" "autotcpdump/checker" ) func main() { cmdlineArgs := os.Args[1:] config := parser.ConfigParser{} if err := config.Parse("config/config.json"); err != nil { log.Fatal(err) } if err := checker.CheckIfPathWritable(config.PcapLocation); err != nil { log.Fatal(err) } filename := fmt.Sprintf("tcpdump_%v.pcap", time.Now().Format("20060102_150405")) fmt.Println("directory:", config.PcapLocation, "filename:", filename) commandOptions := config.CommandOptions + " " + strings.Join(cmdlineArgs, " ") tcpdump := executer.TcpdumpExecuter{} if err := tcpdump.RunTcpdump(config.PcapLocation, filename, commandOptions); err != nil { log.Fatal(err) } if err := tcpdump.TerminateTcpdump(); err != nil { log.Fatal(err) } if err := tcpdump.AdbPullPcapFile(config.PcapLocation, filename); err != nil { log.Fatal(err) } if err := tcpdump.OpenWithWireshark(config.WiresharkLocation, filename); err != nil { log.Fatal(err) } }
package main import ( "fmt" "log" "time" "autotcpdump/parser" "autotcpdump/executer" "autotcpdump/checker" ) func main() { config := parser.ConfigParser{} if err := config.Parse("config/config.json"); err != nil { log.Fatal(err) } if err := checker.CheckIfPathWritable(config.PcapLocation); err != nil { log.Fatal(err) } filename := fmt.Sprintf("tcpdump_%v.pcap", time.Now().Format("20060102_150405")) fmt.Println("directory:", config.PcapLocation, "filename:", filename) tcpdump := executer.TcpdumpExecuter{} if err := tcpdump.RunTcpdump(config.PcapLocation, filename, config.CommandOptions); err != nil { log.Fatal(err) } if err := tcpdump.TerminateTcpdump(); err != nil { log.Fatal(err) } if err := tcpdump.AdbPullPcapFile(config.PcapLocation, filename); err != nil { log.Fatal(err) } if err := tcpdump.OpenWithWireshark(config.WiresharkLocation, filename); err != nil { log.Fatal(err) } }
Add option to preprocess date fields for inline data. resolve #3
/* Compiled 2015-12-15 09:12:13 */ "use strict";angular.module("metricsgraphics",[]).directive("chart",function(){return{link:function(a,b){function c(a){for(var b="ABCDEFGHIJKLMNOPQRSTUVWXYZ",c="",d=0;a>d;d++){var e=Math.floor(Math.random()*b.length);c+=b.substring(e,e+1)}return"mg-chart-"+c}var d={baselines:[],description:null,height:200,right:0,title:null,width:b[0].parentElement.clientWidth||300,x_accessor:null,y_accessor:null};a.options&&Object.keys(a.options).forEach(function(b){d[b]=a.options[b]}),b[0].id=b[0].id?b[0].id:c(5),d.data=a.data||[],d.target="#"+b[0].id,a.convertDateField&&(d.data=MG.convert.date(d.data,a.convertDateField)),MG.data_graphic(d)},restrict:"E",scope:{convertDateField:"@",data:"=",options:"="}}}); //# sourceMappingURL=angular-metrics-graphics.min.map
/* Compiled 2015-12-15 09:12:28 */ "use strict";angular.module("metricsgraphics",[]).directive("chart",function(){return{link:function(a,b){function c(a){for(var b="ABCDEFGHIJKLMNOPQRSTUVWXYZ",c="",d=0;a>d;d++){var e=Math.floor(Math.random()*b.length);c+=b.substring(e,e+1)}return"mg-chart-"+c}var d={baselines:[],description:null,height:200,right:0,title:null,width:b[0].parentElement.clientWidth||300,x_accessor:null,y_accessor:null};a.options&&Object.keys(a.options).forEach(function(b){d[b]=a.options[b]}),b[0].id=b[0].id?b[0].id:c(5),d.data=a.data||[],d.target="#"+b[0].id,a.convertDateField&&(d.data=MG.convert.date(d.data,a.convertDateField)),MG.data_graphic(d)},restrict:"E",scope:{convertDateField:"@",data:"=",options:"="}}}); //# sourceMappingURL=angular-metrics-graphics.min.map
Create header refactoring of classes
import React from 'react'; const CreateFormHeader = () => { const discard = () => { window.history.back(); }; return ( <header className="challenge-create-header"> <h1 className="challenge-create-header__title">Create Challenge</h1> <button className="challenge-create-header__discard" type="button" onClick={ discard }> Discard </button> <button className="challenge-create-header__post" type="submit"> Post </button> </header> ); }; export default CreateFormHeader;
import React from 'react'; const CreateFormHeader = () => { const discard = () => { window.history.back(); }; return ( <header className="challenge-create__header"> <h1 className="challenge-create__title">Create Challenge</h1> <button className="challenge-create__discard" type="button" onClick={ discard }> Discard </button> <button className="challenge-create__post" type="submit"> Post </button> </header> ); }; export default CreateFormHeader;
Test for heart-beat header handling
var Client = require('../index').Client; var Transport = require('./mock/Transport'); var OutgoingFrameStream = require('./mock/OutgoingFrameStream'); var assert = require('assert'); describe('Client.connect', function() { var client, transport, framesOut, framesIn; beforeEach(function() { transport = new Transport(); framesOut = new OutgoingFrameStream(); client = new Client(transport, { outgoingFrameStream: framesOut }); }); it('should send a CONNECT frame and include accept-version header', function(done) { client.connect(); assert(framesOut._frames[0]); var frame = framesOut._frames[0]; assert.equal(frame.command, 'CONNECT'); assert('accept-version' in frame.headers); assert.equal(frame._finished, true); assert.equal(frame._body.length, 0); done(); }); it('should parse the heart-beat header and call setHeartbeat', function(done) { client.connect({ 'heart-beat': '1,2' }); var heartbeat = client.getHeartbeat(); assert.equal(heartbeat[0], 1); assert.equal(heartbeat[1], 2); assert.equal(framesOut._frames[0].headers['heart-beat'], '1,2'); done(); }); });
var Client = require('../index').Client; var Transport = require('./mock/Transport'); var OutgoingFrameStream = require('./mock/OutgoingFrameStream'); var assert = require('assert'); describe('Client.connect', function() { var client, transport, framesOut, framesIn; beforeEach(function() { transport = new Transport(); framesOut = new OutgoingFrameStream(); client = new Client(transport, { outgoingFrameStream: framesOut }); }); it('should send a CONNECT frame and include accept-version header', function(done) { client.connect(); assert(framesOut._frames[0]); var frame = framesOut._frames[0]; assert.equal(frame.command, 'CONNECT'); assert('accept-version' in frame.headers); assert.equal(frame._finished, true); assert.equal(frame._body.length, 0); done(); }); });
Fix news slider not display correct when only one news
export default function() { const $el = $('.blog-carousel'); if($el.length) { $el.owlCarousel({ loop: $el.length > 1, margin: 30, nav: $el.length > 1, dots: false, autoplayHoverPause: false, autoplay: 6000, smartSpeed: 700, navText: [ '<span class="fa fa-angle-left"></span>', '<span class="fa fa-angle-right"></span>' ], responsive:{ 0:{ items:1 }, 600:{ items:1 }, 800:{ items:1 }, 1024:{ items:1 }, 1100:{ items:1 }, 1200:{ items:1 } } }) } }
export default function() { const $el = $('.blog-carousel'); if($el.length) { $('.blog-carousel').owlCarousel({ loop:true, margin:30, nav:true, dots: false, autoplayHoverPause:false, autoplay: 6000, smartSpeed: 700, navText: [ '<span class="fa fa-angle-left"></span>', '<span class="fa fa-angle-right"></span>' ], responsive:{ 0:{ items:1 }, 600:{ items:1 }, 800:{ items:1 }, 1024:{ items:1 }, 1100:{ items:1 }, 1200:{ items:1 } } }) } }
CC-5781: Upgrade script for new storage quota implementation add propel to include path
<?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library') ))); /*set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library/propel/runtime/lib') )));*/ class StorageQuotaUpgrade { public static function startUpgrade() { echo "* Updating storage usage for new quota tracking".PHP_EOL; self::setStorageUsage(); } private static function setStorageUsage() { $musicDir = CcMusicDirsQuery::create() ->filterByDbType('stor') ->filterByDbExists(true) ->findOne(); $storPath = $musicDir->getDbDirectory(); $freeSpace = disk_free_space($storPath); $totalSpace = disk_total_space($storPath); Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace); } }
<?php require_once 'propel/runtime/lib/Propel.php'; class StorageQuotaUpgrade { public static function startUpgrade() { echo "* Updating storage usage for new quota tracking".PHP_EOL; self::setStorageUsage(); } private static function setStorageUsage() { $musicDir = CcMusicDirsQuery::create() ->filterByDbType('stor') ->filterByDbExists(true) ->findOne(); $storPath = $musicDir->getDbDirectory(); $freeSpace = disk_free_space($storPath); $totalSpace = disk_total_space($storPath); Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace); } }
Add trap on index -1 for the array-like
// Copyright (C) 2014 Robert Kowalski. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Array.prototype.contains searches the whole array if the computed index from the given negative fromIndex argument is less than 0 author: Robert Kowalski ---*/ if ([1, 3].contains(1, -4) !== true) { $ERROR('Expected that the whole array was searched'); } if ([1, 3].contains(3, -4) !== true) { $ERROR('Expected that the whole array was searched'); } var arrayLike = { length: 2, 0: 'a', get 1() { return 'b'; }, get '-1'() { $ERROR('Should not try to get the element at index -1'); } }; if (Array.prototype.contains.call(arrayLike, 'a', -4) !== true) { $ERROR('Expected that the whole array-like was searched'); } if (Array.prototype.contains.call(arrayLike, 'b', -4) !== true) { $ERROR('Expected that the whole array-like was searched'); }
// Copyright (C) 2014 Robert Kowalski. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Array.prototype.contains searches the whole array if the computed index from the given negative fromIndex argument is less than 0 author: Robert Kowalski ---*/ if ([1, 3].contains(1, -4) !== true) { $ERROR('Expected that the whole array was searched'); } if ([1, 3].contains(3, -4) !== true) { $ERROR('Expected that the whole array was searched'); } var arrayLike = { length: 2, 0: 'a', get 1() { return 'b'; } }; if (Array.prototype.contains.call(arrayLike, 'a', -4) !== true) { $ERROR('Expected that the whole array-like was searched'); } if (Array.prototype.contains.call(arrayLike, 'b', -4) !== true) { $ERROR('Expected that the whole array-like was searched'); }
Allow package to be installed as an egg
from setuptools import setup from setuptools.command.test import test as TestCommand import sys class Tox(TestCommand): user_options = [('tox-args=', 'a', "Arguments to pass to tox")] def initialize_options(self): TestCommand.initialize_options(self) self.tox_args = None def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox import shlex errno = tox.cmdline(args=shlex.split(self.tox_args)) sys.exit(errno) setup( name = "adbpy", version = "0.0.3", url = "https://github.com/noahgoldman/adbpy", license = "MIT", author = "Noah Goldman", author_email = "noah@phaaze.com", description = "A library to communicate with ADB through it's " "internal socket interface, rather than the command" "line.", platforms = "any", packages = ["adbpy"], zip_safe = True, tests_require = ['tox'], cmdclass = {'test': Tox}, )
from setuptools import setup from setuptools.command.test import test as TestCommand import sys class Tox(TestCommand): user_options = [('tox-args=', 'a', "Arguments to pass to tox")] def initialize_options(self): TestCommand.initialize_options(self) self.tox_args = None def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox import shlex errno = tox.cmdline(args=shlex.split(self.tox_args)) sys.exit(errno) setup( name = "adbpy", version = "0.0.2", url = "https://github.com/noahgoldman/adbpy", license = "MIT", author = "Noah Goldman", author_email = "noah@phaaze.com", description = "A library to communicate with ADB through it's " "internal socket interface, rather than the command" "line.", platforms = "any", packages = ["adbpy"], tests_require = ['tox'], cmdclass = {'test': Tox}, )
Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests
import socket class EchoServer(object): """a simple EchoServer""" def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5): self.ip = ip self.port = port self.backlog = backlog self.socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) self.socket.bind((self.ip, self.port)) self.socket.listen(self.backlog) def start_listening(self): while True: request = [] self.connection, self.addr = self.socket.accept() while True: buffer_ = self.connection.recv(32) if buffer_: request.append(buffer_) else: break self.connection.sendall(" ".join(request)) self.connection.close() if __name__ == "__main__": server = EchoServer() server.start_listening()
import socket class EchoServer(object): """a simple EchoServer""" def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5): self.ip = ip self.port = port self.backlog = backlog self.socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) self.socket.bind((self.ip, self.port)) self.socket.listen(self.backlog) def start_listening(self): while True: self.connection, self.addr = self.socket.accept() words = self.connection.recv(32) if words: self.connection.sendall(unicode(words)) self.connection.close() self.socket.close() break if __name__ == "__main__": server = EchoServer() server.start_listening()
Check for empty response for getMessageList() calls
import Ember from 'ember'; import _ from 'lodash'; export default Ember.Route.extend({ /** * @param {params.mailbox_name} The name of the mailbox ('Inbox', 'Archives') */ model(params) { var mailboxName = params.mailbox_name, mailboxes = this.modelFor('shell.mail'); return new Ember.RSVP.Promise(function (resolve, reject) { var mailbox = _.find(mailboxes, _.matchesProperty('name', mailboxName)); if (!mailbox) { console.error('No mailbox by that name found.'); return reject(); } // TODO: Need design input before we add ways to fetch more messages return mailbox.getMessageList({ sort: 'date desc', collapseThreads: true, fetchMessages: true, limit: 50 }).then(function (response) { let messages = response.length ? response[1] : []; resolve(messages); }, reject); }); } });
import Ember from 'ember'; import _ from 'lodash'; export default Ember.Route.extend({ /** * @param {params.mailbox_name} The name of the mailbox ('Inbox', 'Archives') */ model(params) { var mailboxName = params.mailbox_name, mailboxes = this.modelFor('shell.mail'); return new Ember.RSVP.Promise(function (resolve, reject) { var mailbox = _.find(mailboxes, _.matchesProperty('name', mailboxName)); if (!mailbox) { console.error('No mailbox by that name found.'); return reject(); } // TODO: Need design input before we add ways to fetch more messages mailbox.getMessageList({ sort: 'date desc', collapseThreads: true, fetchMessages: true, limit: 50 }).then(function (response) { resolve(response[1]); }, reject); }); } });
Install kernel extensions for aufs
package main import "github.com/dynport/urknall" type Docker struct { Version string `urknall:"required=true"` // e.g. 1.1.0 CustomInstallDir string Public bool } func (docker *Docker) Render(pkg urknall.Package) { pkg.AddCommands("packages", InstallPackages("aufs-tools", "cgroup-lite", "xz-utils", "git", "linux-image-extra-$(uname -r)")) pkg.AddCommands("install", Mkdir("{{ .InstallDir }}/bin", "root", 0755), Download("http://get.docker.io/builds/Linux/x86_64/docker-{{ .Version }}", "{{ .InstallDir }}/bin/docker", "root", 0755), ) pkg.AddCommands("upstart", WriteFile("/etc/init/docker.conf", dockerUpstart, "root", 0644)) } const dockerUpstart = `exec {{ .InstallDir }}/bin/docker -d -H tcp://{{ if .Public }}0.0.0.0{{ else }}127.0.0.1{{ end }}:4243 -H unix:///var/run/docker.sock 2>&1 | logger -i -t docker ` func (docker *Docker) InstallDir() string { if docker.Version == "" { panic("Version must be set") } if docker.CustomInstallDir != "" { return docker.CustomInstallDir } return "/opt/docker-" + docker.Version }
package main import "github.com/dynport/urknall" type Docker struct { Version string `urknall:"required=true"` // e.g. 1.1.0 CustomInstallDir string Public bool } func (docker *Docker) Render(pkg urknall.Package) { pkg.AddCommands("packages", InstallPackages("aufs-tools", "cgroup-lite", "xz-utils", "git")) pkg.AddCommands("install", Mkdir("{{ .InstallDir }}/bin", "root", 0755), Download("http://get.docker.io/builds/Linux/x86_64/docker-{{ .Version }}", "{{ .InstallDir }}/bin/docker", "root", 0755), ) pkg.AddCommands("upstart", WriteFile("/etc/init/docker.conf", dockerUpstart, "root", 0644)) } const dockerUpstart = `exec {{ .InstallDir }}/bin/docker -d -H tcp://{{ if .Public }}0.0.0.0{{ else }}127.0.0.1{{ end }}:4243 -H unix:///var/run/docker.sock 2>&1 | logger -i -t docker ` func (docker *Docker) InstallDir() string { if docker.Version == "" { panic("Version must be set") } if docker.CustomInstallDir != "" { return docker.CustomInstallDir } return "/opt/docker-" + docker.Version }
Fix para iphone al abrir controlador Al abrir el controlador de forms no se veia el window title
/** * Global Navigation Handler */ Alloy.Globals.Navigator = { /** * Handle to the Navigation Controller */ navGroup: $.nav, open: function(controller, payload){ var win = Alloy.createController(controller, payload || {}).getView(); if(OS_IOS){ $.nav.openWindow(win); } else if(OS_MOBILEWEB){ $.nav.open(win); } else { // added this property to the payload to know if the window is a child if (payload.displayHomeAsUp){ win.addEventListener('open',function(evt){ var activity=win.activity; activity.actionBar.displayHomeAsUp=payload.displayHomeAsUp; activity.actionBar.onHomeIconItemSelected=function(){ evt.source.close(); }; }); } win.open(); } } }; if(OS_IOS){ $.nav.open() } else if(OS_MOBILEWEB){ $.index.open(); } else{ $.index.getView().open(); }
/** * Global Navigation Handler */ Alloy.Globals.Navigator = { /** * Handle to the Navigation Controller */ navGroup: $.nav, open: function(controller, payload){ var win = Alloy.createController(controller, payload || {}).getView(); if(OS_IOS){ $.nav.openWindow(win); } else if(OS_MOBILEWEB){ $.nav.open(win); } else { // added this property to the payload to know if the window is a child if (payload.displayHomeAsUp){ win.addEventListener('open',function(evt){ var activity=win.activity; activity.actionBar.displayHomeAsUp=payload.displayHomeAsUp; activity.actionBar.onHomeIconItemSelected=function(){ evt.source.close(); }; }); } win.open(); } } }; /** * Lets add a loading animation - Just for Fun! */ var loadingView = Alloy.createController("form"); loadingView.getView().open();
Revert "Bugfix defineWidth for List Carousel Image due float" This reverts commit 7be1cc54181636a8d7bb8037e9ab38facd41f58f.
<?php class Kwc_List_Carousel_Image_Component extends Kwc_Basic_Image_Component { public static function getSettings() { $ret = parent::getSettings(); $ret['componentName'] = trlKwfStatic('Carousel'); $ret['dimensions'] = array( 'fullWidth'=>array( 'text' => trlKwf('full width'), 'width' => self::CONTENT_WIDTH, 'height' => 337, 'cover' => true ), ); return $ret; } }
<?php class Kwc_List_Carousel_Image_Component extends Kwc_Basic_Image_Component { public static function getSettings() { $ret = parent::getSettings(); $ret['componentName'] = trlKwfStatic('Carousel'); $ret['dimensions'] = array( 'fullWidth'=>array( 'text' => trlKwf('full width'), 'width' => self::CONTENT_WIDTH, 'height' => 337, 'cover' => true ), ); $ret['defineWidth'] = true; return $ret; } }
Fix urls with %20 instead of whitespaces
package com.chbi.rest; import com.chbi.ApplicationConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; /** * Handles the jenkins urls, appends the json api suffix and replaces url parts if necessary. */ @Service public class UrlRewriter { private static final String API_JSON_URL_ENDING = "api/json"; private static final String HTML_WHITESPACE = "%20"; private static final String WHITESPACE = " "; @Autowired private ApplicationConfiguration configuration; String prepareUrl(String baseUrl) { String preparedUrl = StringUtils.replace(baseUrl, configuration.getUrlSearchPattern(), configuration.getUrlReplacement()); preparedUrl = StringUtils.replace(preparedUrl, HTML_WHITESPACE, WHITESPACE); preparedUrl += API_JSON_URL_ENDING; return preparedUrl; } String getPreparedBaseUrl() { return prepareUrl(configuration.getBaseUrl()); } }
package com.chbi.rest; import com.chbi.ApplicationConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; /** * Handles the jenkins urls, appends the json api suffix and replaces url parts if necessary. */ @Service public class UrlRewriter { public static final String API_JSON_URL_ENDING = "api/json"; @Autowired private ApplicationConfiguration configuration; String prepareUrl(String baseUrl) { String preparedUrl = StringUtils.replace(baseUrl, configuration.getUrlSearchPattern(), configuration.getUrlReplacement()); preparedUrl += API_JSON_URL_ENDING; return preparedUrl; } String getPreparedBaseUrl() { return prepareUrl(configuration.getBaseUrl()); } }
Remove unnecessary stuff from webpack test confs
/* eslint-disable no-var */ var path = require('path'); var merge = require('webpack-merge'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var common = require('./webpack.common'); module.exports = merge(common, { module: { preLoaders: [], loaders: [ { test: /\.js$/, include: [ path.resolve(__dirname, '../app'), path.resolve(__dirname, '../tests'), ], loaders: ['babel'], }, ], }, plugins: [ new HtmlWebpackPlugin({ favicon: './app/assets/images/favicon.ico', inject: true, template: './conf/template.html', }), ], });
/* eslint-disable no-var */ var path = require('path'); var merge = require('webpack-merge'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var common = require('./webpack.common'); module.exports = merge(common, { module: { preLoaders: [], loaders: [ { test: /\.js$/, include: [ path.resolve(__dirname, '../app'), path.resolve(__dirname, '../tests'), ], loaders: ['babel'], }, { test: /\.css$/, loader: 'style!css!postcss-loader', }, { test: /\.scss$/, loader: 'style!css!postcss-loader!sass', }, ], noParse: [ /\/sinon.js/, ], }, plugins: [ new HtmlWebpackPlugin({ favicon: './app/assets/images/favicon.ico', inject: true, template: './conf/template.html', }), ], });
Fix revisions not showing up on the revision datagrid
<?php namespace Backend\Modules\ContentBlocks\ContentBlock; use Backend\Core\Engine\DataGridDB; use Backend\Core\Language\Locale; class RevisionDataGrid extends DataGridDB { /** * @param ContentBlock $contentBlock * @param Locale $locale */ public function __construct(ContentBlock $contentBlock, Locale $locale) { parent::__construct( 'SELECT i.id, i.revision_id, i.title, UNIX_TIMESTAMP(i.edited_on) AS edited_on, i.user_id FROM content_blocks AS i WHERE i.status = :archived AND i.id = :id AND i.language = :language ORDER BY i.edited_on DESC', ['archived' => Status::archived(), 'language' => $locale, 'id' => $contentBlock->getId()] ); } }
<?php namespace Backend\Modules\ContentBlocks\ContentBlock; use Backend\Core\Engine\DataGridDB; use Backend\Core\Language\Locale; class RevisionDataGrid extends DataGridDB { /** * @param ContentBlock $contentBlock * @param Locale $locale */ public function __construct(ContentBlock $contentBlock, Locale $locale) { parent::__construct( 'SELECT i.id, i.revision_id, i.title, UNIX_TIMESTAMP(i.edited_on) AS edited_on, i.user_id FROM content_blocks AS i WHERE i.status = :archived AND i.id = :id AND i.language = :language ORDER BY i.edited_on DESC', ['archived' => Status::active(), 'language' => $locale, 'id' => $contentBlock->getId()] ); } }
Remove all traces of ls.
# Copyright 2014-2015 0xc0170 # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import locale def rmtree_if_exists(directory): if os.path.exists(directory): shutil.rmtree(directory) def uniqify(_list): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, _list, ([], set()))[0] def flatten_list(_list): all_items = [item if len(item) > 1 else sublist for sublist in _list for item in sublist] return uniqify(all_items) def unicode_available(): return locale.getdefaultlocale()[1] == 'UTF-8'
# Copyright 2014-2015 0xc0170 # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import locale def rmtree_if_exists(directory): if os.path.exists(directory): shutil.rmtree(directory) def uniqify(l): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0] def flatten_list(l): all_items = [item if len(item) > 1 else sublist for sublist in l for item in sublist] return uniqify(all_items) def unicode_available(): return locale.getdefaultlocale()[1] == 'UTF-8'
Remove redundant call to disable webpack 'watch' mode
var gulp = require('gulp'); var rename = require('gulp-rename'); var browserSync = require('browser-sync'); var webpackStream = require('webpack-stream'); var webpack = require('webpack'); var config = { module: { loaders: [ { test: /\.csv?$/, loader: 'dsv-loader' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.js$/, loader: 'babel', exclude: /node_modules/ } ] } }; gulp.task('js-dev', function() { config.plugins = []; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('dist/dev/js')) .pipe(browserSync.reload({stream:true})); }); gulp.task('js-prod', function() { config.plugins = [ new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin() ]; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('.tmp/js')); });
var gulp = require('gulp'); var rename = require('gulp-rename'); var browserSync = require('browser-sync'); var webpackStream = require('webpack-stream'); var webpack = require('webpack'); var config = { watch: false, module: { loaders: [ { test: /\.csv?$/, loader: 'dsv-loader' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.js$/, loader: 'babel', exclude: /node_modules/ } ] } }; gulp.task('js-dev', function() { config.plugins = []; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('dist/dev/js')) .pipe(browserSync.reload({stream:true})); }); gulp.task('js-prod', function() { config.plugins = [ new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin() ]; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('.tmp/js')); });
Expand the tree view by defualt
'use babel'; export default class Parser { source: null editor: null parse(source, editor) { this.source = source; this.editor = editor; return this.scan(); } scan() { let result = [], count = 0; // Find 'describes', set indexs, find 'it' this.findInstanceOf('describe(\'', result, 0, this.source.length); this.getEndIndex(result); result.map((obj) => obj.children = []); result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex)); return result; } findInstanceOf(word, result, startIndex, endIndex) { let index = startIndex, wordLength = word.length, name, position; while (index != -1 && index < endIndex) { index++; index = this.source.indexOf(word, index); if (index == -1 || index > endIndex) break; name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1)); position = this.editor.buffer.positionForCharacterIndex(index); result.push({index, name, position, expanded: true,}); } } getEndIndex(arr){ arr.map((obj, index, arr) => { if (arr[index + 1]) { obj.endIndex = arr[index + 1]['index']; } else { obj.endIndex = this.source.length; } }); } }
'use babel'; export default class Parser { source: null editor: null parse(source, editor) { this.source = source; this.editor = editor; return this.scan(); } scan() { let result = [], count = 0; // Find 'describes', set indexs, find 'it' this.findInstanceOf('describe(\'', result, 0, this.source.length); this.getEndIndex(result); result.map((obj) => obj.children = []); result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex)); return result; } findInstanceOf(word, result, startIndex, endIndex) { let index = startIndex, wordLength = word.length, name, position; while (index != -1 && index < endIndex) { index++; index = this.source.indexOf(word, index); if (index == -1 || index > endIndex) break; name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1)); position = this.editor.buffer.positionForCharacterIndex(index); result.push({index, name, position}); } } getEndIndex(arr){ arr.map((obj, index, arr) => { if (arr[index + 1]) { obj.endIndex = arr[index + 1]['index']; } else { obj.endIndex = this.source.length; } }); } }
Update a version number from trunk r9016 git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@9040 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6
# -*- coding: utf-8 -*- __version__ = '$Id$' import family # The Wikia Search family # user-config.py: usernames['wikia']['wikia'] = 'User name' class Family(family.Family): def __init__(self): family.Family.__init__(self) self.name = u'wikia' self.langs = { u'wikia': None, } def hostname(self, code): return u'www.wikia.com' def version(self, code): return "1.16.2" def scriptpath(self, code): return '' def apipath(self, code): return '/api.php'
# -*- coding: utf-8 -*- __version__ = '$Id$' import family # The Wikia Search family # user-config.py: usernames['wikia']['wikia'] = 'User name' class Family(family.Family): def __init__(self): family.Family.__init__(self) self.name = u'wikia' self.langs = { u'wikia': None, } def hostname(self, code): return u'www.wikia.com' def version(self, code): return "1.15.1" def scriptpath(self, code): return '' def apipath(self, code): return '/api.php'
Add heartbeat listener to mock channel provider class
package com.simperium.test; import com.simperium.client.Bucket; import com.simperium.client.ChannelProvider; import java.util.ArrayList; import java.util.List; public class MockChannelProvider implements ChannelProvider { public List<String> logs = new ArrayList<String>(); @Override public MockChannel buildChannel(Bucket bucket) { return new MockChannel(bucket); } @Override public void log(int level, CharSequence message) { // noop logs.add(message.toString()); } @Override public int getLogLevel() { return ChannelProvider.LOG_DISABLED; } @Override public void addHeartbeatListener(HeartbeatListener listener) { } public String getLastLog() { if (logs.size() > 0) { return logs.get(logs.size()-1); } return null; } }
package com.simperium.test; import com.simperium.client.Bucket; import com.simperium.client.ChannelProvider; import java.util.ArrayList; import java.util.List; public class MockChannelProvider implements ChannelProvider { public List<String> logs = new ArrayList<String>(); @Override public MockChannel buildChannel(Bucket bucket) { return new MockChannel(bucket); } @Override public void log(int level, CharSequence message) { // noop logs.add(message.toString()); } @Override public int getLogLevel() { return ChannelProvider.LOG_DISABLED; } public String getLastLog() { if (logs.size() > 0) { return logs.get(logs.size()-1); } return null; } }
Return error if file already exists
package main import ( "net/http" "io/ioutil" "os" ) func saveHandler(w http.ResponseWriter, r *http.Request) { folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/" filename := generateRandomURL() path := folder + filename if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { http.Error(w, err.Error(), http.StatusInternalServerError) return } } r.ParseForm() text := r.Form.Get("text") ioutil.WriteFile(path, []byte(text), 0400) http.Redirect(w, r, "/"+filename, http.StatusCreated) } func generateRandomURL() string { return "1234556" } func main() { http.HandleFunc("/save", saveHandler) http.ListenAndServe(":8080", nil) }
package main import ( "net/http" "io/ioutil" "os" ) func saveHandler(w http.ResponseWriter, r *http.Request) { folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/" filename := generateRandomURL() path := folder + filename if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { http.Error(w, err.Error(), http.StatusInternalServerError) } } r.ParseForm() text := r.Form.Get("text") ioutil.WriteFile(path, []byte(text), 0400) http.Redirect(w, r, "/"+filename, http.StatusCreated) } func generateRandomURL() string { return "1234556" } func main() { http.HandleFunc("/save", saveHandler) http.ListenAndServe(":8080", nil) }
Fix percentage recalculation when both votes are zero
var app = angular.module('catsvsdogs', []); var socket = io.connect({transports:['polling']}); var bg1 = document.getElementById('background-stats-1'); var bg2 = document.getElementById('background-stats-2'); app.controller('statsCtrl', function($scope){ $scope.aPercent = 50; $scope.bPercent = 50; var updateScores = function(){ socket.on('scores', function (json) { data = JSON.parse(json); var a = parseInt(data.a || 0); var b = parseInt(data.b || 0); var percentages = getPercentages(a, b); bg1.style.width = percentages.a + "%"; bg2.style.width = percentages.b + "%"; $scope.$apply(function () { $scope.aPercent = percentages.a; $scope.bPercent = percentages.b; $scope.total = a + b; }); }); }; var init = function(){ document.body.style.opacity=1; updateScores(); }; socket.on('message',function(data){ init(); }); }); function getPercentages(a, b) { var result = {}; if (a + b > 0) { result.a = Math.round(a / (a + b) * 100); result.b = 100 - result.a; } else { result.a = result.b = 50; } return result; }
var app = angular.module('catsvsdogs', []); var socket = io.connect({transports:['polling']}); var bg1 = document.getElementById('background-stats-1'); var bg2 = document.getElementById('background-stats-2'); app.controller('statsCtrl', function($scope){ var animateStats = function(a,b){ if(a+b>0){ var percentA = a/(a+b)*100; var percentB = 100-percentA; bg1.style.width= percentA+"%"; bg2.style.width = percentB+"%"; } }; $scope.aPercent = 50; $scope.bPercent = 50; var updateScores = function(){ socket.on('scores', function (json) { data = JSON.parse(json); var a = parseInt(data.a || 0); var b = parseInt(data.b || 0); animateStats(a, b); $scope.$apply(function() { if(a + b > 0){ $scope.aPercent = a/(a+b) * 100; $scope.bPercent = b/(a+b) * 100; $scope.total = a + b } }); }); }; var init = function(){ document.body.style.opacity=1; updateScores(); }; socket.on('message',function(data){ init(); }); });
Use a named function instead via @hunterloftis
'use strict'; let cli = require('heroku-cli-util'); let request = require('request'); module.exports = { topic: 'builds', command: 'output', needsAuth: true, needsApp: true, description: 'show build output', help: 'Show build output for a Heroku app', variableArgs: true, run: cli.command(showOutput) }; function showOutput(context, heroku) { let id = context.args[0]; if (!id) { cli.error("Usage: heroku builds:output <id> -a <app>") return } return heroku.request({ path: `/apps/${context.app}/builds/${id}`, method: 'GET', headers: { 'Accept': 'application/vnd.heroku+json; version=3.streaming-build-output' }, parseJSON: true }).then(function (build) { request(build.output_stream_url).pipe(process.stdout); }); }
'use strict'; let cli = require('heroku-cli-util'); let request = require('request'); module.exports = { topic: 'builds', command: 'output', needsAuth: true, needsApp: true, description: 'show build output', help: 'Show build output for a Heroku app', variableArgs: true, run: cli.command(function (context, heroku) { let id = context.args[0]; if (!id) { cli.error("Usage: heroku builds:output <id> -a <app>") return } return heroku.request({ path: `/apps/${context.app}/builds/${id}`, method: 'GET', headers: { 'Accept': 'application/vnd.heroku+json; version=3.streaming-build-output' }, parseJSON: true }).then(function (build) { request(build.output_stream_url).pipe(process.stdout); }); }) };
Change status codes and messages
import os from werkzeug.utils import secure_filename import config from flask_restful import Resource from flask import request, abort def allowed_file(filename): return ('.' in filename and filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS) class File(Resource): def post(self): if 'uploaded_data' not in request.files: abort(400, 'Uploaded_data is required for the request') file = request.files['uploaded_data'] if file.filename == '': abort(400, 'Filename cannot be empty') if allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File uploaded successfully'} else: abort(415, 'File type is not supported') def delete(self): filename = secure_filename(request.args.get('filename')) os.remove(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File deleted successfully'}
import os from werkzeug.utils import secure_filename import config from flask_restful import Resource from flask import request, abort def allowed_file(filename): return ('.' in filename and filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS) class File(Resource): def post(self): if 'uploaded_data' not in request.files: abort(500) file = request.files['uploaded_data'] if file.filename == '': abort(500) if allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File uploaded successfully'} def delete(self): filename = request.args.get('filename') os.remove(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File deleted successfully'}
Fix a typo: interacive -> interactive
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="scgv", version="1.0.1", author="Lubomir Chorbadjiev", author_email="lubomir.chorbadjiev@gmail.com", description="SCGV is an interactive graphical tool for single-cell genomics data, with emphasis on single-cell genomics of cancer", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/KrasnitzLab/SCGV", packages=setuptools.find_packages( # 'scgv', exclude=['docs', 'tests'] ), # package_dir={'':'scgv'}, entry_points={ 'console_scripts': [ 'scgview=scgv.tkmain:main', ] }, classifiers=( "Development Status :: 4 - Beta", "Programming Language :: Python :: 3.6", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ), python_requires='>=3.6', )
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="scgv", version="1.0.1", author="Lubomir Chorbadjiev", author_email="lubomir.chorbadjiev@gmail.com", description="SCGV is an interacive graphical tool for single-cell genomics data, with emphasis on single-cell genomics of cancer", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/KrasnitzLab/SCGV", packages=setuptools.find_packages( # 'scgv', exclude=['docs', 'tests'] ), # package_dir={'':'scgv'}, entry_points={ 'console_scripts': [ 'scgview=scgv.tkmain:main', ] }, classifiers=( "Development Status :: 4 - Beta", "Programming Language :: Python :: 3.6", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ), python_requires='>=3.6', )
Allow glfw.init() to fail on CI as well
import pytest @pytest.fixture def pyglui_ui_instance(): import glfw from pyglui import cygl, ui glfw.ERROR_REPORTING = "raise" try: glfw_init_successful = glfw.init() assert glfw_init_successful, "Failed to initialize GLFW" glfw.window_hint(glfw.VISIBLE, glfw.FALSE) window = glfw.create_window(200, 200, "Test window", None, None) except glfw.GLFWError as err: # Skip if CI does not allow creating a window, e.g. on macOS: # > NSGL: Failed to find a suitable pixel format glfw.terminate() pytest.skip(str(err)) glfw.make_context_current(window) # required for GLEW init cygl.utils.init() global_ui_instance = ui.UI() yield global_ui_instance global_ui_instance.terminate() glfw.destroy_window(window) glfw.terminate() @pytest.fixture def attribute_context(): return {"test": 5} def test_Color_Legend(pyglui_ui_instance, attribute_context): import pyglui.ui black = (0.0, 0.0, 0.0, 1.0) pyglui.ui.Color_Legend(black, "test color")
import pytest @pytest.fixture def pyglui_ui_instance(): import glfw from pyglui import cygl, ui glfw.ERROR_REPORTING = "raise" glfw_init_successful = glfw.init() assert glfw_init_successful, "Failed to initialize GLFW" glfw.window_hint(glfw.VISIBLE, glfw.FALSE) try: window = glfw.create_window(200, 200, "Test window", None, None) except glfw.GLFWError as err: # Skip if CI does not allow creating a window, e.g. on macOS: # > NSGL: Failed to find a suitable pixel format glfw.terminate() pytest.skip(str(err)) glfw.make_context_current(window) # required for GLEW init cygl.utils.init() global_ui_instance = ui.UI() yield global_ui_instance global_ui_instance.terminate() glfw.destroy_window(window) glfw.terminate() @pytest.fixture def attribute_context(): return {"test": 5} def test_Color_Legend(pyglui_ui_instance, attribute_context): import pyglui.ui black = (0.0, 0.0, 0.0, 1.0) pyglui.ui.Color_Legend(black, "test color")
Make in-built version args work
/* * index.js: Top-level include for flatiron-cli-version * * (C) 2012, Pavan Kumar Sunkara * */ var path = require('path'); var cliVersion = exports = module.exports; cliVersion.name = 'cli-version'; cliVersion.attach = function (options) { var app = this; options = options || {}; if (!app.cli) { app.cli = {}; } app.cli.version = true; var data = { exports: {} }; require('pkginfo')(data, { include: ['name', 'version'], dir: options.dir || __dirname }); if (!app.name) { app.name = data.exports.name; } app.version = data.exports.version; }; cliVersion.init = function (done) { var app = this; if (!app.plugins.cli) { throw new Error('`cli` plugin is required to use `flatiron-cli-version`'); } app.commands['version'] = function (cb) { app.log.info(app.name + ' ' + ('v' + app.version).yellow.bold); cb(null); }; app.commands['version'].usage = [ 'Display app version', '', app.name + ' version' ].join("\n"); done(); };
/* * index.js: Top-level include for flatiron-cli-version * * (C) 2012, Pavan Kumar Sunkara * */ var path = require('path'); var cliVersion = exports = module.exports; cliVersion.name = 'cli-version'; cliVersion.attach = function (options) { var app = this; options = options || {}; if (!app.plugins.cli) { throw new Error('`cli` plugin is required to use `flatiron-cli-version`'); } var data = { exports: {} }; require('pkginfo')(data, { include: ['name', 'version'], dir: options.dir || __dirname }); if (!app.name) { app.name = data.exports.name; } app.version = data.exports.version; app.commands['version'] = function (cb) { app.log.info(app.name + ' ' + ('v' + app.version).yellow.bold); cb(null); }; app.commands['version'].usage = [ 'Display app version', '', app.name + ' version' ].join("\n"); };
Fix not being able to serve fonts and other assets using query string cache busters.
'use strict'; import config from '../config'; import url from 'url'; import browserSync from 'browser-sync'; import gulp from 'gulp'; gulp.task('browserSync', function() { const DEFAULT_FILE = 'index.html'; const ASSET_EXTENSION_REGEX = /\b(?!\?)\.(js|css|png|jpe?g|gif|svg|eot|otf|ttc|ttf|woff2?)(?!\.)/i; browserSync.init({ server: { baseDir: config.buildDir, middleware: function(req, res, next) { let fileHref = url.parse(req.url).href; if ( !ASSET_EXTENSION_REGEX.test(fileHref) ) { req.url = '/' + DEFAULT_FILE; } return next(); } }, port: config.browserPort, ui: { port: config.UIPort }, ghostMode: { links: false } }); });
'use strict'; import config from '../config'; import url from 'url'; import browserSync from 'browser-sync'; import gulp from 'gulp'; gulp.task('browserSync', function() { const DEFAULT_FILE = 'index.html'; const ASSET_EXTENSIONS = ['js', 'css', 'png', 'jpg', 'jpeg', 'gif']; browserSync.init({ server: { baseDir: config.buildDir, middleware: function(req, res, next) { let fileHrefArray = url.parse(req.url).href.split('.'); let fileExtension = fileHrefArray[fileHrefArray.length - 1]; if ( ASSET_EXTENSIONS.indexOf(fileExtension) === -1 ) { req.url = '/' + DEFAULT_FILE; } return next(); } }, port: config.browserPort, ui: { port: config.UIPort }, ghostMode: { links: false } }); });
Fix a bug in the bug-catching code Well this is ironic. No idea how to test this either.
import stdio from './stdio' import { resolve } from 'path' import { inspect } from 'util' import { writeFileSync, unlinkSync } from 'fs' const sysio = stdio({ debug: !!process.env.DEBUG, format: 'normal' }) const bugs = new Map() process.on('unhandledRejection', (reason, p) => { bugs.set(p, reason) }) process.on('rejectionHandled', (p) => { bugs.delete(p) }) process.on('exit', code => { const log = resolve('./ez-build-debug.log') if (bugs.size) { sysio.error(`\n---\n\nYou've found a bug! :o(\n`) sysio.error(`Please include the following file with any support request:\n`) sysio.error(` ${log}\n\n---`) let reasons = [] reasons.push(`Unhandled rejections: ${bugs.size}\n`) for (let [_, reason] of bugs) { reasons.push(`Rejection #${reasons.length}:\n${inspect(reason)}\n`) } writeFileSync(log, reasons.join('\n')) process.exit(1) } else { try { unlinkSync(log) } catch (e) { /* Let's not care about errors */ } } })
import stdio from './stdio' import { resolve } from 'path' import { inspect } from 'util' import { writeFileSync, unlinkSync } from 'fs' const sysio = stdio({ debug: !!process.env.DEBUG, format: 'normal' }) const bugs = new Map() process.on('unhandledRejection', (reason, p) => { bugs.set(p, reason) }) process.on('rejectionHandled', (p) => { bugs.delete(p) }) process.on('exit', code => { if (bugs.size) { sysio.error(`\n---\n\nYou've found a bug! :o(\n`) sysio.error(`Please include the following file with any support request:\n`) const log = resolve('./ez-build-debug.log') sysio.error(` ${log}\n\n---`) let reasons = [] reasons.push(`Unhandled rejections: ${bugs.size}\n`) for (let [_, reason] of bugs) { reasons.push(`Rejection #${reasons.length}:\n${inspect(reason)}\n`) } writeFileSync(log, reasons.join('\n')) process.exit(1) } else { try { unlinkSync(log) } catch (e) { /* Let's not care about errors */ } } })
Add sorting by fissure tier This sorts the fissures in the list in ascending order according to tier, starting with Lith and ending with Axi.
'use strict'; const Command = require('../../Command.js'); const FissureEmbed = require('../../embeds/FissureEmbed.js'); /** * Displays the currently active Invasions */ class Fissures extends Command { /** * Constructs a callable command * @param {Genesis} bot The bot object */ constructor(bot) { super(bot, 'warframe.worldstate.fissures', 'fissures', 'Get the current list of Void Fissure Missions'); } /** * Run the command * @param {Message} message Message with a command to handle, reply to, * or perform an action based on parameters. */ run(message) { this.bot.settings.getChannelPlatform(message.channel) .then(platform => this.bot.worldStates[platform].getData()) .then((ws) => { const fissures = ws.fissures.sort((a, b) => { return a.tierNum > b.TierNum; }); this.messageManager.embed(message, new FissureEmbed(this.bot, fissures), true, false); }) .catch(this.logger.error); } } module.exports = Fissures;
'use strict'; const Command = require('../../Command.js'); const FissureEmbed = require('../../embeds/FissureEmbed.js'); /** * Displays the currently active Invasions */ class Fissures extends Command { /** * Constructs a callable command * @param {Genesis} bot The bot object */ constructor(bot) { super(bot, 'warframe.worldstate.fissures', 'fissures', 'Get the current list of Void Fissure Missions'); } /** * Run the command * @param {Message} message Message with a command to handle, reply to, * or perform an action based on parameters. */ run(message) { this.bot.settings.getChannelPlatform(message.channel) .then(platform => this.bot.worldStates[platform].getData()) .then((ws) => { const fissures = ws.fissures; this.messageManager.embed(message, new FissureEmbed(this.bot, fissures), true, false); }) .catch(this.logger.error); } } module.exports = Fissures;
Validate data in stream test
'use strict' var fs = require('../') var rimraf = require('rimraf') var mkdirp = require('mkdirp') var test = require('tap').test var p = require('path').resolve(__dirname, 'files') process.chdir(__dirname) // Make sure to reserve the stderr fd process.stderr.write('') var num = 4097 var paths = new Array(num) test('write files', function (t) { rimraf.sync(p) mkdirp.sync(p) t.plan(num) for (var i = 0; i < num; ++i) { paths[i] = 'files/file-' + i var stream = fs.createWriteStream(paths[i]) stream.on('finish', function () { t.pass('success') }) stream.write('content') stream.end() } }) test('read files', function (t) { // now read them t.plan(num) for (var i = 0; i < num; ++i) (function (i) { var stream = fs.createReadStream(paths[i]) var data = '' stream.on('data', function (c) { data += c }) stream.on('end', function () { t.equal(data, 'content') }) })(i) }) test('cleanup', function (t) { rimraf.sync(p) t.end() })
'use strict' var fs = require('../') var rimraf = require('rimraf') var mkdirp = require('mkdirp') var test = require('tap').test var p = require('path').resolve(__dirname, 'files') process.chdir(__dirname) // Make sure to reserve the stderr fd process.stderr.write('') var num = 4097 var paths = new Array(num) test('write files', function (t) { rimraf.sync(p) mkdirp.sync(p) var done = 0 for (var i = 0; i < num; ++i) { paths[i] = 'files/file-' + i var stream = fs.createWriteStream(paths[i]) stream.on('end', function () { ++done if (done === num) { t.pass('success') t.end() } }) stream.write('content') stream.end() } t.end() }) test('read files', function (t) { // now read them var done = 0 for (var i = 0; i < num; ++i) { var stream = fs.createReadStream(paths[i]) stream.on('data', function (data) {}) stream.on('end', function () { ++done if (done === num) { t.pass('success') t.end() } }) } }) test('cleanup', function (t) { rimraf.sync(p) t.end() })
Change names of variables in settings file
import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import bodyParser from "body-parser" import mongoose, { Schema } from "mongoose" import schema from "./graphql" import Item from "./db/item" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb.database}`, { useMongoClient: true } ) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(() => ({ schema })) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import bodyParser from "body-parser" import mongoose, { Schema } from "mongoose" import schema from "./graphql" import Item from "./db/item" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongo.url}:${CONFIG.mongo.port}/${CONFIG.mongo.database}`, { useMongoClient: true } ) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(() => ({ schema })) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
Adjust extras sublime plugin to follow new changes
import sublime import sublime_plugin from os.path import basename, dirname import subprocess def parse_file_name(file_name): if file_name is None: title = "Untitled" basepath = None else: title = basename(file_name) basepath = dirname(file_name) return title, basepath class MdownPreviewCommand(sublime_plugin.TextCommand): def run(self, edit): title, basepath = parse_file_name(self.view.file_name()) self.convert(title, basepath) def convert(self, title, basepath): binary = sublime.load_settings("mdown.sublime-settings").get("binary", None) if binary is not None: cmd = [binary, "-T", title, "-s", "-p"] if basepath is not None: cmd += ["-b", basepath] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in self.view.lines(sublime.Region(0, self.view.size())): p.stdin.write((self.view.substr(line) + '\n').encode('utf-8')) print(p.communicate()[0].decode("utf-8"))
import sublime import sublime_plugin from os.path import basename, dirname import subprocess def parse_file_name(file_name): if file_name is None: title = "Untitled" basepath = None else: title = basename(file_name) basepath = dirname(file_name) return title, basepath class MdownPreviewCommand(sublime_plugin.TextCommand): def run(self, edit): title, basepath = parse_file_name(self.view.file_name()) self.convert(title, basepath) def convert(self, title, basepath): binary = sublime.load_settings("mdown.sublime-settings").get("binary", None) if binary is not None: cmd = [binary, "-t", title, "-s", "-p"] if basepath is not None: cmd += ["-b", basepath] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in self.view.lines(sublime.Region(0, self.view.size())): p.stdin.write((self.view.substr(line) + '\n').encode('utf-8')) print(p.communicate()[0].decode("utf-8"))
Update to handle modal window submits.
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { data = $(data); var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); $("#modal .modal-header h3").text(heading.text()); var submit = data.find("form input[type=submit]").eq(0).remove(); $("#modal .modal-body").html(data.html()); footer = $("#modal .modal-footer") var old_submit = footer.find("#modal .modal-footer input[type=submit]").eq(0).remove(); if (submit) { footer.prepend(submit); } $("#modal").modal("show"); } var display_modal = function(event) { event.preventDefault(); $.get(this.href, "", populate_modal, "html"); return false; } var ajax_form_catch = function(event) { event.preventDefault(); var form = $("#modal form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); return false; }; $("a.ajax_window").live("click", display_modal); $("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch); $("#modal form").live("submit", ajax_form_catch); });
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { data = $(data); var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); $("#modal .modal-header h3").text(heading.text()); var submit = data.find("form input[type=submit]").eq(0).remove(); $("#modal .modal-body").html(data.html()); if (submit) $("#modal .modal-footer").html(submit.wrap('<div>').parent().html()); $("#modal").modal("show"); } var display_modal = function(event) { event.preventDefault(); $.get(this.href, "", populate_modal, "html"); return false; } var ajax_form_catch = function(event) { event.preventDefault(); var form = $("#modal form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); return false; }; $("a.ajax_window").live("click", display_modal); $("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch); $("#modal form").live("submit", ajax_form_catch); });
Add sumRating methods to fetch rating when using +1/-1 style ratings.
<?php namespace willvincent\Rateable; trait Rateable { /** * This model has many ratings. * * @return Rating */ public function ratings() { return $this->morphMany('willvincent\Rateable\Rating', 'rateable'); } public function averageRating() { return $this->ratings() ->selectRaw('AVG(rating) as averageRating') ->pluck('averageRating'); } public function sumRating() { return $this->ratings() ->selectRaw('SUM(rating) as sumRating') ->pluck('sumRating'); } public function ratingPercent($max = 5) { $ratings = $this->ratings(); $quantity = $ratings->count(); $total = $ratings->selectRaw('SUM(rating) as total')->pluck('total'); return $total / (($quantity * $max) / 100); } public function getAverageRatingAttribute() { return $this->averageRating(); } public function getSumRatingAttribute() { return $this->sumRating(); } }
<?php namespace willvincent\Rateable; trait Rateable { /** * This model has many ratings. * * @return Rating */ public function ratings() { return $this->morphMany('willvincent\Rateable\Rating', 'rateable'); } public function averageRating() { return $this->ratings() ->selectRaw('AVG(rating) as averageRating') ->pluck('averageRating'); } public function ratingPercent($max = 5) { $ratings = $this->ratings(); $quantity = $ratings->count(); $total = $ratings->selectRaw('SUM(rating) as total')->pluck('total'); return $total / (($quantity * $max) / 100); } public function getAverageRatingAttribute() { return $this->averageRating(); } }
Add support for overriding global metaData
var request = require('./request'); var config = require('./config'); var notifierVersion = require('./version').notifierVersion; function merge(target, obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { target[key] = obj[key]; } } return target; } function notify(err, options) { if (!options) options = {}; request(config.endpoint, { payloadVersion: '3', notifierVersion: notifierVersion, apiKey: config.apiKey, projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host, context: config.context || window.location.pathname, user: config.user, metaData: merge(merge({}, config.metaData), config.metaData || {}), releaseStage: config.releaseStage, appVersion: config.appVersion, url: window.location.href, userAgent: navigator.userAgent, language: navigator.language || navigator.userLanguage, severity: options.severity || config.severity, name: err.name, message: err.message, stacktrace: err.stack || err.backtrace || err.stacktrace, file: err.fileName || err.sourceURL, lineNumber: -1, columnNumber: -1, breadcrumbs: [] }); } module.exports = notify;
var request = require('./request'); var config = require('./config'); var notifierVersion = require('./version').notifierVersion; function merge(target, obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { target[key] = obj[key]; } } return target; } function notify(err, options) { if (!options) options = {}; request(config.endpoint, { payloadVersion: '3', notifierVersion: notifierVersion, apiKey: config.apiKey, projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host, context: config.context || window.location.pathname, user: config.user, metaData: merge({}, merge(options.metaData || {}, config.metaData)), releaseStage: config.releaseStage, appVersion: config.appVersion, url: window.location.href, userAgent: navigator.userAgent, language: navigator.language || navigator.userLanguage, severity: options.severity || config.severity, name: err.name, message: err.message, stacktrace: err.stack || err.backtrace || err.stacktrace, file: err.fileName || err.sourceURL, lineNumber: -1, columnNumber: -1, breadcrumbs: [] }); } module.exports = notify;
Stop telling people to run npm rebuild with --force This forces a local compilation (slow) when they just want to download right binary (fast).
/*! * node-sass: lib/errors.js */ var sass = require('./extensions'), pkg = require('../package.json'); function humanEnvironment() { return sass.getHumanEnvironment(sass.getBinaryName()); } function foundBinaries() { return [ 'Found bindings for the following environments:', foundBinariesList(), ].join('\n'); } function foundBinariesList() { return sass.getInstalledBinaries().map(function(env) { return ' - ' + sass.getHumanEnvironment(env); }).join('\n'); } function missingBinaryFooter() { return [ 'This usually happens because your environment has changed since running `npm install`.', 'Run `npm rebuild node-sass` to download the binding for your current environment.', ].join('\n'); } module.exports.unsupportedEnvironment = function() { return [ 'Node Sass does not yet support your current environment: ' + humanEnvironment(), 'For more information on which environments are supported please see:', 'https://github.com/sass/node-sass/releases/tag/v' + pkg.version ].join('\n'); }; module.exports.missingBinary = function() { return [ 'Missing binding ' + sass.getBinaryPath(), 'Node Sass could not find a binding for your current environment: ' + humanEnvironment(), '', foundBinaries(), '', missingBinaryFooter(), ].join('\n'); };
/*! * node-sass: lib/errors.js */ var sass = require('./extensions'), pkg = require('../package.json'); function humanEnvironment() { return sass.getHumanEnvironment(sass.getBinaryName()); } function foundBinaries() { return [ 'Found bindings for the following environments:', foundBinariesList(), ].join('\n'); } function foundBinariesList() { return sass.getInstalledBinaries().map(function(env) { return ' - ' + sass.getHumanEnvironment(env); }).join('\n'); } function missingBinaryFooter() { return [ 'This usually happens because your environment has changed since running `npm install`.', 'Run `npm rebuild node-sass --force` to build the binding for your current environment.', ].join('\n'); } module.exports.unsupportedEnvironment = function() { return [ 'Node Sass does not yet support your current environment: ' + humanEnvironment(), 'For more information on which environments are supported please see:', 'https://github.com/sass/node-sass/releases/tag/v' + pkg.version ].join('\n'); }; module.exports.missingBinary = function() { return [ 'Missing binding ' + sass.getBinaryPath(), 'Node Sass could not find a binding for your current environment: ' + humanEnvironment(), '', foundBinaries(), '', missingBinaryFooter(), ].join('\n'); };
Remove hide()s on page load (already done with CSS)
'use strict'; var questionView = { $getOptions: $( '.get-options' ), $followupNoNotSure: $( '.followup__no-not-sure' ), $followupYes: $( '.followup__yes' ), $nextSteps: $( '.next-steps' ), $feedback: $( '.feedback' ), init: function() { this.bigQuestionListener(); }, bigQuestionListener: function() { $( '.question_answers > .btn' ).on( 'click', function() { if ( $( this ).attr( 'id' ) === 'question_answer-yes' ) { questionView.$followupYes.show(); questionView.$followupNoNotSure.hide(); } else { questionView.$followupNoNotSure.show(); questionView.$followupYes.hide(); } // Show the rest of the page with a 600 millisecond animation. questionView.$getOptions.show( 'slow' ); questionView.$nextSteps.show( 'slow' ); questionView.$feedback.show( 'slow' ); } ); } }; module.exports = questionView;
'use strict'; var questionView = { $getOptions: $( '.get-options' ), $followupNoNotSure: $( '.followup__no-not-sure' ), $followupYes: $( '.followup__yes' ), $nextSteps: $( '.next-steps' ), $feedback: $( '.feedback' ), init: function() { this.$followupNoNotSure.hide(); this.$followupYes.hide(); this.$getOptions.hide(); this.$nextSteps.hide(); this.$feedback.hide(); this.bigQuestionListener(); }, bigQuestionListener: function() { $( '.question_answers > .btn' ).on( 'click', function() { if ( $( this ).attr( 'id' ) === 'question_answer-yes' ) { questionView.$followupYes.show(); questionView.$followupNoNotSure.hide(); } else { questionView.$followupNoNotSure.show(); questionView.$followupYes.hide(); } // Show the rest of the page with a 600 millisecond animation. questionView.$getOptions.show( 'slow' ); questionView.$nextSteps.show( 'slow' ); questionView.$feedback.show( 'slow' ); } ); } }; module.exports = questionView;
Tweak to fix sql table name
package uk.ac.ebi.biosamples.accession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Service; @Service public class AccessionDao { private Logger log = LoggerFactory.getLogger(getClass()); @Autowired @Qualifier("accessionJdbcTemplate") protected JdbcTemplate jdbcTemplate; public void doAssayAccessionCallback(RowCallbackHandler rch) { String sql = "SELECT * FROM SAMPLE_ASSAY"; jdbcTemplate.query(sql, rch); } public void doReferenceAccessionCallback(RowCallbackHandler rch) { String sql = "SELECT * FROM SAMPLE_REFERENCE"; jdbcTemplate.query(sql, rch); } public void doGroupAccessionCallback(RowCallbackHandler rch) { String sql = "SELECT * FROM SAMPLE_GROUPS"; jdbcTemplate.query(sql, rch); } }
package uk.ac.ebi.biosamples.accession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Service; @Service public class AccessionDao { private Logger log = LoggerFactory.getLogger(getClass()); @Autowired @Qualifier("accessionJdbcTemplate") protected JdbcTemplate jdbcTemplate; public void doAssayAccessionCallback(RowCallbackHandler rch) { String sql = "SELECT * FROM SAMPLE_ASSAY"; jdbcTemplate.query(sql, rch); } public void doReferenceAccessionCallback(RowCallbackHandler rch) { String sql = "SELECT * FROM SAMPLE_REFERENCE"; jdbcTemplate.query(sql, rch); } public void doGroupAccessionCallback(RowCallbackHandler rch) { String sql = "SELECT * FROM SAMPLE_GROUP"; jdbcTemplate.query(sql, rch); } }
Fix having not set this up correctly
// // This file talks to the main process by fetching the path to the user data. // It also writes updates to the user-data file. // var ipc = require('electron').ipcRenderer var fs = require('fs') var getData = function () { var data = {} data.path = ipc.sendSync('getUserDataPath', null) data.contents = JSON.parse(fs.readFileSync(data.path)) return data } var getSavedDir = function () { var savedDir = {} savedDir.path = ipc.sendSync('getUserSavedDir', null) savedDir.contents = JSON.parse(fs.readFileSync(savedDir.path)) return savedDir } var writeData = function (data) { fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) { if (err) return console.log(err) }) } // this could take in a boolean on compelte status // and be named better in re: to updating ONE challenge, not all var updateData = function (challenge) { var data = getData() data.contents[challenge].completed = true writeData(data) } var updateCurrentDirectory = function (path) { var data = getSavedDir() data.contents.savedDir = path writeData(data) } module.exports.getData = getData module.exports.getSavedDir = getSavedDir module.exports.updateData = updateData module.exports.updateCurrentDirectory = updateCurrentDirectory
// // This file talks to the main process by fetching the path to the user data. // It also writes updates to the user-data file. // var ipc = require('electron').ipcRenderer var fs = require('fs') var getData = function () { var data = {} data.path = ipc.sendSync('getUserDataPath', null) data.contents = JSON.parse(fs.readFileSync(data.path)) return data } var getSavedDir = function () { var savedDir = {} data.path = ipc.sendSync('getUserSavedDir', null) data.contents = JSON.parse(fs.readFileSync(data.path)) return savedDir } var writeData = function (data) { fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) { if (err) return console.log(err) }) } // this could take in a boolean on compelte status // and be named better in re: to updating ONE challenge, not all var updateData = function (challenge) { var data = getData() data.contents[challenge].completed = true writeData(data) } var updateCurrentDirectory = function (path) { var data = getSavedDir() data.contents.savedDir = path writeData(data) } module.exports.getData = getData module.exports.updateData = updateData module.exports.updateCurrentDirectory = updateCurrentDirectory
Fix stat named map providers cache count
'use strict'; const statKeyTemplate = ctx => `windshaft.named-map-provider-cache.${ctx.metric}`; module.exports = class NamedMapProviderReporter { constructor ({ namedMapProviderCache, intervalInMilliseconds } = {}) { this.namedMapProviderCache = namedMapProviderCache; this.intervalInMilliseconds = intervalInMilliseconds; this.intervalId = null; } start () { const { providerCache: cache } = this.namedMapProviderCache; const { statsClient: stats } = global; this.intervalId = setInterval(() => { const providers = cache.dump(); stats.gauge(statKeyTemplate({ metric: 'named-map.count' }), providers.length); const namedMapInstantiations = providers.reduce((acc, { v: providers }) => { acc += Object.keys(providers).length; return acc; }, 0); stats.gauge(statKeyTemplate({ metric: 'named-map.instantiation.count' }), namedMapInstantiations); }, this.intervalInMilliseconds); } stop () { clearInterval(this.intervalId); this.intervalId = null; } };
'use strict'; const statKeyTemplate = ctx => `windshaft.named-map-provider-cache.${ctx.metric}`; module.exports = class NamedMapProviderReporter { constructor ({ namedMapProviderCache, intervalInMilliseconds } = {}) { this.namedMapProviderCache = namedMapProviderCache; this.intervalInMilliseconds = intervalInMilliseconds; this.intervalId = null; } start () { const { providerCache: cache } = this.namedMapProviderCache; const { statsClient: stats } = global; this.intervalId = setInterval(() => { stats.gauge(statKeyTemplate({ metric: 'named-map.count' }), cache.length); const providers = cache.dump(); const namedMapInstantiations = providers.reduce((acc, { v: providers }) => { acc += Object.keys(providers).length; return acc; }, 0); stats.gauge(statKeyTemplate({ metric: 'named-map.instantiation.count' }), namedMapInstantiations); }, this.intervalInMilliseconds); } stop () { clearInterval(this.intervalId); this.intervalId = null; } };
Change knugen command to use array in config/data.json instead of hardcoded array.
import discord import asyncio import random import configparser import json def RunBot(config_file): config = configparser.ConfigParser() config.read(config_file) client = discord.Client() @client.event async def on_ready(): print('------') print('Logged in as %s (%s)' % (client.user.name, client.user.id)) print('------') @client.event async def on_message(message): if message.channel.id == "123410749765713920": if message.content.startswith('-knugen'): with open('config/data.json') as data_file: data = json.loads(data_file.read()) await client.send_message(message.channel, random.choice(data['knugenLinks'])) client.run(config['Bot']['token']) if __name__ == "__main__": print("Please use the start.py script in the root directory instead")
import discord import asyncio import random import configparser import json def RunBot(config_file): config = configparser.ConfigParser() config.read(config_file) client = discord.Client() @client.event async def on_ready(): print('------') print('Logged in as %s (%s)' % (client.user.name, client.user.id)) print('------') @client.event async def on_message(message): if message.channel.id == "123410749765713920": if message.content.startswith('-knugen'): await client.send_message(message.channel, random.choice(knugenLinks)) client.run(config['Bot']['token']) if __name__ == "__main__": print("Please use the start.py script in the root directory instead")
Support /home/gian environment variable in GetUserDirectory()
/*§ =========================================================================== Caravel =========================================================================== Copyright (C) 2015 Gianluca Costa =========================================================================== 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 caravel import ( "os" "os/user" "path/filepath" ) /* GetUserDirectory returns the user's directory, or an error on failure. First it looks for a "HOME" environment variable; then it employs user.Current() */ func GetUserDirectory() (userDir string, err error) { environmentHome := os.Getenv("HOME") if environmentHome != "" { return environmentHome, nil } user, err := user.Current() if err != nil { return "", err } return user.HomeDir, nil } /* GetUserDesktop returns the user's "Desktop" directory, or an error on failure. */ func GetUserDesktop() (desktopDir string, err error) { userDir, err := GetUserDirectory() if err != nil { return "", err } desktopDir = filepath.Join(userDir, "Desktop") return desktopDir, nil }
/*§ =========================================================================== Caravel =========================================================================== Copyright (C) 2015 Gianluca Costa =========================================================================== 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 caravel import ( "os/user" "path/filepath" ) /* GetUserDirectory returns the user's directory, or an error on failure. */ func GetUserDirectory() (userDir string, err error) { user, err := user.Current() if err != nil { return "", err } return user.HomeDir, nil } /* GetUserDesktop returns the user's "Desktop" directory, or an error on failure. */ func GetUserDesktop() (desktopDir string, err error) { userDir, err := GetUserDirectory() if err != nil { return "", err } desktopDir = filepath.Join(userDir, "Desktop") return desktopDir, nil }
Fix bug on frontpage with video
<?php namespace Drupal\ga_slide; use Drupal\file\Entity\File; use Drupal\image\Entity\ImageStyle; class SlideUtils { public static function getSlides() { $slideNids = \Drupal::entityQuery('slide') ->sort('weight', 'ASC') ->execute(); $slideEntities = \Drupal::entityTypeManager()->getStorage("slide")->loadMultiple($slideNids); $slides = []; foreach ($slideEntities as $slideEntity) { $slides[] = array( "name" => $slideEntity->label(), "image" => File::load($slideEntity->getImage()[0]) ? ImageStyle::load('slide')->buildUrl(File::load($slideEntity->getImage()[0])->getFileUri()) : null, "video" => File::load($slideEntity->getVideo()[0]) ? File::load($slideEntity->getVideo()[0])->getFileUri() : null, "link" => $slideEntity->getLink() ); } return $slides; } }
<?php namespace Drupal\ga_slide; use Drupal\file\Entity\File; use Drupal\image\Entity\ImageStyle; class SlideUtils { public static function getSlides() { $slideNids = \Drupal::entityQuery('slide') ->sort('weight', 'ASC') ->execute(); $slideEntities = \Drupal::entityTypeManager()->getStorage("slide")->loadMultiple($slideNids); $slides = []; foreach ($slideEntities as $slideEntity) { $slides[] = array( "name" => $slideEntity->label(), "image" => isset($slideEntity->getImage()[0]) ? ImageStyle::load('slide')->buildUrl(File::load($slideEntity->getImage()[0])->getFileUri()) : null, "video" => isset($slideEntity->getVideo()[0]) ? File::load($slideEntity->getVideo()[0])->getFileUri() : null, "link" => $slideEntity->getLink() ); } return $slides; } }
Update only tables in visible schemas
"""Add meta_search table Revision ID: 1a73867b1e79 Revises: 1c6e2fb3d3b6 Create Date: 2019-04-29 11:47:04.783168 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import sessionmaker from api.actions import update_meta_search from dataedit.views import schema_whitelist # revision identifiers, used by Alembic. revision = "1a73867b1e79" down_revision = "1c6e2fb3d3b6" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "meta_search", sa.Column("schema", sa.String(length=100), nullable=False), sa.Column("table", sa.String(length=100), nullable=False), sa.Column("comment", postgresql.TSVECTOR(), nullable=True), sa.PrimaryKeyConstraint("schema", "table"), schema="public", ) conn = op.get_bind() meta = sa.MetaData(bind=conn) meta.reflect() for table in meta.tables.values(): if table.schema in schema_whitelist: update_meta_search(table.name, table.schema) def downgrade(): op.drop_table("meta_search", schema="public")
"""Add meta_search table Revision ID: 1a73867b1e79 Revises: 1c6e2fb3d3b6 Create Date: 2019-04-29 11:47:04.783168 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import sessionmaker from api.actions import update_meta_search # revision identifiers, used by Alembic. revision = "1a73867b1e79" down_revision = "1c6e2fb3d3b6" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "meta_search", sa.Column("schema", sa.String(length=100), nullable=False), sa.Column("table", sa.String(length=100), nullable=False), sa.Column("comment", postgresql.TSVECTOR(), nullable=True), sa.PrimaryKeyConstraint("schema", "table"), schema="public", ) conn = op.get_bind() meta = sa.MetaData(bind=conn) meta.reflect() for table in meta.tables.values(): update_meta_search(table.name, table.schema) def downgrade(): op.drop_table("meta_search", schema="public")
Add link to report from hell
'use strict'; const moment = require('moment') const _ = require('lodash') const lastBusinessDay = require('../../businessDays').last module.exports = ({ getChatUsers, getWorkEntries }) => { return async function warnAboutMissingTimesheet () { const day = lastBusinessDay(moment()).format('YYYY-MM-DD'); const users = await getChatUsers() const workEntries = users.map(slackId => { return (async function () { const workEntries = await getWorkEntries(slackId, day, day) const hours = _.reduce(workEntries, function (sum, entry) { return sum + entry[ 'hours' ] }, 0); if (hours < 8) { return { text: `Ieri ha segnato solo ${hours} ore, non è che ti sei dimenticato di qualcosa?\n Puoi <https://report.ideato.it/|aggiornare il timesheet>`, channel: slackId } } }()) }) return _.filter(await Promise.all(workEntries)) } }
'use strict'; const moment = require('moment') const _ = require('lodash') const lastBusinessDay = require('../../businessDays').last module.exports = ({ getChatUsers, getWorkEntries }) => { return async function warnAboutMissingTimesheet () { const day = lastBusinessDay(moment()).format('YYYY-MM-DD'); const users = await getChatUsers() const workEntries = users.map(slackId => { return (async function () { const workEntries = await getWorkEntries(slackId, day, day) const hours = _.reduce(workEntries, function (sum, entry) { return sum + entry[ 'hours' ] }, 0); if (hours < 8) { return { text: `Ieri ha segnato solo ${hours} ore\n, non è che ti sei dimenticato di qualcosa?`, channel: slackId } } }()) }) return _.filter(await Promise.all(workEntries)) } }
Fix the dashboard migration for UUID
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-06-20 12:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workflow', '0023_auto_20180425_0136'), ] operations = [ migrations.AddField( model_name='dashboard', name='dashboard_uuid', field=models.UUIDField(blank=True, null=True, default=None, verbose_name='Dashboard UUID'), ), migrations.AddField( model_name='dashboard', name='public_url_token', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AlterField( model_name='dashboard', name='public', field=models.CharField(blank=True, choices=[('org', 'Organization'), ('url', 'URL'), ('all', 'All')], max_length=5, null=True), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-06-20 12:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workflow', '0023_auto_20180425_0136'), ] operations = [ migrations.AddField( model_name='dashboard', name='dashboard_uuid', field=models.UUIDField(default=None, verbose_name='Dashboard UUID'), ), migrations.AddField( model_name='dashboard', name='public_url_token', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AlterField( model_name='dashboard', name='public', field=models.CharField(blank=True, choices=[('org', 'Organization'), ('url', 'URL'), ('all', 'All')], max_length=5, null=True), ), ]
Move down invalid unit test for better consistency
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Test / Unit / Framework / Date / ValueObject */ namespace PH7\Test\Unit\Framework\Date\ValueObject; use PH7\Framework\Date\ValueObject\DateTime as VODateTime; use PH7\Framework\Date\ValueObject\InvalidDateFormatException; use PHPUnit_Framework_TestCase; class DateTimeTest extends PHPUnit_Framework_TestCase { public function testGetDateTimeValue() { $sDateValue = '2018-05-31 10:00:05'; $oDatetime = new VODateTime($sDateValue); $this->assertSame($sDateValue, $oDatetime->asString()); } public function testInvalidDateTime() { $this->expectException(InvalidDateFormatException::class); new VODateTime('31-05-2018 10:00:05'); } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Test / Unit / Framework / Date / ValueObject */ namespace PH7\Test\Unit\Framework\Date\ValueObject; use PH7\Framework\Date\ValueObject\DateTime as VODateTime; use PH7\Framework\Date\ValueObject\InvalidDateFormatException; use PHPUnit_Framework_TestCase; class DateTimeTest extends PHPUnit_Framework_TestCase { public function testInvalidDateTime() { $this->expectException(InvalidDateFormatException::class); new VODateTime('31-05-2018 10:00:05'); } public function testGetDateTimeValue() { $sDateValue = '2018-05-31 10:00:05'; $oDatetime = new VODateTime($sDateValue); $this->assertSame($sDateValue, $oDatetime->asString()); } }
Reduce contention during lifecycle tracking
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.proofpoint.bootstrap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; class LifeCycleMethodsMap { private final Map<Class<?>, LifeCycleMethods> map = new ConcurrentHashMap<>(); public LifeCycleMethods get(Class<?> clazz) { return map.computeIfAbsent(clazz, LifeCycleMethods::new); } }
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.proofpoint.bootstrap; import com.google.common.collect.Maps; import java.util.Map; class LifeCycleMethodsMap { private final Map<Class<?>, LifeCycleMethods> map = Maps.newHashMap(); synchronized LifeCycleMethods get(Class<?> clazz) { LifeCycleMethods methods = map.get(clazz); if (methods == null) { methods = new LifeCycleMethods(clazz); map.put(clazz, methods); } return methods; } }
Make TryStart recover more gracefully git-svn-id: abd770af2affaf62930f25b244f6edafe8ddae5b@269 164481a5-15cb-f69f-4b93-856c5b7754c5
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. function TryStart() { try { var raw_json_data = document.getElementById('json').textContent; var json = JSON.parse(raw_json_data); var port = chrome.extension.connect(); port.postMessage({message: 'start', benchmark: json}); } catch(err) { console.log("TryStart retrying after exception: " + err); setTimeout(TryStart, 1000); // TODO(mbelshe): remove me! This is for debugging. console.log("Body is: " + document.body.innerHTML); return; } var status_element = document.getElementById('status'); status_element.textContent = "ACK"; } // We wait 1s before starting the test just to let chrome warm up better. setTimeout(TryStart, 250);
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. function TryStart() { try { var raw_json_data = document.getElementById('json').textContent; var json = JSON.parse(raw_json_data); var port = chrome.extension.connect(); port.postMessage({message: 'start', benchmark: json}); } catch(err) { console.log("TryStart retring after exception: " + err); setTimeout(TryStart, 1000); } var status_element = document.getElementById('status'); status_element.textContent = "ACK"; } // We wait 1s before starting the test just to let chrome warm up better. setTimeout(TryStart, 250);
Implement default next() and prev()
class KasenIterator { constructor(iter, func) { this.iter = iter; this.func = func; } // eslint-disable-next-line class-methods-use-this, no-unused-vars __base(_direction) { throw new Error("not implemented"); } next() { return this.__base("next"); } prev() { return this.__base("prev"); } } export class MapIterator extends KasenIterator { __base(direction) { const result = this.iter[direction](); if (!result.done) { result.value = this.func(result.value, result.key); } return result; } } export class FilterIterator extends KasenIterator { __base(direction) { let result; // eslint-disable-next-line no-cond-assign while (!(result = this.iter[direction]()).done) { if (this.func(result.value, result.key)) { // TODO: Shrink "key" if Array break; } } return result; } } export class ReverseIterator extends KasenIterator { next() { return this.iter.prev(); } prev() { return this.iter.next(); } }
class KasenIterator { constructor(iter, func) { this.iter = iter; this.func = func; } // eslint-disable-next-line class-methods-use-this next() { throw new Error("not implemented"); } // eslint-disable-next-line class-methods-use-this prev() { throw new Error("not implemented"); } } export class MapIterator extends KasenIterator { __base(direction) { const result = this.iter[direction](); if (!result.done) { result.value = this.func(result.value, result.key); } return result; } next() { return this.__base("next"); } prev() { return this.__base("prev"); } } export class FilterIterator extends KasenIterator { __base(direction) { let result; // eslint-disable-next-line no-cond-assign while (!(result = this.iter[direction]()).done) { if (this.func(result.value, result.key)) { // TODO: Shrink "key" if Array break; } } return result; } next() { return this.__base("next"); } prev() { return this.__base("prev"); } } export class ReverseIterator extends KasenIterator { next() { return this.iter.prev(); } prev() { return this.iter.next(); } }
Fix recovery iterations quota checking
package org.spoofax.jsglr2.recovery; public class RecoveryJob { public int backtrackChoicePointIndex; public int offset; public int iteration; final int iterationsQuota; public int quota; public RecoveryJob(int backtrackChoicePointIndex, int offset, int iterationsQuota) { this.backtrackChoicePointIndex = backtrackChoicePointIndex; this.offset = offset; this.iteration = -1; this.iterationsQuota = iterationsQuota; } boolean hasNextIteration() { return iteration + 1 < iterationsQuota; } int nextIteration() { quota = (++iteration + 1); return iteration; } public int iterationBacktrackChoicePointIndex() { return Math.max(backtrackChoicePointIndex - iteration, 0); } }
package org.spoofax.jsglr2.recovery; public class RecoveryJob { public int backtrackChoicePointIndex; public int offset; public int iteration; final int iterationsQuota; public int quota; public RecoveryJob(int backtrackChoicePointIndex, int offset, int iterationsQuota) { this.backtrackChoicePointIndex = backtrackChoicePointIndex; this.offset = offset; this.iteration = -1; this.iterationsQuota = iterationsQuota; } boolean hasNextIteration() { return iteration < iterationsQuota; } int nextIteration() { quota = (++iteration + 1); return iteration; } public int iterationBacktrackChoicePointIndex() { return Math.max(backtrackChoicePointIndex - iteration, 0); } }
Allow a little difference between systems. The fixtures are created on my machine but Travis's generated screenshots don't *exactly* match - one of the tests returning a difference of 4. This seems to be an acceptable range.
var http = require('http') , mocha = require('mocha') , queue = require('queue-async') , app = require('./app') , server = http.createServer(app) , Chart = require('./chart') , assert = require('assert') , FUZZY = 4 describe('Peity', function() { before(function(done) { server.listen(0, function() { Chart.port(server.address().port) done() }) }) after(function() { server.close() }) Chart.forEach(function(chart) { it(chart.id, function(done) { queue(1) .defer(chart.screenshot.bind(chart), chart.imagePath) .defer(chart.compare.bind(chart)) .await(function(err, _, difference) { if (err) throw err assert.ok(difference <= FUZZY, 'unacceptable difference of ' + difference) done() }) }) }) })
var http = require('http') , mocha = require('mocha') , queue = require('queue-async') , app = require('./app') , server = http.createServer(app) , Chart = require('./chart') , assert = require('assert') describe('Peity', function() { before(function(done) { server.listen(0, function() { Chart.port(server.address().port) done() }) }) after(function() { server.close() }) Chart.forEach(function(chart) { it(chart.id, function(done) { queue(1) .defer(chart.screenshot.bind(chart), chart.imagePath) .defer(chart.compare.bind(chart)) .await(function(err, _, difference) { if (err) throw err assert.strictEqual(difference, 0) done() }) }) }) })
Check checkLoggedIn in owncloud package
<?php OCP\User::checkLoggedIn(); if (@file_exists(__DIR__.'/app/index.php')) { include_once OC_App::getAppPath('rainloop').'/lib/RainLoopHelper.php'; OC_RainLoop_Helper::regRainLoopDataFunction(); if (isset($_GET['OwnCloudAuth'])) { $sEmail = ''; $sEncodedPassword = ''; $sUser = OCP\User::getUser(); if (OCP\Config::getAppValue('rainloop', 'rainloop-autologin', false)) { $sEmail = $sUser; $sEncodedPassword = OCP\Config::getUserValue($sUser, 'rainloop', 'rainloop-autologin-password', ''); } else { $sEmail = OCP\Config::getUserValue($sUser, 'rainloop', 'rainloop-email', ''); $sEncodedPassword = OCP\Config::getUserValue($sUser, 'rainloop', 'rainloop-password', ''); } $sDecodedPassword = OC_RainLoop_Helper::decodePassword($sEncodedPassword, md5($sEmail)); $_ENV['___rainloop_owncloud_email'] = $sEmail; $_ENV['___rainloop_owncloud_password'] = $sDecodedPassword; } include __DIR__.'/app/index.php'; }
<?php if (@file_exists(__DIR__.'/app/index.php')) { include_once OC_App::getAppPath('rainloop').'/lib/RainLoopHelper.php'; OC_RainLoop_Helper::regRainLoopDataFunction(); if (isset($_GET['OwnCloudAuth'])) { $sEmail = ''; $sEncodedPassword = ''; $sUser = OCP\User::getUser(); if (OCP\Config::getAppValue('rainloop', 'rainloop-autologin', false)) { $sEmail = $sUser; $sEncodedPassword = OCP\Config::getUserValue($sUser, 'rainloop', 'rainloop-autologin-password', ''); } else { $sEmail = OCP\Config::getUserValue($sUser, 'rainloop', 'rainloop-email', ''); $sEncodedPassword = OCP\Config::getUserValue($sUser, 'rainloop', 'rainloop-password', ''); } $sDecodedPassword = OC_RainLoop_Helper::decodePassword($sEncodedPassword, md5($sEmail)); $_ENV['___rainloop_owncloud_email'] = $sEmail; $_ENV['___rainloop_owncloud_password'] = $sDecodedPassword; } include __DIR__.'/app/index.php'; }
Use set_request_property instead of subscriber to improve performance
""" simplified mongodb integration 1. Add two lines to app/__init__.py ( the import and the call to initialize_mongo_db ) import python_mongodb def main(global_config, **settings): ## ... # Initialize mongodb , which is a subscriber python_mongodb.initialize_mongo_db( config , settings ) ## ... return config.make_wsgi_app() 2. in each of your envinronment.ini files, have: mongodb.use = true mongodb.uri = mongodb://localhost mongodb.name = myapp if "mongodb.use" is not "true", then it won't be configured -- so you can do your local development / tests / etc without having mongodb running ( should you want to ) """ import pymongo from gridfs import GridFS def initialize_mongo_db(config, settings): if ('mongodb.use' in settings) and (settings['mongodb.use'] == 'true'): conn = pymongo.Connection(settings['mongodb.uri']) config.registry.settings['!mongodb.conn'] = conn config.set_request_property(add_mongo_db, 'mongodb', reify=True) def add_mongo_db(request): settings = request.registry.settings db = settings['!mongodb.conn'][settings['mongodb.name']] request.mongodb = db request.gridfs = GridFS(db)
""" simplified mongodb integration 1. Add two lines to app/__init__.py ( the import and the call to initialize_mongo_db ) import python_mongodb def main(global_config, **settings): ## ... # Initialize mongodb , which is a subscriber python_mongodb.initialize_mongo_db( config , settings ) ## ... return config.make_wsgi_app() 2. in each of your envinronment.ini files, have: mongodb.use = true mongodb.uri = mongodb://localhost mongodb.name = myapp if "mongodb.use" is not "true", then it won't be configured -- so you can do your local development / tests / etc without having mongodb running ( should you want to ) """ import pymongo from gridfs import GridFS def initialize_mongo_db( config, settings ): if ( 'mongodb.use' in settings ) and ( settings['mongodb.use'] == 'true' ): conn = pymongo.Connection( settings['mongodb.uri'] ) config.registry.settings['!mongodb.conn'] = conn config.add_subscriber(add_mongo_db, 'pyramid.events.NewRequest') def add_mongo_db(event): settings = event.request.registry.settings db = settings['!mongodb.conn'][settings['mongodb.name']] event.request.mongodb = db event.request.gridfs = GridFS(db)
Fix missing default empty options
module.exports = client => async (key, get, options = {}) => { if ((typeof options === 'object' && options.asSeconds) || typeof options === 'number') { options = { expire: options }; } if (typeof options.expire === 'object' && options.expire.asSeconds) { options.expire = options.expire.asSeconds(); } let value; if (client.getJSON) { value = await client.getJSON(key); } else { value = await client.get(key); } if (!value || (options.invalidate && options.invalidate(value))) { value = await get(); if (client.setJSON) { await client.setJSON(key, value, options.expire); } else { if (options.expire) { await client.set(key, value, 'EX', options.expire); } else { await client.set(key, value); } } } else if (options.refresh) { await client.expire(key, options.expire); } return value; };
module.exports = client => async (key, get, options) => { if ((typeof options === 'object' && options.asSeconds) || typeof options === 'number') { options = { expire: options }; } if (typeof options.expire === 'object' && options.expire.asSeconds) { options.expire = options.expire.asSeconds(); } let value; if (client.getJSON) { value = await client.getJSON(key); } else { value = await client.get(key); } if (!value || (options.invalidate && options.invalidate(value))) { value = await get(); if (client.setJSON) { await client.setJSON(key, value, options.expire); } else { if (options.expire) { await client.set(key, value, 'EX', options.expire); } else { await client.set(key, value); } } } else if (options.refresh) { await client.expire(key, options.expire); } return value; };
Return sha of most recent commit.
var github = require('octonode'); var _ = require('lodash'); function GitHub(options) { this.client = github.client({ username: options.user, password: options.password }); } GitHub.prototype.commits = function (repo, base, head, callback) { console.log('Retrieving info from GitHub...'); var repo = this.client.repo('wishabi/' + repo); return new Promise(function(resolve, reject) { repo.compare(base, head, function(err, data, headers){ if(err !== null) return reject(err); var tickets = []; var commits = []; data.commits.forEach(function(commit) { var ticket = commit.commit.message.match(/(FP|PS)-[0-9]*/g); if (ticket !== null) { tickets.push(ticket[0]); } else { commits.push({ sha: commit.sha, link: 'https://github.com/wishabi/flyers/commit/' + commit.sha, author: commit.commit.author.name, message: commit.commit.message }); } }); resolve({ headSha: data.commits.pop().sha, commits: commits, tickets: _.uniq(tickets) }); }); }); } module.exports = GitHub;
var github = require('octonode'); var _ = require('lodash'); function GitHub(options) { this.client = github.client({ username: options.user, password: options.password }); } GitHub.prototype.commits = function (repo, base, head, callback) { console.log('Retrieving info from GitHub...'); var repo = this.client.repo('wishabi/' + repo); return new Promise(function(resolve, reject) { repo.compare(base, head, function(err, data, headers){ if(err !== null) return reject(err); var tickets = []; var commits = []; data.commits.forEach(function(commit) { var ticket = commit.commit.message.match(/(FP|PS)-[0-9]*/g); if (ticket !== null) { tickets.push(ticket[0]); } else { commits.push({ sha: commit.sha, link: 'https://github.com/wishabi/flyers/commit/' + commit.sha, author: commit.commit.author.name, message: commit.commit.message }); } }); resolve({ commits: commits, tickets: _.uniq(tickets) }); }); }); } module.exports = GitHub;
Update snippet to use .enqueue Per https://issues.corp.twilio.com/browse/DEVED-3483, enqueueTask() no longer works – the lib now expects .enqueue()
// Download the Node helper library from twilio.com/docs/node/install // These consts are your accountSid and authToken from https://www.twilio.com/console const VoiceResponse = require('twilio').twiml.VoiceResponse; const express = require('express'); const app = express(); app.post('/enqueue_call', (request, response) => { const resp = new VoiceResponse(); const json = { account_number: '12345abcdef' }; resp .enqueue({ workflowSid: 'WW0123456789abcdef0123456789abcdef', waitUrl: '/hold_music.php', action: '/post_bridge_survey.php', }) .task({}, JSON.stringify(json)); response.setHeader('Content-Type', 'application/xml'); response.write(resp.toString()); response.end(); }); app.listen(8080);
// Download the Node helper library from twilio.com/docs/node/install // These consts are your accountSid and authToken from https://www.twilio.com/console const VoiceResponse = require('twilio').twiml.VoiceResponse; const express = require('express'); const app = express(); app.post('/enqueue_call', (request, response) => { const resp = new VoiceResponse(); const json = { account_number: '12345abcdef' }; resp .enqueueTask({ workflowSid: 'WW0123456789abcdef0123456789abcdef', waitUrl: '/hold_music.php', action: '/post_bridge_survey.php', }) .task({}, JSON.stringify(json)); response.setHeader('Content-Type', 'application/xml'); response.write(resp.toString()); response.end(); }); app.listen(8080);
Update Register from bind to singleton
<?php namespace Edujugon\GoogleAds\Providers; use Edujugon\GoogleAds\Console\RefreshTokenCommand; use Edujugon\GoogleAds\GoogleAds; use Illuminate\Support\ServiceProvider; class GoogleAdsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php'; $this->publishes([ __DIR__.'/../Config/config.php' => $config_path, ], 'config'); } /** * Register the application services. * * @return void */ public function register() { // Console commands $this->commands([ RefreshTokenCommand::class, ]); $this->app->singleton('edujugonGoogleAds', function ($app) { return new GoogleAds(); }); } }
<?php namespace Edujugon\GoogleAds\Providers; use Edujugon\GoogleAds\Console\RefreshTokenCommand; use Edujugon\GoogleAds\GoogleAds; use Illuminate\Support\ServiceProvider; class GoogleAdsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php'; $this->publishes([ __DIR__.'/../Config/config.php' => $config_path, ], 'config'); } /** * Register the application services. * * @return void */ public function register() { // Console commands $this->commands([ RefreshTokenCommand::class, ]); $this->app->bind('edujugonGoogleAds', function ($app) { return new GoogleAds(); }); } }
Add guard to prevent TypeError during paste
import { isArray, contains } from 'underscore'; export default { run(ed) { const em = ed.getModel(); const clp = em.get('clipboard'); const selected = ed.getSelected(); if (clp && selected) { ed.getSelectedAll().forEach(comp => { if (!comp) return; const coll = comp.collection; if (!coll) return; const at = coll.indexOf(comp) + 1; const copyable = clp.filter(cop => cop.get('copyable')); let added; if (contains(clp, comp) && comp.get('copyable')) { added = coll.add(comp.clone(), { at }); } else { added = coll.add( copyable.map(cop => cop.clone()), { at } ); } added = isArray(added) ? added : [added]; added.forEach(add => ed.trigger('component:paste', add)); }); selected.emitUpdate(); } } };
import { isArray, contains } from 'underscore'; export default { run(ed) { const em = ed.getModel(); const clp = em.get('clipboard'); const selected = ed.getSelected(); if (clp && selected) { ed.getSelectedAll().forEach(comp => { if (!comp) return; const coll = comp.collection; const at = coll.indexOf(comp) + 1; const copyable = clp.filter(cop => cop.get('copyable')); let added; if (contains(clp, comp) && comp.get('copyable')) { added = coll.add(comp.clone(), { at }); } else { added = coll.add(copyable.map(cop => cop.clone()), { at }); } added = isArray(added) ? added : [added]; added.forEach(add => ed.trigger('component:paste', add)); }); selected.emitUpdate(); } } };
docs: Add doc comments for program builder
"use strict"; var program = require('commander'); var path = require('path'); var os = require('os'); var appDir = path.resolve(os.tmpDir(), 'cartridge'); var newCommand = require('./commands/new')(appDir); var pkg = require(path.resolve(__dirname, '..', 'package.json')); /** * Get the ball-rolling for the whole program */ module.exports = function() { setProgramBaseSettings(); setNewCommand(); initProgram(); } /** * Setup the 'new' command */ function setNewCommand() { program .command('new') .description('Create a new project') .action(function() { newCommand.init(getProgramOptions()); }); } /** * Initialise program */ function initProgram() { program.parse(process.argv); if (!process.argv.slice(2).length) { program.outputHelp(); } } /** * Get program option flags */ function getProgramOptions() { return { silent: program.silent, verbose: program.verbose } } /** * Set program base settings: version, option flags */ function setProgramBaseSettings() { program .version(pkg.version) .option('-s, --silent', 'Surpress all on-screen messages') .option('-v, --verbose', 'Show all on-screen messages'); }
"use strict"; var program = require('commander'); var path = require('path'); var os = require('os'); var appDir = path.resolve(os.tmpDir(), 'cartridge'); var newCommand = require('./commands/new')(appDir); var pkg = require(path.resolve(__dirname, '..', 'package.json')); module.exports = function() { setProgramBaseSettings(); setNewCommand(); initProgram(); } function setNewCommand() { program .command('new') .description('Create a new project') .action(function() { newCommand.init(getProgramOptions()); }); } function initProgram() { program.parse(process.argv); if (!process.argv.slice(2).length) { program.outputHelp(); } } function getProgramOptions() { return { silent: program.silent, verbose: program.verbose } } function setProgramBaseSettings() { program .version(pkg.version) .option('-s, --silent', 'Surpress all on-screen messages') .option('-v, --verbose', 'Show all on-screen messages'); }
Make an exception and remove page title on Parent Page templates, plus code clean
<header class="entry-header"> <?php if (is_single()) { the_title('<h1 class="entry-title">', '</h1>'); } elseif (is_front_page() && is_home()) { the_title('<h3 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h3>'); } elseif (is_page_template('page-parent.php') && empty(get_the_content())) { // Don't render the title if content is empty on pages with the Parent Page template applied } else { the_title('<h2 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h2>'); } if ('post' === get_post_type()) { echo '<div class="entry-meta">'; if (is_single() || is_archive() || is_home()) { keitaro_posted_on(); } echo '</div><!-- .entry-meta -->'; }; ?> </header>
<?php if ( is_sticky() && is_home() ) : // echo twentyseventeen_get_svg( array( 'icon' => 'thumb-tack' ) ); endif; ?> <header class="entry-header"> <?php if ( is_single() ) { the_title( '<h1 class="entry-title">', '</h1>' ); } elseif ( is_front_page() && is_home() ) { the_title( '<h3 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h3>' ); } else { the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' ); } if ( 'post' === get_post_type() ) { echo '<div class="entry-meta">'; if ( is_single() || is_archive() || is_home() ) { keitaro_posted_on(); } echo '</div><!-- .entry-meta -->'; }; ?> </header>
Add getters for constructor parameters
package org.jcodegen.java; /** * ... */ public class FunctionArgument { private final String name; private final String type; private final boolean isFinal; public FunctionArgument(final String type, final String name) { this(type, name, true); } public FunctionArgument(final String type, final String name, final boolean isFinal) { this.type = type; this.name = name; this.isFinal = isFinal; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); if (isFinal) buf.append("final "); buf.append(type); buf.append(" "); buf.append(name); return buf.toString(); } public String getName() { return name; } public String getType() { return type; } public boolean isFinal() { return isFinal; } }
package org.jcodegen.java; /** * ... */ public class FunctionArgument { private final String name; private final String type; private final boolean isFinal; public FunctionArgument(final String type, final String name) { this(type, name, true); } public FunctionArgument(final String type, final String name, final boolean isFinal) { this.type = type; this.name = name; this.isFinal = isFinal; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); if (isFinal) buf.append("final "); buf.append(type); buf.append(" "); buf.append(name); return buf.toString(); } }
Revert "Add patch_json method to our test Client" This reverts commit deef2f98deeeaf51bd9ddda4c5a200d082e16522. Somehow, I missed that this method was already there and added it again. I'm going to blame it on burnout.
import json import django.test from .user import UserMixin class Client(django.test.Client): def patch_json(self, path, data=None, **kwargs): return self.patch(path, **self._json_kwargs(data, kwargs)) def post_json(self, path, data=None, **kwargs): return self.post(path, **self._json_kwargs(data, kwargs)) def put_json(self, path, data=None, **kwargs): return self.put(path, **self._json_kwargs(data, kwargs)) def _json_kwargs(self, data, kwargs): if data is not None: data = json.dumps(data) kwargs['data'] = data kwargs['content_type'] = 'application/json' return kwargs class FunctionalTestCase(django.test.TestCase, UserMixin): """Base class for view tests. It adds the following to Django's `TestCase`: - Convenient user creation & login - Convenient POSTs, PUTs, and PATCHes with a JSON body """ client_class = Client
import json import django.test from .user import UserMixin class Client(django.test.Client): def patch_json(self, path, data=None, **kwargs): return self.patch(path, **self._json_kwargs(data, kwargs)) def post_json(self, path, data=None, **kwargs): return self.post(path, **self._json_kwargs(data, kwargs)) def put_json(self, path, data=None, **kwargs): return self.put(path, **self._json_kwargs(data, kwargs)) def patch_json(self, path, data=None, **kwargs): return self.patch(path, **self._json_kwargs(data, kwargs)) def _json_kwargs(self, data, kwargs): if data is not None: data = json.dumps(data) kwargs['data'] = data kwargs['content_type'] = 'application/json' return kwargs class FunctionalTestCase(django.test.TestCase, UserMixin): """Base class for view tests. It adds the following to Django's `TestCase`: - Convenient user creation & login - Convenient POSTs, PUTs, and PATCHes with a JSON body """ client_class = Client
Update CC BY 3.0 link to zh-TW localized version.
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ // Relative to the samples folder "GETTING_STARTED" : "root/Getting Started", "ADOBE_THIRD_PARTY" : "http://www.adobe.com/go/thirdparty/", "WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/deed.zh_TW" });
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ // Relative to the samples folder "GETTING_STARTED" : "root/Getting Started", "ADOBE_THIRD_PARTY" : "http://www.adobe.com/go/thirdparty/", "WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/" });
Add version 0.10.0 in test for Marionette versions
/* * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package io.github.bonigarcia.wdm.test; import org.junit.Before; import io.github.bonigarcia.wdm.MarionetteDriverManager; import io.github.bonigarcia.wdm.base.BaseVersionTst; /** * Test asserting Marionette versions. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.4.0 */ public class MarionetteVersionTest extends BaseVersionTst { @Before public void setup() { browserManager = MarionetteDriverManager.getInstance(); specificVersions = new String[] { "0.10.0", "0.9.0", "0.8.0", "0.6.2", "0.5.0", "0.4.0", "0.3.0" }; } }
/* * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package io.github.bonigarcia.wdm.test; import org.junit.Before; import io.github.bonigarcia.wdm.MarionetteDriverManager; import io.github.bonigarcia.wdm.base.BaseVersionTst; /** * Test asserting Marionette versions. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.4.0 */ public class MarionetteVersionTest extends BaseVersionTst { @Before public void setup() { browserManager = MarionetteDriverManager.getInstance(); specificVersions = new String[] { "0.9.0", "0.8.0", "0.6.2", "0.5.0", "0.4.0", "0.3.0" }; } }
Add the check that would've saved me 30 minutes just now.
module.exports = chain; // steps, cb // Each step is either: // [fn, arg, arg, arg] or // [obj, "method", arg, arg, arg] // The eventual cb passed to chain is resolved with an array of // all the results, and/or an error if one was returned. function chain () /* step, step, ..., cb */ { var steps = Array.prototype.slice.call(arguments, 0), cb = steps.pop(); if (typeof(cb) !== "function") { throw new Error("Invalid callback: "+typeof(cb)); } (function S (step, results) { if (!step) return cb(null, results); var obj, fn; if (typeof step[0] === "object") { obj = step.shift(); } if (typeof step[0] === "function") { fn = step.shift(); } else { fn = obj[step.shift()]; } if (typeof fn !== "function") throw new Error( "Non-function in chain(). (Did you forget a comma?)"); step.push(function (er, ok) { if (er) cb(er, results); else { results.push(ok); S(steps.shift(), results); } }); try { fn.apply(obj, step); } catch (er) { cb(er, results); } })(steps.shift(), []); }
module.exports = chain; // steps, cb // Each step is either: // [fn, arg, arg, arg] or // [obj, "method", arg, arg, arg] // The eventual cb passed to chain is resolved with an array of // all the results, and/or an error if one was returned. function chain () /* step, step, ..., cb */ { var steps = Array.prototype.slice.call(arguments, 0), cb = steps.pop(); if (typeof(cb) !== "function") { throw new Error("Invalid callback: "+typeof(cb)); } (function S (step, results) { if (!step) return cb(null, results); var obj, fn; if (typeof step[0] === "object") { obj = step.shift(); } if (typeof step[0] === "function") { fn = step.shift(); } else { fn = obj[step.shift()]; } step.push(function (er, ok) { if (er) cb(er, results); else { results.push(ok); S(steps.shift(), results); } }); try { fn.apply(obj, step); } catch (er) { cb(er, results); } })(steps.shift(), []); }
Add support to server side rendering.
import { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; const useCreatePortal = typeof ReactDom.createPortal === 'function'; class Portal extends Component { componentWillMount() { if (typeof window !== 'undefined') { this.popup = document.createElement('div'); document.body.appendChild(this.popup); this.renderLayer(); } } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { if (!useCreatePortal) { ReactDom.unmountComponentAtNode(this.popup); } document.body.removeChild(this.popup); } renderLayer() { if (!useCreatePortal) { ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); } } render() { if (useCreatePortal) { return ReactDom.createPortal(this.props.children, this.popup); } return null; } } Portal.propTypes = { children: PropTypes.node, // eslint-disable-line }; export default Portal;
import { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; const useCreatePortal = typeof ReactDom.createPortal === 'function'; class Portal extends Component { componentWillMount() { this.popup = document.createElement('div'); document.body.appendChild(this.popup); this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { if (!useCreatePortal) { ReactDom.unmountComponentAtNode(this.popup); } document.body.removeChild(this.popup); } renderLayer() { if (!useCreatePortal) { ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); } } render() { if (useCreatePortal) { return ReactDom.createPortal(this.props.children, this.popup); } return null; } } Portal.propTypes = { children: PropTypes.node, // eslint-disable-line }; export default Portal;
Move Charts loading up to the parent template
<!-- resources/views/gendata/hvl.blade.php --> <table class="table table-striped table-hover"> <thead> <tr> <th>kV</th> <th>HVL</th> </tr> </thead> <tbody> @foreach ($hvl as $h) <tr> <td>{{ $h->kv }}</td> <td>{{ $h->hvl }}</td> </tr> @endforeach </tbody> </table> <div class="panel panel-default"> <div class="panel-body"> <p>{!! $hvlChart->render() !!}</p> </div> </div>
<!-- resources/views/gendata/hvl.blade.php --> <table class="table table-striped table-hover"> <thead> <tr> <th>kV</th> <th>HVL</th> </tr> </thead> <tbody> @foreach ($hvl as $h) <tr> <td>{{ $h->kv }}</td> <td>{{ $h->hvl }}</td> </tr> @endforeach </tbody> </table> {!! Charts::assets(['google']) !!} <div class="panel panel-default"> <div class="panel-body"> <p>{!! $hvlChart->render() !!}</p> </div> </div>
Modify test tear down function
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import print_function from subprocrunner import SubprocessRunner from typepy.type import RealNumber from tcconfig._const import Tc from tcconfig._converter import Humanreadable def is_invalid_param( rate, delay, packet_loss, packet_duplicate, corrupt, reordering): param_value_list = [ delay, packet_loss, packet_duplicate, corrupt, reordering, ] print(param_value_list) is_invalid = all([ not RealNumber(param_value).is_type() or param_value <= 0 for param_value in param_value_list ]) try: Humanreadable(rate, kilo_size=1000).to_bit() except (TypeError, ValueError): pass else: is_invalid = False return is_invalid def execute_tcdel(device): SubprocessRunner( "{:s} --device {} --all".format(Tc.Command.TCDEL, device), dry_run=False).run()
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import print_function from subprocrunner import SubprocessRunner from typepy.type import RealNumber from tcconfig._const import Tc from tcconfig._converter import Humanreadable def is_invalid_param( rate, delay, packet_loss, packet_duplicate, corrupt, reordering): param_value_list = [ delay, packet_loss, packet_duplicate, corrupt, reordering, ] print(param_value_list) is_invalid = all([ not RealNumber(param_value).is_type() or param_value <= 0 for param_value in param_value_list ]) try: Humanreadable(rate, kilo_size=1000).to_bit() except (TypeError, ValueError): pass else: is_invalid = False return is_invalid def execute_tcdel(device): SubprocessRunner( "{:s} --device {}".format(Tc.Command.TCDEL, device), dry_run=False).run()
Use spec 1.1 --with-timing option
from invoke import ctask as task @task(help={ 'module': "Just runs tests/STRING.py.", 'runner': "Use STRING to run tests instead of 'spec'.", 'opts': "Extra flags for the test runner", 'pty': "Whether to run tests under a pseudo-tty", }) def test(c, module=None, runner=None, opts=None, pty=True): """ Run a Spec or Nose-powered internal test suite. """ runner = runner or 'spec' # Allow selecting specific submodule specific_module = " --tests=tests/%s.py" % module args = (specific_module if module else "") if opts: args += " " + opts # Always enable timing info by default. OPINIONATED args += " --with-timing" # Use pty by default so the spec/nose/Python process buffers "correctly" c.run(runner + args, pty=pty)
from invoke import ctask as task @task(help={ 'module': "Just runs tests/STRING.py.", 'runner': "Use STRING to run tests instead of 'spec'.", 'opts': "Extra flags for the test runner", 'pty': "Whether to run tests under a pseudo-tty", }) def test(c, module=None, runner=None, opts=None, pty=True): """ Run a Spec or Nose-powered internal test suite. """ runner = runner or 'spec' # Allow selecting specific submodule specific_module = " --tests=tests/%s.py" % module args = (specific_module if module else "") if opts: args += " " + opts # Use pty by default so the spec/nose/Python process buffers "correctly" c.run(runner + args, pty=pty)
Add a '@return void' annotation, so that implementors know what to do in the overridden method.
<?php namespace Codeception\Module\Drupal\UserRegistry; /** * Interface TestUserManagerInterface. * * @package Codeception\Module\DrupalUserRegistry */ interface TestUserManagerInterface { /** * Create a test user. * * @param DrupalTestUser $user * The user to create. * * @return void */ public function createUser($user); /** * Create multiple test users. * * @param array $users * An array of DrupalTestUser objects to create. * * @return void */ public function createUsers($users); /** * Delete a test user. * * @param DrupalTestUser $user * The user to delete. * * @return void */ public function deleteUser($user); /** * Delete multiple test users. * * @param array $users * An array of DrupalTestUser objects to delete. * * @return void */ public function deleteUsers($users); /** * Determine if a user with a given username exists. * * @param string $username * The username to check. * * @return bool * True if the user exists, false otherwise. */ public function userExists($username); }
<?php namespace Codeception\Module\Drupal\UserRegistry; /** * Interface TestUserManagerInterface. * * @package Codeception\Module\DrupalUserRegistry */ interface TestUserManagerInterface { /** * Create a test user. * * @param DrupalTestUser $user * The user to create. */ public function createUser($user); /** * Create multiple test users. * * @param array $users * An array of DrupalTestUser objects to create. */ public function createUsers($users); /** * Delete a test user. * * @param DrupalTestUser $user * The user to delete. */ public function deleteUser($user); /** * Delete multiple test users. * * @param array $users * An array of DrupalTestUser objects to delete. */ public function deleteUsers($users); /** * Determine if a user with a given username exists. * * @param string $username * The username to check. * * @return bool * True if the user exists, false otherwise. */ public function userExists($username); }
Fix running nonHeadless e2e tests against latest chromedriver Can't pass null args. Must pass *some* args in order to have nightwatch overwrite defaults.
require("babel-register"); const selenium = require("selenium-server-standalone-jar"); const chromedriver = require("chromedriver"); module.exports = { src_folders: ["./test/e2e"], output_folder: "reports", selenium: { start_process: true, server_path: selenium.path, log_path: "reports", cli_args: { "webdriver.chrome.driver": chromedriver.path } }, test_settings: { default: { launch_url: `http://localhost:${process.env.SERVER_PORT || 9091}/`, selenium_port: 4444, selenium_host: "localhost", desiredCapabilities: { browserName: "chrome", chromeOptions: { args: ["--headless"] } }, globals: { waitForConditionTimeout: 5000 } }, nonHeadless: { desiredCapabilities: { browserName: "chrome", chromeOptions: { args: ["--default"] } } }, ci: { desiredCapabilities: { browserName: "chrome", chromeOptions: { args: ["--no-sandbox", "--headless"] } } } } };
require("babel-register"); const selenium = require("selenium-server-standalone-jar"); const chromedriver = require("chromedriver"); module.exports = { src_folders: ["./test/e2e"], output_folder: "reports", selenium: { start_process: true, server_path: selenium.path, log_path: "reports", cli_args: { "webdriver.chrome.driver": chromedriver.path } }, test_settings: { default: { launch_url: `http://localhost:${process.env.SERVER_PORT || 9091}/`, selenium_port: 4444, selenium_host: "localhost", desiredCapabilities: { browserName: "chrome", chromeOptions: { args: ["--headless"] } }, globals: { waitForConditionTimeout: 5000 } }, nonHeadless: { desiredCapabilities: { browserName: "chrome", chromeOptions: { args: null } } }, ci: { desiredCapabilities: { browserName: "chrome", chromeOptions: { args: ["--no-sandbox", "--headless"] } } } } };
Add port to logging. Fix print statement.
# -*- coding: utf-8 -*- import network BLOCK_SIZE = 256 PORT = 53 def listen(port): if port is None: port = PORT print('Listening for data via DNS on port {0}.'.format(port)) l = network.get_listener('UDP', port) print('Data Received:') while 1: data, addr = l.recvfrom(1500) dns = network.parse_dns(data) name = str(dns.get_q().get_qname()) dec = network.decode_data(name.rstrip('.')) print(dec) def send(server, port, data): if port is None: port = PORT print('Sending data via DNS to {0} on port {1}.'.format(server, port)) print('Data Sent:') for n in range(0, len(data), BLOCK_SIZE): block = data[n:n + BLOCK_SIZE] print(block) enc = network.encode_data(block) network.send_dns_query(server, port, enc)
# -*- coding: utf-8 -*- import network BLOCK_SIZE = 256 PORT = 53 def listen(port): if port is None: port = PORT print('Listening for data via DNS.') l = network.get_listener('UDP', port) print('Data Received:') while 1: data, addr = l.recvfrom(1500) dns = network.parse_dns(data) name = str(dns.get_q().get_qname()) dec = network.decode_data(name.rstrip('.')) print(dec) def send(server, port, data): if port is None: port = PORT print('Sending data to {0} via DNS.'.format(server)) print('Data Sent:') for n in range(0, len(data), BLOCK_SIZE): block = data[n:n + BLOCK_SIZE] print block enc = network.encode_data(block) network.send_dns_query(server, port, enc)
Make sure colors are in static order
import textures from 'textures' export const colors = ['#ffd300', '#f56d00', '#15c2e8', '#1d70b7', '#c792ca', '#ba4b7a'] export const colorTextures = { '#ffd300': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#f56d00': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#15c2e8': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#1d70b7': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#c792ca': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#ba4b7a': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, }
import textures from 'textures' export const colorTextures = { '#ffd300': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#f56d00': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#15c2e8': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#1d70b7': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#c792ca': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, '#ba4b7a': () => { return textures.lines() .stroke('#f48335') .background('#f36d20') }, } export const colors = Object.keys(colorTextures)
Add javascript for locating latest stable version.
var versions = ['dev', '0.8.0', '0.7.0', '0.6', '0.5', '0.4', '0.3']; function insert_version_links() { for (i = 0; i < versions.length; i++){ open_list = '<li>' if (typeof(DOCUMENTATION_OPTIONS) !== 'undefined') { if ((DOCUMENTATION_OPTIONS['VERSION'] == versions[i]) || (DOCUMENTATION_OPTIONS['VERSION'].match(/dev$/) && (i == 0))) { open_list = '<li id="current">' } } document.write(open_list); document.write('<a href="URL">skimage VERSION</a> </li>\n' .replace('VERSION', versions[i]) .replace('URL', 'http://scikit-image.org/docs/' + versions[i])); } } function stable_version() { return versions[1]; }
function insert_version_links() { var labels = ['dev', '0.8.0', '0.7.0', '0.6', '0.5', '0.4', '0.3']; for (i = 0; i < labels.length; i++){ open_list = '<li>' if (typeof(DOCUMENTATION_OPTIONS) !== 'undefined') { if ((DOCUMENTATION_OPTIONS['VERSION'] == labels[i]) || (DOCUMENTATION_OPTIONS['VERSION'].match(/dev$/) && (i == 0))) { open_list = '<li id="current">' } } document.write(open_list); document.write('<a href="URL">skimage VERSION</a> </li>\n' .replace('VERSION', labels[i]) .replace('URL', 'http://scikit-image.org/docs/' + labels[i])); } }
Use alternate text for the schedule tweet when there's a new stage
const TwitterPostBase = require('./TwitterPostBase'); const { captureScheduleScreenshot } = require('../screenshots'); const { readData, readJson } = require('../utilities'); const path = require('path'); const stagesPath = path.resolve('storage/stages.json'); class ScheduleTweet extends TwitterPostBase { getKey() { return 'schedule'; } getName() { return 'Schedule'; } getSchedules() { return readData('schedules.json'); } getData() { return this.getSchedules().regular.find(s => s.start_time == this.getDataTime()); } getTestData() { return this.getSchedules().regular[0]; } getImage(data) { return captureScheduleScreenshot(data.start_time); } getText(data) { // Load known stages let stages = readJson(stagesPath); for (let stage of [data.stage_a, data.stage_b]) { let stageInfo = stages.find(s => s.id == stage.id); // If this is the first time the stage has been available, return some different text if (stageInfo && stageInfo.first_available == data.start_time) return `New stage ${stage.name} is now open! #splatoon2`; } return 'Current Splatoon 2 map rotation'; } } module.exports = ScheduleTweet;
const TwitterPostBase = require('./TwitterPostBase'); const { captureScheduleScreenshot } = require('../screenshots'); const { readData } = require('../utilities'); class ScheduleTweet extends TwitterPostBase { getKey() { return 'schedule'; } getName() { return 'Schedule'; } getSchedules() { return readData('schedules.json'); } getData() { return this.getSchedules().regular.find(s => s.start_time == this.getDataTime()); } getTestData() { return this.getSchedules().regular[0]; } getImage(data) { return captureScheduleScreenshot(data.start_time); } getText(data) { return 'Current Splatoon 2 map rotation'; } } module.exports = ScheduleTweet;
Add comment for check for nil receiver.
package events import ( "strconv" "strings" "time" ) type Event struct { Time time.Time Data map[string]*float64 // TODO: change to map[string]struct{} Tags []string } func NewEvent(data map[string]*float64) *Event { return &Event{Time: time.Now(), Data: data, Tags: make([]string, 0)} } func (e *Event) AddTag(t string) { e.Tags = append(e.Tags, t) } func (e *Event) IsRedAlert() bool { for _, tag := range e.Tags { if tag == "redalert" { return true } } return false } func (e *Event) HasTag(t string) bool { for _, tag := range e.Tags { if tag == t { return true } } return false } func (e *Event) DisplayMetric(metric string) string { if e.Data[metric] == nil { return "" } return strconv.FormatFloat(*e.Data[metric], 'f', 1, 64) } func (e *Event) DisplayTags() string { // required as used in template if e == nil { return "" } return strings.Join(e.Tags, " ") }
package events import ( "fmt" "strconv" "strings" "time" ) type Event struct { Time time.Time Data map[string]*float64 // TODO: change to map[string]struct{} Tags []string } func NewEvent(data map[string]*float64) *Event { return &Event{Time: time.Now(), Data: data, Tags: make([]string, 0)} } func (e *Event) AddTag(t string) { e.Tags = append(e.Tags, t) } func (e *Event) IsRedAlert() bool { for _, tag := range e.Tags { if tag == "redalert" { return true } } return false } func (e *Event) HasTag(t string) bool { for _, tag := range e.Tags { if tag == t { return true } } return false } func (e *Event) DisplayMetric(metric string) string { if e.Data[metric] == nil { return "" } return strconv.FormatFloat(*e.Data[metric], 'f', 1, 64) } func (e *Event) DisplayTags() string { if e == nil { return "" } // if e.Tags == nil { // return "" // } fmt.Println(e) return strings.Join(e.Tags, " ") }
Use helper method to read files
import re import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() init_path = 'random_object_id/__init__.py' version = re.search('"([0-9\.]+)"', read(init_path)).group(1) long_description = read('README.rst') setup( name='random-object-id', packages=['random_object_id'], entry_points={ 'console_scripts': [ 'random_object_id=random_object_id.random_object_id:main', ], }, version=version, description='Generate a random MongoDB ObjectId.', long_description=long_description, author='Max Rozentsveyg', author_email='maxr@outlook.com', url='https://github.com/mxr/random-object-id', )
import re from setuptools import setup init_contents = open('random_object_id/__init__.py').read() version = re.search('"([0-9\.]+)"', init_contents).group(1) with open('README.rst', 'rb') as f: long_description = f.read().decode('utf-8') setup( name='random-object-id', packages=['random_object_id'], entry_points={ 'console_scripts': [ 'random_object_id=random_object_id.random_object_id:main', ], }, version=version, description='Generate a random MongoDB ObjectId.', long_description=long_description, author='Max Rozentsveyg', author_email='maxr@outlook.com', url='https://github.com/mxr/random-object-id', )
Fix to import_module_from_string() to prevent multiple imports
import importlib import logging import sys from typing import Sequence, Tuple, Callable import pkg_resources logger = logging.getLogger(__name__) def import_module_from_string(name): if name in sys.modules: return sys.modules[name] else: return importlib.import_module(name) def import_from_string(name): components = name.split(".") mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]: """Load classes specified in an entrypoint Entrypoints are specified in setup.py, and Lightbus uses them to discover plugins & transports. """ found_classes = [] for entrypoint in pkg_resources.iter_entry_points(entrypoint_name): class_ = entrypoint.load() found_classes.append((entrypoint.module_name, entrypoint.name, class_)) return found_classes
import importlib import logging from typing import Sequence, Tuple, Callable import pkg_resources logger = logging.getLogger(__name__) def import_module_from_string(name): return importlib.import_module(name) def import_from_string(name): components = name.split(".") mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]: """Load classes specified in an entrypoint Entrypoints are specified in setup.py, and Lightbus uses them to discover plugins & transports. """ found_classes = [] for entrypoint in pkg_resources.iter_entry_points(entrypoint_name): class_ = entrypoint.load() found_classes.append((entrypoint.module_name, entrypoint.name, class_)) return found_classes
Apply "visibility_required" CS rule to constants php-cs-fixer fix --rules='{"visibility_required": ["property", "method", "const"]}'
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\FirewallEntryPointBundle\Security; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; class EntryPointStub implements AuthenticationEntryPointInterface { public const RESPONSE_TEXT = '2be8e651259189d841a19eecdf37e771e2431741'; public function start(Request $request, AuthenticationException $authException = null): Response { return new Response(self::RESPONSE_TEXT); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\FirewallEntryPointBundle\Security; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; class EntryPointStub implements AuthenticationEntryPointInterface { const RESPONSE_TEXT = '2be8e651259189d841a19eecdf37e771e2431741'; public function start(Request $request, AuthenticationException $authException = null): Response { return new Response(self::RESPONSE_TEXT); } }
Resolve bug with CORS, get user data
import * as actionTypes from '../actionTypes/actionTypes'; import 'whatwg-fetch'; /** ACTIONS *** Actions define the action type, and do something based on the value of 'type' (i.e. receiveUserData) Action creators will send information to the 'store', by going through reducers, which will change state based on the action type. Action creators (i.e. getUserData) are executable in containers that use Redux's 'connect' helper. 'bindActionCreators()' binds action creators to dispatch */ /** *Default request handler **/ export const requestUserData = (data) => { return { type: actionTypes.GET_USER, data, } } /** * Receive data from fetch **/ export const receiveUserData = (data) => { return { type: actionTypes.GET_USER_SUCCESS, results: data, } } /** *Error handling for failed fetch **/ export const failedFetch = (err) => { return { type: actionTypes.GET_USER_FAILURE, err } } /** * Fetch current user's information **/ export const getUserData = () => { console.log('INSIDE GET USER DATA FUNCTION'); return (dispatch) => { dispatch(requestUserData) return fetch('/get_info/', { method: 'get', }).then(res => res.json()) .then(json => dispatch(receiveUserData(json))) .catch(err => dispatch(failedFetch(err))) } }
import * as actionTypes from '../actionTypes/actionTypes'; import 'whatwg-fetch'; /** ACTIONS *** Actions define the action type, and do something based on the value of 'type' (i.e. receiveUserData) Action creators will send information to the 'store', by going through reducers, which will change state based on the action type. Action creators (i.e. getUserData) are executable in containers that use Redux's 'connect' helper. 'bindActionCreators()' binds action creators to dispatch */ export const requestUserData = (data) => { return { type: actionTypes.GET_USER, data, } } /** * Receive data from fetch **/ export const receiveUserData = (data) => { return { type: actionTypes.GET_USER_SUCCESS, results: data, } } /** * Fetch current user's information **/ export const getUserData = () => { console.log('INSIDE GET USER DATA FUNCTION'); return (dispatch) => { dispatch(requestUserData) return fetch('/get_info/', { method: 'get', mode: 'no-cors', }).then(res => res.json()) .then(json => dispatch(receiveUserData(json))) .catch(err => dispatch({ type: actionTypes.GET_USER_FAILURE, results: err, })) } }
Fix bug in timer panel display
from flask import template_rendered from flaskext.debugtoolbar.panels import DebugPanel _ = lambda x: x class TemplateDebugPanel(DebugPanel): """ Panel that displays the time a response took in milliseconds. """ name = 'Template' has_content = True def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.templates = [] template_rendered.connect(self._store_template_info) def _store_template_info(self, sender, **kwargs): self.templates.append(kwargs) def process_request(self, request): pass def process_response(self, request, response): pass def nav_title(self): return _('Templates') def nav_subtitle(self): return "%d rendered" % len(self.templates) def title(self): return _('Templates') def url(self): return '' def content(self): return self.render('panels/template.html', { 'templates': self.templates })
from flask import template_rendered from flaskext.debugtoolbar.panels import DebugPanel _ = lambda x: x class TemplateDebugPanel(DebugPanel): """ Panel that displays the time a response took in milliseconds. """ name = 'Timer' has_content = True def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.templates = [] template_rendered.connect(self._store_template_info) def _store_template_info(self, sender, **kwargs): self.templates.append(kwargs) def process_request(self, request): pass def process_response(self, request, response): pass def nav_title(self): return _('Templates') def nav_subtitle(self): return "%d rendered" % len(self.templates) def title(self): return _('Templates') def url(self): return '' def content(self): return self.render('panels/template.html', { 'templates': self.templates })
Fix call to OC.generateUrl for caldav birthday calendar on/off Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>
/** * @copyright 2017, Georg Ehrke <oc.list@georgehrke.com> * * @author Georg Ehrke <oc.list@georgehrke.com> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ "use strict"; $('#caldavSendInvitations').change(function() { var val = $(this)[0].checked; OCP.AppConfig.setValue('dav', 'sendInvitations', val ? 'yes' : 'no'); }); $('#caldavGenerateBirthdayCalendar').change(function() { var val = $(this)[0].checked; if (val) { $.post(OC.generateUrl('/apps/dav/enableBirthdayCalendar')); } else { $.post(OC.generateUrl('/apps/dav/disableBirthdayCalendar')); } });
/** * @copyright 2017, Georg Ehrke <oc.list@georgehrke.com> * * @author Georg Ehrke <oc.list@georgehrke.com> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ "use strict"; $('#caldavSendInvitations').change(function() { var val = $(this)[0].checked; OCP.AppConfig.setValue('dav', 'sendInvitations', val ? 'yes' : 'no'); }); $('#caldavGenerateBirthdayCalendar').change(function() { var val = $(this)[0].checked; if (val) { $.post(OC.generateUrl(OC.linkTo("dav", "enableBirthdayCalendar"))); } else { $.post(OC.generateUrl(OC.linkTo("dav", "disableBirthdayCalendar"))); } });