text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use SGF loader if open file with unrecognized extension
const {extname} = require('path') let sgf = require('./sgf') let ngf = require('./ngf') let gib = require('./gib') let modules = {sgf, ngf, gib} exports = module.exports = Object.assign({}, modules) let extensions = Object.keys(modules).map(key => modules[key].meta) let combinedExtensions = extensions.map(x => x.extensions) .reduce((acc, x) => [...acc, ...x], []) exports.meta = [ {name: 'Game Records', extensions: combinedExtensions}, ...extensions ] exports.getModuleByExtension = function(extension) { return modules[Object.keys(modules).find(key => modules[key].meta.extensions.includes(extension.toLowerCase()) )] || sgf } exports.parseFile = function(filename, onProgress) { let extension = extname(filename).slice(1) let m = exports.getModuleByExtension(extension) return m.parseFile(filename, onProgress) }
const {extname} = require('path') let sgf = require('./sgf') let ngf = require('./ngf') let gib = require('./gib') let modules = {sgf, ngf, gib} exports = module.exports = modules let extensions = Object.keys(modules).map(key => modules[key].meta) let combinedExtensions = extensions.map(x => x.extensions) .reduce((acc, x) => [...acc, ...x], []) exports.meta = [ {name: 'Game Records', extensions: combinedExtensions}, ...extensions ] exports.getModuleByExtension = function(extension) { return modules[Object.keys(modules).find(key => modules[key].meta.extensions.includes(extension.toLowerCase()) )] || sgf } exports.parseFile = function(filename, onProgress) { let extension = extname(filename).slice(1) let m = exports.getModuleByExtension(extension) return m.parseFile(filename, onProgress) }
Make more syntactically correct. No operational changes.
/** * Copyright (c) 2012-2012 Malhar, Inc. * All rights reserved. */ package com.malhartech.demos.performance; import com.malhartech.api.ApplicationFactory; import com.malhartech.api.DAG; import org.apache.hadoop.conf.Configuration; /** * Example of application configuration in Java.<p> */ public class Application implements ApplicationFactory { private static final boolean inline = false; @Override public DAG getApplication(Configuration conf) { DAG dag = new DAG(conf); dag.getAttributes().attr(DAG.STRAM_CHECKPOINT_INTERVAL_MILLIS).set(0); // disable operator state saving RandomWordInputModule wordGenerator = dag.addOperator("wordGenerator", RandomWordInputModule.class); // DoNothingModule<byte[]> noOpProcessor = dag.addOperator("noOpProcessor", new DoNothingModule<byte[]>()); WordCountModule<byte[]> counter = dag.addOperator("counter", new WordCountModule<byte[]>()); // dag.addStream("Generator2Processor", wordGenerator.output, noOpProcessor.input).setInline(inline); // dag.addStream("Processor2Counter", noOpProcessor.output, counter.input).setInline(inline); dag.addStream("Generator2Counter", wordGenerator.output, counter.input).setInline(inline); return dag; } }
/** * Copyright (c) 2012-2012 Malhar, Inc. * All rights reserved. */ package com.malhartech.demos.performance; import com.malhartech.api.ApplicationFactory; import com.malhartech.api.DAG; import org.apache.hadoop.conf.Configuration; /** * Example of application configuration in Java.<p> */ public class Application implements ApplicationFactory { private static final boolean inline = false; @Override public DAG getApplication(Configuration conf) { DAG dag = new DAG(conf); dag.getAttributes().attr(DAG.STRAM_CHECKPOINT_INTERVAL_MILLIS).set(0); // disable operator state saving RandomWordInputModule wordGenerator = dag.addOperator("wordGenerator", RandomWordInputModule.class); // DoNothingModule<byte[]> noOpProcessor = dag.addOperator("noOpProcessor", new DoNothingModule<byte[]>()); WordCountModule<byte[]> counter = dag.addOperator("counter", WordCountModule.class); // dag.addStream("Generator2Processor", wordGenerator.output, noOpProcessor.input).setInline(inline); // dag.addStream("Processor2Counter", noOpProcessor.output, counter.input).setInline(inline); dag.addStream("Generator2Counter", wordGenerator.output, counter.input).setInline(inline); return dag; } }
Use the new system in test entity types
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.EntityTypeDeferredRegister; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.entity.BetterEnderPearlEntity; import net.minecraft.entity.*; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; public class TestEntityTypes { public static final EntityTypeDeferredRegister ENTITY_TYPES = EntityTypeDeferredRegister.create(TestMod.MODID); public static final RegistryObject<EntityType<BetterEnderPearlEntity>> BETTER_ENDERPEARL = ENTITY_TYPES.register("better_enderpearl", () -> EntityType.Builder.<BetterEnderPearlEntity> create(BetterEnderPearlEntity::new, EntityClassification.MISC).size(0.25F, 0.25F).setTrackingRange(128).setUpdateInterval(20).setShouldReceiveVelocityUpdates(true)); public static void register(IEventBus bus) { ENTITY_TYPES.register(bus); } }
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.CommonDeferredRegister; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.entity.BetterEnderPearlEntity; import net.minecraft.entity.*; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.ForgeRegistries; public class TestEntityTypes { public static final CommonDeferredRegister<EntityType<?>> ENTITY_TYPES = CommonDeferredRegister.create(ForgeRegistries.ENTITIES, TestMod.MODID); public static final RegistryObject<EntityType<BetterEnderPearlEntity>> BETTER_ENDERPEARL = ENTITY_TYPES.register("better_enderpearl", () -> EntityType.Builder.<BetterEnderPearlEntity> create(BetterEnderPearlEntity::new, EntityClassification.MISC).size(0.25F, 0.25F).setTrackingRange(128).setUpdateInterval(20).setShouldReceiveVelocityUpdates(true).build(null)); public static void register(IEventBus bus) { ENTITY_TYPES.register(bus); } }
Use correct Script subtypes for init scripts.
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configuration; import org.gradle.api.internal.GradleInternal; import org.gradle.groovy.scripts.BasicScript; import org.gradle.initialization.InitScript; public class InitScriptTarget extends DefaultScriptTarget { public InitScriptTarget(GradleInternal target) { super(target); } @Override public Class<? extends BasicScript> getScriptClass() { return InitScript.class; } @Override public String getClasspathBlockName() { return "initscript"; } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configuration; import org.gradle.api.internal.GradleInternal; public class InitScriptTarget extends DefaultScriptTarget { public InitScriptTarget(GradleInternal target) { super(target); } @Override public String getClasspathBlockName() { return "initscript"; } }
Remove unneeded component import extension
import React, { Component } from 'react'; import Button from './components/Button'; export default class App extends Component { constructor() { super(); this.state = { selectedRange: 'bar', ranges: [] }; } handleClick = (foo) => { this.setState({selectedRange: foo}); }; render() { return ( <div className='app-container'> <h1>App</h1> <Button handleClick={this.handleClick.bind(null, 'blerg')}>Click me!</Button> <span>{this.state.selectedRange}</span> </div> ); } }
import React, { Component } from 'react'; import Button from './components/Button.jsx'; export default class App extends Component { constructor() { super(); this.state = { selectedRange: 'bar', ranges: [] }; } handleClick = (foo) => { this.setState({selectedRange: foo}); }; render() { return ( <div className='app-container'> <h1>App</h1> <Button handleClick={this.handleClick.bind(null, 'blerg')}>Click me!</Button> <span>{this.state.selectedRange}</span> </div> ); } }
Update test values. Trie no longer provides 2 of the answers.
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', None, # 'sept e nary +1' lost when Trie threshold was changed. 'binary +1', None, None, # 'qui nary +9' lost when Trie threshold was changed. None, None, 'quaternary +12', None ]))
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', 'sept e nary +1', 'binary +1', None, 'qui nary +9', None, None, 'quaternary +12', None ]))
Add sorting to repair list
module.exports = function() { console.log("Maintaining Structures... " + Game.getUsedCpu()); Object.keys(Game.structures).forEach(function(id) { var structure = Game.getObjectById(id); console.log(structure.structureType + " " + structure.hits + ":" + structure.hitsMax); if(structure.hits < (structure.hitsMax / 2) && Memory.repairList.indexOf(id) === -1) { console.log(structure.structureType + " " + structure.id + " added."); Memory.repairList.push(id); } else { console.log(structure.structureType + " " + structure.hits + ":" + structure.hitsMax + " index:" + Memory.repairList.indexOf(id)); var index = Memory.repairList.indexOf(id); if(index > -1 && structure.hits >= (structure.hitsMax / 2)) { Memory.repairList.splice(index, 1); } } Memory.repairList.sort(function(a, b) { return Game.getObjectById(b).hits - Game.getObjectById(a).hits; }); }); console.log("Finished " + Game.getUsedCpu()); }
module.exports = function() { console.log("Maintaining Structures... " + Game.getUsedCpu()); Object.keys(Game.structures).forEach(function(id) { var structure = Game.getObjectById(id); console.log(structure.structureType + " " + structure.hits + ":" + structure.hitsMax); if(structure.hits < (structure.hitsMax / 2) && Memory.repairList.indexOf(id) === -1) { console.log(structure.structureType + " " + structure.id + " added."); Memory.repairList.push(id); } else { console.log(structure.structureType + " " + structure.hits + ":" + structure.hitsMax + " index:" + Memory.repairList.indexOf(id)); var index = Memory.repairList.indexOf(id); if(index > -1 && structure.hits >= (structure.hitsMax / 2)) { Memory.repairList.splice(index, 1); } } }); console.log("Finished " + Game.getUsedCpu()); }
Disable event dispatching for this test
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use function count; use PHPUnit\Event\Facade; use PHPUnit\TestFixture\DoubleTestCase; use PHPUnit\TestFixture\Success; /** * @small */ final class TestImplementorTest extends TestCase { public function testSuccessfulRun(): void { $result = new TestResult; $test = new DoubleTestCase(new Success('testOne')); Facade::suspend(); $test->run($result); Facade::resume(); $this->assertCount(count($test), $result); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); } }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use function count; use PHPUnit\TestFixture\DoubleTestCase; use PHPUnit\TestFixture\Success; /** * @small */ final class TestImplementorTest extends TestCase { public function testSuccessfulRun(): void { $result = new TestResult; $test = new DoubleTestCase(new Success('testOne')); $test->run($result); $this->assertCount(count($test), $result); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); } }
[Tests] Test large number as response for check_answer
import unittest from units.trivia import check_answer class TestCheckAnswer(unittest.TestCase): def test_correct_answer(self): self.assertTrue(check_answer("correct", "correct")) def test_incorrect_answer(self): self.assertFalse(check_answer("correct", "incorrect")) def test_large_number(self): self.assertFalse( check_answer( "33 1/3", "128347192834719283561293847129384719238471234" ) ) def test_parentheses_with_article_prefix(self): self.assertTrue( check_answer( "the ISS (the International Space Station)", "International Space Station" ) ) self.assertTrue( check_answer("Holland (The Netherlands)", "Netherlands") ) def test_wrong_encoding(self): self.assertTrue(check_answer("a résumé", "resume")) self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan")) if __name__ == "__main__": unittest.main()
import unittest from units.trivia import check_answer class TestCheckAnswer(unittest.TestCase): def test_correct_answer(self): self.assertTrue(check_answer("correct", "correct")) def test_incorrect_answer(self): self.assertFalse(check_answer("correct", "incorrect")) def test_parentheses_with_article_prefix(self): self.assertTrue( check_answer( "the ISS (the International Space Station)", "International Space Station" ) ) self.assertTrue( check_answer("Holland (The Netherlands)", "Netherlands") ) def test_wrong_encoding(self): self.assertTrue(check_answer("a résumé", "resume")) self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan")) if __name__ == "__main__": unittest.main()
Fix pathnames issue in webpack
var webpack = require('webpack'); var precss = require('precss'); var autoprefixer = require('autoprefixer'); module.exports = { entry: [ './src/js/main.js' ], module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader!postcss-loader' }, { test: /\.js$/, exclude: /node_modules/, loader: ['babel'], query: { 'presets': ['react', 'es2015'], 'plugins': [ 'transform-object-rest-spread' ] } } ] }, postcss: function () { return [precss, autoprefixer({ browsers: ['> 5%'] })] }, resolve: { extensions: ['', '.js'] }, output: { path: __dirname + '/dist', publicPath: 'js', // it depends on what we set as content-base option with // the CLI filename: './js/model-explorer.js' } }
var webpack = require('webpack'); var precss = require('precss'); var autoprefixer = require('autoprefixer'); module.exports = { entry: [ './src/js/main.js' ], module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader!postcss-loader' }, { test: /\.js$/, exclude: /node_modules/, loader: ['babel'], query: { 'presets': ['react', 'es2015'], 'plugins': [ 'transform-object-rest-spread' ] } } ] }, postcss: function () { return [precss, autoprefixer({ browsers: ['> 5%'] })] }, resolve: { extensions: ['', '.js'] }, output: { path: __dirname + '/dist/js', publicPath: 'js', // it depends on what we set as content-base option with // the CLI filename: 'model-explorer.js' } }
Include kafka-check, bump to v0.2.6
from setuptools import setup from setuptools import find_packages from yelp_kafka_tool import __version__ setup( name="yelp-kafka-tool", version=__version__, author="Distributed systems team", author_email="team-dist-sys@yelp.com", description="Kafka management tools", packages=find_packages(exclude=["scripts", "tests"]), data_files=[ ("bash_completion.d", ["bash_completion.d/kafka-info"]), ], scripts=[ "scripts/kafka-info", "scripts/kafka-reassignment", "scripts/kafka-partition-manager", "scripts/kafka-consumer-manager", "scripts/yelpkafka", "scripts/kafka-check", ], install_requires=[ "argcomplete", "kazoo>=2.0.post2,<3.0.0", "PyYAML<4.0.0", "yelp-kafka>=4.0.0,<5.0.0", "requests<3.0.0" ], )
from setuptools import setup from setuptools import find_packages from yelp_kafka_tool import __version__ setup( name="yelp-kafka-tool", version=__version__, author="Distributed systems team", author_email="team-dist-sys@yelp.com", description="Kafka management tools", packages=find_packages(exclude=["scripts", "tests"]), data_files=[ ("bash_completion.d", ["bash_completion.d/kafka-info"]), ], scripts=[ "scripts/kafka-info", "scripts/kafka-reassignment", "scripts/kafka-partition-manager", "scripts/kafka-consumer-manager", "scripts/yelpkafka", ], install_requires=[ "argcomplete", "kazoo>=2.0.post2,<3.0.0", "PyYAML<4.0.0", "yelp-kafka>=4.0.0,<5.0.0", "requests<3.0.0" ], )
Test case compatibility with Webpack 4.3+
var SriPlugin = require('webpack-subresource-integrity'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var createExtractTextLoader = require('../utils').createExtractTextLoader; var webpackVersionMajMin = require('webpack/package.json') .version.split('.') .map(Number); // https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/763 const placeholder = webpackVersionMajMin[0] > 4 || (webpackVersionMajMin[0] === 4 && webpackVersionMajMin[1] >= 3) ? 'md5:contenthash:hex:20' : 'contenthash'; module.exports = { entry: './index.js', output: { filename: 'bundle.js', crossOriginLoading: 'anonymous' }, module: webpackVersionMajMin[0] > 1 ? { rules: [{ test: /\.css$/, use: createExtractTextLoader() }] } : { loaders: [{ test: /\.css$/, loader: createExtractTextLoader() }] }, plugins: [ new HtmlWebpackPlugin({ hash: true, inject: false, filename: 'index.html', template: 'index.ejs' }), new ExtractTextPlugin('bundle.css?[' + placeholder + ']'), new SriPlugin({ hashFuncNames: ['sha256', 'sha384'] }) ] };
var SriPlugin = require('webpack-subresource-integrity'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var createExtractTextLoader = require('../utils').createExtractTextLoader; var webpackVersion = Number( require('webpack/package.json').version.split('.')[0] ); module.exports = { entry: './index.js', output: { filename: 'bundle.js', crossOriginLoading: 'anonymous' }, module: webpackVersion > 1 ? { rules: [{ test: /\.css$/, use: createExtractTextLoader() }] } : { loaders: [{ test: /\.css$/, loader: createExtractTextLoader() }] }, plugins: [ new HtmlWebpackPlugin({ hash: true, inject: false, filename: 'index.html', template: 'index.ejs' }), new ExtractTextPlugin('bundle.css?[contenthash]'), new SriPlugin({ hashFuncNames: ['sha256', 'sha384'] }) ] };
Fix to integratie with Homi's laravel integration
<?php namespace Magister\Services\Http; use GuzzleHttp\Client; use Magister\Services\Support\ServiceProvider; use GuzzleHttp\Subscriber\Cache\CacheSubscriber; /** * Class HttpServiceProvider. */ class HttpServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function register() { $this->registerGuzzle(); } /** * Register the Guzzle driver. * * @return void */ protected function registerGuzzle() { $this->app->singleton('http', function ($app) { $client = new Client(['base_url' => "https://{$app['school']}.magister.net/api/"]); $client->setDefaultOption('exceptions', false); $client->setDefaultOption('headers', [ 'X-API-Client-ID' => function_exists('env') ? env('MAGISTER_API_KEY', '12D8') : '12D8', ]); $client->setDefaultOption('cookies', new SessionCookieJar($app['cookie'])); CacheSubscriber::attach($client); return $client; }); } }
<?php namespace Magister\Services\Http; use GuzzleHttp\Client; use Magister\Services\Support\ServiceProvider; use GuzzleHttp\Subscriber\Cache\CacheSubscriber; /** * Class HttpServiceProvider. */ class HttpServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function register() { $this->registerGuzzle(); } /** * Register the Guzzle driver. * * @return void */ protected function registerGuzzle() { $this->app->singleton('http', function ($app) { $client = new Client(['base_url' => "https://{$app['school']}.magister.net/api/"]); $client->setDefaultOption('exceptions', false); $client->setDefaultOption('headers', ['X-API-Client-ID' => '12D8']); $client->setDefaultOption('cookies', new SessionCookieJar($app['cookie'])); CacheSubscriber::attach($client); return $client; }); } }
Fix for issue with presence input name
<?php namespace Rhubarb\Scaffolds\Communications\Leaves\CommunicationItem; use Rhubarb\Leaf\Controls\Common\Checkbox\CheckboxView; class CommunicationItemCollectionCheckboxView extends CheckboxView { protected function printViewContent() { ?> <label class="switch"> <?php $attributes = $this->getNameValueClassAndAttributeString(false); $attributes .= $this->model->value ? ' checked="checked"' : ''; $presence = $this->getPresenceInputName(); print "<input type='hidden' name='{$presence}' value='0'><input type='checkbox' {$attributes}/>"; ?> <div class="slider"></div> </label> <?php } /** * @return string */ protected function getPresenceInputName() { return "set_{$this->model->leafPath}_"; } }
<?php namespace Rhubarb\Scaffolds\Communications\Leaves\CommunicationItem; use Rhubarb\Leaf\Controls\Common\Checkbox\CheckboxView; class CommunicationItemCollectionCheckboxView extends CheckboxView { protected function printViewContent() { ?> <label class="switch"> <?php $attributes = $this->getNameValueClassAndAttributeString(false); $attributes .= $this->model->value ? ' checked="checked"' : ''; $presence = $this->getPresenceInputName(); print "<input type='hidden' name='{$presence}' value='0'><input type='checkbox' {$attributes}/>"; ?> <div class="slider"></div> </label> <?php } /** * @return string */ private function getPresenceInputName() { return "set_{$this->model->leafPath}_"; } }
Simplify 'go' for string identifiers
// 404 page using mapbox to show cities around the world. // Helper to generate the kind of coordinate pairs I'm using to store cities function bounds() { var center = map.getCenter(); return {lat: center.lat, lng: center.lng, zoom: map.getZoom()}; } L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg"; var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false}); function go(city) { var placenames = Object.keys(places); city = city || placenames[Math.floor(Math.random() * placenames.length)]; var pos = places[city]; map.setView( [pos.lat, pos.lng], pos.zoom ); } go();
// 404 page using mapbox to show cities around the world. // Helper to generate the kind of coordinate pairs I'm using to store cities function bounds() { var center = map.getCenter(); return {lat: center.lat, lng: center.lng, zoom: map.getZoom()}; } L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg"; var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false}); function go(city) { var placenames = Object.keys(places); city = typeof city === "undefined" ? placenames[Math.floor(Math.random() * placenames.length)] : city; var pos = places[city]; map.setView( [pos.lat, pos.lng], pos.zoom ); } go();
[PIXELS] Add original state to output This will help show where we started from. Tests: - tested using cli directly
package com.bert.pixels; import com.bert.pixels.models.Chamber; import com.bert.pixels.view.TextVisualization; import java.util.ArrayList; import java.util.List; /** * Entry point to solve the pixel exercise */ public class Animation { private final static int MAX_SIZE = 10; public static void main(String[] args) { final int speed = Integer.parseInt(args[1]); TextVisualization visualization = new TextVisualization(MAX_SIZE); final Chamber chamber = visualization.from(args[0]); // We could try to get the max nb of iteration by using the size of the chamber and the speed // and only allocate that many entries in the list #prematureoptimization List<String> iterations = new ArrayList<>(); iterations.add(visualization.to(chamber)); while (!chamber.isEmpty()) { iterations.add(visualization.to(chamber.movePixels(speed))); } System.out.println(String.join("\n", iterations)); } }
package com.bert.pixels; import com.bert.pixels.models.Chamber; import com.bert.pixels.view.TextVisualization; import java.util.ArrayList; import java.util.List; /** * Entry point to solve the pixel exercise */ public class Animation { private final static int MAX_SIZE = 10; public static void main(String[] args) { final int speed = Integer.parseInt(args[1]); TextVisualization visualization = new TextVisualization(MAX_SIZE); final Chamber chamber = visualization.from(args[0]); // We could try to get the max nb of iteration by using the size of the chamber and the speed // and only allocate that many entries in the list #prematureoptimization List<String> iterations = new ArrayList<>(); while (!chamber.isEmpty()) { iterations.add(visualization.to(chamber.movePixels(speed))); } System.out.println(String.join("\n", iterations)); } }
Use variadic args in main method
/* * 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. */ package com.mpalourdio.proxyserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy @EnableDiscoveryClient public class ProxyserverApplication { public static void main(final String ...args) { SpringApplication.run(ProxyserverApplication.class, args); } }
/* * 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. */ package com.mpalourdio.proxyserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy @EnableDiscoveryClient public class ProxyserverApplication { public static void main(final String[] args) { SpringApplication.run(ProxyserverApplication.class, args); } }
Fix closing of multiplexed table writer to close all constituent table writers in presence of exceptions
package org.grouplens.lenskit.util.tablewriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MultiplexedTableWriter implements TableWriter { private TableLayout layout; private List<TableWriter> writers; public MultiplexedTableWriter(TableLayout layout, List<TableWriter> writers) { this.layout = layout; this.writers = writers; } public MultiplexedTableWriter(TableLayout layout, TableWriter... writers) { this(layout, Arrays.asList(writers)); } @Override public TableLayout getLayout() { return layout; } @Override public void writeRow(Object[] row) throws IOException { for (TableWriter w: writers) { w.writeRow(row); } } @Override public void close() throws IOException { ArrayList<IOException> closeExceptions = new ArrayList<IOException>(writers.size()); for (TableWriter w : writers) { try { w.close(); } catch (IOException e) { closeExceptions.add(e); } } if (!closeExceptions.isEmpty()) { throw closeExceptions.get(0); } } }
package org.grouplens.lenskit.util.tablewriter; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.grouplens.lenskit.eval.util.table.TableImpl; public class MultiplexedTableWriter implements TableWriter { private TableLayout layout; private List<TableWriter> writers; public MultiplexedTableWriter(TableLayout layout, List<TableWriter> writers) { this.layout = layout; this.writers = writers; } public MultiplexedTableWriter(TableLayout layout, TableWriter... writers) { this(layout, Arrays.asList(writers)); } @Override public TableLayout getLayout() { return layout; } @Override public void writeRow(Object[] row) throws IOException { for (TableWriter w: writers) { w.writeRow(row); } } @Override public void close() throws IOException { for (TableWriter w : writers) { w.close(); } } }
Install enum34 if not provided
from setuptools import setup, find_packages import re VERSIONFILE = "openomni/_version.py" verstrline = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,)) setup(name='openomni', version=verstr, description='Omnipod Packet Decoding Library', url='http://github.com/openaps/omni', # See https://github.com/openaps/openomni/graphs/contributors for actual # contributors... author='Pete Schwamb', author_email='pete@schwamb.net', scripts=[ 'openomni/bin/decode_omni', 'openomni/bin/omni_listen_rfcat', 'openomni/bin/omni_akimbo', 'openomni/bin/omni_explore', 'openomni/bin/omni_send_rfcat', 'openomni/bin/omni_forloop'], packages=find_packages(), install_requires=[ 'crccheck', 'enum34;python_version<"3.4"', ], zip_safe=False)
from setuptools import setup, find_packages import re VERSIONFILE = "openomni/_version.py" verstrline = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,)) setup(name='openomni', version=verstr, description='Omnipod Packet Decoding Library', url='http://github.com/openaps/omni', # See https://github.com/openaps/openomni/graphs/contributors for actual # contributors... author='Pete Schwamb', author_email='pete@schwamb.net', scripts=[ 'openomni/bin/decode_omni', 'openomni/bin/omni_listen_rfcat', 'openomni/bin/omni_akimbo', 'openomni/bin/omni_explore', 'openomni/bin/omni_send_rfcat', 'openomni/bin/omni_forloop'], packages=find_packages(), install_requires=[ 'crccheck', ], zip_safe=False)
Add optional timeout argument to probe Popen.communicate() supports a timeout argument which is useful in case there is a risk that the probe hangs.
import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', timeout=None, **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code, an :class:`Error` is returned with a generic error message. The stderr output can be retrieved by accessing the ``stderr`` property of the exception. """ args = [cmd, '-show_format', '-show_streams', '-of', 'json'] args += convert_kwargs_to_cmd_line_args(kwargs) args += [filename] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(timeout=timeout) if p.returncode != 0: raise Error('ffprobe', out, err) return json.loads(out.decode('utf-8')) __all__ = ['probe']
import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code, an :class:`Error` is returned with a generic error message. The stderr output can be retrieved by accessing the ``stderr`` property of the exception. """ args = [cmd, '-show_format', '-show_streams', '-of', 'json'] args += convert_kwargs_to_cmd_line_args(kwargs) args += [filename] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode != 0: raise Error('ffprobe', out, err) return json.loads(out.decode('utf-8')) __all__ = ['probe']
Handle updated boto exception format. See https://github.com/boto/boto/issues/625
# -*- coding: utf-8 -*- """ This module contains the set of Dynochemy's exceptions :copyright: (c) 2012 by Rhett Garber. :license: ISC, see LICENSE for more details. """ import json class Error(Exception): """This is an ambiguous error that occured.""" pass class SyncUnallowedError(Error): pass class DuplicateBatchItemError(Error): pass class IncompleteSolventError(Error): pass class ExceededBatchRequestsError(Error): pass class ItemNotFoundError(Error): pass class DynamoDBError(Error): pass class ProvisionedThroughputError(DynamoDBError): pass class UnprocessedItemError(DynamoDBError): pass def parse_error(raw_error): """Parse the error we get out of Boto into something we can code around""" if isinstance(raw_error, Error): return raw_error if 'ProvisionedThroughputExceededException' in raw_error.error_code: return ProvisionedThroughputError(raw_error.error_message) else: return DynamoDBError(raw_error.error_message, raw_error.error_code) __all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
# -*- coding: utf-8 -*- """ This module contains the set of Dynochemy's exceptions :copyright: (c) 2012 by Rhett Garber. :license: ISC, see LICENSE for more details. """ import json class Error(Exception): """This is an ambiguous error that occured.""" pass class SyncUnallowedError(Error): pass class DuplicateBatchItemError(Error): pass class IncompleteSolventError(Error): pass class ExceededBatchRequestsError(Error): pass class ItemNotFoundError(Error): pass class DynamoDBError(Error): pass class ProvisionedThroughputError(DynamoDBError): pass class UnprocessedItemError(DynamoDBError): pass def parse_error(raw_error): """Parse the error we get out of Boto into something we can code around""" if isinstance(raw_error, Error): return raw_error error_data = json.loads(raw_error.data) if 'ProvisionedThroughputExceededException' in error_data['__type']: return ProvisionedThroughputError(error_data['message']) else: return DynamoDBError(error_data['message'], error_data['__type']) __all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
Make path to server more TS friendly by removing strict file type
'use strict'; const path = require('path'); const fs = require('fs'); const nodePaths = (process.env.NODE_PATH || '') .split(process.platform === 'win32' ? ';' : ':') .filter(Boolean) .filter(folder => !path.isAbsolute(folder)) .map(resolveApp); function ensureSlash(path, needsSlash) { const hasSlash = path.endsWith('/'); if (hasSlash && !needsSlash) { return path.substr(path, path.length - 1); } else if (!hasSlash && needsSlash) { return `${path}/`; } else { return path; } } function resolveApp(relativePath) { return path.resolve(fs.realpathSync(process.cwd()), relativePath); } function resolveOwn(relativePath) { return path.resolve(__dirname, '..', relativePath); } module.exports = { appPath: resolveApp('.'), appBuild: resolveApp('build'), appBuildPublic: resolveApp('build/public'), appManifest: resolveApp('build/assets.json'), appPublic: resolveApp('public'), appNodeModules: resolveApp('node_modules'), appSrc: resolveApp('src'), appServerIndexJs: resolveApp('src'), appClientIndexJs: resolveApp('src/client'), appBabelRc: resolveApp('.babelrc'), appRazzleConfig: resolveApp('razzle.config.js'), nodePaths: nodePaths, ownPath: resolveOwn('.'), ownNodeModules: resolveOwn('node_modules'), };
'use strict'; const path = require('path'); const fs = require('fs'); const nodePaths = (process.env.NODE_PATH || '') .split(process.platform === 'win32' ? ';' : ':') .filter(Boolean) .filter(folder => !path.isAbsolute(folder)) .map(resolveApp); function ensureSlash(path, needsSlash) { const hasSlash = path.endsWith('/'); if (hasSlash && !needsSlash) { return path.substr(path, path.length - 1); } else if (!hasSlash && needsSlash) { return `${path}/`; } else { return path; } } function resolveApp(relativePath) { return path.resolve(fs.realpathSync(process.cwd()), relativePath); } function resolveOwn(relativePath) { return path.resolve(__dirname, '..', relativePath); } module.exports = { appPath: resolveApp('.'), appBuild: resolveApp('build'), appBuildPublic: resolveApp('build/public'), appManifest: resolveApp('build/assets.json'), appPublic: resolveApp('public'), appNodeModules: resolveApp('node_modules'), appSrc: resolveApp('src'), appServerIndexJs: resolveApp('src/index.js'), appClientIndexJs: resolveApp('src/client'), appBabelRc: resolveApp('.babelrc'), appRazzleConfig: resolveApp('razzle.config.js'), nodePaths: nodePaths, ownPath: resolveOwn('.'), ownNodeModules: resolveOwn('node_modules'), };
Check `o.name` docstring ("doc:" was omitted from comment test)
Date; //doc: Creates JavaScript Date instances which let you work with dates and times. new Date; //doc: Creates JavaScript Date instances which let you work with dates and times. var myalias = Date; myalias; //doc: Creates JavaScript Date instances which let you work with dates and times. // This is variable foo. var foo = 10; foo; //doc: This is variable foo. // This function returns a monkey. function makeMonkey() { return "monkey"; } makeMonkey; //doc: This function returns a monkey. var monkeyAlias = makeMonkey; monkeyAlias; //doc: This function returns a monkey. // This is an irrelevant comment. // This describes abc. var abc = 20; abc; //doc: This describes abc. // Quux is a thing. And here are a bunch more sentences that would // make the docstring too long, and are thus wisely stripped by Tern's // brain-dead heuristics. Ayay. function Quux() {} Quux; //doc: Quux is a thing. /* Extra bogus * whitespace is also stripped. */ var baz = "hi"; baz; //doc: Extra bogus whitespace is also stripped. var o = { // Get the name. getName: function() { return this.name; }, // The name name: "Harold" }; o.getName; //doc: Get the name. o.name; //doc: The name
Date; //doc: Creates JavaScript Date instances which let you work with dates and times. new Date; //doc: Creates JavaScript Date instances which let you work with dates and times. var myalias = Date; myalias; //doc: Creates JavaScript Date instances which let you work with dates and times. // This is variable foo. var foo = 10; foo; //doc: This is variable foo. // This function returns a monkey. function makeMonkey() { return "monkey"; } makeMonkey; //doc: This function returns a monkey. var monkeyAlias = makeMonkey; monkeyAlias; //doc: This function returns a monkey. // This is an irrelevant comment. // This describes abc. var abc = 20; abc; //doc: This describes abc. // Quux is a thing. And here are a bunch more sentences that would // make the docstring too long, and are thus wisely stripped by Tern's // brain-dead heuristics. Ayay. function Quux() {} Quux; //doc: Quux is a thing. /* Extra bogus * whitespace is also stripped. */ var baz = "hi"; baz; //doc: Extra bogus whitespace is also stripped. var o = { // Get the name. getName: function() { return this.name; }, // The name name: "Harold" }; o.getName; //doc: Get the name. o.name; // The name
Add test for context manager
import pytest import aiohttp from aiohttp import web @pytest.mark.run_loop async def test_await(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) assert resp.status == 200 assert resp.connection is not None await resp.release() assert resp.connection is None @pytest.mark.run_loop async def test_response_context_manager(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) async with resp: assert resp.status == 200 assert resp.connection is not None assert resp.connection is None @pytest.mark.run_loop async def test_client_api_context_manager(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) async with aiohttp.get(url+'/', loop=loop) as resp: assert resp.status == 200 assert resp.connection is not None assert resp.connection is None
import pytest import aiohttp from aiohttp import web @pytest.mark.run_loop async def test_await(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) assert resp.status == 200 assert resp.connection is not None await resp.release() assert resp.connection is None @pytest.mark.run_loop async def test_response_context_manager(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) async with resp: assert resp.status == 200 assert resp.connection is not None assert resp.connection is None
Make the package installable with python3
# -*- coding: utf-8 -*- from pathlib import Path from setuptools import setup, find_packages install_requires = [ 'pytz', 'requests', 'lxml', 'python-dateutil', 'parsedatetime', 'cached-property', 'click', 'enum34', # backported versions from Python3 'pathlib', 'configparser', 'zope.interface', 'attrs', ] console_scripts = [ 'poker = poker.commands:poker', ] classifiers = [ "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ] setup( name='poker', version='0.23.1', description='Poker Framework', long_description=Path('README.rst').read_text(), classifiers=classifiers, keywords='poker', author=u'Kiss György', author_email="kissgyorgy@me.com", url="https://github.com/pokerregion/poker", license="MIT", packages=find_packages(), install_requires=install_requires, entry_points={'console_scripts': console_scripts}, tests_require=['pytest', 'coverage', 'coveralls'], )
# -*- coding: utf-8 -*- import sys if sys.version_info[0] != 2: sys.exit("Sorry, Python 3 is not supported yet") from setuptools import setup, find_packages install_requires = [ 'pytz', 'requests', 'lxml', 'python-dateutil', 'parsedatetime', 'cached-property', 'click', 'enum34', # backported versions from Python3 'pathlib', 'configparser', 'zope.interface', 'attrs', ] console_scripts = [ 'poker = poker.commands:poker', ] classifiers = [ "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ] setup( name='poker', version='0.23.1', description='Poker Framework', long_description=open('README.rst', 'r').read().decode('utf-8'), classifiers=classifiers, keywords='poker', author=u'Kiss György', author_email="kissgyorgy@me.com", url="https://github.com/pokerregion/poker", license="MIT", packages=find_packages(), install_requires=install_requires, entry_points={'console_scripts': console_scripts}, tests_require=['pytest', 'coverage', 'coveralls'], )
Check config for jukebox mode
<?php namespace App\Listeners; use App\Events\SomeEvent; use App\Events\SongChanged; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use lxmpd; class SongChangedEventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SongChanged $event) { // //\Log::alert('song change event fired'); echo "song change event fired" . PHP_EOL; if(($event->status['nextsongid'] == 0) && (config('jukebox.jukebox_mode')) ){ if(lxmpd::playlistExists('jukebox.jukebox_mode')){ //todo: queue song from playlist } else { } } } }
<?php namespace App\Listeners; use App\Events\SomeEvent; use App\Events\SongChanged; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class SongChangedEventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SongChanged $event) { // //\Log::alert('song change event fired'); echo "song change event fired" . PHP_EOL; if(($event->status['nextsongid'] == 0) && (config('jukebox.jukebox_mode')) ){ //todo: queue song from playlist } } }
Switch to go-yaml library from candiedyaml [#126429343]
package config import ( "io/ioutil" "gopkg.in/yaml.v2" ) type RoutingAPIConfig struct { URI string `yaml:"uri"` Port int `yaml:"port"` AuthDisabled bool `yaml:"auth_disabled"` } type OAuthConfig struct { TokenEndpoint string `yaml:"token_endpoint"` Port int `yaml:"port"` SkipSSLValidation bool `yaml:"skip_ssl_validation"` ClientName string `yaml:"client_name"` ClientSecret string `yaml:"client_secret"` CACerts string `yaml:"ca_certs"` } type Config struct { OAuth OAuthConfig `yaml:"oauth"` RoutingAPI RoutingAPIConfig `yaml:"routing_api"` } func New(path string) (*Config, error) { c := &Config{} err := c.initConfigFromFile(path) if err != nil { return nil, err } return c, nil } func (c *Config) initConfigFromFile(path string) error { var e error b, e := ioutil.ReadFile(path) if e != nil { return e } return yaml.Unmarshal(b, &c) }
package config import ( "io/ioutil" "github.com/cloudfoundry-incubator/candiedyaml" ) type RoutingAPIConfig struct { URI string `yaml:"uri"` Port int `yaml:"port"` AuthDisabled bool `yaml:"auth_disabled"` } type OAuthConfig struct { TokenEndpoint string `yaml:"token_endpoint"` Port int `yaml:"port"` SkipSSLValidation bool `yaml:"skip_ssl_validation"` ClientName string `yaml:"client_name"` ClientSecret string `yaml:"client_secret"` CACerts string `yaml:"ca_certs"` } type Config struct { OAuth OAuthConfig `yaml:"oauth"` RoutingAPI RoutingAPIConfig `yaml:"routing_api"` } func New(path string) (*Config, error) { c := &Config{} err := c.initConfigFromFile(path) if err != nil { return nil, err } return c, nil } func (c *Config) initConfigFromFile(path string) error { var e error b, e := ioutil.ReadFile(path) if e != nil { return e } return candiedyaml.Unmarshal(b, &c) }
Fix Event class instance variables
class Event: def __init__(self, source, event, data=None): self.source = source self.event = event self.data = data SOURCE_OTHER = 0 SOURCE_GUI = 1 SOURCE_RUBIK = 2 SOURCE_SIMON = 3 SOURCE_GEARS = 4 EVENT_DEFAULT = 0 EVENT_BUTTON1 = 1 EVENT_BUTTON2 = 2 EVENT_BUTTON3 = 3 EVENT_BUTTON4 = 4 EVENT_BUTTON5 = 5 EVENT_CUBE_LIFT = 6 EVENT_CUBE_SET = 7 EVENT_SUCCESS = 8 EVENT_FAILURE = 9 EVENT_BUTTON_RESET = -1 EVENT_STRINGS = { EVENT_DEFAULT: "DEFAULT", EVENT_BUTTON1: "BUTTON1", EVENT_BUTTON2: "BUTTON2", EVENT_BUTTON3: "BUTTON3", EVENT_BUTTON4: "BUTTON4", EVENT_BUTTON5: "BUTTON5", EVENT_CUBE_LIFT: "CUBE LIFT", EVENT_CUBE_SET: "CUBE SET", EVENT_SUCCESS: "SUCCESS", EVENT_FAILURE: "FAILURE", EVENT_BUTTON_RESET: "RESET" }
class Event: source = None event = None data = None def __init__(self, source, event, data=None): self.source = source self.event = event self.data = data SOURCE_OTHER = 0 SOURCE_GUI = 1 SOURCE_RUBIK = 2 SOURCE_SIMON = 3 SOURCE_GEARS = 4 EVENT_DEFAULT = 0 EVENT_BUTTON1 = 1 EVENT_BUTTON2 = 2 EVENT_BUTTON3 = 3 EVENT_BUTTON4 = 4 EVENT_BUTTON5 = 5 EVENT_CUBE_LIFT = 6 EVENT_CUBE_SET = 7 EVENT_SUCCESS = 8 EVENT_FAILURE = 9 EVENT_BUTTON_RESET = -1 EVENT_STRINGS = { EVENT_DEFAULT: "DEFAULT", EVENT_BUTTON1: "BUTTON1", EVENT_BUTTON2: "BUTTON2", EVENT_BUTTON3: "BUTTON3", EVENT_BUTTON4: "BUTTON4", EVENT_BUTTON5: "BUTTON5", EVENT_CUBE_LIFT: "CUBE LIFT", EVENT_CUBE_SET: "CUBE SET", EVENT_SUCCESS: "SUCCESS", EVENT_FAILURE: "FAILURE", EVENT_BUTTON_RESET: "RESET" }
Add twitter email on twitter package
Twitter = {}; var urls = { requestToken: "https://api.twitter.com/oauth/request_token", authorize: "https://api.twitter.com/oauth/authorize", accessToken: "https://api.twitter.com/oauth/access_token", authenticate: "https://api.twitter.com/oauth/authenticate" }; // https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials Twitter.whitelistedFields = ['profile_image_url', 'profile_image_url_https', 'lang', 'email']; OAuth.registerService('twitter', 1, urls, function(oauthBinding) { var identity = oauthBinding.get('https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true').data; var serviceData = { id: identity.id_str, screenName: identity.screen_name, accessToken: OAuth.sealSecret(oauthBinding.accessToken), accessTokenSecret: OAuth.sealSecret(oauthBinding.accessTokenSecret) }; // include helpful fields from twitter var fields = _.pick(identity, Twitter.whitelistedFields); _.extend(serviceData, fields); return { serviceData: serviceData, options: { profile: { name: identity.name } } }; }); Twitter.retrieveCredential = function(credentialToken, credentialSecret) { return OAuth.retrieveCredential(credentialToken, credentialSecret); };
Twitter = {}; var urls = { requestToken: "https://api.twitter.com/oauth/request_token", authorize: "https://api.twitter.com/oauth/authorize", accessToken: "https://api.twitter.com/oauth/access_token", authenticate: "https://api.twitter.com/oauth/authenticate" }; // https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials Twitter.whitelistedFields = ['profile_image_url', 'profile_image_url_https', 'lang']; OAuth.registerService('twitter', 1, urls, function(oauthBinding) { var identity = oauthBinding.get('https://api.twitter.com/1.1/account/verify_credentials.json').data; var serviceData = { id: identity.id_str, screenName: identity.screen_name, accessToken: OAuth.sealSecret(oauthBinding.accessToken), accessTokenSecret: OAuth.sealSecret(oauthBinding.accessTokenSecret) }; // include helpful fields from twitter var fields = _.pick(identity, Twitter.whitelistedFields); _.extend(serviceData, fields); return { serviceData: serviceData, options: { profile: { name: identity.name } } }; }); Twitter.retrieveCredential = function(credentialToken, credentialSecret) { return OAuth.retrieveCredential(credentialToken, credentialSecret); };
[http] Unify criteria for split name Add missing Etag from zendframework/zf2#5302 c22ec11bf67f7d3f36edcd824ecdb26960c789d5
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19 */ class Etag implements HeaderInterface { public static function fromString($headerLine) { $header = new static(); list($name, $value) = GenericHeader::splitHeaderLine($headerLine); // check to ensure proper header type for this factory if (strtolower($name) !== 'etag') { throw new Exception\InvalidArgumentException('Invalid header line for Etag string: "' . $name . '"'); } // @todo implementation details $header->value = $value; return $header; } public function getFieldName() { return 'Etag'; } public function getFieldValue() { return $this->value; } public function toString() { return 'Etag: ' . $this->getFieldValue(); } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Http\Header; /** * @throws Exception\InvalidArgumentException * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19 */ class Etag implements HeaderInterface { public static function fromString($headerLine) { $header = new static(); list($name, $value) = explode(': ', $headerLine, 2); // check to ensure proper header type for this factory if (strtolower($name) !== 'etag') { throw new Exception\InvalidArgumentException('Invalid header line for Etag string: "' . $name . '"'); } // @todo implementation details $header->value = $value; return $header; } public function getFieldName() { return 'Etag'; } public function getFieldValue() { return $this->value; } public function toString() { return 'Etag: ' . $this->getFieldValue(); } }
Add six module as require package The six module is imported at `values.py`
from setuptools import setup, find_packages # Dynamically calculate the version based on dbsettings.VERSION version_tuple = (0, 7, None) if version_tuple[2] is not None: if type(version_tuple[2]) == int: version = "%d.%d.%s" % version_tuple else: version = "%d.%d_%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] setup( name='django-dbsettings', version=version, description='Application settings whose values can be updated while a project is up and running.', long_description=open('README.rst').read(), author='Samuel Cormier-Iijima', author_email='sciyoshi@gmail.com', maintainer='Jacek Tomaszewski', maintainer_email='jacek.tomek@gmail.com', url='http://github.com/zlorf/django-dbsettings', packages=find_packages(), include_package_data=True, license='BSD', install_requires=( 'six', ), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
from setuptools import setup, find_packages # Dynamically calculate the version based on dbsettings.VERSION version_tuple = (0, 7, None) if version_tuple[2] is not None: if type(version_tuple[2]) == int: version = "%d.%d.%s" % version_tuple else: version = "%d.%d_%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] setup( name='django-dbsettings', version=version, description='Application settings whose values can be updated while a project is up and running.', long_description=open('README.rst').read(), author='Samuel Cormier-Iijima', author_email='sciyoshi@gmail.com', maintainer='Jacek Tomaszewski', maintainer_email='jacek.tomek@gmail.com', url='http://github.com/zlorf/django-dbsettings', packages=find_packages(), include_package_data=True, license='BSD', install_requires=( ), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dblist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dblist.append(str(db).replace('"','')) n += 1 dblist.sort() for db in dblist: # print db print "AdminConfig.show( db ): " AdminConfig.show( db ) print "AdminConfig.showall( db ): " AdminConfig.showall( db ) # AdminConfig.showAttribute(t1,'statementCacheSize' ) # AdminConfig.showAttribute(t1,'[statementCacheSize]' )
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dblist = [] for db in dbs: dbname = db.split('(') n = 0 for i in dbname: if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dblist.append(str(db).replace('"','')) n += 1 dblist.sort() for db in dblist: #t1 = ibmcnx.functions.getDSId( db ) print db # AdminConfig.show( t1 ) # print '\n\n' # AdminConfig.showall( t1 ) # AdminConfig.showAttribute(t1,'statementCacheSize' ) # AdminConfig.showAttribute(t1,'[statementCacheSize]' )
Use join for serializing words and lemmas to avoid printing last ; as required by ATF format. Print also references, notes and links.
from mako.template import Template class Line(object): template = Template("""\n${label}.\t\\ ${' '.join(words)}\\ % if references: % for reference in references: ^${reference}^ % endfor % endif % if lemmas: \n#lem:\\ ${'; '.join(lemmas)}\\ % endif % if notes: \n % for note in notes: ${note.serialize()} % endfor % endif % if links: \n#link: \\ % for link in links: ${link}; % endfor % endif """, output_encoding='utf-8') def __init__(self, label): self.label = label self.words = [] self.lemmas = [] self.witnesses = [] self.translation = None self.notes = [] self.references = [] self.links = [] def __str__(self): return self.template.render_unicode(**vars(self)) def serialize(self): return self.template.render_unicode(**vars(self))
from mako.template import Template class Line(object): template = Template("""${label}. \\ % for word in words: ${word} \\ % endfor % if lemmas: \n#lem: \\ % for lemma in lemmas: ${lemma}; \\ % endfor \n %endif """, output_encoding='utf-8') def __init__(self, label): self.label = label self.words = [] self.lemmas = [] self.witnesses = [] self.translation = None self.notes = [] self.references = [] self.links = [] def __str__(self): return self.template.render_unicode(**vars(self)) def serialize(self): return self.template.render_unicode(**vars(self))
Prepare kill test for mock - use hyperspeed
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. from __future__ import print_function import sys, os, signal, time, subprocess32 sys.path.append('../../..') from jenkinsflow.mocked import hyperspeed def _killer(pid, sleep_time, num_kills): print("\nKiller going to sleep for", sleep_time, "seconds") time.sleep(sleep_time) print("\nKiller woke up") for ii in range(0, num_kills): os.kill(pid, signal.SIGTERM) print("\nKiller sent", ii + 1, "of", num_kills, "SIGTERM signals to ", pid) hyperspeed.sleep(1) if __name__ == '__main__': _killer(int(sys.argv[1]), float(sys.argv[2]), int(sys.argv[3])) def kill(sleep_time, num_kills): """Kill this process""" pid = os.getpid() print("kill, pid:", pid) subprocess32.Popen([sys.executable, __file__, repr(pid), repr(sleep_time), repr(num_kills)])
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. from __future__ import print_function import sys, os, signal, time, subprocess32 def _killer(pid, sleep_time, num_kills): print("\nKiller going to sleep for", sleep_time, "seconds") time.sleep(sleep_time) print("\nKiller woke up") for ii in range(0, num_kills): os.kill(pid, signal.SIGTERM) print("\nKiller sent", ii + 1, "of", num_kills, "SIGTERM signals to ", pid) time.sleep(1) if __name__ == '__main__': _killer(int(sys.argv[1]), float(sys.argv[2]), int(sys.argv[3])) def kill(sleep_time, num_kills): """Kill this process""" pid = os.getpid() print("kill, pid:", pid) subprocess32.Popen([sys.executable, __file__, repr(pid), repr(sleep_time), repr(num_kills)])
Clear the screen before drawing
package bobby; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import javax.swing.JApplet; /** * * @author Kiarash Korki <kiarash96@users.sf.net> */ public class SceneManager extends Thread { private final JApplet parent; private ArrayList<SceneObject> list; public SceneManager(JApplet parent) { list = new ArrayList<>(); this.parent = parent; } public void draw(Graphics g) { // TODO: implement double buffering // clear the screen g.setColor(Color.WHITE); g.fillRect(0, 0, parent.getWidth(), parent.getHeight()); for (SceneObject sobject : list) sobject.draw(g); // TODO: sleep } @Override public void run() { while (true) parent.repaint(); } public void add(SceneObject so) { list.add(so); } public void remove(SceneObject so) { list.remove(so); } }
package bobby; import java.awt.Graphics; import java.util.ArrayList; import javax.swing.JApplet; /** * * @author Kiarash Korki <kiarash96@users.sf.net> */ public class SceneManager extends Thread { private final JApplet parent; private ArrayList<SceneObject> list; public SceneManager(JApplet parent) { list = new ArrayList<>(); this.parent = parent; } public void draw(Graphics g) { // TODO: implement double buffering for (SceneObject sobject : list) sobject.draw(g); } @Override public void run() { while (true) parent.repaint(); } public void add(SceneObject so) { list.add(so); } public void remove(SceneObject so) { list.remove(so); } }
Send triggered emails in the background
'use strict'; var Promise = require('bluebird'); var Handlebars = require('handlebars'); var Notification = require('../../api/models/Notification'); var Users = require('../../api/collections/Users'); var users = new Users(); module.exports = function(router, resources) { resources.actions.notify = function(conn, project, options) { var roleIds = options.role_ids || []; // get all project assignments return Promise.settle(Object.keys(project.assignments.data).map(function(userId) { var assignment = project.assignments.data[userId]; // only notify specified roles if(roleIds.indexOf(assignment.role_id) === -1) return; // create a notification return Notification.create(conn, { user_id: userId, subject: options.subject, // TODO: first pull user from db to get name, etc content: Handlebars.compile(options.template || '')({ project: project, cycle: project.cycle }) }, true) .then(function(notification){ return users.get(conn, notification.user_id, true) .then(function(user){ // send mail in the background resources.mail({ to: user.email, subject: notification.subject, html: notification.content }); }); }); })); }; };
'use strict'; var Promise = require('bluebird'); var Handlebars = require('handlebars'); var Notification = require('../../api/models/Notification'); var Users = require('../../api/collections/Users'); var users = new Users(); module.exports = function(router, resources) { resources.actions.notify = function(conn, project, options) { var roleIds = options.role_ids || []; // get all project assignments return Promise.all(Object.keys(project.assignments.data).map(function(userId) { var assignment = project.assignments.data[userId]; // only notify specified roles if(roleIds.indexOf(assignment.role_id) === -1) return; // create a notification return Notification.create(conn, { user_id: userId, subject: options.subject, // TODO: first pull user from db to get name, etc content: Handlebars.compile(options.template || '')({ project: project, cycle: project.cycle }) }, true) .then(function(notification){ return users.get(conn, notification.user_id, true) // email recovery token to user .then(function(user){ return resources.mail({ to: user.email, subject: notification.subject, html: notification.content }); }); }); })); }; };
Use get(), set(), unset() methods (with or w/o paths).
<?php /** * User: Alex Gusev <alex@flancer64.com> */ namespace Flancer32\Lib; /** * Access properties of the data object using accessors (getters & setters). * * @SuppressWarnings(PHPMD.CamelCaseMethodName) */ class DataT030AccessorsSimpleTest extends \PHPUnit_Framework_TestCase { public function test_010_asScalar() { $value = 'value'; $obj = new Data(); $obj->setProperty($value); $this->assertEquals($value, $obj->getProperty()); } public function test_020_asObj() { $value = new \stdClass(); $value->prop = 32; $obj = new Data(); $obj->setProperty($value); $this->assertEquals(32, $obj->getProperty()->prop); } public function test_030_asArr() { $value = ['prop' => 64]; $obj = new Data(); $obj->setProperty($value); $this->assertEquals(64, $obj->getProperty()['prop']); } }
<?php /** * User: Alex Gusev <alex@flancer64.com> */ namespace Flancer32\Lib; /** * Access properties of the data object using accessors (getters & setters). * * @SuppressWarnings(PHPMD.CamelCaseMethodName) */ class DataT030AccessorsSimpleTest extends \PHPUnit_Framework_TestCase { public function test_010_asScalar() { $value = 'value'; $obj = new Data(); $obj->setProperty($value); $this->assertEquals($value, $obj->getProperty()); } public function test_020_asObj() { $value = new class { public $prop = 32; }; $obj = new Data(); $obj->setProperty($value); $this->assertEquals(32, $obj->getProperty()->prop); } public function test_030_asArr() { $value = ['prop' => 64]; $obj = new Data(); $obj->setProperty($value); $this->assertEquals(64, $obj->getProperty()['prop']); } }
Support for the exclude option
var Transform = require('broccoli-transform'); var RSVP = require('rsvp'); var requirejs = require('requirejs'); var mkdirp = require('mkdirp'); var fs = require('fs'); var path = require('path'); var _ = require('lodash'); function RequireJsFilter(inputTree, options) { if (!(this instanceof RequireJsFilter)) { return new RequireJsFilter(inputTree, options); } this.inputTree = inputTree; this.options = options || {}; } RequireJsFilter.prototype = Object.create(Transform.prototype); RequireJsFilter.prototype.constructor = RequireJsFilter; RequireJsFilter.prototype.transform = function (srcDir, destDir) { var options = this.options; var requirejs_options = options.requirejs || {}; return new RSVP.Promise(function(resolve, reject) { var tmp_options = _.clone(requirejs_options); if (requirejs_options.baseUrl) { tmp_options.baseUrl = path.join(srcDir, requirejs_options.baseUrl); } else { tmp_options.baseUrl = srcDir; } if (requirejs_options.mainConfigFile) { tmp_options.mainConfigFile = path.join(srcDir, requirejs_options.mainConfigFile); } if (requirejs_options.exclude) { tmp_options.exclude = requirejs_options.exclude; } tmp_options.out = path.join(destDir,requirejs_options.out); requirejs.optimize(tmp_options, function (buildResponse) { resolve(destDir); }); }.bind(this)); }; module.exports = RequireJsFilter;
var Transform = require('broccoli-transform'); var RSVP = require('rsvp'); var requirejs = require('requirejs'); var mkdirp = require('mkdirp'); var fs = require('fs'); var path = require('path'); var _ = require('lodash'); function RequireJsFilter(inputTree, options) { if (!(this instanceof RequireJsFilter)) { return new RequireJsFilter(inputTree, options); } this.inputTree = inputTree; this.options = options || {}; } RequireJsFilter.prototype = Object.create(Transform.prototype); RequireJsFilter.prototype.constructor = RequireJsFilter; RequireJsFilter.prototype.transform = function (srcDir, destDir) { var options = this.options; var requirejs_options = options.requirejs || {}; return new RSVP.Promise(function(resolve, reject) { var tmp_options = _.clone(requirejs_options); if (requirejs_options.baseUrl) { tmp_options.baseUrl = path.join(srcDir, requirejs_options.baseUrl); } else { tmp_options.baseUrl = srcDir; } if (requirejs_options.mainConfigFile) { tmp_options.mainConfigFile = path.join(srcDir, requirejs_options.mainConfigFile); } tmp_options.out = path.join(destDir,requirejs_options.out); requirejs.optimize(tmp_options, function (buildResponse) { resolve(destDir); }); }.bind(this)); }; module.exports = RequireJsFilter;
Test on an Internet server
// Constants var constant = {}; constant.pageCount = 4; constant.library = { // Canopé name: "Canopé", database: "http://laske.fr/tmp/torido/canope.php", videos: "https://videos.reseau-canope.fr/download.php?file=lesfondamentaux/%id%_sd", images: "https://www.reseau-canope.fr/lesfondamentaux/uploads/tx_cndpfondamentaux/%id%%imgsuffix%.png" }; /*constant.library = { // Khan Academy name: "Khan Academy", database: "http://laske.fr/tmp/torido/khan.php", videos: "http://s3.amazonaws.com/KA-youtube-converted/%id%.mp4/%id%", images: "http://s3.amazonaws.com/KA-youtube-converted/%id%.mp4/%id%.png" };*/ constant.videoType = "mp4";
// Constants var constant = {}; constant.pageCount = 4; constant.library = { // Canopé name: "Canopé", database: "http://localhost:81/torido/canope.php", videos: "https://videos.reseau-canope.fr/download.php?file=lesfondamentaux/%id%_sd", images: "https://www.reseau-canope.fr/lesfondamentaux/uploads/tx_cndpfondamentaux/%id%%imgsuffix%.png" }; /*constant.library = { // Khan Academy name: "Khan Academy", database: "http://localhost:81/torido/khan.php", videos: "http://s3.amazonaws.com/KA-youtube-converted/%id%.mp4/%id%", images: "http://s3.amazonaws.com/KA-youtube-converted/%id%.mp4/%id%.png" };*/ constant.videoType = "mp4";
Make ids BigInteger for postgres
from sqlalchemy import Column, BigInteger, String from keybaseproofbot.database import Base class Proof(Base): __tablename__ = 'proofs' user_id = Column(BigInteger, primary_key=True) keybase_username = Column(String) telegram_username = Column(String) chat_id = Column(BigInteger) message_id = Column(BigInteger) proof_object = Column(String) signed_block = Column(String) def __init__(self, user_id, keybase_username, telegram_username, chat_id, message_id, proof_object, signed_block): self.user_id = user_id self.keybase_username = keybase_username self.telegram_username = telegram_username self.chat_id = chat_id self.message_id = message_id self.proof_object = proof_object self.signed_block = signed_block
from sqlalchemy import Column, Integer, String from keybaseproofbot.database import Base class Proof(Base): __tablename__ = 'proofs' user_id = Column(Integer, primary_key=True) keybase_username = Column(String) telegram_username = Column(String) chat_id = Column(Integer) message_id = Column(Integer) proof_object = Column(String) signed_block = Column(String) def __init__(self, user_id, keybase_username, telegram_username, chat_id, message_id, proof_object, signed_block): self.user_id = user_id self.keybase_username = keybase_username self.telegram_username = telegram_username self.chat_id = chat_id self.message_id = message_id self.proof_object = proof_object self.signed_block = signed_block
Fix bower config value for tests
var fs = require('fs'), Libraries = require('../lib/libraries'), should = require('should'); describe('Libraries', function() { describe('#bowerLibraries', function() { beforeEach(function() { require('bower').config.directory = 'bower_components'; }); var readdirSync = fs.readdirSync, statSync = fs.statSync, context = { event: {emit: function() {}} }; before(function() { fs.statSync = function(path) { if (/bar\//.test(path)) { throw new Error(); } }; }); after(function() { fs.readdirSync = readdirSync; fs.statSync = statSync; }); it('should return all modules in bower directory', function() { fs.readdirSync = function(path) { return ['foo', 'bar', 'baz']; }; var library = new Libraries(); library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']); }); it('should not error on fs error', function() { fs.readdirSync = function(path) { throw new Error(); }; var library = new Libraries(); should.not.exist(library.bowerLibraries(context)); }); }); });
var fs = require('fs'), Libraries = require('../lib/libraries'), should = require('should'); describe('Libraries', function() { describe('#bowerLibraries', function() { var readdirSync = fs.readdirSync, statSync = fs.statSync, context = { event: {emit: function() {}} }; before(function() { fs.statSync = function(path) { if (/bar\//.test(path)) { throw new Error(); } }; }); after(function() { fs.readdirSync = readdirSync; fs.statSync = statSync; }); it('should return all modules in bower directory', function() { fs.readdirSync = function(path) { return ['foo', 'bar', 'baz']; }; var library = new Libraries(); library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']); }); it('should not error on fs error', function() { fs.readdirSync = function(path) { throw new Error(); }; var library = new Libraries(); should.not.exist(library.bowerLibraries(context)); }); }); });
Resolve path in case it involves a symlink Reviewed By: ppwwyyxx Differential Revision: D27823003 fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
Change header and title classes
<?php /** * The template used for displaying page content in page.php * * @package Flacso */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="page-header"> <?php the_title( '<h1 class="page-title">', '</h1>' ); ?> </header><!-- .page-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'flacso' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php edit_post_link( __( 'Edit', 'flacso' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
<?php /** * The template used for displaying page content in page.php * * @package Flacso */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'flacso' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php edit_post_link( __( 'Edit', 'flacso' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
Replace SYS_IOCTL by cross platform version
// +build !windows package gottyclient import ( "encoding/json" "fmt" "golang.org/x/sys/unix" "os" "os/signal" "syscall" ) func notifySignalSIGWINCH(c chan<- os.Signal) { signal.Notify(c, syscall.SIGWINCH) } func resetSignalSIGWINCH() { signal.Reset(syscall.SIGWINCH) } func syscallTIOCGWINSZ() ([]byte, error) { ws, err := unix.IoctlGetWinsize(0, 0) if err != nil { return nil, fmt.Errorf("ioctl error: %v", err) } b, err := json.Marshal(ws) if err != nil { return nil, fmt.Errorf("json.Marshal error: %v", err) } return b, err }
// +build !windows package gottyclient import ( "encoding/json" "fmt" "os" "os/signal" "syscall" "unsafe" ) func notifySignalSIGWINCH(c chan<- os.Signal) { signal.Notify(c, syscall.SIGWINCH) } func resetSignalSIGWINCH() { signal.Reset(syscall.SIGWINCH) } func syscallTIOCGWINSZ() ([]byte, error) { ws := winsize{} syscall.Syscall(syscall.SYS_IOCTL, uintptr(0), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&ws))) b, err := json.Marshal(ws) if err != nil { return nil, fmt.Errorf("json.Marshal error: %v", err) } return b, err }
Return early from Submission.submit when already pending
'use strict' var Struct = require('observ-struct') var Observ = require('observ') var valueError = require('value-error') var Event = require('weakmap-event') var WeakError = require('weak-error') module.exports = Submission function Submission (data) { data = data || {} return Struct({ pending: Observ(data.pending || false), error: Observ(data.error || null) }) } Submission.submit = function submit (state, fn) { if (state.pending()) return state.pending.set(true) fn(createHandler(state)) } var DataEvent = Event() var ErrorEvent = WeakError() Submission.onData = DataEvent.listen Submission.onError = ErrorEvent.listen function createHandler (state) { return function onResult (err, data) { state.pending.set(false) if (err) { state.error.set(valueError(err)) return ErrorEvent.broadcast(state, err) } DataEvent.broadcast(state, data) } }
'use strict' var Struct = require('observ-struct') var Observ = require('observ') var valueError = require('value-error') var Event = require('weakmap-event') var WeakError = require('weak-error') module.exports = Submission function Submission (data) { data = data || {} return Struct({ pending: Observ(data.pending || false), error: Observ(data.error || null) }) } Submission.submit = function submit (state, fn) { state.pending.set(true) fn(createHandler(state)) } var DataEvent = Event() var ErrorEvent = WeakError() Submission.onData = DataEvent.listen Submission.onError = ErrorEvent.listen function createHandler (state) { return function onResult (err, data) { state.pending.set(false) if (err) { state.error.set(valueError(err)) return ErrorEvent.broadcast(state, err) } DataEvent.broadcast(state, data) } }
Fix typo in function name
import cozydb from 'cozydb'; import invariant from 'invariant'; import logger from 'debug'; import hasValue from '../hasValue'; const debug = logger('app:model:favorite_tag'); const FavoriteTag = cozydb.getModel('FavoriteTag', { 'label': String, 'application': String, }); export default FavoriteTag; FavoriteTag.allForTasky = (callback) => { invariant(hasValue(callback), '`callback` is a mandatory parameter'); invariant(typeof callback === 'function', '`callback` must be a function'); debug('Retrieve all favorite tag for app Tasky.'); FavoriteTag.request('allByApp', {key: 'tasky'}, (err, tags) => { const error = err || tags.error; if (hasValue(error)) { callback(error); } else { const labels = tags.map(tag => tag.label); callback(null, labels); } }); }; FavoriteTag.byLabelForTasky = (label, callback) => { invariant(hasValue(label), '`label` is a mandatory parameter'); invariant(hasValue(callback), '`callback` is a mandatory parameter'); invariant(typeof label === 'string', '`label` must be a string'); invariant(typeof callback === 'function', '`callback` must be a function'); debug('Retrieve a favorite tag given a label, for app Tasky.'); const options = { key: ['tasky', label], }; FavoriteTag.request('byAppByLabel', options, callback); };
import cozydb from 'cozydb'; import invariant from 'invariant'; import logger from 'debug'; import hasValue from '../hasValue'; const debug = logger('app:model:favorite_tag'); const FavoriteTag = cozydb.getModel('FavoriteTag', { 'label': String, 'application': String, }); export default FavoriteTag; FavoriteTag.allForTasky = (callback) => { invariant(hasValue(callback), '`callback` is a mandatory parameter'); invariant(typeof callback === 'function', '`callback` must be a function'); debug('Retrieve all favorite tag for app Tasky.'); FavoriteTag.request('allByApp', {key: 'tasky'}, (err, tags) => { const error = err || tags.error; if (hasValue(error)) { callback(error); } else { const labels = tags.map(tag => tag.label); callback(null, labels); } }); }; FavoriteTag.ByLabelForTasky = (label, callback) => { invariant(hasValue(label), '`label` is a mandatory parameter'); invariant(hasValue(callback), '`callback` is a mandatory parameter'); invariant(typeof label === 'string', '`label` must be a string'); invariant(typeof callback === 'function', '`callback` must be a function'); debug('Retrieve a favorite tag given a label, for app Tasky.'); const options = { key: ['tasky', label], }; FavoriteTag.request('byAppByLabel', options, callback); };
Use <label /> for a label
/* * Localisation Manager * * @author: Nils Hörrmann, post@nilshoerrmann.de * @source: http://github.com/symphonists/localisationmanager */ (function($) { $(document).ready(function() { // Language strings Symphony.Language.add({ 'Sort strings alphabetically': false }); // Append sort option var context = $('#context'), table = $('table'), sort = $('<label style="float: right;"><input type="checkbox" name="sortit" /> ' + Symphony.Language.get('Sort strings alphabetically') + '</label>').appendTo(context); // Events sort.click(function(event) { // Get status var checked = $(event.target).attr('checked'); // Add or remove sort option table.find('a').each(function(index, link) { link = $(link); var href = link.attr('href'); // Is checked? if(checked) { link.attr('href', href + '?sort'); } // Is not checked? else { link.attr('href', href.replace('?sort', '')); } }); }); }); })(jQuery.noConflict());
/* * Localisation Manager * * @author: Nils Hörrmann, post@nilshoerrmann.de * @source: http://github.com/symphonists/localisationmanager */ (function($) { $(document).ready(function() { // Language strings Symphony.Language.add({ 'Sort strings alphabetically': false }); // Append sort option var context = $('#context'), table = $('table'), sort = $('<div class="sorting" style="float: right;"><input type="checkbox" name="sortit" /> ' + Symphony.Language.get('Sort strings alphabetically') + '</div>').appendTo(context); // Events sort.click(function(event) { // Get status var checked = $(event.target).attr('checked'); // Add or remove sort option table.find('a').each(function(index, link) { link = $(link); var href = link.attr('href'); // Is checked? if(checked) { link.attr('href', href + '?sort'); } // Is not checked? else { link.attr('href', href.replace('?sort', '')); } }); }); }); })(jQuery.noConflict());
Add stability annotation to ol.source.GeoJSON
goog.provide('ol.source.GeoJSON'); goog.require('ol.format.GeoJSON'); goog.require('ol.source.VectorFile'); /** * @constructor * @extends {ol.source.VectorFile} * @param {olx.source.GeoJSONOptions=} opt_options Options. * @todo stability experimental */ ol.source.GeoJSON = function(opt_options) { var options = goog.isDef(opt_options) ? opt_options : {}; goog.base(this, { attributions: options.attributions, extent: options.extent, format: new ol.format.GeoJSON({ defaultProjection: options.defaultProjection }), logo: options.logo, object: options.object, projection: options.projection, reprojectTo: options.reprojectTo, text: options.text, url: options.url, urls: options.urls }); }; goog.inherits(ol.source.GeoJSON, ol.source.VectorFile);
goog.provide('ol.source.GeoJSON'); goog.require('ol.format.GeoJSON'); goog.require('ol.source.VectorFile'); /** * @constructor * @extends {ol.source.VectorFile} * @param {olx.source.GeoJSONOptions=} opt_options Options. */ ol.source.GeoJSON = function(opt_options) { var options = goog.isDef(opt_options) ? opt_options : {}; goog.base(this, { attributions: options.attributions, extent: options.extent, format: new ol.format.GeoJSON({ defaultProjection: options.defaultProjection }), logo: options.logo, object: options.object, projection: options.projection, reprojectTo: options.reprojectTo, text: options.text, url: options.url, urls: options.urls }); }; goog.inherits(ol.source.GeoJSON, ol.source.VectorFile);
Use Carbon instead of DateTime
<?php namespace HMS\Traits\Entities; use Carbon\Carbon; trait SoftDeletable { /** * @var Carbon */ protected $deletedAt; /** * Sets deletedAt. * * @param Carbon|null $deletedAt * * @return $this */ public function setDeletedAt(Carbon $deletedAt = null) { $this->deletedAt = $deletedAt; return $this; } /** * Returns deletedAt. * * @return Carbon */ public function getDeletedAt() { return $this->deletedAt; } /** * Is deleted? * * @return bool */ public function isDeleted() { return null !== $this->deletedAt; } }
<?php namespace HMS\Traits\Entities; trait SoftDeletable { /** * @var \DateTime */ protected $deletedAt; /** * Sets deletedAt. * * @param \DateTime|null $deletedAt * * @return $this */ public function setDeletedAt(\DateTime $deletedAt = null) { $this->deletedAt = $deletedAt; return $this; } /** * Returns deletedAt. * * @return \DateTime */ public function getDeletedAt() { return $this->deletedAt; } /** * Is deleted? * * @return bool */ public function isDeleted() { return null !== $this->deletedAt; } }
Add client side stub to call dot-scripted module in the server.
/******************************************************************************* * @license * Copyright (c) 2012 VMware, Inc. All Rights Reserved. * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. * You can obtain a current copy of the Eclipse Public License from * http://www.opensource.org/licenses/eclipse-1.0.php * * Contributors: * Kris De Volder - initial API and implementation ******************************************************************************/ /*global require define console module setTimeout XMLHttpRequest */ if (typeof define !== 'function') { var define = require('amdefine')(module); } define(function(require, exports, module) { var basePath = '/jsdepend'; var makeServletStub = require('./stub-maker').makeServletStub; //TODO: This information is repeated between client and server code... // it shouldn't be. var signatures = { getDependencies: ['JSON', 'callback'], getTransitiveDependencies: ['JSON', 'callback'], getContents: ['JSON', 'callback', 'errback'], findFileNamesContaining: ['JSON', 'JSON', 'callback', 'errback'], getDGraph: ['JSON', 'callback'], getConf: ['JSON', 'callback'] }; for (var functionName in signatures) { if (signatures.hasOwnProperty(functionName)) { exports[functionName] = makeServletStub(basePath+'/'+functionName, signatures[functionName]); } } });
/******************************************************************************* * @license * Copyright (c) 2012 VMware, Inc. All Rights Reserved. * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. * You can obtain a current copy of the Eclipse Public License from * http://www.opensource.org/licenses/eclipse-1.0.php * * Contributors: * Kris De Volder - initial API and implementation ******************************************************************************/ /*global require define console module setTimeout XMLHttpRequest */ if (typeof define !== 'function') { var define = require('amdefine')(module); } define(function(require, exports, module) { var basePath = '/jsdepend'; var makeServletStub = require('./stub-maker').makeServletStub; //TODO: This information is repeated between client and server code... // it shouldn't be. var signatures = { getDependencies: ['JSON', 'callback'], getTransitiveDependencies: ['JSON', 'callback'], getContents: ['JSON', 'callback', 'errback'], findFileNamesContaining: ['JSON', 'JSON', 'callback', 'errback'], getDGraph: ['JSON', 'callback'] }; var expectedSig = JSON.stringify(['JSON', 'callback', 'errback']); for (var functionName in signatures) { if (signatures.hasOwnProperty(functionName)) { exports[functionName] = makeServletStub(basePath+'/'+functionName, signatures[functionName]); } } });
Remove old code in addFavorite
var Storage = require('FuseJS/Storage'); var data = 'favorites'; /* ... -----------------------------------------------------------------------------*/ var addFavorite , deleteFavorite , getFavorites; /* Functions -----------------------------------------------------------------------------*/ addFavorite = function(id) { var favorite = getFavorites(); if (favorite[id]) { return; } favorite[id] = { name: 'woop' }; Storage.writeSync(data, JSON.stringify(favorite)); } deleteFavorite = function(id) { var favorite = getFavorites(); if (favorite[id]) { delete favorite[id]; Storage.writeSync(data, JSON.stringify(favorite)); } } getFavorites = function() { var favorites = JSON.parse(Storage.readSync(data)); if (favorites === null) { favorites = {}; Storage.write(data, JSON.stringify(favorites)); } return favorites; } /* Exports -----------------------------------------------------------------------------*/ module.exports = { addFavorite: addFavorite, deleteFavorite: deleteFavorite, getFavorites: getFavorites };
var Storage = require('FuseJS/Storage'); var data = 'favorites'; /* ... -----------------------------------------------------------------------------*/ var addFavorite , deleteFavorite , getFavorites; /* Functions -----------------------------------------------------------------------------*/ addFavorite = function(id) { var favorite = getFavorites(); if (favorite === null) { favorite = {}; } if (favorite[id]) { return; } favorite[id] = { name: 'woop' }; Storage.writeSync(data, JSON.stringify(favorite)); } deleteFavorite = function(id) { var favorite = getFavorites(); if (favorite[id]) { delete favorite[id]; Storage.writeSync(data, JSON.stringify(favorite)); } } getFavorites = function() { var favorites = JSON.parse(Storage.readSync(data)); if (favorites === null) { favorites = {}; Storage.write(data, JSON.stringify(favorites)); } return favorites; } /* Exports -----------------------------------------------------------------------------*/ module.exports = { addFavorite: addFavorite, deleteFavorite: deleteFavorite, getFavorites: getFavorites };
Include sender address in completion log. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@101358 91177308-0d34-0410-b5e6-96231b3b80d8
#!/usr/bin/env python import sys from socket import * from time import localtime, strftime def main(): if len(sys.argv) < 4: print "completion_logger_server.py <listen address> <listen port> <log file>" exit(1) host = sys.argv[1] port = int(sys.argv[2]) buf = 1024 * 8 addr = (host,port) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) print "Listing on {0}:{1} and logging to '{2}'".format(host, port, sys.argv[3]) # Open the logging file. f = open(sys.argv[3], "a") # Receive messages while 1: data,addr = UDPSock.recvfrom(buf) if not data: break else: f.write(strftime("'%a, %d %b %Y %H:%M:%S' ", localtime())) f.write("'{0}' ".format(addr[0])) f.write(data) f.write('\n') f.flush() # Close socket UDPSock.close() if __name__ == '__main__': main()
#!/usr/bin/env python import sys from socket import * from time import localtime, strftime def main(): if len(sys.argv) < 4: print "completion_logger_server.py <listen address> <listen port> <log file>" exit(1) host = sys.argv[1] port = int(sys.argv[2]) buf = 1024 * 8 addr = (host,port) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) print "Listing on {0}:{1} and logging to '{2}'".format(host, port, sys.argv[3]) # Open the logging file. f = open(sys.argv[3], "a") # Receive messages while 1: data,addr = UDPSock.recvfrom(buf) if not data: break else: f.write(strftime("'%a, %d %b %Y %H:%M:%S' ", localtime())) f.write(data) f.write('\n') # Close socket UDPSock.close() if __name__ == '__main__': main()
Add a close class to the close button.
function overlay(name) { var path = 'story/' + name + '.html'; var $overlay = $('#overlay').load(path, function() { $overlay.show() .append($('<span>Close</span>').attr({ 'class': 'button close' }).click(function() { $overlay.hide(); })); }); } function printHelp() { lograw('Navigate with the "hjkl yubn" keys (<a href="">help</a>)') .addClass('important') .find('a').click(function() { overlay('intro'); return false; }); } (function() { printHelp(); if (World.load()) { log('Game restored. Welcome back, %s.', world.player); } else { if (!Save.exists('playedBefore')) { overlay('intro'); Save.save('playedBefore', true); } World.reset(); } }()); $(window).unload(function() { world.save(); }); /* Get things going. */ world.display(); world.run();
function overlay(name) { var path = 'story/' + name + '.html'; var $overlay = $('#overlay').load(path, function() { $overlay.show() .append($('<span>Close</span>').attr({ 'class': 'button' }).click(function() { $overlay.hide(); })); }); } function printHelp() { lograw('Navigate with the "hjkl yubn" keys (<a href="">help</a>)') .addClass('important') .find('a').click(function() { overlay('intro'); return false; }); } (function() { printHelp(); if (World.load()) { log('Game restored. Welcome back, %s.', world.player); } else { if (!Save.exists('playedBefore')) { overlay('intro'); Save.save('playedBefore', true); } World.reset(); } }()); $(window).unload(function() { world.save(); }); /* Get things going. */ world.display(); world.run();
Add date/time created timestamp to Vote model
from django.db import models from django.contrib.auth.models import User class Voter(models.Model): ''' Models someone who may vote ''' user = models.OneToOneField(User) def __str__(self): return self.user.username class Flag(models.Model): ''' Models a flag which may be voted on ''' name = models.CharField(max_length=200) designer = models.CharField(max_length=200) image_url = models.URLField(max_length=1024) def __str__(self): return self.name class Vote(models.Model): ''' Models a single vote cast by a `Voter` for a `Flag` ''' flag = models.ForeignKey(Flag, on_delete=models.CASCADE) voter = models.ForeignKey(Voter, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return "{0} voted for {1} at {2}".format( self.voter.user.username, self.flag.name, self.created )
from django.db import models from django.contrib.auth.models import User class Voter(models.Model): ''' Models someone who may vote ''' user = models.OneToOneField(User) def __str__(self): return self.user.username class Flag(models.Model): ''' Models a flag which may be voted on ''' name = models.CharField(max_length=200) designer = models.CharField(max_length=200) image_url = models.URLField(max_length=1024) def __str__(self): return self.name class Vote(models.Model): ''' Models a single vote cast by a `Voter` for a `Flag` ''' flag = models.ForeignKey(Flag, on_delete=models.CASCADE) voter = models.ForeignKey(Voter, on_delete=models.CASCADE)
BAP-16497: Change ClassLoader component - test failing tests
<?php namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs; use Symfony\Component\ClassLoader\UniversalClassLoader; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class TestKernel extends Kernel { public function __construct() { parent::__construct('test_stub_env', true); } public function init() { } public function getRootDir() { return sys_get_temp_dir() . '/translation-test-stub-cache'; } public function registerBundles() { $loader = new UniversalClassLoader(); $loader->registerNamespace('SomeProject\\', array(__DIR__)); $loader->registerNamespace('SomeAnotherProject\\', array(__DIR__)); $loader->register(); return array( new \SomeProject\Bundle\SomeBundle\SomeBundle(), new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle() ); } public function registerContainerConfiguration(LoaderInterface $loader) { } }
<?php namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs; use Symfony\Component\ClassLoader\ClassLoader; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\HttpKernel\Kernel; class TestKernel extends Kernel { public function __construct() { parent::__construct('test_stub_env', true); } public function init() { } public function getRootDir() { return sys_get_temp_dir() . '/translation-test-stub-cache'; } public function registerBundles() { $loader = new ClassLoader(); $loader->addPrefix('SomeProject\\', array(__DIR__)); $loader->addPrefix('SomeAnotherProject\\', array(__DIR__)); $loader->register(); return array( new \SomeProject\Bundle\SomeBundle\SomeBundle(), new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle() ); } public function registerContainerConfiguration(LoaderInterface $loader) { } }
Tweak how request is generated for commandline. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Routing; use Illuminate\Http\Request; class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->registerRequestOnConsole(); parent::register(); } /** * Register the requst on console interface. * * @return void */ protected function registerRequestOnConsole() { $app = $this->app; if ($app->runningInConsole()) { $url = $app['config']->get('app.url', 'http://localhost'); $app->instance('request', Request::create($url, 'GET', [], [], [], $_SERVER)); } } /** * Register the router instance. * * @return void */ protected function registerRouter() { $this->app['router'] = $this->app->share(function ($app) { return new Router($app['events'], $app); }); } }
<?php namespace Orchestra\Routing; use Illuminate\Http\Request; class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->registerRequestOnConsole(); parent::register(); } /** * Register the requst on console interface. * * @return void */ protected function registerRequestOnConsole() { if ($this->app->runningInConsole()) { $this->app->instance('request', Request::createFromGlobals()); } } /** * Register the router instance. * * @return void */ protected function registerRouter() { $this->app['router'] = $this->app->share(function ($app) { return new Router($app['events'], $app); }); } }
Disable integration test on Linux See gh-19836
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.cloudnativebuildpack.docker; import java.io.IOException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.springframework.boot.cloudnativebuildpack.docker.type.ImageReference; import org.springframework.boot.testsupport.testcontainers.DisabledIfDockerUnavailable; /** * Integration tests for {@link DockerApi}. * * @author Phillip Webb */ @DisabledIfDockerUnavailable @DisabledOnOs(OS.LINUX) class DockerApiIntegrationTests { private final DockerApi docker = new DockerApi(); @Test void pullImage() throws IOException { this.docker.image().pull(ImageReference.of("cloudfoundry/cnb:bionic"), new TotalProgressPullListener(new TotalProgressBar("Pulling: "))); } }
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.cloudnativebuildpack.docker; import java.io.IOException; import org.junit.jupiter.api.Test; import org.springframework.boot.cloudnativebuildpack.docker.type.ImageReference; import org.springframework.boot.testsupport.testcontainers.DisabledIfDockerUnavailable; /** * Integration tests for {@link DockerApi}. * * @author Phillip Webb */ @DisabledIfDockerUnavailable class DockerApiIntegrationTests { private final DockerApi docker = new DockerApi(); @Test void pullImage() throws IOException { this.docker.image().pull(ImageReference.of("cloudfoundry/cnb:bionic"), new TotalProgressPullListener(new TotalProgressBar("Pulling: "))); } }
Use routes from config object.
"use strict"; var View = require("./view"); var Router = require("./router"); var util = require("substance-util"); var _ = require("underscore"); // Substance.Application // ========================================================================== // // Application abstraction suggesting strict MVC var Application = function(config) { View.call(this); this.config = config; }; Application.Prototype = function() { // Init router // ---------- this.initRouter = function() { this.router = new Router(); _.each(this.config.routes, function(route) { this.router.route(route.route, route.name, _.bind(this.controller[route.command], this.controller)); }, this); Router.history.start(); }; // Start Application // ---------- // this.start = function() { this.initRouter(); this.$el = $('body'); this.el = this.$el[0]; this.render(); }; }; // Setup prototype chain Application.Prototype.prototype = View.prototype; Application.prototype = new Application.Prototype(); module.exports = Application;
"use strict"; var View = require("./view"); var Router = require("./router"); var util = require("substance-util"); var _ = require("underscore"); // Substance.Application // ========================================================================== // // Application abstraction suggesting strict MVC var Application = function(config) { View.call(this); this.config = config; }; Application.Prototype = function() { // Init router // ---------- this.initRouter = function() { this.router = new Router(); _.each(Lens.routes, function(route) { this.router.route(route.route, route.name, _.bind(this.controller[route.command], this.controller)); }, this); Router.history.start(); }; // Start Application // ---------- // this.start = function() { this.initRouter(); this.$el = $('body'); this.el = this.$el[0]; this.render(); }; }; // Setup prototype chain Application.Prototype.prototype = View.prototype; Application.prototype = new Application.Prototype(); module.exports = Application;
Fix custom method options + Allow callback to be passed to the submit method
var api = require('@request/api') module.exports = (client, provider, methods, config, transform) => { return api(methods, { api: function (name) { this._options.api = name return this }, auth: function (arg1, arg2) { var alias = (this._options.api || provider.api || '__default') config.endpoint.auth(alias, this._options, arg1, arg2) return this }, submit: function (callback) { var options = this._options if (callback) { options.callback = callback } var alias = (options.api || provider.api || '__default') if (!config.aliases[alias]) { throw new Error('Purest: non existing alias!') } transform.oauth(options) transform.parse(options) options = config.endpoint.options(alias, options) if (!/^http/.test(options.url)) { options.url = config.url(alias, options) } return client(options) } }) }
var api = require('@request/api') module.exports = (client, provider, methods, config, transform) => { return api(methods, { api: function (options, name) { options.api = name return this }, auth: function (options, arg1, arg2) { var alias = (options.api || provider.api || '__default') config.endpoint.auth(alias, options, arg1, arg2) return this }, submit: function (options) { var alias = (options.api || provider.api || '__default') if (!config.aliases[alias]) { throw new Error('Purest: non existing alias!') } transform.oauth(options) transform.parse(options) options = config.endpoint.options(alias, options) if (!/^http/.test(options.url)) { options.url = config.url(alias, options) } return client(options) } }) }
Add rig_assets.json as package data.
version = '0.1.0' with open('requirements.txt', 'r') as f: install_requires = [x.strip() for x in f.readlines()] from setuptools import setup, find_packages setup( name='bodylabs-rigger', version=version, author='Body Labs', author_email='david.smith@bodylabs.com', description="Utilities for rigging a mesh from Body Labs' BodyKit API.", url='https://github.com/bodylabs/rigger', license='BSD', packages=find_packages(), package_data={ 'bodylabs_rigger.static': ['rig_assets.json'] }, install_requires=install_requires, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
version = '0.1.0' with open('requirements.txt', 'r') as f: install_requires = [x.strip() for x in f.readlines()] from setuptools import setup, find_packages setup( name='bodylabs-rigger', version=version, author='Body Labs', author_email='david.smith@bodylabs.com', description="Utilities for rigging a mesh from Body Labs' BodyKit API.", url='https://github.com/bodylabs/rigger', license='BSD', packages=find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Fix message with 462 numeric
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
Add link from conversations to message batches.
from django.db import models from go.contacts.models import Contact class Conversation(models.Model): """A conversation with an audience""" user = models.ForeignKey('auth.User') subject = models.CharField('Conversation Name', max_length=255) message = models.TextField('Message') start_date = models.DateField() start_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) groups = models.ManyToManyField('contacts.ContactGroup') previewcontacts = models.ManyToManyField('contacts.Contact') def people(self): return Contact.objects.filter(groups__in=self.groups.all()) class Meta: ordering = ['-updated_at'] get_latest_by = 'updated_at' def __unicode__(self): return self.subject class MessageBatch(models.Model): """A set of messages that belong to a conversation. The full data about messages is stored in the Vumi API message store. This table is just a link from Vumi Go's conversations to the Vumi API's batches. """ conversation = models.ForeignKey(Conversation) batch_id = models.CharField(max_length=32) # uuid4 as hex
from django.db import models from go.contacts.models import Contact class Conversation(models.Model): """A conversation with an audience""" user = models.ForeignKey('auth.User') subject = models.CharField('Conversation Name', max_length=255) message = models.TextField('Message') start_date = models.DateField() start_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) groups = models.ManyToManyField('contacts.ContactGroup') previewcontacts = models.ManyToManyField('contacts.Contact') def people(self): return Contact.objects.filter(groups__in=self.groups.all()) class Meta: ordering = ['-updated_at'] get_latest_by = 'updated_at' def __unicode__(self): return self.subject
Make TF2_BEHAVIOR=0 disable TF2 behavior. Prior to this change, the mere presence of a TF2_BEHAVIOR environment variable would enable TF2 behavior. With this, setting that environment variable to "0" will disable it. PiperOrigin-RevId: 223804383
# Copyright 2018 The TensorFlow Authors. 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. # ============================================================================== """Tools to help with the TensorFlow 2.0 transition. This module is meant for TensorFlow internal implementation, not for users of the TensorFlow library. For that see tf.compat instead. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" return _force_enable or os.getenv("TF2_BEHAVIOR", "0") != "0"
# Copyright 2018 The TensorFlow Authors. 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. # ============================================================================== """Tools to help with the TensorFlow 2.0 transition. This module is meant for TensorFlow internal implementation, not for users of the TensorFlow library. For that see tf.compat instead. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" return _force_enable or os.getenv("TF2_BEHAVIOR") is not None
Fix token given story hrefs Summary: derp to tha derp Fixes T2578. Test Plan: click click Reviewers: chad Reviewed By: chad CC: aran Maniphest Tasks: T2578 Differential Revision: https://secure.phabricator.com/D5054
<?php final class PhabricatorTokenGivenFeedStory extends PhabricatorFeedStory { public function getPrimaryObjectPHID() { return $this->getValue('objectPHID'); } public function getRequiredHandlePHIDs() { $phids = array(); $phids[] = $this->getValue('objectPHID'); $phids[] = $this->getValue('authorPHID'); return $phids; } public function renderView() { $view = new PhabricatorFeedStoryView(); $view->setViewed($this->getHasViewed()); $href = $this->getHandle($this->getPrimaryObjectPHID())->getURI(); $view->setHref($href); $title = pht( '%s awarded %s a token.', $this->linkTo($this->getValue('authorPHID')), $this->linkTo($this->getValue('objectPHID'))); $view->setTitle($title); $view->setOneLineStory(true); return $view; } public function renderText() { // TODO: This is grotesque; the feed notification handler relies on it. return strip_tags($this->renderView()->render()); } }
<?php final class PhabricatorTokenGivenFeedStory extends PhabricatorFeedStory { public function getPrimaryObjectPHID() { return $this->getValue('objectPHID'); } public function getRequiredHandlePHIDs() { $phids = array(); $phids[] = $this->getValue('objectPHID'); $phids[] = $this->getValue('authorPHID'); return $phids; } public function renderView() { $view = new PhabricatorFeedStoryView(); $view->setViewed($this->getHasViewed()); $href = $this->getHandle($this->getPrimaryObjectPHID())->getURI(); $view->setHref($view); $title = pht( '%s awarded %s a token.', $this->linkTo($this->getValue('authorPHID')), $this->linkTo($this->getValue('objectPHID'))); $view->setTitle($title); $view->setOneLineStory(true); return $view; } public function renderText() { // TODO: This is grotesque; the feed notification handler relies on it. return strip_tags($this->renderView()->render()); } }
Revert "Add hypothesis as test requirement." This reverts commit 7e340017f4bb0a8a99219f3896071ab07a017f4f.
from setuptools import setup, find_packages import unittest import doctest # Read in the version number exec(open('src/nash/version.py', 'r').read()) requirements = ["numpy==1.11.2"] def test_suite(): """Discover all tests in the tests dir""" test_loader = unittest.TestLoader() # Read in unit tests test_suite = test_loader.discover('tests') # Read in doctests from README test_suite.addTests(doctest.DocFileSuite('README.md', optionflags=doctest.ELLIPSIS)) return test_suite setup( name='nashpy', version=__version__, install_requires=requirements, author='Vince Knight, James Campbell', author_email=('knightva@cardiff.ac.uk'), packages=find_packages('src'), package_dir={"": "src"}, test_suite='setup.test_suite', url='', license='The MIT License (MIT)', description='A library to compute equilibria of 2 player normal form games', )
from setuptools import setup, find_packages import unittest import doctest # Read in the version number exec(open('src/nash/version.py', 'r').read()) requirements = ["numpy==1.11.2"] test_requirements = ['hypothesis>=3.6.0'] def test_suite(): """Discover all tests in the tests dir""" test_loader = unittest.TestLoader() # Read in unit tests test_suite = test_loader.discover('tests') # Read in doctests from README test_suite.addTests(doctest.DocFileSuite('README.md', optionflags=doctest.ELLIPSIS)) return test_suite setup( name='nashpy', version=__version__, install_requires=requirements, tests_require=test_requirements, author='Vince Knight, James Campbell', author_email=('knightva@cardiff.ac.uk'), packages=find_packages('src'), package_dir={"": "src"}, test_suite='setup.test_suite', url='', license='The MIT License (MIT)', description='A library to compute equilibria of 2 player normal form games', )
Check for typeof string on cache hit
var xhr = require('xhr'); var defaults = require('lodash.defaults'); module.exports = function (options, callback) { // Set default options defaults(options, { method: 'GET', useCache: true, json: {}, timeout: 60000 // 60 seconds }); // Use URI and prepend the API host if (typeof options.url !== 'undefined') { options.uri = options.url; delete options.url; } options.uri = 'https://gist.githubusercontent.com/thisandagain' + options.uri; // Set cache key var key = 'cache::' + options.method.toLowerCase() + '::' + options.uri; // Use device cache if window.Android is available & options.useCache is true if (window.Android && options.useCache === true) { window.Android.logText('Fetching from cache "' + key + '"'); var hit = window.Android.getSharedPreferences(key); if (typeof hit === 'string') return callback(null, JSON.parse(hit)); } // XHR request xhr(options, function (err, res, body) { if (err) return callback(err); // Set cache if window.Android is available if (window.Android) { window.Android.setSharedPreferences(key, JSON.stringify(body)); } // Return response body callback(null, body); }); };
var xhr = require('xhr'); var defaults = require('lodash.defaults'); module.exports = function (options, callback) { // Set default options defaults(options, { method: 'GET', useCache: true, json: {}, timeout: 60000 // 60 seconds }); // Use URI and prepend the API host if (typeof options.url !== 'undefined') { options.uri = options.url; delete options.url; } options.uri = 'https://gist.githubusercontent.com/thisandagain' + options.uri; // Set cache key var key = 'cache::' + options.method.toLowerCase() + '::' + options.uri; // Use device cache if window.Android is available & options.useCache is true if (window.Android && options.useCache === true) { window.Android.logText('Fetching from cache "' + key + '"'); var hit = window.Android.getSharedPreferences(key); if (typeof hit !== 'undefined') return callback(null, JSON.parse(hit)); } // XHR request xhr(options, function (err, res, body) { if (err) return callback(err); // Set cache if window.Android is available if (window.Android) { window.Android.setSharedPreferences(key, JSON.stringify(body)); } // Return response body callback(null, body); }); };
Update jQuery and BS to latest version for tests
/** * Jasmine test to check success callback */ describe('stan-loader-ok', function() { // Declare status var var status; // Activate async beforeEach(function(done) { // Initiate $STAN loader using normal window load events $STAN_Load([ '//code.jquery.com/jquery-1.11.2.min.js', '//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js' ], function() { status = 'ok'; done(); }, function() { status = 'error'; done(); }); }); // Perform tests it("JS libs loaded in to the DOM", function() { // Check status has been set to ok expect(status).toBe('ok'); // Check jQuery is loaded expect($).toBeDefined(); // Check bootstrap is loaded expect($().tab()).toBeDefined(); }); });
/** * Jasmine test to check success callback */ describe('stan-loader-ok', function() { // Declare status var var status; // Activate async beforeEach(function(done) { // Initiate $STAN loader using normal window load events $STAN_Load([ '//code.jquery.com/jquery-1.10.1.min.js', '//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js' ], function() { status = 'ok'; done(); }, function() { status = 'error'; done(); }); }); // Perform tests it("JS libs loaded in to the DOM", function() { // Check status has been set to ok expect(status).toBe('ok'); // Check jQuery is loaded expect($).toBeDefined(); // Check bootstrap is loaded expect($().tab()).toBeDefined(); }); });
Comment out buggy declation emitter
module.exports = { entry: './src/confirm.ts', output: { path: './dist', filename: 'angular2-bootstrap-confirm.js', libraryTarget: 'umd', library: 'ng2BootstrapConfirm' }, externals: { 'angular2/core': { root: ['ng', 'core'], commonjs: 'angular2/core', commonjs2: 'angular2/core', amd: 'angular2/core' }, 'ng2-bootstrap/components/position': 'ng2-bootstrap/components/position' }, devtool: 'source-map', module: { preLoaders: [{ test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/ }], loaders: [{ test: /\.ts$/, loader: 'ts', exclude: /node_modules/, /*query: { compilerOptions: { declaration: true } }*/ }] }, resolve: { extensions: ['', '.ts', '.js'] } };
module.exports = { entry: './src/confirm.ts', output: { path: './dist', filename: 'angular2-bootstrap-confirm.js', libraryTarget: 'umd', library: 'ng2BootstrapConfirm' }, externals: { 'angular2/core': { root: ['ng', 'core'], commonjs: 'angular2/core', commonjs2: 'angular2/core', amd: 'angular2/core' }, 'ng2-bootstrap/components/position': 'ng2-bootstrap/components/position' }, devtool: 'source-map', module: { preLoaders: [{ test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/ }], loaders: [{ test: /\.ts$/, loader: 'ts', exclude: /node_modules/, query: { compilerOptions: { declaration: true } } }] }, resolve: { extensions: ['', '.ts', '.js'] } };
Add check sub grid method
# Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle def check_rows(grid): i = 0 while i < len(grid): j = 0 ref_check = {} while j < len(grid[i]): if grid[i][j] != '.' and grid[i][j] in ref_check: return False else: ref_check[grid[i][j]] = 1 j += 1 i += 1 return True def check_columns(grid): column = 0 length = len(grid) while column < length: row = 0 ref_check = {} while row < length: if grid[row][column] != '.' and grid[row][column] in ref_check: return False else: ref_check[grid[row][column]] = 1 row += 1 column += 1 return True def create_sub_grid(grid): ref_check = {} for square in grid: if square != '.' and square in ref_check: return False else: ref_check[square] = 1 return True
# Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle def check_rows(grid): i = 0 while i < len(grid): j = 0 ref_check = {} while j < len(grid[i]): if grid[i][j] != '.' and grid[i][j] in ref_check: return False else: ref_check[grid[i][j]] = 1 j += 1 i += 1 return True def check_columns(grid): column = 0 length = len(grid) while column < length: row = 0 ref_check = {} while row < length: if grid[row][column] != '.' and grid[row][column] in ref_check: return False else: ref_check[grid[row][column]] = 1 row += 1 column += 1 return True
Fix bug where load was being called on null.
<?php namespace App\Http\ViewComposers; use Illuminate\Contracts\View\View; class NotificationsComposer { /** * Binds the relevant notification information to the view. * * @param View $view * @return void */ public function compose(View $view) { if (auth()->check()) { $user = \Auth::user()->load('watchNotifications'); $notificationCount = 0; $watchNotifications = $user->watchNotifications; $notificationCount += $watchNotifications->count(); $view->with('watchNotifications', $watchNotifications) ->with('notificationCount', $notificationCount); } } }
<?php namespace App\Http\ViewComposers; use Illuminate\Contracts\View\View; class NotificationsComposer { /** * Binds the relevant notification information to the view. * * @param View $view * @return void */ public function compose(View $view) { $user = \Auth::user()->load('watchNotifications'); if (auth()->check()) { $notificationCount = 0; $watchNotifications = $user->watchNotifications; $notificationCount += $watchNotifications->count(); $view->with('watchNotifications', $watchNotifications) ->with('notificationCount', $notificationCount); } } }
Fix an issue where some versions of php need the $path property to be converted to a string.
<?php namespace Swiftmade\Blogdown\Commands; use Swiftmade\Blogdown\Parser; use Illuminate\Console\Command; use Swiftmade\Blogdown\Repository; use Illuminate\Support\Facades\File; class Build extends Command { /** * @var Repository */ private $repository; protected $signature = 'blog:build'; protected $description = 'Caches blog articles'; public function __construct(Repository $repository) { parent::__construct(); $this->repository = $repository; } public function handle() { $this->repository->flush(); $blogPath = base_path(config('blogdown.blog_folder')); collect(File::files($blogPath)) ->filter(function ($file) { return pathinfo($file, PATHINFO_EXTENSION) === 'md'; }) ->each(function ($path) { $blog = Parser::parse(((string)$path); $this->repository->put($blog); $this->info('Cached /' . $blog->meta->slug); }); } }
<?php namespace Swiftmade\Blogdown\Commands; use Swiftmade\Blogdown\Parser; use Illuminate\Console\Command; use Swiftmade\Blogdown\Repository; use Illuminate\Support\Facades\File; class Build extends Command { /** * @var Repository */ private $repository; protected $signature = 'blog:build'; protected $description = 'Caches blog articles'; public function __construct(Repository $repository) { parent::__construct(); $this->repository = $repository; } public function handle() { $this->repository->flush(); $blogPath = base_path(config('blogdown.blog_folder')); collect(File::files($blogPath)) ->filter(function ($file) { return pathinfo($file, PATHINFO_EXTENSION) === 'md'; }) ->each(function ($path) { $blog = Parser::parse($path); $this->repository->put($blog); $this->info('Cached /' . $blog->meta->slug); }); } }
Fix for double attempt at circle on iOS.
// @flow import React from 'react'; import { Image, Platform, View } from 'react-native'; import theme from '../../theme'; type Props = { size?: number, source: string, style?: Object, }; export default function Avatar({ size = 44, source, style, ...props }: Props) { const styles = { wrapper: { backgroundColor: theme.color.sceneBg, borderRadius: size, overflow: 'hidden', height: size, width: size, }, image: { borderRadius: Platform.OS === 'android' ? size : 0, height: size, width: size, }, }; return ( <View style={[styles.wrapper, style]} {...props}> <Image source={{ uri: source }} style={styles.image} /> </View> ); }
// @flow import React from 'react'; import { Image, View } from 'react-native'; import theme from '../../theme'; type Props = { size?: number, source: string, style?: Object, }; export default function Avatar({ size = 44, source, style, ...props }: Props) { const styles = { wrapper: { backgroundColor: theme.color.sceneBg, borderRadius: size, overflow: 'hidden', height: size, width: size, }, image: { borderRadius: size, height: size, width: size, }, }; return ( <View style={[styles.wrapper, style]} {...props}> <Image source={{ uri: source }} style={styles.image} /> </View> ); }
Update manifest files being bumped.
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/manifest.json', 'src/chrome/extension/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/dist_build/manifest.json', 'src/chrome/app/dev_build/manifest.json', 'src/chrome/extension/dist_build/manifest.json', 'src/chrome/extension/dev_build/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
Disable the registration portal for now
<?php // Copyright 2019 Peter Beverloo. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. error_reporting((E_ALL | E_STRICT) & ~E_WARNING); ini_set('display_errors', 1); require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/error.php'; Header('Access-Control-Allow-Origin: *'); Header('Content-Type: application/json'); $environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']); if (!$environment->isValid()) dieWithError('Unrecognized volunteer portal environment.'); echo json_encode([ 'contactName' => 'Peter', 'contactTarget' => 'mailto:' . $environment->getContact(), 'title' => $environment->getName(), 'events' => [ [ 'name' => 'AnimeCon 2021', 'enablePortal' => false, 'enableRegistration' => false, 'timezone' => 'Europe/Amsterdam', 'website' => 'https://www.animecon.nl/', ], ], ]);
<?php // Copyright 2019 Peter Beverloo. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. error_reporting((E_ALL | E_STRICT) & ~E_WARNING); ini_set('display_errors', 1); require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/error.php'; Header('Access-Control-Allow-Origin: *'); Header('Content-Type: application/json'); $environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']); if (!$environment->isValid()) dieWithError('Unrecognized volunteer portal environment.'); echo json_encode([ 'contactName' => 'Peter', 'contactTarget' => 'mailto:' . $environment->getContact(), 'title' => $environment->getName(), 'events' => [ [ 'name' => 'AnimeCon 2021', 'enablePortal' => false, 'enableRegistration' => true, 'timezone' => 'Europe/Amsterdam', 'website' => 'https://www.animecon.nl/', ], ], ]);
:bug: Fix bug on CanBuildBaseString trait test.
<?php use PHPUnit\Framework\TestCase; use Risan\OAuth1\Signature\CanBuildBaseString; use Risan\OAuth1\Signature\BaseStringBuilderInterface; class CanBuildBaseStringTest extends TestCase { private $canBuildBaseStringStub; function setUp() { $this->canBuildBaseStringStub = $this->getMockForTrait(CanBuildBaseString::class); } /** @test */ function can_build_base_string_trait_can_get_base_string_builder_interface_instance() { $this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseStringStub->getBaseStringBuilder()); } /** @test */ function can_build_base_string_trait_can_build_base_string() { $baseString = $this->canBuildBaseStringStub->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST'); $this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $baseString); } }
<?php use PHPUnit\Framework\TestCase; use Risan\OAuth1\Signature\CanBuildBaseString; use Risan\OAuth1\Signature\BaseStringBuilderInterface; class CanBuildBaseStringTest extends TestCase { private $canBuildBaseStringStub; function setUp() { $this->canBuildBaseStringStub = $this->getMockForTrait(CanBuildBaseString::class); } /** @test */ function can_build_base_string_trait_can_get_base_string_builder_interface_instance() { $this->assertInstanceOf(BaseStringBuilderInterface::class, $this->canBuildBaseStringStub->getBaseStringBuilder()); } /** @test */ function can_build_base_string_trait_can_build_base_string() { $baseString = $this->canBuildBaseStringStub->buildBaseString('http://example.com/path', ['foo' => 'bar'], 'POST'); $this->assertEquals('POST&http%3A%2F%2Fexample.com%2Fpath&foo%3Dbar', $canBuildBaseStringStub); } }
Fix handling of empty file
import os import uuid from mischief.actors.pipe import get_local_ip import yaml def read_serfnode_yml(): with open('/serfnode.yml') as input: conf = yaml.load(input) or {} return conf.get('serfnode', {}) yml = read_serfnode_yml() role = os.environ.get('ROLE') or yml.get('ROLE') or 'no_role' peer = os.environ.get('PEER') or yml.get('PEER') ip = (os.environ.get('SERF_IP') or yml.get('SERF_IP') or get_local_ip('8.8.8.8')) bind_port = os.environ.get('SERF_PORT') or yml.get('SERF_PORT') or 7946 node = os.environ.get('NODE_NAME') or uuid.uuid4().hex rpc_port = os.environ.get('RPC_PORT') or 7373 service = os.environ.get('SERVICE_IP') or yml.get('SERVICE_IP') or ip service_port = os.environ.get('SERVICE_PORT') or yml.get('SERVICE_PORT') or 0
import os import uuid from mischief.actors.pipe import get_local_ip import yaml def read_serfnode_yml(): with open('/serfnode.yml') as input: conf = yaml.load(input) or {} return conf['serfnode'] yml = read_serfnode_yml() role = os.environ.get('ROLE') or yml.get('ROLE') or 'no_role' peer = os.environ.get('PEER') or yml.get('PEER') ip = (os.environ.get('SERF_IP') or yml.get('SERF_IP') or get_local_ip('8.8.8.8')) bind_port = os.environ.get('SERF_PORT') or yml.get('SERF_PORT') or 7946 node = os.environ.get('NODE_NAME') or uuid.uuid4().hex rpc_port = os.environ.get('RPC_PORT') or 7373 service = os.environ.get('SERVICE_IP') or yml.get('SERVICE_IP') or ip service_port = os.environ.get('SERVICE_PORT') or yml.get('SERVICE_PORT') or 0
Add the 'get_work' part in the client example
package main import ( "fmt" "github.com/levigross/grequests" "github.com/ryanskidmore/GoWork" "strings" ) func main() { response, err := grequests.Get("http://127.0.0.1:3000/register", nil) if err != nil { panic("Unable to register:" + err.Error()) } respdata := strings.Split(response.String(), ",") id := respdata[0] clienttest := respdata[1] worker, err := gowork.NewWorker("w4PYxQjVP9ZStjWpBt5t28CEBmRs8NPx", id, clienttest) testresponse, err := grequests.Post("http://127.0.0.1:3000/verify", &grequests.RequestOptions{Params: map[string]string{"id": id, "clientresp": worker.Verification.ClientResponse}}) if err != nil { panic("Unable to verify:" + err.Error()) } worker = worker.SetAuthenticationKey(testresponse.String()) fmt.Println(worker.SessionAuthenticationKey) testresponse, err = grequests.Post("http://127.0.0.1:3000/get_work", &grequests.RequestOptions{Params: map[string]string{"id": id, "sessionauthkey": worker.SessionAuthenticationKey}}) fmt.Println(testresponse.String()) }
package main import ( "fmt" "github.com/levigross/grequests" "github.com/ryanskidmore/GoWork" "strings" ) func main() { response, err := grequests.Get("http://127.0.0.1:3000/register", nil) if err != nil { panic("Unable to register:" + err.Error()) } respdata := strings.Split(response.String(), ",") id := respdata[0] clienttest := respdata[1] worker, err := gowork.NewWorker("w4PYxQjVP9ZStjWpBt5t28CEBmRs8NPx", id, clienttest) testresponse, err := grequests.Post("http://127.0.0.1:3000/verify", &grequests.RequestOptions{Params: map[string]string{"id": id, "clientresp": worker.Verification.ClientResponse}}) if err != nil { panic("Unable to verify:" + err.Error()) } worker = worker.SetAuthenticationKey(testresponse.String()) fmt.Println(worker.SessionAuthenticationKey) }
Remove setTimeout left over from debugging.
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setLoading(false); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setTimeout(() => { setLoading(false); }, 10000); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
Remove models/ subpackage from api due to migration to QuantEcon.applications
""" Import the main names to top level. """ from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
""" Import the main names to top level. """ from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
doc: Update Neural Entity (now complete)
from Entity import * class NeuralEntity(Entity): """Entity the represents timestamps of action potentials, i.e. spike times. Cutouts of the waveforms corresponding to spike data in a neural entity might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`). """ def __init__(self, nsfile, eid, info): super(NeuralEntity,self).__init__(eid, nsfile, info) @property def probe_info(self): return self._info['ProbeInfo'] @property def source_entity_id(self): """[*Optional*] Id of the source entity of this spike, if any. For example the spike waveform of the action potential corresponding to this spike might have been recoreded in a segment entity.""" return self._info['SourceEntityID'] @property def source_unit_id(self): """[*Optional*] unit id used in the source entity (cf. :func:`source_entity_id`)""" return self._info['SourceUnitID'] def get_data (self, index=0, count=-1): """Retrieve the spike times associated with this entity. A subset of the data can be requested via the ``index`` and ``count`` parameters.""" lib = self.file.library if count < 0: count = self.item_count data = lib._get_neural_data (self, index, count) return data
from Entity import * class NeuralEntity(Entity): """Entity the represents timestamps of action potentials, i.e. spike times. Cutouts of the waveforms corresponding to spike data in a neural entity might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`). """ def __init__(self, nsfile, eid, info): super(NeuralEntity,self).__init__(eid, nsfile, info) @property def probe_info(self): return self._info['ProbeInfo'] @property def source_entity_id(self): """[**Optional**] Id of the source entity of this spike, if any. For example the spike waveform of the action potential corresponding to this spike might have been recoreded in a segment entity.""" return self._info['SourceEntityID'] @property def source_unit_id(self): return self._info['SourceUnitID'] def get_data (self, index=0, count=-1): """Retrieve the spike times associated with this entity. A subset of the data can be requested via the ``inde`` and ``count`` parameters.""" lib = self.file.library if count < 0: count = self.item_count data = lib._get_neural_data (self, index, count) return data
Add error handling for posts_per_page type conversion
from app.models import Setting class AppSettings(dict): def __init__(self): super().__init__() self.update({setting.name: setting.value for setting in Setting.query.all()}) try: self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page'))) except KeyError: pass def __setitem__(self, key, value): super().__setitem__(key, value) setting = Setting.query.filter_by(name=key).first() if setting is not None: setting.value = value else: setting = Setting(name=key, value=value) setting.save() def __setattr__(self, key, value): self.__setitem__(key, value)
from app.models import Setting class AppSettings(dict): def __init__(self): super().__init__() self.update({setting.name: setting.value for setting in Setting.query.all()}) self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page'))) def __setitem__(self, key, value): super().__setitem__(key, value) setting = Setting.query.filter_by(name=key).first() if setting is not None: setting.value = value else: setting = Setting(name=key, value=value) setting.save() def __setattr__(self, key, value): self.__setitem__(key, value)
Remove no-longer-necessary line of code
'use strict' var isPresent = require('is-present') var hasClass = require('has-class-selector') var SelectorTokenizer = require('css-selector-tokenizer') module.exports = function classRepeat (selector, options) { if (typeof selector !== 'string') { throw new TypeError('class-repeat expects a string') } options = options || {} options.repeat = options.repeat || 2 if (hasClass(selector)) { var tokens = SelectorTokenizer.parse(selector).nodes[0] || { nodes: [] } var tokensWithRepeatedClasses = [] tokens.nodes.map(function (node, index) { if (node.type === 'class' || isPseudo(node)) { for (var i = 0; i < options.repeat; i++) { tokensWithRepeatedClasses.push(node) } } else { tokensWithRepeatedClasses.push(node) } }) return SelectorTokenizer.stringify({ type: 'selectors', nodes: [{ type: 'selector', nodes: tokensWithRepeatedClasses }] }) } else { return selector } } function isPseudo(token) { return token && (token.type === 'pseudo-element' || token.type === 'pseudo-class') }
'use strict' var isPresent = require('is-present') var hasClass = require('has-class-selector') var SelectorTokenizer = require('css-selector-tokenizer') module.exports = function classRepeat (selector, options) { if (typeof selector !== 'string') { throw new TypeError('class-repeat expects a string') } options = options || {} options.repeat = options.repeat || 2 if (hasClass(selector)) { var tokens = SelectorTokenizer.parse(selector).nodes[0] || { nodes: [] } var tokensWithRepeatedClasses = [] tokens.nodes.map(function (node, index) { if (node.type === 'class' || isPseudo(node)) { for (var i = 0; i < options.repeat; i++) { tokensWithRepeatedClasses.push(node) var nextToken = tokens.nodes[index + 1] } } else { tokensWithRepeatedClasses.push(node) } }) return SelectorTokenizer.stringify({ type: 'selectors', nodes: [{ type: 'selector', nodes: tokensWithRepeatedClasses }] }) } else { return selector } } function isPseudo(token) { return token && (token.type === 'pseudo-element' || token.type === 'pseudo-class') }
Add a check for division by zero
package main // Build a standalone executable with 'go build go-calc' // Or just do a one time run test with 'go run go-calc 1 / 4' import "fmt" import "os" // For ARGV import "strconv" func main() { var arg_count int = len(os.Args) - 1; if (arg_count != 3) { fmt.Fprintf(os.Stdout,"Usage: %s [num1] [+-/*] [num2]\n", os.Args[0]); os.Exit(3); } var num1, _ = strconv.ParseFloat(os.Args[1],32); var num2, _ = strconv.ParseFloat(os.Args[3],32); var operand = os.Args[2]; var total float64 = 0; if (operand == "+") { total = num1 + num2; } else if (operand == "-") { total = num1 - num2; } else if (operand == "/") { // Test for division by zero if (num2 == 0) { fmt.Fprintf(os.Stdout, "Error: division by zero\n"); os.Exit(9); } total = num1 / num2; } else if (operand == "*") { total = num1 * num2; } else { fmt.Fprintf(os.Stdout, "Unknown operand '%s'\n", operand); os.Exit(2); } fmt.Fprintf(os.Stdout, "%g %s %g = %g\n", num1, operand, num2, total); }
package main // Build a standalone executable with 'go build go-calc' // Or just do a one time run test with 'go run go-calc 1 / 4' import "fmt" import "os" // For ARGV import "strconv" func main() { var arg_count int = len(os.Args) - 1; if (arg_count != 3) { fmt.Fprintf(os.Stdout,"Usage: %s [num1] [+-/*] [num2]\n", os.Args[0]); os.Exit(3); } var num1, _ = strconv.ParseFloat(os.Args[1],32); var num2, _ = strconv.ParseFloat(os.Args[3],32); var operand = os.Args[2]; var total float64 = 0; if (operand == "+") { total = num1 + num2; } else if (operand == "-") { total = num1 - num2; } else if (operand == "/") { total = num1 / num2; } else if (operand == "*") { total = num1 * num2; } else { fmt.Fprintf(os.Stdout, "Unknown operand '%s'\n", operand); os.Exit(2); } fmt.Fprintf(os.Stdout, "%g %s %g = %g\n", num1, operand, num2, total); }
Move user login code to djangoautoconf.
from djangoautoconf.django_utils import retrieve_param from django.utils import timezone from provider.oauth2.backends import AccessTokenBackend from provider.oauth2.models import AccessToken from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import login from djangoautoconf.req_with_auth import login_by_django_user def login_from_oauth2(request): data = retrieve_param(request) target = data.get("target", "/admin") if "access_token" in data: access_tokens = AccessToken.objects.filter(token=data["access_token"], expires__gt=timezone.now()) if access_tokens.exists(): user_access_token = access_tokens[0] user_access_token.expires = timezone.now() user_access_token.save() django_user_instance = user_access_token.user login_by_django_user(django_user_instance, request) return HttpResponseRedirect(target)
from djangoautoconf.django_utils import retrieve_param from django.utils import timezone from provider.oauth2.backends import AccessTokenBackend from provider.oauth2.models import AccessToken from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import login def login_from_oauth2(request): data = retrieve_param(request) target = data.get("target", "/admin") if "access_token" in data: access_tokens = AccessToken.objects.filter(token=data["access_token"], expires__gt=timezone.now()) if access_tokens.exists(): user_access_token = access_tokens[0] user_access_token.expires = timezone.now() user_access_token.save() user_instance = user_access_token.user # User.objects.get(username=user_access_token.user) user_instance.backend = "django.contrib.auth.backends.ModelBackend" login(request, user_instance) return HttpResponseRedirect(target)
Align bottom sheet to center
// @flow import * as React from 'react'; import { View } from 'react-native'; import { Dimensions } from 'react-native'; import { BottomSheet as CommonBottomSheet, Device, type OnDimensionsChange, } from '@kiwicom/react-native-app-shared'; import { getWidth, openHeight, closedHeight } from '../bottomSheetDimensions'; type Props = {| children: React.Node, |}; type State = {| screenWidth: number, |}; export default class BottomSheet extends React.Component<Props, State> { isTablet: boolean; constructor(props: Props) { super(props); this.isTablet = Device.isTablet(); this.state = { screenWidth: Dimensions.get('screen').width, }; } componentDidMount = () => { Dimensions.addEventListener('change', this.onDimensionsChanged); }; componentWillUnmount = () => { Dimensions.removeEventListener('change', this.onDimensionsChanged); }; onDimensionsChanged = ({ screen: { width } }: OnDimensionsChange) => { this.setState({ screenWidth: width }); }; getWidth = () => getWidth(this.state.screenWidth, this.isTablet); render = () => { const { children } = this.props; return ( <View style={{ width: this.getWidth(), alignSelf: 'center' }}> <CommonBottomSheet openHeight={openHeight} closedHeight={closedHeight}> {children} </CommonBottomSheet> </View> ); }; }
// @flow import * as React from 'react'; import { View } from 'react-native'; import { Dimensions } from 'react-native'; import { BottomSheet as CommonBottomSheet, Device, type OnDimensionsChange, } from '@kiwicom/react-native-app-shared'; import { getWidth, openHeight, closedHeight } from '../bottomSheetDimensions'; type Props = {| children: React.Node, |}; type State = {| screenWidth: number, |}; export default class BottomSheet extends React.Component<Props, State> { isTablet: boolean; constructor(props: Props) { super(props); this.isTablet = Device.isTablet(); this.state = { screenWidth: Dimensions.get('screen').width, }; } componentDidMount = () => { Dimensions.addEventListener('change', this.onDimensionsChanged); }; componentWillUnmount = () => { Dimensions.removeEventListener('change', this.onDimensionsChanged); }; onDimensionsChanged = ({ screen: { width } }: OnDimensionsChange) => { this.setState({ screenWidth: width }); }; getWidth = () => getWidth(this.state.screenWidth, this.isTablet); render = () => { const { children } = this.props; return ( <View style={{ width: this.getWidth() }}> <CommonBottomSheet openHeight={openHeight} closedHeight={closedHeight}> {children} </CommonBottomSheet> </View> ); }; }
Expand the entire job definition by default
import Ember from 'ember'; import JSONFormatterPkg from 'npm:json-formatter-js'; const { Component, computed, run } = Ember; // json-formatter-js is packaged in a funny way that ember-cli-browserify // doesn't unwrap properly. const { default: JSONFormatter } = JSONFormatterPkg; export default Component.extend({ classNames: ['json-viewer'], json: null, expandDepth: Infinity, formatter: computed('json', 'expandDepth', function() { return new JSONFormatter(this.get('json'), this.get('expandDepth'), { theme: 'nomad', }); }), didReceiveAttrs() { const json = this.get('json'); if (!json) { return; } run.scheduleOnce('afterRender', this, embedViewer); }, }); function embedViewer() { this.$() .empty() .append(this.get('formatter').render()); }
import Ember from 'ember'; import JSONFormatterPkg from 'npm:json-formatter-js'; const { Component, computed, run } = Ember; // json-formatter-js is packaged in a funny way that ember-cli-browserify // doesn't unwrap properly. const { default: JSONFormatter } = JSONFormatterPkg; export default Component.extend({ classNames: ['json-viewer'], json: null, expandDepth: 2, formatter: computed('json', 'expandDepth', function() { return new JSONFormatter(this.get('json'), this.get('expandDepth'), { theme: 'nomad', }); }), didReceiveAttrs() { const json = this.get('json'); if (!json) { return; } run.scheduleOnce('afterRender', this, embedViewer); }, }); function embedViewer() { this.$().empty().append(this.get('formatter').render()); }
Use jQuery live events for radio button detection. Allow the field to be used in Django inlines.
(function($) { $(document).ready(function(){ var widgets = $("ul.any_urlfield-url_type"); widgets.find("input").live('change', onUrlTypeChange); // Apply by default widgets.each(function(){ updatePanels($(this)); }); }); function onUrlTypeChange(event) { var widget = $(this).parent().closest('.any_urlfield-url_type'); updatePanels(widget); } function updatePanels(widget) { var inputs = widget.find('input'); inputs.each(function(){ var slugvalue = this.value.replace(/[^a-z0-9-_]/, ''); var pane = widget.siblings(".any_urlfield-url-" + slugvalue); pane[ this.checked ? "show" : "hide" ](); }); } })(window.jQuery || window.django.jQuery);
(function($) { $(document).ready(function(){ var widgets = $("ul.any_urlfield-url_type"); widgets.find("input").change(onUrlTypeChange); // Apply by default widgets.each(function(){ updatePanels($(this)); }); }); function onUrlTypeChange(event) { var widget = $(this).parent().closest('.any_urlfield-url_type'); updatePanels(widget); } function updatePanels(widget) { var inputs = widget.find('input'); inputs.each(function(){ var slugvalue = this.value.replace(/[^a-z0-9-_]/, ''); var pane = widget.siblings(".any_urlfield-url-" + slugvalue); pane[ this.checked ? "show" : "hide" ](); }); } })(window.jQuery || window.django.jQuery);
Make create tag group more compatible with older laravel
<?php namespace Conner\Tagging\Console\Commands; use Conner\Tagging\TaggingUtility; use Conner\Tagging\Model\TagGroup; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputArgument; class GenerateTagGroup extends Command { protected $name = 'tagging:create-group'; protected $signature = 'tagging:create-group {group}'; protected $description = 'Create a laravel tag group'; public function handle() { $groupName = $this->argument('group'); $tagGroup = new TagGroup(); $tagGroup->name = $groupName; $tagGroup->slug = TaggingUtility::normalize($groupName); $tagGroup->save(); $this->info('Created tag group: '.$groupName); } protected function getArguments() { return [ ['group', InputArgument::REQUIRED, 'Name of the group to create.'], ]; } }
<?php namespace Conner\Tagging\Console\Commands; use Conner\Tagging\TaggingUtility; use Conner\Tagging\Model\TagGroup; use Illuminate\Console\Command; class GenerateTagGroup extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'tagging:create-group {group_name}'; /** * The console command description. * * @var string */ protected $description = 'Create a laravel tag group'; /** * Execute the console command. * * @return mixed */ public function handle() { $groupName = $this->argument('group_name'); $tagGroup = new TagGroup(); $tagGroup->name = $groupName; $tagGroup->slug = TaggingUtility::normalize($groupName); $tagGroup->save(); $this->info('Created tag group: ' . $groupName); } }
Add Appointment issuer (User) field support
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAppointmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('appointments', function(Blueprint $table) { $table->increments('id'); $table->integer('issuer_id')->unsigned()->nullable(); $table->foreign('issuer_id')->references('id')->on('users')->onDelete('cascade'); $table->integer('contact_id')->unsigned(); $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade'); $table->integer('business_id')->unsigned(); $table->foreign('business_id')->references('id')->on('businesses')->onDelete('cascade'); $table->string('hash', 32)->unique(); $table->enum('status', ['R','C', 'A', 'S']); // Reserved, Confirmed, Annulated, Served $table->timestamp('start_at')->index(); $table->integer('duration')->nullable(); $table->integer('service_id')->unsigned()->nullable(); $table->foreign('service_id')->references('id')->on('services')->onDelete('cascade'); $table->string('comments')->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('appointments'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAppointmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('appointments', function(Blueprint $table) { $table->increments('id'); $table->integer('contact_id')->unsigned(); $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade'); $table->integer('business_id')->unsigned(); $table->foreign('business_id')->references('id')->on('businesses')->onDelete('cascade'); $table->string('hash', 32)->unique(); $table->enum('status', ['R','C', 'A', 'S']); // Reserved, Confirmed, Annulated, Served $table->timestamp('start_at')->index(); $table->integer('duration')->nullable(); $table->integer('service_id')->unsigned()->nullable(); $table->foreign('service_id')->references('id')->on('services')->onDelete('cascade'); $table->string('comments')->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('appointments'); } }
Adjust dir structure for exports
const siteSlug = process.argv[2]; const fs = require('fs'); import { getQuestionsStream, getAnswersStream, uninitDB } from './datastore.js'; import { decodify } from './codify.js'; const baseLang = 'en'; function createDirs(dir) { let subdirs = dir.split('/').splice(1); let path = './'; subdirs.forEach(subdir => { path += `${subdir}/`; if (!fs.existsSync(path)) { fs.mkdirSync(path); } }); } let sequence = Promise.resolve(); sequence = sequence.then(getQuestionsStream.bind(null, siteSlug, baseLang, { }, question => { createDirs(`./translations/export/${siteSlug}`); sequence = sequence.then(decodify.bind(null, question.body)); sequence = sequence.then(data => { fs.writeFileSync(`./translations/export/${siteSlug}/q${question.id}.html`, data.normalizedBody); fs.writeFileSync(`./translations/export/${siteSlug}/t${question.id}.html`, question.title); }); })); sequence = sequence.then(getAnswersStream.bind(null, siteSlug, baseLang, { }, answer => { sequence = sequence.then(decodify.bind(null, answer.body)); sequence = sequence.then(data => { fs.writeFileSync(`./translations/${siteSlug}/a${answer.id}.html`, data.normalizedBody); }); })); sequence = sequence.then(uninitDB); sequence.catch(err => console.error(err));
const siteSlug = process.argv[2]; const fs = require('fs'); import { getQuestionsStream, getAnswersStream, uninitDB } from './datastore.js'; import { decodify } from './codify.js'; const baseLang = 'en'; let sequence = Promise.resolve(); sequence = sequence.then(getQuestionsStream.bind(null, siteSlug, baseLang, { }, question => { if (!fs.existsSync('./translations')) { fs.mkdirSync('./translations'); } if (!fs.existsSync(`./translations/${siteSlug}`)) { fs.mkdirSync(`./translations/${siteSlug}`); } sequence = sequence.then(decodify.bind(null, question.body)); sequence = sequence.then(data => { fs.writeFileSync(`./translations/${siteSlug}/q${question.id}.html`, data.normalizedBody); fs.writeFileSync(`./translations/${siteSlug}/t${question.id}.html`, question.title); }); })); sequence = sequence.then(getAnswersStream.bind(null, siteSlug, baseLang, { }, answer => { sequence = sequence.then(decodify.bind(null, answer.body)); sequence = sequence.then(data => { fs.writeFileSync(`./translations/${siteSlug}/a${answer.id}.html`, data.normalizedBody); }); })); sequence = sequence.then(uninitDB); sequence.catch(err => console.error(err));
Add compound statements back in.
module.exports = grammar({ name: 'ruby', extras: $ => [ $.comment, $._line_break, /[ \t\r]/ ], rules: { program: $ => $._compound_statement, _compound_statement: $ => repeat(seq($._statement, optional($._terminator))), _statement: $ => choice($._expression), _expression: $ => choice($._argument), _argument: $ => choice($._primary), _primary: $ => choice($._variable), _variable: $ => choice($.identifier , 'nil', 'self'), identifier: $ => seq(repeat(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/), comment: $ => token(seq('#', /.*/)), _line_break: $ => '\n', _terminator: $ => choice($._line_break, ';'), } });
module.exports = grammar({ name: 'ruby', extras: $ => [ $.comment, $._line_break, /[ \t\r]/ ], rules: { program: $ => repeat(seq($._statement, optional($._terminator))), _statement: $ => choice($._expression), _expression: $ => choice($._argument), _argument: $ => choice($._primary), _primary: $ => choice($._variable), _variable: $ => choice($.identifier , 'nil', 'self'), identifier: $ => seq(repeat(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/), comment: $ => token(seq('#', /.*/)), _line_break: $ => '\n', _terminator: $ => choice($._line_break, ';'), } });
Update event firing to check first if event type exists
/** * Event handler. * @constructor */ function EventTarget(){ this._listeners = {}; } /** * @method * @param {string} type * @param {function} listener */ EventTarget.prototype.addListener = function(type, listener){ if (!(type in this._listeners)) { this._listeners[type] = []; } this._listeners[type].push(listener); }; /** * @method * @param {string} type Type of event to be fired. * @param {Object} [event] Optional event object. */ EventTarget.prototype.fire = function(type, event){ var e = {}; if (typeof event !== 'undefined'){ e = event; } e.event = type; e.target = this; var listeners = this._listeners[type]; if (typeof listeners !== 'undefined'){ for (var i = 0, len = listeners.length; i < len; i++) { listeners[i].call(this, e); } } }; /** * @method * @param {string} type * @param {function} listener */ EventTarget.prototype.removeListener = function(type, listener){ var listeners = this._listeners[type]; for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i] === listener) { listeners.splice(i, 1); } } }; module.exports = EventTarget;
/** * Event handler. * @constructor */ function EventTarget(){ this._listeners = {}; } /** * @method * @param {string} type * @param {function} listener */ EventTarget.prototype.addListener = function(type, listener){ if (!(type in this._listeners)) { this._listeners[type] = []; } this._listeners[type].push(listener); }; /** * @method * @param {string} type Type of event to be fired. * @param {Object} [event] Optional event object. */ EventTarget.prototype.fire = function(type, event){ var e = {}; if (typeof event !== 'undefined'){ e = event; } e.event = type; e.target = this; var listeners = this._listeners[type]; for (var i = 0, len = listeners.length; i < len; i++) { listeners[i].call(this, e); } }; /** * @method * @param {string} type * @param {function} listener */ EventTarget.prototype.removeListener = function(type, listener){ var listeners = this._listeners[type]; for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i] === listener) { listeners.splice(i, 1); } } }; module.exports = EventTarget;
Use full path to api in stead of relatieve path At this moment a relative path is used (../../../), for the cde saikuWidget. But the preview of the dashboard and the 'normal' view are on a different directory level, so one of them needs an extra ../ Fixed by using the full path /pentaho/plugin/saiku/api But this won't work if somebody use a different 'directory' for pentaho. But I guess that is not a big problem...
var saikuWidgetComponent = BaseComponent.extend({ update : function() { var myself=this; var htmlId = "#" + myself.htmlObject; if (myself.saikuFilePath.substr(0,1) == "/") { myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 ); } var parameters = {}; if (myself.parameters) { _.each(myself.parameters, function(parameter) { var k = parameter[0]; var v = parameter[1]; if (window.hasOwnProperty(v)) { v = window[v]; } parameters[k] = v; }); } if (myself.width) { $(htmlId).width(myself.width); } if (myself.width) { $(htmlId).height(myself.height); } if ("table" == myself.renderMode) { $(htmlId).addClass('workspace_results'); var t = $("<div></div>"); $(htmlId).html(t); htmlId = t; } var myClient = new SaikuClient({ server: "/pentaho/plugin/saiku/api", path: "/cde-component" }); myClient.execute({ file: myself.saikuFilePath, htmlObject: htmlId, render: myself.renderMode, mode: myself.renderType, zoom: true, params: parameters }); } });
var saikuWidgetComponent = BaseComponent.extend({ update : function() { var myself=this; var htmlId = "#" + myself.htmlObject; if (myself.saikuFilePath.substr(0,1) == "/") { myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 ); } var parameters = {}; if (myself.parameters) { _.each(myself.parameters, function(parameter) { var k = parameter[0]; var v = parameter[1]; if (window.hasOwnProperty(v)) { v = window[v]; } parameters[k] = v; }); } if (myself.width) { $(htmlId).width(myself.width); } if (myself.width) { $(htmlId).height(myself.height); } if ("table" == myself.renderMode) { $(htmlId).addClass('workspace_results'); var t = $("<div></div>"); $(htmlId).html(t); htmlId = t; } var myClient = new SaikuClient({ server: "../../../plugin/saiku/api", path: "/cde-component" }); myClient.execute({ file: myself.saikuFilePath, htmlObject: htmlId, render: myself.renderMode, mode: myself.renderType, zoom: true, params: parameters }); } });
Add test for cli 'add' command
# Copyright (c) 2015 "Hugo Herter http://hugoherter.com" # # This file is part of Billabong. # # Intercom 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/>. """Test CLI interface.""" import os from .fixtures import record assert record def run(cmd): """Helper to test running a CLI command.""" os.system('python -m billabong ' + cmd) def test_cli(record): """Test main supported CLI commands.""" ID = record['id'] run('ls') run('records') run('blobs') run('info ' + ID) run('info ' + ID + ' --no-color') run('search txt') run('check') run('push') run('pull') run('echo ' + ID) run('status') run('version') run('add hello.txt')
# Copyright (c) 2015 "Hugo Herter http://hugoherter.com" # # This file is part of Billabong. # # Intercom 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/>. """Test CLI interface.""" import os from .fixtures import record assert record def run(cmd): """Helper to test running a CLI command.""" os.system('python -m billabong ' + cmd) def test_cli(record): """Test main supported CLI commands.""" ID = record['id'] run('ls') run('blobs') run('info ' + ID) run('search txt') run('check') run('push') run('pull') run('echo ' + ID) run('status') run('version')
TMS-227: Support sequences with value_type other than combination
import zc.form.field import zc.form.interfaces import zope.schema.interfaces class DynamicCombination(zc.form.field.Combination): def __init__(self, type_field, type_interface, **kw): self.type_field = type_field self.type_field.__name__ = "combination_00" self.fields = (type_field,) self.type_interface = type_interface super(zc.form.field.Combination, self).__init__(**kw) def generate_fields(self, selector): result = [] field = self.type_interface[selector] if zope.schema.interfaces.ICollection.providedBy(field): field = field.value_type if zc.form.interfaces.ICombinationField.providedBy(field): result.extend(field.fields) else: result.append(field) result = [x.bind(self.context) for x in result] for ix, field in enumerate(result): field.__name__ = "combination_%02d" % (ix + 1) return result def _validate(self, value): # XXX I hope we can get away with no validation here, since all input # happens through widgets and so should be valid anyway. Otherwise we # have to synthesize fields here too, like DynamicCombinationWidget. pass
import zc.form.field import zope.schema.interfaces class DynamicCombination(zc.form.field.Combination): def __init__(self, type_field, type_interface, **kw): self.type_field = type_field self.type_field.__name__ = "combination_00" self.fields = (type_field,) self.type_interface = type_interface super(zc.form.field.Combination, self).__init__(**kw) def generate_fields(self, selector): fields = [] field = self.type_interface[selector] if zope.schema.interfaces.ICollection.providedBy(field): fields.extend(field.value_type.fields) else: fields.append(field) fields = [x.bind(self.context) for x in fields] for ix, field in enumerate(fields): field.__name__ = "combination_%02d" % (ix + 1) return fields def _validate(self, value): # XXX I hope we can get away with no validation here, since all input # happens through widgets and so should be valid anyway. Otherwise we # have to synthesize fields here too, like DynamicCombinationWidget. pass
Test against generated table object
<?php namespace WyriHaximus\React\Tests\Cake\Orm; use WyriHaximus\React\Cake\Orm\AsyncTableGenerator; use WyriHaximus\React\Cake\Orm\GeneratedTable; use WyriHaximus\React\TestApp\Cake\Orm\Table\ScreenshotsTable; class AsyncTableGeneratorTest extends TestCase { public function testGenerate() { $tmpDir = sys_get_temp_dir() . DS . uniqid('WyriHaximus-Cake-Async-ORM-', true) . DS; mkdir($tmpDir, 0777, true); $generator = new AsyncTableGenerator($tmpDir); $generatedTable = $generator->generate(ScreenshotsTable::class); $this->assertInstanceOf(GeneratedTable::class, $generatedTable); $this->assertFileEquals( dirname(__DIR__) . DS . 'test_app' . DS . 'ExpectedGeneratedAsyncTable' . DS . 'C17a66dcf052f6878c3f1c553db4d6bd0_Ff47f6f78cf1b377de64788b3705cda9c.php', $tmpDir . $generatedTable->getClassName() . '.php' ); } }
<?php namespace WyriHaximus\React\Tests\Cake\Orm; use WyriHaximus\React\Cake\Orm\AsyncTableGenerator; use WyriHaximus\React\TestApp\Cake\Orm\Table\ScreenshotsTable; class AsyncTableGeneratorTest extends TestCase { public function testGenerate() { $tmpDir = sys_get_temp_dir() . DS . uniqid('WyriHaximus-Cake-Async-ORM-', true) . DS; mkdir($tmpDir, 0777, true); $generator = new AsyncTableGenerator($tmpDir); $filename = $generator->generate(ScreenshotsTable::class); $this->assertFileEquals( dirname(__DIR__) . DS . 'test_app' . DS . 'ExpectedGeneratedAsyncTable' . DS . 'C17a66dcf052f6878c3f1c553db4d6bd0_Ff47f6f78cf1b377de64788b3705cda9c.php', $tmpDir . $filename . '.php' ); } }
Define a mapping between byte and class.
# -*- coding: utf-8 -*- """ hyper/http20/frame ~~~~~~~~~~~~~~~~~~ Defines framing logic for HTTP/2.0. Provides both classes to represent framed data and logic for aiding the connection when it comes to reading from the socket. """ # A map of type byte to frame class. FRAMES = { 0x00: DataFrame } class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError()
# -*- coding: utf-8 -*- """ hyper/http20/frame ~~~~~~~~~~~~~~~~~~ Defines framing logic for HTTP/2.0. Provides both classes to represent framed data and logic for aiding the connection when it comes to reading from the socket. """ class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError()
Update notification update api to PUT Signed-off-by: Federico Claramonte <9aaaa8bfe6a7a51765b462c528e1446dcf049286@caviumnetworks.com>
// // Copyright (c) 2017 Cavium // // SPDX-License-Identifier: Apache-2.0 // package distro import ( "io" "net/http" "github.com/go-zoo/bone" ) func replyPing(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/text; charset=utf-8") w.WriteHeader(http.StatusOK) str := `pong` io.WriteString(w, str) } func replyNotifyRegistrations(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/text; charset=utf-8") w.WriteHeader(http.StatusOK) io.WriteString(w, "") RefreshRegistrations() } // HTTPServer function func HTTPServer() http.Handler { mux := bone.New() mux.Get("/api/v1/ping", http.HandlerFunc(replyPing)) mux.Put("/api/v1/notify/registrations", http.HandlerFunc(replyNotifyRegistrations)) return mux }
// // Copyright (c) 2017 Cavium // // SPDX-License-Identifier: Apache-2.0 // package distro import ( "io" "net/http" "github.com/go-zoo/bone" ) func replyPing(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/text; charset=utf-8") w.WriteHeader(http.StatusOK) str := `pong` io.WriteString(w, str) } func replyNotifyRegistrations(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/text; charset=utf-8") w.WriteHeader(http.StatusOK) io.WriteString(w, "") RefreshRegistrations() } // HTTPServer function func HTTPServer() http.Handler { mux := bone.New() mux.Get("/api/v1/ping", http.HandlerFunc(replyPing)) mux.Get("/api/v1/notify/registrations", http.HandlerFunc(replyNotifyRegistrations)) return mux }
Change rule from warning to off
/** * Created by AlexanderC on 9/15/15. */ /* eslint no-unused-vars: 0 */ 'use strict'; var exports = module.exports = function(callback) { var microservice = this.microservice; var provisioning = this.provisioning; if (this.isUpdate) { console.log('Update! Skipping public bucket location retrieval post deploy hook...'); callback(); return; } console.log('Start retrieving public bucket location in "' + microservice.identifier + '" post deploy hook.'); var s3 = provisioning.s3; var publicBucket = provisioning.config.s3.buckets.public.name; s3.getBucketLocation({Bucket: publicBucket}, function(error, data) { if (error) { console.error('Error while retrieving public bucket(' + publicBucket + ') location: ' + error); } else { var region = data.LocationConstraint || 'unknown'; console.log('Public bucket(' + publicBucket + ') is located in "' + region + '" region.'); } callback(); return; }); };
/** * Created by AlexanderC on 9/15/15. */ /* eslint no-unused-vars: 1 */ 'use strict'; var exports = module.exports = function(callback) { var microservice = this.microservice; var provisioning = this.provisioning; if (this.isUpdate) { console.log('Update! Skipping public bucket location retrieval post deploy hook...'); callback(); return; } console.log('Start retrieving public bucket location in "' + microservice.identifier + '" post deploy hook.'); var s3 = provisioning.s3; var publicBucket = provisioning.config.s3.buckets.public.name; s3.getBucketLocation({Bucket: publicBucket}, function(error, data) { if (error) { console.error('Error while retrieving public bucket(' + publicBucket + ') location: ' + error); } else { var region = data.LocationConstraint || 'unknown'; console.log('Public bucket(' + publicBucket + ') is located in "' + region + '" region.'); } callback(); return; }); };
Use https for gravatar images
<?php /** * Skeleton subclass for representing a row from the 'profile' table. * * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package propel.generator.lib.model */ class Profile extends BaseProfile { const DEFAULT_AVATAR_URL = "mm"; public function __toString() { return ($this->getNickname() != '') ? $this->getNickname() : $this->getsfGuardUser()->getUsername(); } public function getAvatarUrl($size = 24) { return sprintf("https://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($this->getEmail()))), urlencode(self::DEFAULT_AVATAR_URL), $size); } /** * @static * @param string $email * @param int $size * @return string */ public static function getAvatarUrlFromEmail($email, $size = 24) { if (null === $email) { $email = 0; } return sprintf("https://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($email))), urlencode(self::DEFAULT_AVATAR_URL), $size); } } // Profile
<?php /** * Skeleton subclass for representing a row from the 'profile' table. * * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package propel.generator.lib.model */ class Profile extends BaseProfile { const DEFAULT_AVATAR_URL = "mm"; public function __toString() { return ($this->getNickname() != '') ? $this->getNickname() : $this->getsfGuardUser()->getUsername(); } public function getAvatarUrl($size = 24) { return sprintf("http://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($this->getEmail()))), urlencode(self::DEFAULT_AVATAR_URL), $size); } /** * @static * @param string $email * @param int $size * @return string */ public static function getAvatarUrlFromEmail($email, $size = 24) { if (null === $email) { $email = 0; } return sprintf("http://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($email))), urlencode(self::DEFAULT_AVATAR_URL), $size); } } // Profile