text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add information on Copy command. Adding extra information to track down mysterious mac build failures. tbr=bradnelson@google.com git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@9679 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import shutil import sys """Copy Sources Copy from a source file or directory to a new file or directory. This supports renaming of the file. """ def ErrOut(text): print '\n\n' print ' '.join(sys.argv) print text sys.exit(1) def MakeDir(outdir): if outdir and not os.path.exists(outdir): os.makedirs(outdir) def Main(argv): if len(argv) != 3: print 'Expecting: copy_sources.py <source file> <dest file/dir>' return 1 if not os.path.exists(argv[1]): print 'File not found: %s' % argv[1] return 1 shutil.copy(argv[1], argv[2]) print 'From %s to %s\n' % (argv[1], argv[2]) return 0 if __name__ == '__main__': sys.exit(Main(sys.argv))
#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import shutil import sys """Copy Sources Copy from a source file or directory to a new file or directory. This supports renaming of the file. """ def ErrOut(text): print '\n\n' print ' '.join(sys.argv) print text sys.exit(1) def MakeDir(outdir): if outdir and not os.path.exists(outdir): os.makedirs(outdir) def Main(argv): if len(argv) != 3: print 'Expecting: copy_sources.py <source file> <dest file/dir>' return 1 if not os.path.exists(argv[1]): print 'File not found: %s' % argv[1] return 1 shutil.copy(argv[1], argv[2]) return 0 if __name__ == '__main__': sys.exit(Main(sys.argv))
Implement basic Twitch Plays Pokemon for chat
// Do NOT include this line if you are using the browser version. var irc = require("tmi.js"); var fs = require('fs'); var gameboyButtons = ['a', 'b', 'left', 'right', 'up', 'down', 'start', 'select']; var options = { options: { debug: true }, connection: { cluster: "aws", reconnect: true }, identity: { username: "Sagnewshreds", password: process.env.TWITCH_OAUTH_TOKEN }, channels: ["#sagnewshreds"] }; var client = new irc.client(options); // Connect the client to the server.. client.connect(); client.on('connected', function(channel, user, message, self) { client.say('sagnewshreds', 'THIS IS NOW TWITCH PLAYS POKEMON CHAT! HYPE!'); }); client.on("chat", function (channel, user, message, self) { var button = message.toLowerCase(); console.log(user.username + ': ' + message); if(gameboyButtons.indexOf(button) >= 0) { if(button === 'a' || button === 'b') { button = button.toUpperCase(); } fs.writeFileSync('button.txt', button, 'utf8'); } });
// Do NOT include this line if you are using the browser version. var irc = require("tmi.js"); var options = { options: { debug: true }, connection: { cluster: "aws", reconnect: true }, identity: { username: "Sagnewshreds", password: process.env.TWITCH_OAUTH_TOKEN }, channels: ["#sagnewshreds"] }; var client = new irc.client(options); // Connect the client to the server.. client.connect(); client.on('connected', function(channel, user, message, self) { client.say('sagnewshreds', 'HELLO TWITCH WHAT UP'); }); client.on("chat", function (channel, user, message, self) { console.log(user.username + ': ' + message); });
Add new BG test case for foreign natural persons
<?php declare (strict_types=1); namespace DragonBe\Test\Vies\Validator; class ValidatorBGTest extends AbstractValidatorTest { /** * @covers \DragonBe\Vies\Validator\ValidatorBG * @dataProvider vatNumberProvider */ public function testValidator(string $vatNumber, bool $state) { $this->validateVatNumber('BG', $vatNumber, $state); } public function vatNumberProvider() { return [ ['301004503', true], ['10100450', false], ['301004502', false], ['8311046307', true], ['3002779909', true], ]; } }
<?php declare (strict_types=1); namespace DragonBe\Test\Vies\Validator; class ValidatorBGTest extends AbstractValidatorTest { /** * @covers \DragonBe\Vies\Validator\ValidatorBG * @dataProvider vatNumberProvider */ public function testValidator(string $vatNumber, bool $state) { $this->validateVatNumber('BG', $vatNumber, $state); } public function vatNumberProvider() { return [ ['301004503', true], ['10100450', false], ['301004502', false], ['8311046307', true], ]; } }
Add user to session when they create a new account
var express = require('express'); var router = express.Router(); import encryptUtils from '../utilities/encrypt'; import userUtils from '../utilities/users_service.js'; import { userAuth, adminAuth } from '../utilities/auth'; router.post('/', (req, res) => { const { first_name, last_name, email, username, password } = req.body; encryptUtils.encryptPassword(password).then((hashedPassword) => { const newUser = { first_name, last_name, email, username, password: hashedPassword }; userUtils.createUser(newUser).then((createdUser) => { req.session.username = createdUser.username; req.session.status = createdUser.status; res.json(createdUser); }, () => res.sendStatus(400)); }, () => res.sendStatus(500)); }); router.get('/', adminAuth, (req, res) => { userUtils.getUsers().then((users) => { res.json(users); }, () => res.sendStatus(404)); }); router.get('/:id', adminAuth, (req, res) => { const userID = req.params.id; userUtils.getUser(userID).then((user) => { res.json(user); }, () => res.sendStatus(404)); }); module.exports = router;
var express = require('express'); var router = express.Router(); import encryptUtils from '../utilities/encrypt'; import userUtils from '../utilities/users_service.js'; import { userAuth, adminAuth } from '../utilities/auth'; router.post('/', (req, res) => { const { first_name, last_name, email, username, password } = req.body; encryptUtils.encryptPassword(password).then((hashedPassword) => { const newUser = { first_name, last_name, email, username, password: hashedPassword }; userUtils.createUser(newUser).then((createdUser) => { res.json(createdUser); }, () => res.sendStatus(400)); }, () => res.sendStatus(500)); }); router.get('/', adminAuth, (req, res) => { userUtils.getUsers().then((users) => { res.json(users); }, () => res.sendStatus(404)); }); router.get('/:id', adminAuth, (req, res) => { const userID = req.params.id; userUtils.getUser(userID).then((user) => { res.json(user); }, () => res.sendStatus(404)); }); module.exports = router;
Fix the ordering of stripping and transliteration This was kind of a silly way to do this. First stripping everything that is not default, and then using iconv transliteration. At that point there would be no special chars left. This explains why i always lose my French éàç characters in the slug :) Fixes #8
<?php namespace Kunstmaan\UtilitiesBundle\Helper; /** * Sulgifier is a helper to slugify a certain string */ class Slugifier { /** * Slugify a string * * @param string $text Text to slugify * @param string $default Default return value (override when slugify would return an empty string) * * @return string */ public static function slugify($text, $default = 'n-a') { // transliterate if (function_exists('iconv')) { $previouslocale = setlocale(LC_CTYPE, 0); setlocale(LC_CTYPE, 'en_US.UTF8'); $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); setlocale(LC_CTYPE, $previouslocale); } $text = preg_replace('#[^\\pL\d\/]+#u', '-', $text); // replace non letter or digits by - $text = trim($text, '-'); //trim $text = strtolower($text); // lowercase $text = preg_replace('#[^-\w\/]+#', '', $text); // remove unwanted characters if (empty($text)) { return empty($default) ? '' : $default; } return $text; } }
<?php namespace Kunstmaan\UtilitiesBundle\Helper; /** * Sulgifier is a helper to slugify a certain string */ class Slugifier { /** * Slugify a string * * @param string $text Text to slugify * @param string $default Default return value (override when slugify would return an empty string) * * @return string */ public static function slugify($text, $default = 'n-a') { $text = preg_replace('#[^\\pL\d\/]+#u', '-', $text); // replace non letter or digits by - $text = trim($text, '-'); //trim // transliterate if (function_exists('iconv')) { $previouslocale = setlocale(LC_CTYPE, 0); setlocale(LC_CTYPE, 'en_US.UTF8'); $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); setlocale(LC_CTYPE, $previouslocale); } $text = strtolower($text); // lowercase $text = preg_replace('#[^-\w\/]+#', '', $text); // remove unwanted characters if (empty($text)) { return empty($default) ? '' : $default; } return $text; } }
Remove Rollup options that are unnecessary now that `@web/test-runner-mocha` is no longer bundled.
import commonjs from '@rollup/plugin-commonjs'; import {nodeResolve} from '@rollup/plugin-node-resolve'; export default [ { input: 'chai.js', output: { file: 'chai-bundle.js', format: 'es', }, plugins: [ commonjs(), nodeResolve({ preferBuiltins: false, }), ], }, { input: 'core-js_url.js', output: { file: 'core-js_url-bundle.js', format: 'es', }, plugins: [ commonjs(), nodeResolve({ preferBuiltins: false, }), ], }, ];
import commonjs from '@rollup/plugin-commonjs'; import {nodeResolve} from '@rollup/plugin-node-resolve'; export default [ { input: 'chai.js', output: { file: 'chai-bundle.js', format: 'es', }, plugins: [ commonjs(), nodeResolve({ preferBuiltins: false, }), ], }, { input: 'core-js_url.js', output: { file: 'core-js_url-bundle.js', format: 'es', }, plugins: [ commonjs(), nodeResolve({ preferBuiltins: false, }), ], makeAbsoluteExternalsRelative: false, external: ['/__web-dev-server__web-socket.js'], }, ];
Use CoreMatchers.anything where it makes sense
package rxbroadcast; import nl.jqno.equalsverifier.EqualsVerifier; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; @SuppressWarnings({"checkstyle:MagicNumber"}) public final class VectorTimestampTest { @Test public final void equalsContract() { EqualsVerifier.forClass(VectorTimestamp.class) .withCachedHashCode("hashCode", "computeHashCode", new VectorTimestamp( new Sender[]{new Sender(new byte[] {42}), new Sender(new byte[]{43})}, new long[]{1, 2} )) .verify(); } @Test(expected = IllegalArgumentException.class) public final void timestampMustHaveEqualLengthFields() { Assert.assertThat(new VectorTimestamp(new Sender[0], new long[]{3, 4}), CoreMatchers.anything()); } }
package rxbroadcast; import nl.jqno.equalsverifier.EqualsVerifier; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; @SuppressWarnings({"checkstyle:MagicNumber"}) public final class VectorTimestampTest { @Test public final void equalsContract() { EqualsVerifier.forClass(VectorTimestamp.class) .withCachedHashCode("hashCode", "computeHashCode", new VectorTimestamp( new Sender[]{new Sender(new byte[] {42}), new Sender(new byte[]{43})}, new long[]{1, 2} )) .verify(); } @Test(expected = IllegalArgumentException.class) public final void timestampMustHaveEqualLengthFields() { final VectorTimestamp t = new VectorTimestamp(new Sender[0], new long[]{3, 4}); Assert.assertThat(t, CoreMatchers.notNullValue()); } }
Use our $A.util classes for browser compat
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ testEmptyItems:{ test:function(cmp){ var element = cmp.getElement(); $A.test.assertTrue($A.util.hasClass(element, "uiMessage"), "Expected to see a message to indicate no data."); var text = $A.test.getText(element); $A.test.assertEquals("No data found.", $A.util.trim(text), "Message to indicate no data is absent or incorrect"); } } })
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ testEmptyItems:{ test:function(cmp){ var element = cmp.getElement(); $A.test.assertTrue(element.className.indexOf("uiMessage")!=-1, "Expected to see a message to indicate no data."); $A.test.assertEquals("No data found.", $A.test.getText(element).trim(), "Message to indicate no data is absent or incorrect"); } } })
Optimize dom replacement for board viewer This one line cuts down the "loading" slice from the chrome timeline from 25% to 3%. jQuery.html performs a very expensive html validation before inserting to into the dom. Because we *hope* that we're sending valid html before hand we don't need to do this. This leaves page redraw and paint as the next largest bottleneck, which cannot be overcome without using something other than svg.
import Mousetrap from "mousetrap"; import socket from "../socket" import "../empties/modal"; const logError = resp => { console.error("Unable to join", resp) }; const init = (gameId) => { if(typeof gameId === "undefined") { return; } const boardViewerChannel = socket.channel(`board_viewer:${gameId}`, {contentType: "html"}); const gameAdminChannel = socket.channel(`game_admin:${gameId}`); boardViewerChannel.on("tick", ({content}) => { document.getElementById("board-viewer").innerHTML = content; }); boardViewerChannel. join(). receive("error", logError); gameAdminChannel. join(). receive("error", logError); const cmd = (request) => { console.log(request); gameAdminChannel. push(request). receive("error", e => console.error(`push "${request}" failed`, e)); }; Mousetrap.bind(["q"], () => cmd("stop")); Mousetrap.bind(["h", "left"], () => cmd("prev")); Mousetrap.bind(["j", "up"], () => cmd("resume")); Mousetrap.bind(["k", "down"], () => cmd("pause")); Mousetrap.bind(["l", "right"], () => cmd("next")); Mousetrap.bind("R", () => cmd("replay")); }; export default { init };
import Mousetrap from "mousetrap"; import $ from "jquery"; import socket from "../socket" import "../empties/modal"; const logError = resp => { console.error("Unable to join", resp) }; const init = (gameId) => { if(typeof gameId === "undefined") { return; } const boardViewerChannel = socket.channel(`board_viewer:${gameId}`, {contentType: "html"}); const gameAdminChannel = socket.channel(`game_admin:${gameId}`); boardViewerChannel.on("tick", ({content}) => { $("#board-viewer").html() }); boardViewerChannel. join(). receive("error", logError); gameAdminChannel. join(). receive("error", logError); const cmd = (request) => { console.log(request); gameAdminChannel. push(request). receive("error", e => console.error(`push "${request}" failed`, e)); }; Mousetrap.bind(["q"], () => cmd("stop")); Mousetrap.bind(["h", "left"], () => cmd("prev")); Mousetrap.bind(["j", "up"], () => cmd("resume")); Mousetrap.bind(["k", "down"], () => cmd("pause")); Mousetrap.bind(["l", "right"], () => cmd("next")); Mousetrap.bind("R", () => cmd("replay")); }; export default { init };
Use 'auth' as key in the result hash instead of 'valid'.
<?php class Authenticator { private $dbh; function __construct() { $this->dbh = Database::instance()->connection(); } function authenticate($creds) { $query = "select status from users " . "where username = ? and password = ?"; $sth = $this->dbh->prepare($query); $sth->execute(array($creds['username'], $creds['password'])); $row = $sth->fetch(); $ret = array(); if ($row['status'] == false) { $ret['auth'] = false; $ret['msg'] = 'Authentication failed'; } elseif ($status == 'inactive') { $ret['auth'] = false; $ret['msg'] = 'This user account is inactive'; } elseif ($status == 'active') { $ret['auth'] = true; $ret['msg'] = 'Logged in as ' . $creds['username']; } else { $ret['auth'] = false; $ret['msg'] = 'An unknown error occurred'; } return $ret; } }
<?php class Authenticator { private $dbh; function __construct() { $this->dbh = Database::instance()->connection(); } function authenticate($creds) { $query = "select status from users " . "where username = ? and password = ?"; $sth = $this->dbh->prepare($query); $sth->execute(array($creds['username'], $creds['password'])); $row = $sth->fetch(); $ret = array(); if ($row['status'] == false) { $ret['valid'] = false; $ret['msg'] = 'Authentication failed'; } elseif ($status == 'inactive') { $ret['valid'] = false; $ret['msg'] = 'This user account is inactive'; } elseif ($status == 'active') { $ret['valid'] = true; $ret['msg'] = 'Logged in as ' . $creds['username']; } else { $ret['valid'] = false; $ret['msg'] = 'An unknown error occurred'; } return $ret; } }
Reset docs theme, RTD should override
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) from gravity import __version__ # noqa: E402 project = 'Gravity' copyright = '2022, The Galaxy Project' author = 'The Galaxy Project' release = __version__ # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration master_doc = 'index' extensions = [] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_theme = 'default' html_static_path = ['_static']
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) from gravity import __version__ # noqa: E402 project = 'Gravity' copyright = '2022, The Galaxy Project' author = 'The Galaxy Project' release = __version__ # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration master_doc = 'index' extensions = [] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_theme = 'alabaster' html_static_path = ['_static']
Add test for latest datasets
import pytest from tests import api RESULT_ATTRIBUTES = [ 'id', 'total_products', 'total_stores', 'total_inventories', 'total_product_inventory_count', 'total_product_inventory_volume_in_milliliters', 'total_product_inventory_price_in_cents', 'store_ids', 'product_ids', 'added_product_ids', 'removed_product_ids', 'removed_product_ids', 'removed_store_ids', 'removed_store_ids', 'csv_dump', 'created_at', 'updated_at', ] DATASET_ID = 800 def _check_result_attrs(result_set): for attr in RESULT_ATTRIBUTES: assert attr in result_set def test_datasets_without_args(): resp = api.datasets() assert resp['status'] == 200 assert 'pager' in resp assert 'result' in resp for res in resp['result']: _check_result_attrs(res) @pytest.mark.parametrize("test_input", [ "latest", DATASET_ID, ]) def test_datasets_with_dataset_id(test_input): resp = api.datasets(test_input) assert resp['status'] == 200 assert 'pager' not in resp assert 'result' in resp _check_result_attrs(resp['result'])
import pytest from tests import api RESULT_ATTRIBUTES = [ 'id', 'total_products', 'total_stores', 'total_inventories', 'total_product_inventory_count', 'total_product_inventory_volume_in_milliliters', 'total_product_inventory_price_in_cents', 'store_ids', 'product_ids', 'added_product_ids', 'removed_product_ids', 'removed_product_ids', 'removed_store_ids', 'removed_store_ids', 'csv_dump', 'created_at', 'updated_at', ] DATASET_ID = 800 def _check_result_attrs(result_set): for attr in RESULT_ATTRIBUTES: assert attr in result_set def test_datasets_without_args(): resp = api.datasets() assert resp['status'] == 200 assert 'pager' in resp assert 'result' in resp for res in resp['result']: _check_result_attrs(res) def test_datasets_with_dataset_id(): resp = api.datasets(DATASET_ID) assert resp['status'] == 200 assert 'pager' not in resp assert 'result' in resp _check_result_attrs(resp['result'])
Comment out test. (Can't compile)
package org.embulk.input; //import com.google.common.base.Optional; //import org.embulk.EmbulkTestRuntime; //import org.embulk.config.ConfigSource; //import org.embulk.spi.Exec; //import org.junit.Rule; //import org.junit.Test; // //import java.util.Collections; // //import static org.hamcrest.CoreMatchers.is; //import static org.junit.Assert.assertThat; public class TestRemoteFileInputPlugin { // @Rule // public EmbulkTestRuntime runtime = new EmbulkTestRuntime(); // // @Test // public void checkDefaultValues() // { // ConfigSource config = Exec.newConfigSource(); // // RemoteFileInputPlugin.PluginTask task = config.loadConfig(RemoteFileInputPlugin.PluginTask.class); // assertThat(task.getHosts(), is(Collections.<String>emptyList())); // assertThat(task.getHostsCommand(), is(Optional.<String>absent())); // assertThat(task.getHostsSeparator(), is(" ")); // assertThat(task.getPath(), is("")); // assertThat(task.getPathCommand(), is(Optional.<String>absent())); // assertThat(task.getAuth(), is(Collections.<String, String>emptyMap())); // assertThat(task.getLastTarget(), is(Optional.<RemoteFileInputPlugin.Target>absent())); // } }
package org.embulk.input; import com.google.common.base.Optional; import org.embulk.EmbulkTestRuntime; import org.embulk.config.ConfigSource; import org.embulk.spi.Exec; import org.junit.Rule; import org.junit.Test; import java.util.Collections; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class TestRemoteFileInputPlugin { @Rule public EmbulkTestRuntime runtime = new EmbulkTestRuntime(); @Test public void checkDefaultValues() { ConfigSource config = Exec.newConfigSource(); RemoteFileInputPlugin.PluginTask task = config.loadConfig(RemoteFileInputPlugin.PluginTask.class); assertThat(task.getHosts(), is(Collections.<String>emptyList())); assertThat(task.getHostsCommand(), is(Optional.<String>absent())); assertThat(task.getHostsSeparator(), is(" ")); assertThat(task.getPath(), is("")); assertThat(task.getPathCommand(), is(Optional.<String>absent())); assertThat(task.getAuth(), is(Collections.<String, String>emptyMap())); assertThat(task.getLastTarget(), is(Optional.<RemoteFileInputPlugin.Target>absent())); } }
Remove foreign key constraint on api_log Table
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateApiLogTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('api_log', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->nullable()->unsigned(); $table->integer('api_key_id')->nullable(); $table->text('images'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('api_log'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateApiLogTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('api_log', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->nullable()->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->integer('api_key_id')->nullable(); $table->text('images'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('api_log'); } }
Update the server listening message too
require('app-module-path').addPath(__dirname); var express = require('express'); var passport = require('passport'); var session = require('express-session'); var app = express(); var inventory_router = require('api/inventory.js'); var reservations_router = require('api/reservations.js'); var auth = require('api/auth.js'); var users_router = require('api/users.js'); var auth_router = auth.router; var ensureAuthenticated = auth.ensureAuthenticated; /* Setup session middleware */ app.use(session({ secret: 'a secret key', cookie: { secure: false } })); app.use(passport.initialize()); app.use(passport.session()); app.use('/api', auth_router); /* Auth requests aren't behind the authentication barrier themselves */ app.use('/public', express.static('public')); /* For serving the login page, etc. */ app.get('/', (req, res) => { if(req.user) { res.redirect('/inventory.html'); } else { res.redirect('/public/login.html'); } }); /* API requests below this need to be authenticated */ app.use(ensureAuthenticated); app.use('/api', users_router); app.use('/api', inventory_router); app.use('/api', reservations_router); app.use(express.static('static')); app.listen(80, () => { console.log("Server listening on port 80."); });
require('app-module-path').addPath(__dirname); var express = require('express'); var passport = require('passport'); var session = require('express-session'); var app = express(); var inventory_router = require('api/inventory.js'); var reservations_router = require('api/reservations.js'); var auth = require('api/auth.js'); var users_router = require('api/users.js'); var auth_router = auth.router; var ensureAuthenticated = auth.ensureAuthenticated; /* Setup session middleware */ app.use(session({ secret: 'a secret key', cookie: { secure: false } })); app.use(passport.initialize()); app.use(passport.session()); app.use('/api', auth_router); /* Auth requests aren't behind the authentication barrier themselves */ app.use('/public', express.static('public')); /* For serving the login page, etc. */ app.get('/', (req, res) => { if(req.user) { res.redirect('/inventory.html'); } else { res.redirect('/public/login.html'); } }); /* API requests below this need to be authenticated */ app.use(ensureAuthenticated); app.use('/api', users_router); app.use('/api', inventory_router); app.use('/api', reservations_router); app.use(express.static('static')); app.listen(80, () => { console.log("Server listening on port 3000."); });
Allow new directories to fully respect umask. (Prior to this patch, the group and other bytes would *never* be writeable. With this patch, they'll be writeable if the umask has been set appropriately.)
<?php namespace CRM\CivixBundle\Builder; use CRM\CivixBundle\Builder; use Symfony\Component\Console\Output\OutputInterface; /** * Build/update empty directories */ class Dirs implements Builder { // Mask applied to new new directory permissions. // Note: Permissions will be further restricted by umask const MODE = 0777; function __construct($paths) { $this->paths = $paths; } function loadInit(&$ctx) { } function init(&$ctx) { } function load(&$ctx) { } function save(&$ctx, OutputInterface $output) { sort($this->paths); foreach ($this->paths as $dir) { $parts = explode(DIRECTORY_SEPARATOR, $dir); if (!is_dir($dir)) { //quiet//$output->writeln("<info>Create ${dir}/</info>"); mkdir($dir, self::MODE, TRUE); } else { // $output->writeln("<comment>Found ${dir}/</comment>"); } } } }
<?php namespace CRM\CivixBundle\Builder; use CRM\CivixBundle\Builder; use Symfony\Component\Console\Output\OutputInterface; /** * Build/update empty directories */ class Dirs implements Builder { const MODE = 0755; function __construct($paths) { $this->paths = $paths; } function loadInit(&$ctx) { } function init(&$ctx) { } function load(&$ctx) { } function save(&$ctx, OutputInterface $output) { sort($this->paths); foreach ($this->paths as $dir) { $parts = explode(DIRECTORY_SEPARATOR, $dir); if (!is_dir($dir)) { //quiet//$output->writeln("<info>Create ${dir}/</info>"); mkdir($dir, self::MODE, TRUE); } else { // $output->writeln("<comment>Found ${dir}/</comment>"); } } } }
hugolib: Fix Windows build failure, take 2
// Copyright 2015 The Hugo 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. package hugolib import ( "testing" "github.com/spf13/hugo/tpl/tplimpl" ) const ( win_base = "c:\\a\\windows\\path\\layout" win_path = "c:\\a\\windows\\path\\layout\\sub1\\index.html" ) func TestTemplatePathSeparator(t *testing.T) { t.Parallel() tmpl := new(tplimpl.GoHTMLTemplate) if name := tplimpl.GenerateTemplateNameFrom(win_base, win_path); name != "sub1/index.html" { t.Fatalf("Template name incorrect. got %s but expected %s", name, "sub1/index.html") } }
// Copyright 2015 The Hugo 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. package hugolib import ( "testing" "github.com/spf13/hugo/tpl/tplimpl" ) const ( win_base = "c:\\a\\windows\\path\\layout" win_path = "c:\\a\\windows\\path\\layout\\sub1\\index.html" ) func TestTemplatePathSeparator(t *testing.T) { t.Parallel() tmpl := new(tpl.GoHTMLTemplate) if name := tplimpl.GenerateTemplateNameFrom(win_base, win_path); name != "sub1/index.html" { t.Fatalf("Template name incorrect. got %s but expected %s", name, "sub1/index.html") } }
Add callback for compile action
<?php namespace TlAssetsBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; use Symfony\Component\Process\Process; class CompileCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('tlassets:compile') ->setDescription('Compile assets based on Gulp buffer created by the command tlassets:dump'); } protected function execute(InputInterface $input, OutputInterface $output) { $compilerManager = $this->getContainer()->get('tl_assets.compiler'); $callback = function ($type, $buffer) use($output) { if (Process::ERR === $type) { $output->writeln('<error>'.$buffer.'</error>'); } else { $output->writeln('<info>'.$buffer.'</info>'); } }; $compilerManager->compileAssets(null, $callback); } }
<?php namespace TlAssetsBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; use Symfony\Component\Process\Process; class CompileCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('tlassets:compile') ->setDescription('Compile assets based on Gulp buffer'); } protected function execute(InputInterface $input, OutputInterface $output) { $compilerManager = $this->getContainer()->get('tl_assets.compiler'); $callback = function ($type, $buffer) use($output) { if (Process::ERR === $type) { $output->writeln('<error>'.$buffer.'</error>'); } else { $output->writeln('<info>'.$buffer.'</info>'); } }; $compilerManager->compileAssets(null, $callback); } }
[GSCOLLECT-622] Rename collection parameters to iterable. git-svn-id: c173b60cd131fd691c78c4467fb70aa9fb29b506@18 d5c9223b-1aff-41ac-aadd-f810b4a99ac4
/* * Copyright 2011 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.impl.partition.set; import com.gs.collections.api.partition.set.PartitionImmutableSet; import com.gs.collections.api.set.ImmutableSet; import net.jcip.annotations.Immutable; @Immutable public class PartitionImmutableSetImpl<T> implements PartitionImmutableSet<T> { private final ImmutableSet<T> selected; private final ImmutableSet<T> rejected; public PartitionImmutableSetImpl(AbstractPartitionMutableSet<T> partitionUnifiedSet) { this.selected = partitionUnifiedSet.getSelected().toImmutable(); this.rejected = partitionUnifiedSet.getRejected().toImmutable(); } public ImmutableSet<T> getSelected() { return this.selected; } public ImmutableSet<T> getRejected() { return this.rejected; } }
/* * Copyright 2011 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.impl.partition.set; import com.gs.collections.api.partition.set.PartitionImmutableSet; import com.gs.collections.api.set.ImmutableSet; import net.jcip.annotations.Immutable; @Immutable public class PartitionImmutableSetImpl<T> implements PartitionImmutableSet<T> { private final ImmutableSet<T> selected; private final ImmutableSet<T> rejected; public PartitionImmutableSetImpl(AbstractPartitionMutableSet<T> partitionUnifiedSet) { this.selected = partitionUnifiedSet.getSelected().toImmutable(); this.rejected = partitionUnifiedSet.getRejected().toImmutable(); } public ImmutableSet<T> getSelected() { return this.selected; } public ImmutableSet<T> getRejected() { return this.rejected; } }
Remove unnecessary comment from Javascript file
$(document).ready(function () { /* Add the current year to the footer */ function getYear() { var d = new Date(); var n = d.getFullYear(); return n.toString(); } $('#year').html(getYear()); /* Enable Bootstrap tooltips */ $("body").tooltip({ selector: '[data-toggle=tooltip]' }); /* Avatar Hover Zoom */ $("#about-avatar").hover(function () { $(this).switchClass('avatar-md', 'avatar-lg'); }, function () { $(this).switchClass('avatar-lg', 'avatar-md'); } ); /* goBack() function */ function goBack() { window.history.back() } });
/** * Project: masterroot24.github.io */ $(document).ready(function () { /* Add the current year to the footer */ function getYear() { var d = new Date(); var n = d.getFullYear(); return n.toString(); } $('#year').html(getYear()); /* Enable Bootstrap tooltips */ $("body").tooltip({ selector: '[data-toggle=tooltip]' }); /* Avatar Hover Zoom */ $("#about-avatar").hover(function () { $(this).switchClass('avatar-md', 'avatar-lg'); }, function () { $(this).switchClass('avatar-lg', 'avatar-md'); } ); /* goBack() function */ function goBack() { window.history.back() } });
Bump version again. Descriptor emulation is more faithful.
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='class_namespaces', version='0.3.0', description='Class Namespaces', long_description=long_description, url='https://github.com/mwchase/class-namespaces', author='Max Woerner Chase', author_email='max.chase@gmail.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='class namespaces', packages=find_packages(exclude=['contrib', 'docs', 'tests']), extras_require={ 'test': ['coverage', 'pytest'], }, )
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='class_namespaces', version='0.2.1', description='Class Namespaces', long_description=long_description, url='https://github.com/mwchase/class-namespaces', author='Max Woerner Chase', author_email='max.chase@gmail.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='class namespaces', packages=find_packages(exclude=['contrib', 'docs', 'tests']), extras_require={ 'test': ['coverage', 'pytest'], }, )
Add test for applying a distance to a coordinate via a quantity
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function from numpy import testing as npt from ... import units as u """ This includes tests for distances/cartesian points that are *not* in the API tests. Right now that's just regression tests. """ def test_distance_change(): from .. import RA, Dec, ICRSCoordinates, Distance ra = RA("4:08:15.162342", unit=u.hour) dec = Dec("-41:08:15.162342", unit=u.degree) c = ICRSCoordinates(ra, dec) c.distance = Distance(1, unit=u.kpc) oldx = c.x assert (oldx - 0.35284083171901953) < 1e-10 #now x should increase when the distance increases c.distance = Distance(2, unit=u.kpc) assert c.x == oldx * 2 def test_distance_from_quantity(): from .. import RA, Dec, ICRSCoordinates, Distance ra = RA("4:08:15.162342", unit=u.hour) dec = Dec("-41:08:15.162342", unit=u.degree) c = ICRSCoordinates(ra, dec) # a Quantity object should be able to supply a distance q = 2 * u.kpc c.distance = q
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function from numpy import testing as npt from ... import units as u """ This includes tests for distances/cartesian points that are *not* in the API tests. Right now that's just regression tests. """ def test_distance_change(): from .. import RA, Dec, ICRSCoordinates, Distance ra = RA("4:08:15.162342", unit=u.hour) dec = Dec("-41:08:15.162342", unit=u.degree) c = ICRSCoordinates(ra, dec) c.distance = Distance(1, unit=u.kpc) oldx = c.x assert (oldx - 0.35284083171901953) < 1e-10 #now x should increase when the distance increases c.distance = Distance(2, unit=u.kpc) assert c.x == oldx * 2
Create lib dir if it doesn't exist
const ScopeParser = require("../lib/ScopeParser.js"); const fs = require('fs'); const path = require('path'); const beautify = require('js-beautify').js_beautify; const assert = require('assert'); let scope = new ScopeParser(); let srcDir = path.join(__dirname, "scopeSrc"); let libDir = path.join(__dirname, "scopeLib"); let expectDir = path.join(__dirname, "scopeExpect"); let srcFiles = fs.readdirSync(srcDir); const tests = []; srcFiles.forEach((f) => { let srcFilename = path.join(srcDir, f); let libFilename = path.join(libDir, f.replace(".sc", ".js")); let expectFilename = path.join(expectDir, f.replace(".sc", ".js")); //let astFilename = path.join(libDir, f.replace(".sc", ".json")); let srcCode = fs.readFileSync(srcFilename, "utf8"); let translation = scope.translate(srcCode); //let libAst = JSON.stringify(translation.ast, null, " "); //fs.writeFileSync(astFilename, libAst); if (!fs.existsSync(libDir)) { fs.mkdirSync(libDir); } fs.writeFileSync(libFilename, beautify(translation.js, {indent_size: 2})); tests.push({ program: require(libFilename), expectation: require(expectFilename) }); }); tests.forEach((obj) => { obj.expectation(assert, obj.program); });
const ScopeParser = require("../lib/ScopeParser.js"); const fs = require('fs'); const path = require('path'); const beautify = require('js-beautify').js_beautify; const assert = require('assert'); let scope = new ScopeParser(); let srcDir = path.join(__dirname, "scopeSrc"); let libDir = path.join(__dirname, "scopeLib"); let expectDir = path.join(__dirname, "scopeExpect"); let srcFiles = fs.readdirSync(srcDir); const tests = []; srcFiles.forEach((f) => { let srcFilename = path.join(srcDir, f); let libFilename = path.join(libDir, f.replace(".sc", ".js")); let expectFilename = path.join(expectDir, f.replace(".sc", ".js")); //let astFilename = path.join(libDir, f.replace(".sc", ".json")); let srcCode = fs.readFileSync(srcFilename, "utf8"); let translation = scope.translate(srcCode); //let libAst = JSON.stringify(translation.ast, null, " "); //fs.writeFileSync(astFilename, libAst); fs.writeFileSync(libFilename, beautify(translation.js, {indent_size: 2})); tests.push({ program: require(libFilename), expectation: require(expectFilename) }); }); tests.forEach((obj) => { obj.expectation(assert, obj.program); });
tests: Use only 1 IMAP connection by default We don't want to hammmer IMAP servers for the test series too much to avoid being locked out. We will need a few tests to test concurrent connections, but by default one connection should be fine. Signed-off-by: Sebastian Spaeth <98dcb2717ddae152d5b359c6ea97e4fe34a29d4c@SSpaeth.de>
#Constants, that don't rely on anything else in the module # Copyright (C) 2012- Sebastian Spaeth & contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from cStringIO import StringIO default_conf=StringIO("""[general] #will be set automatically metadata = accounts = test ui = quiet [Account test] localrepository = Maildir remoterepository = IMAP [Repository Maildir] Type = Maildir # will be set automatically during tests localfolders = [Repository IMAP] type=IMAP # Don't hammer the server with too many connection attempts: maxconnections=1 folderfilter= lambda f: f.startswith('INBOX.OLItest') """)
#Constants, that don't rely on anything else in the module # Copyright (C) 2012- Sebastian Spaeth & contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from cStringIO import StringIO default_conf=StringIO("""[general] #will be set automatically metadata = accounts = test ui = quiet [Account test] localrepository = Maildir remoterepository = IMAP [Repository Maildir] Type = Maildir # will be set automatically during tests localfolders = [Repository IMAP] type=IMAP folderfilter= lambda f: f.startswith('INBOX.OLItest') """)
Make the testing coverage great again
from django.test import TestCase from apps.curia_vista.models import Council class TestCouncil(TestCase): def setUp(self): self.T = Council(id=1, updated='2010-12-26T13:07:49Z', abbreviation='NR', code='RAT_1_', type='N', name='Nationalrat') self.T.save() def test___str__(self): self.assertEqual('Nationalrat', str(self.T)) def test_name_translation(self): from django.utils import translation translation.activate('fr') T, created = Council.objects.update_or_create(id=1, updated='2010-12-26T13:07:49Z', code='RAT_1_', type='N', defaults={'abbreviation': 'CN', 'name': 'Conseil national'}) self.assertFalse(created) self.assertEqual('Conseil national', T.name) translation.activate('de') self.assertEqual('Nationalrat', T.name)
from django.test import TestCase from apps.curia_vista.models import Council class TestCouncil(TestCase): def setUp(self): self.T = Council(id=1, updated='2010-12-26T13:07:49Z', abbreviation='NR', code='RAT_1_', type='N', name='Nationalrat') self.T.save() def test___str__(self): self.assertEqual('Nationalrat', self.T.name) def test_name_translation(self): from django.utils import translation translation.activate('fr') T, created = Council.objects.update_or_create(id=1, updated='2010-12-26T13:07:49Z', code='RAT_1_', type='N', defaults={'abbreviation': 'CN', 'name': 'Conseil national'}) self.assertFalse(created) self.assertEqual('Conseil national', T.name) translation.activate('de') self.assertEqual('Nationalrat', T.name)
Use alias instead of stub module for meteor/package imports. Aliases are lighter weight than stub module functions, and easier for the dynamic import(...) dependency traversal logic to understand.
function install(name, mainModule) { var meteorDir = {}; // Given a package name <name>, install a stub module in the // /node_modules/meteor directory called <name>.js, so that // require.resolve("meteor/<name>") will always return // /node_modules/meteor/<name>.js instead of something like // /node_modules/meteor/<name>/index.js, in the rare but possible event // that the package contains a file called index.js (#6590). if (typeof mainModule === "string") { // Set up an alias from /node_modules/meteor/<package>.js to the main // module, e.g. meteor/<package>/index.js. meteorDir[name + ".js"] = mainModule; } else { // back compat with old Meteor packages meteorDir[name + ".js"] = function (r, e, module) { module.exports = Package[name]; }; } meteorInstall({ node_modules: { meteor: meteorDir } }); } // This file will be modified during computeJsOutputFilesMap to include // install(<name>) calls for every Meteor package.
function install(name, mainModule) { var meteorDir = {}; // Given a package name <name>, install a stub module in the // /node_modules/meteor directory called <name>.js, so that // require.resolve("meteor/<name>") will always return // /node_modules/meteor/<name>.js instead of something like // /node_modules/meteor/<name>/index.js, in the rare but possible event // that the package contains a file called index.js (#6590). if (mainModule) { meteorDir[name + ".js"] = [mainModule, function (require, e, module) { module.exports = require(mainModule); }]; } else { // back compat with old Meteor packages meteorDir[name + ".js"] = function (r, e, module) { module.exports = Package[name]; }; } meteorInstall({ node_modules: { meteor: meteorDir } }); } // This file will be modified during computeJsOutputFilesMap to include // install(<name>) calls for every Meteor package.
Make sure to reset alias when switching between characters if the new one has no alias
$(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if(gon.gallery[id].aliases !== undefined) { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>'); for(var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide().val(''); } } };
$(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if(gon.gallery[id].aliases !== undefined) { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>'); for(var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide(); } } };
Address group recipient link issue
import extract from 'flarum/common/utils/extract'; import username from 'flarum/common/helpers/username'; import User from 'flarum/common/models/User'; import Group from 'flarum/common/models/Group'; import LinkButton from 'flarum/common/components/LinkButton'; export default function recipientLabel(recipient, attrs = {}) { attrs.style = attrs.style || {}; attrs.className = 'RecipientLabel ' + (attrs.className || ''); attrs.href = extract(attrs, 'link'); let label; if (recipient instanceof User) { label = username(recipient); if (attrs.href) { attrs.title = recipient.username() || ''; attrs.href = app.route.user(recipient); } } else if (recipient instanceof Group) { return <span class={attrs.className}>{recipient.namePlural()}</span> } else { attrs.className += ' none'; label = app.translator.trans('fof-byobu.forum.labels.user_deleted'); } return LinkButton.component(attrs, label); }
import extract from 'flarum/common/utils/extract'; import username from 'flarum/common/helpers/username'; import User from 'flarum/common/models/User'; import Group from 'flarum/common/models/Group'; import LinkButton from 'flarum/common/components/LinkButton'; export default function recipientLabel(recipient, attrs = {}) { attrs.style = attrs.style || {}; attrs.className = 'RecipientLabel ' + (attrs.className || ''); attrs.href = extract(attrs, 'link'); let label; if (recipient instanceof User) { label = username(recipient); if (attrs.href) { attrs.title = recipient.username() || ''; attrs.href = app.route.user(recipient); } } else if (recipient instanceof Group) { label = recipient.namePlural(); } else { attrs.className += ' none'; label = app.translator.trans('fof-byobu.forum.labels.user_deleted'); } return LinkButton.component(attrs, label); }
Use empty string for install dir
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', 'Theano==0.8.2', ] with open('README.md', 'r') as f: readme = f.read() setup( name="wincast", version='0.0.1', url='https://github.com/kahnjw/wincast', author_email='thomas.welfley+djproxy@gmail.com', long_description=readme, license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=install_requires, data_files=[ ('', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']), ('', ['data/Xy.csv']) ] )
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', 'Theano==0.8.2', ] with open('README.md', 'r') as f: readme = f.read() setup( name="wincast", version='0.0.1', url='https://github.com/kahnjw/wincast', author_email='thomas.welfley+djproxy@gmail.com', long_description=readme, license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=install_requires, data_files=[ ('models', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']), ('data', ['data/Xy.csv']) ] )
Use the $extras argument as a $context parameter Useful for providing dynamic data while keeping the same $message for several events.
<?php namespace Guzzle\Log; use Monolog\Logger; /** * @deprecated * @codeCoverageIgnore */ class MonologLogAdapter extends AbstractLogAdapter { /** * syslog to Monolog mappings */ private static $mapping = array( LOG_DEBUG => Logger::DEBUG, LOG_INFO => Logger::INFO, LOG_WARNING => Logger::WARNING, LOG_ERR => Logger::ERROR, LOG_CRIT => Logger::CRITICAL, LOG_ALERT => Logger::ALERT ); public function __construct(Logger $logObject) { $this->log = $logObject; } public function log($message, $priority = LOG_INFO, $extras = array()) { $this->log->addRecord(self::$mapping[$priority], $message, $extras); } }
<?php namespace Guzzle\Log; use Monolog\Logger; /** * @deprecated * @codeCoverageIgnore */ class MonologLogAdapter extends AbstractLogAdapter { /** * syslog to Monolog mappings */ private static $mapping = array( LOG_DEBUG => Logger::DEBUG, LOG_INFO => Logger::INFO, LOG_WARNING => Logger::WARNING, LOG_ERR => Logger::ERROR, LOG_CRIT => Logger::CRITICAL, LOG_ALERT => Logger::ALERT ); public function __construct(Logger $logObject) { $this->log = $logObject; } public function log($message, $priority = LOG_INFO, $extras = array()) { $this->log->addRecord(self::$mapping[$priority], $message); } }
Add git add . to bold pattern
package com.todoist.markup; import java.util.regex.Pattern; class Patterns { private static final String PATTERN_BASE = "%s\\s*((?!%s).+?)\\s*%s"; public static final Pattern HEADER = Pattern.compile("^\\*\\s+"); public static final Pattern BOLD = Pattern.compile(PATTERN_BASE.replaceAll("%s", "(?:__|!!|\\\\*\\\\*)")); public static final Pattern ITALIC = Pattern.compile(PATTERN_BASE.replaceAll("%s", "[_\\*]")); public static final Pattern INLINE_CODE = Pattern.compile(PATTERN_BASE.replaceAll("%s", "`")); public static final Pattern CODE_BLOCK = Pattern.compile(PATTERN_BASE.replaceAll("%s", "`{3}"), Pattern.DOTALL); public static final Pattern LINK = Pattern.compile("((?:[a-zA-Z]+)://[^\\s]+)(?:\\s+\\(([^)]+)\\))?"); public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]"); public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]"); public static final Pattern THUNDERBIRD = Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]"); }
package com.todoist.markup; import java.util.regex.Pattern; class Patterns { private static final String PATTERN_BASE = "%s\\s*((?!%s).+?)\\s*%s"; public static final Pattern HEADER = Pattern.compile("^\\*\\s+"); public static final Pattern BOLD = Pattern.compile(PATTERN_BASE.replaceAll("%s", "(?:__|\\\\*\\\\*)")); public static final Pattern ITALIC = Pattern.compile(PATTERN_BASE.replaceAll("%s", "[_\\*]")); public static final Pattern INLINE_CODE = Pattern.compile(PATTERN_BASE.replaceAll("%s", "`")); public static final Pattern CODE_BLOCK = Pattern.compile(PATTERN_BASE.replaceAll("%s", "`{3}"), Pattern.DOTALL); public static final Pattern LINK = Pattern.compile("((?:[a-zA-Z]+)://[^\\s]+)(?:\\s+\\(([^)]+)\\))?"); public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]"); public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]"); public static final Pattern THUNDERBIRD = Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]"); }
Add error handling in case nvidia plugin daemon is not running
#!/usr/bin/env python import requests import yaml # query nvidia docker plugin for the command-line parameters to use with the # `docker run` command try: response = requests.get('http://localhost:3476/docker/cli/json') except requests.exceptions.ConnectionError, e: print('Cannot connect to the nvidia docker plugin. Did you install it? Is the plugin daemon running on this host?') raise e docker_cli_params = response.json() devices = docker_cli_params['Devices'] volumes = docker_cli_params['Volumes'] # load the template docker compose file to extend the configuration of our # DTK development container and make it GPU-aware with open('docker-compose.template.yml', 'r') as fin: config = yaml.load(fin) # add devices and volumes configuration options to the template config['services']['dtk_dev']['devices'] = devices config['services']['dtk_dev']['volumes'] = volumes config['volumes'] = {} config['volumes'][volumes[0].split(':')[0]] = {'external': True} # write out the extension of the basic DTK docker compose file with open('docker-compose.yml', 'w') as fout: fout.write(yaml.safe_dump(config, default_flow_style=False))
#!/usr/bin/env python import requests import yaml # query nvidia docker plugin for the command-line parameters to use with the # `docker run` command response = requests.get('http://localhost:3476/docker/cli/json') docker_cli_params = response.json() devices = docker_cli_params['Devices'] volumes = docker_cli_params['Volumes'] # load the template docker compose file to extend the configuration of our # DTK development container and make it GPU-aware with open('docker-compose.template.yml', 'r') as fin: config = yaml.load(fin) # add devices and volumes configuration options to the template config['services']['dtk_dev']['devices'] = devices config['services']['dtk_dev']['volumes'] = volumes config['volumes'] = {} config['volumes'][volumes[0].split(':')[0]] = {'external': True} # write out the extension of the basic DTK docker compose file with open('docker-compose.yml', 'w') as fout: fout.write(yaml.safe_dump(config, default_flow_style=False))
Add input for numeric measures
// import React and Redux dependencies var React = require('react'); var connect = require('react-redux').connect; var _ = require('underscore'); var bindActionCreators = require('redux').bindActionCreators; var Immutable = require('immutable'); var MeasureActions = require('../../actions/Measures'); function mapStatetoProps (state, ownProps) { return { unit: state.Measures.getIn([ownProps.measureId, 'unit']), }; } function mapDispatchtoProps (dispatch) { return { actions: bindActionCreators(MeasureActions, dispatch) }; } var MeasureNumeric = React.createClass({ setUnit: function () { this.props.actions.setUnit(this.refs.unit.value, this.props.measureId); }, render: function () { return ( <div> <label> Choose Unit<input ref="unit" type="text" value={this.props.unit} onChange={this.setUnit} /> </label> </div> ); } }); module.exports = connect(mapStatetoProps, mapDispatchtoProps)(MeasureNumeric);
// import React and Redux dependencies var React = require('react'); var connect = require('react-redux').connect; var _ = require('underscore'); var bindActionCreators = require('redux').bindActionCreators; var Immutable = require('immutable'); // import actions var MeasureActions = require('../../actions/Measures'); var Actions = _.extend(MeasureActions); function mapStatetoProps (state, ownProps) { return { unit: state.Measures.getIn([ownProps.measureId, 'unit']), }; } function mapDispatchtoProps (dispatch) { return { actions: bindActionCreators(Actions, dispatch) }; } var MeasureNumeric = React.createClass({ handleChange: function () { this.props.actions.setUnit(this.refs.unit.value, this.props.measureId); }, render: function () { return ( <div> <input ref="unit" type="text" onChange={this.handleChange}/> <div>Current unit: {this.props.unit} </div> </div> ); } }); module.exports = connect(mapStatetoProps, mapDispatchtoProps)(MeasureNumeric);
Remove setup_log function from misc init (no longer present)
""" =============================== Misc (:mod:`macroeco.misc`) =============================== This module contains miscellaneous functions that support the functions of other modules of macroeco. Support Functions ================= .. autosummary:: :toctree: generated/ log_start_end inherit_docstring_from doc_sub check_parameter_file """ """ Data Formatting Functions ========================= .. autosummary:: :toctree: generated/ data_read_write format_dense """ from .misc import (log_start_end, _thread_excepthook, inherit_docstring_from, doc_sub, check_parameter_file) from .rcparams import ggplot_rc from .format_data import (data_read_write, format_dense) _thread_excepthook() # Make desktop app catch and log sys except from thread
""" =============================== Misc (:mod:`macroeco.misc`) =============================== This module contains miscellaneous functions that support the functions of other modules of macroeco. Support Functions ================= .. autosummary:: :toctree: generated/ setup_log log_start_end inherit_docstring_from doc_sub """ """ Data Formatting Functions ========================= .. autosummary:: :toctree: generated/ data_read_write format_dense """ from .misc import (log_start_end, _thread_excepthook, inherit_docstring_from, doc_sub, check_parameter_file) from .rcparams import ggplot_rc from .format_data import (data_read_write, format_dense) _thread_excepthook() # Make desktop app catch and log sys except from thread
Refactor a test into its own "given" test class
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import ComposedAssertion from ..uri import URI # There are three URIs that I need to use: # # http://catalog.hathitrust.org/api/volumes/brief/oclc/[OCLC].json # http://mirlyn-aleph.lib.umich.edu/cgi-bin/bc2meta?id=[BARCODE]&type=bc&schema=marcxml # http://www.worldcat.org/webservices/catalog/content/libraries/[OCLC]?wskey=[WC_KEY]&format=json&maximumLibraries=50 class URITest (unittest.TestCase): def test_null_uri_yields_empty_string (self): uri = URI(None) assert_that(uri(), is_(equal_to(""))) def test_simple_uri_yields_itself (self): uri = URI("hello") assert_that(uri(), is_(equal_to("hello"))) class GivenEmptyStrURI (unittest.TestCase): def setUp (self): self.uri = URI("") def test_when_called_without_args_yields_empty_str (self): assert_that(self.uri(), is_(equal_to("")))
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import ComposedAssertion from ..uri import URI # There are three URIs that I need to use: # # http://catalog.hathitrust.org/api/volumes/brief/oclc/[OCLC].json # http://mirlyn-aleph.lib.umich.edu/cgi-bin/bc2meta?id=[BARCODE]&type=bc&schema=marcxml # http://www.worldcat.org/webservices/catalog/content/libraries/[OCLC]?wskey=[WC_KEY]&format=json&maximumLibraries=50 class URITest (unittest.TestCase): def test_null_uri_yields_empty_string (self): uri = URI(None) assert_that(uri(), is_(equal_to(""))) def test_empty_uri_yields_empty_string (self): uri = URI("") assert_that(uri(), is_(equal_to(""))) def test_simple_uri_yields_itself (self): uri = URI("hello") assert_that(uri(), is_(equal_to("hello")))
db: Update db host to mongo
import json import pymongo import praw from pymongo import MongoClient client = MongoClient("mongo") db = client.reddit posts = db.data posts.create_index([("text", pymongo.TEXT), ("subreddit", pymongo.ASCENDING), ("created_utc", pymongo.DESCENDING)]); print "Configuring database" def save(obj): toInsert = {} toInsert["id"] = obj.id toInsert["created_utc"] = obj.created_utc toInsert["subreddit"] = str(obj.subreddit) if type(obj) is praw.objects.Submission: toInsert["text"] = obj.title print "Saving a thread" else: toInsert["text"] = obj.body print "Saving a comment" posts.insert_one(toInsert) def get(obj): subreddit = obj["subreddit"] from_time = int(obj["from_time"]) to_time = int(obj["to_time"]) keyword = obj["keyword"] query = {"subreddit": subreddit, "created_utc": {"$gte": from_time, "$lte": to_time}}; if not keyword is None: query["$text"] = {"$search": keyword} return posts.find(query)
import json import pymongo import praw from pymongo import MongoClient client = MongoClient() db = client.reddit posts = db.data posts.create_index([("text", pymongo.TEXT), ("subreddit", pymongo.ASCENDING), ("created_utc", pymongo.DESCENDING)]); print "Configuring database" def save(obj): toInsert = {} toInsert["id"] = obj.id toInsert["created_utc"] = obj.created_utc toInsert["subreddit"] = str(obj.subreddit) if type(obj) is praw.objects.Submission: toInsert["text"] = obj.title print "Saving a thread" else: toInsert["text"] = obj.body print "Saving a comment" posts.insert_one(toInsert) def get(obj): subreddit = obj["subreddit"] from_time = int(obj["from_time"]) to_time = int(obj["to_time"]) keyword = obj["keyword"] query = {"subreddit": subreddit, "created_utc": {"$gte": from_time, "$lte": to_time}}; if not keyword is None: query["$text"] = {"$search": keyword} return posts.find(query)
Add a lower layer to the drawing manager
var p; var drawings = []; var lowerLayer = []; var DrawingManager = function (p5Sketch) { p = p5Sketch; }; DrawingManager.prototype.add = function (drawing) { if (drawing.pulse.layer) { lowerLayer.unshift(drawing); } else { console.log('Added ' + drawing); drawings.unshift(drawing); } } DrawingManager.prototype.drawAll = function () { for (var i = lowerLayer.length - 1; i >= 0; i--) { lowerLayer[i].draw(p); if (lowerLayer[i].done()) { lowerLayer.splice(i, 1); } }; for (var i = drawings.length - 1; i >= 0; i--) { drawings[i].draw(p); if (drawings[i].done()) { drawings.splice(i, 1); } }; } DrawingManager.prototype.update = function (pulse, config) { for (var i = drawings.length - 1; i >= 0; i--) { if (drawings[i].pulse.name === pulse.name) { drawings[i].update(p, pulse, config); console.log("UPDATED pulse", drawings[i].pulse.name); } } } DrawingManager.prototype.clear = function () { drawings = []; } module.exports = DrawingManager;
var p; var drawings = []; var DrawingManager = function (p5Sketch) { p = p5Sketch; }; DrawingManager.prototype.add = function (drawing) { console.log('Added ' + drawing); drawings.unshift(drawing); } DrawingManager.prototype.drawAll = function () { for (var i = drawings.length - 1; i >= 0; i--) { drawings[i].draw(p); if (drawings[i].done()) { drawings.splice(i, 1); } }; } DrawingManager.prototype.update = function (pulse, config) { for (var i = drawings.length - 1; i >= 0; i--) { if (drawings[i].pulse.name === pulse.name) { drawings[i].update(p, pulse, config); console.log("UPDATED pulse", drawings[i].pulse.name); } } } DrawingManager.prototype.clear = function () { drawings = []; } module.exports = DrawingManager;
Fix Error in CDVFile on Android, wrong condition url
package com.makina.offline.mbtiles; import org.apache.cordova.CordovaResourceApi; import android.content.Context; import android.net.Uri; /** * {@link IMBTilesActions} SQLite implementation. * * @author <a href="mailto:sebastien.grimault@makina-corpus.com">S. Grimault</a> */ public class MBTilesActionsCDVFileImpl extends MBTilesActionsGenDatabaseImpl { public MBTilesActionsCDVFileImpl(Context context, String url, CordovaResourceApi resourceApi) { super(context); if (url == null || url.length() <= 0) { if (FileUtils.checkExternalStorageState()) { url = "cdvfile://localhost/persistent/tiles/"; } } if (url != null) { Uri fileURL = resourceApi.remapUri(Uri.parse(url)); mDirectory = fileURL.getPath(); } } }
package com.makina.offline.mbtiles; import org.apache.cordova.CordovaResourceApi; import android.content.Context; import android.net.Uri; /** * {@link IMBTilesActions} SQLite implementation. * * @author <a href="mailto:sebastien.grimault@makina-corpus.com">S. Grimault</a> */ public class MBTilesActionsCDVFileImpl extends MBTilesActionsGenDatabaseImpl { public MBTilesActionsCDVFileImpl(Context context, String url, CordovaResourceApi resourceApi) { super(context); if (url != null && url.length() > 0) { if (FileUtils.checkExternalStorageState()) { url = "cdvfile://localhost/persistent/tiles/"; } } if (url != null) { Uri fileURL = resourceApi.remapUri(Uri.parse(url)); mDirectory = fileURL.getPath(); } } }
Move mobile menu functions into object
require('./mobile-menu.sass'); document.addEventListener('DOMContentLoaded', () => { const menuButton = document.querySelector('.top-bar button.ion-md-menu'); const menuElem = document.getElementById('mobile-menu'); const topBar = document.getElementsByClassName('top-bar')[0]; const menuLinks = menuElem.getElementsByTagName('a'); window.mobileMenu = { open: () => { menuElem.style.display = 'block'; menuButton.classList.add('open'); menuElem.classList.add('open'); topBar.classList.add('mobile-menu-open'); for (let i = 0; i < menuLinks.length; i += 1) { // Use staggered delay for fading in menu links while opening setTimeout(() => { menuLinks[i].classList.add('visible'); }, 250 * i); } }, close: () => { menuButton.classList.remove('open'); menuElem.classList.remove('open'); topBar.classList.remove('mobile-menu-open'); setTimeout(() => { menuElem.style.display = 'none'; }, 500); for (let i = 0; i < menuLinks.length; i += 1) { menuLinks[i].classList.remove('visible'); } }, toggle: () => { if (menuElem.classList.contains('open')) window.mobileMenu.close(); else window.mobileMenu.open(); }, }; menuButton.addEventListener('click', window.mobileMenu.toggle); });
require('./mobile-menu.sass'); document.addEventListener('DOMContentLoaded', () => { const menuButton = document.querySelector('.top-bar button.ion-md-menu'); const menu = document.getElementById('mobile-menu'); const topBar = document.getElementsByClassName('top-bar')[0]; const menuLinks = menu.getElementsByTagName('a'); function openMenu() { menu.style.display = 'block'; menuButton.classList.add('open'); menu.classList.add('open'); topBar.classList.add('mobile-menu-open'); for (let i = 0; i < menuLinks.length; i += 1) { // Use staggered delay for fading in menu links while opening setTimeout(() => { menuLinks[i].classList.add('visible'); }, 250 * i); } } function closeMenu() { menuButton.classList.remove('open'); menu.classList.remove('open'); topBar.classList.remove('mobile-menu-open'); setTimeout(() => { menu.style.display = 'none'; }, 500); for (let i = 0; i < menuLinks.length; i += 1) { menuLinks[i].classList.remove('visible'); } } function toggleMenu() { if (menu.classList.contains('open')) closeMenu(); else openMenu(); } menuButton.addEventListener('click', toggleMenu); });
Fix the test to expect the new behaviour
<?php /** * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace Test\BackgroundJob; class Job extends \Test\TestCase { private $run = false; protected function setUp() { parent::setUp(); $this->run = false; } public function testRemoveAfterException() { $jobList = new DummyJobList(); $job = new TestJob($this, function () { throw new \Exception(); }); $jobList->add($job); $logger = $this->getMockBuilder('OCP\ILogger') ->disableOriginalConstructor() ->getMock(); $logger->expects($this->once()) ->method('error') ->with('Error while running background job: '); $this->assertCount(1, $jobList->getAll()); $job->execute($jobList, $logger); $this->assertTrue($this->run); $this->assertCount(1, $jobList->getAll()); } public function markRun() { $this->run = true; } }
<?php /** * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace Test\BackgroundJob; class Job extends \Test\TestCase { private $run = false; protected function setUp() { parent::setUp(); $this->run = false; } public function testRemoveAfterException() { $jobList = new DummyJobList(); $job = new TestJob($this, function () { throw new \Exception(); }); $jobList->add($job); $this->assertCount(1, $jobList->getAll()); $job->execute($jobList); $this->assertTrue($this->run); $this->assertCount(0, $jobList->getAll()); } public function markRun() { $this->run = true; } }
Remove superfluous use statement (thanks eclipse!!)
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2011, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ namespace lithium\data\source\database\adapter\my_sql; class Result extends \lithium\data\source\database\Result { public function prev() { if ($this->_current = $this->_prev()) { $this->_iterator--; return $this->_current; } } protected function _prev() { if ($this->_resource && $this->_iterator) { if(mysql_data_seek($this->_resource, $this->_iterator -1)) { return mysql_fetch_row($this->_resource); } } } protected function _next() { if ($this->_resource) { $inRange = $this->_iterator < mysql_num_rows($this->_resource); if($inRange && mysql_data_seek($this->_resource, $this->_iterator)) { return mysql_fetch_row($this->_resource); } } } protected function _close() { if ($this->_resource) { mysql_free_result($this->_resource); } } } ?>
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2011, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ namespace lithium\data\source\database\adapter\my_sql; use lithium\data\source\database; class Result extends \lithium\data\source\database\Result { public function prev() { if ($this->_current = $this->_prev()) { $this->_iterator--; return $this->_current; } } protected function _prev() { if ($this->_resource && $this->_iterator) { if(mysql_data_seek($this->_resource, $this->_iterator -1)) { return mysql_fetch_row($this->_resource); } } } protected function _next() { if ($this->_resource) { $inRange = $this->_iterator < mysql_num_rows($this->_resource); if($inRange && mysql_data_seek($this->_resource, $this->_iterator)) { return mysql_fetch_row($this->_resource); } } } protected function _close() { if ($this->_resource) { mysql_free_result($this->_resource); } } } ?>
Add abstact methods for config
<?php namespace Peast\Syntax; abstract class Config { abstract public function getIdRegex($part = false); abstract public function getSymbols(); abstract public function getWhitespaces(); abstract public function getLineTerminators(); abstract public function getLineTerminatorsSequences(); protected $compiledUnicodeArray = array(); protected function cachedCompiledUnicodeArray($name) { if (!isset($this->cachedCompiledUnicodeArray[$name])) { $this->cachedCompiledUnicodeArray[$name] = array_map( array($this, "handleUnicode"), $this->$name ); } return $this->cachedCompiledUnicodeArray[$name]; } protected function handleUnicode($num) { return is_string($num) ? $num : Utils::unicodeToUtf8($num); } }
<?php namespace Peast\Syntax; abstract class Config { protected $compiledUnicodeArray = array(); protected function cachedCompiledUnicodeArray($name) { if (!isset($this->cachedCompiledUnicodeArray[$name])) { $this->cachedCompiledUnicodeArray[$name] = array_map( array($this, "handleUnicode"), $this->$name ); } return $this->cachedCompiledUnicodeArray[$name]; } protected function handleUnicode($num) { return is_string($num) ? $num : Utils::unicodeToUtf8($num); } }
Add utility methods to Languages object
import Settings from 'utils/Settings'; import cs from './lang/cs'; import en_gb from './lang/en-gb'; import en_us from './lang/en-us'; import es from './lang/es'; import nl from './lang/nl'; import sk from './lang/sk'; const ALL = [ cs, en_gb, en_us, es, nl, sk ]; function getAvailable() { return ALL.slice(); } function getSelectedLanguageCode() { return Settings.get().then(({ language }) => language); } function find(languageCode) { if (!languageCode) return null; const normalisedLanguageCode = languageCode.toLowerCase().replace('_', '-'); const exactMatch = ALL.find(({ code }) => code === normalisedLanguageCode); if (exactMatch) return exactMatch; const [majorLanguageCode] = normalisedLanguageCode.split(/-/); const majorMatch = ALL.find(({ code }) => code.split('-').shift() === majorLanguageCode); if (majorMatch) return majorMatch; return null; } function getFacebookLanguageCode() { return document.documentElement.getAttribute('lang'); } function getBrowserLanguageCode() { return navigator.language; } function getFallbackLanguageCode() { return 'en-gb'; } function getFirstSupportedFallbackLanguageCode() { const facebookLanguageCode = getFacebookLanguageCode(); const browserLanguageCode = getBrowserLanguageCode(); const fallbackLanguageCode = getFallbackLanguageCode(); const languageCodes = [facebookLanguageCode, browserLanguageCode, fallbackLanguageCode]; return languageCodes.find(languageCode => !!find(languageCode)); } export default { find, getAvailable, getBrowserLanguageCode, getFacebookLanguageCode, getFallbackLanguageCode, getSelectedLanguageCode, getFirstSupportedFallbackLanguageCode };
import Settings from 'utils/Settings'; import cs from './lang/cs'; import en_gb from './lang/en-gb'; import en_us from './lang/en-us'; import es from './lang/es'; import nl from './lang/nl'; import sk from './lang/sk'; const ALL = [ cs, en_gb, en_us, es, nl, sk ]; function getAvailable() { return ALL.slice(); } function getSelected() { return Settings.get().then(({ language }) => language); } function find(languageCode) { const majorLanguageCode = languageCode.split(/-_/).shift().toLowerCase(); return ALL.find(({ code }) => code === majorLanguageCode); } function detect(document) { const siteLanguageCode = document.documentElement.getAttribute('lang'); const navigatorLanguageCode = navigator.language; const detectedlanguage = find(siteLanguageCode) || find(navigatorLanguageCode) || find('en'); return detectedlanguage || null; } export default { detect, find, getAvailable, getSelected };
Fix the python-windows installer generator by making it include the .dll files in the installer. That list originally consisted only of "*.dll". When the build system was modified to generate .pyd files for the binary modules, it was changed to "*.pyd". The Subversion libraries and the dependencies are still .dll files, though, so "*.dll" needs to be brought back. * packages/python-windows/setup.py: Add *.dll to the list of package data. Patch by: <DXDragon@yandex.ru> git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@878116 13f79535-47bb-0310-9956-ffa450edef68
#!/usr/bin/env python # ==================================================================== # Copyright (c) 2006 CollabNet. All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://subversion.tigris.org/license-1.html. # If newer versions of this license are posted there, you may use a # newer version instead, at your option. # # This software consists of voluntary contributions made by many # individuals. For exact contribution history, see the revision # history and logs, available at http://subversion.tigris.org/. # ==================================================================== from distutils.core import setup setup (name = "svn-python", description = "Subversion Python Bindings", maintainer = "Subversion Developers <dev@subversion.tigris.org>", url = "http://subversion.tigris.org", version = "1.4.0", packages = ["libsvn", "svn"], package_data = {"libsvn": ["*.dll", "*.pyd"]})
#!/usr/bin/env python # ==================================================================== # Copyright (c) 2006 CollabNet. All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://subversion.tigris.org/license-1.html. # If newer versions of this license are posted there, you may use a # newer version instead, at your option. # # This software consists of voluntary contributions made by many # individuals. For exact contribution history, see the revision # history and logs, available at http://subversion.tigris.org/. # ==================================================================== from distutils.core import setup setup (name = "svn-python", description = "Subversion Python Bindings", maintainer = "Subversion Developers <dev@subversion.tigris.org>", url = "http://subversion.tigris.org", version = "1.4.0", packages = ["libsvn", "svn"], package_data = {"libsvn": ["*.pyd"]})
Add mod selection to the search command
"""Package command line interface.""" import curses import click from .curse import Game, Mod from .tui import select_mod # Static data MINECRAFT = {'id': 432, 'name': 'Minecraft'} @click.group() def cli(): """Minecraft Curse CLI client.""" # Initialize terminal for querying curses.setupterm() @cli.command() @click.option( '--refresh', is_flag=True, default=False, help='Force refreshing of search data.' ) @click.argument('text', nargs=-1, type=str) def search(refresh, text): """Search for TEXT in mods on CurseForge.""" if not text: raise SystemExit('No text to search for!') mc = Game(**MINECRAFT) text = ' '.join(text) refresh = refresh or not mc.have_fresh_data() if refresh: click.echo('Refreshing search data, please wait…', err=True) mc.refresh_data() found = Mod.search(mc.database.session(), text) title = 'Search results for "{}"'.format(text) instructions = 'Choose mod to open its project page, or press [q] to quit.' chosen = select_mod(found, title, instructions) if chosen is not None: project_url_fmt = 'https://www.curseforge.com/projects/{mod.id}/' click.launch(project_url_fmt.format(mod=chosen))
"""Package command line interface.""" import click from .curse import Game, Mod # Static data MINECRAFT = {'id': 432, 'name': 'Minecraft'} @click.group() def cli(): """Minecraft Curse CLI client.""" @cli.command() @click.option( '--refresh', is_flag=True, default=False, help='Force refreshing of search data.' ) @click.argument('text', nargs=-1, type=str) def search(refresh, text): """Search for TEXT in mods on CurseForge.""" if not text: raise SystemExit('No text to search for!') mc = Game(**MINECRAFT) text = ' '.join(text) refresh = refresh or not mc.have_fresh_data() if refresh: click.echo('Refreshing search data, please wait…', err=True) mc.refresh_data() mod_fmt = '{0.name}: {0.summary}' for mod in Mod.search(mc.database.session(), text): click.echo(mod_fmt.format(mod)) # If run as a package, run whole cli cli()
Allow to reduce Operations in 2.0 and 3.0.0 to App.op
from __future__ import absolute_import from ..scan import Dispatcher from ..errs import SchemaError from ..spec.v3_0_0.objects import Operation as Op3 from ..spec.v2_0.objects import Operation as Op2 from ..utils import scope_compose from ..consts import private class TypeReduce(object): """ Type Reducer, collect Operation & Model spreaded in Resources put in a global accessible place. """ class Disp(Dispatcher): pass def __init__(self, sep=private.SCOPE_SEPARATOR): self.op = {} self.__sep = sep @Disp.register([Op3, Op2]) def _op(self, path, obj, _): scope = obj.tags[0] if obj.tags and len(obj.tags) > 0 else None name = obj.operationId if obj.operationId else None # in swagger 2.0, both 'operationId' and 'tags' are optional. # When 'operationId' is empty, it causes 'scope_compose' return something # duplicated with other Operations with the same tag. if not name: return new_scope = scope_compose(scope, name, sep=self.__sep) if new_scope: if new_scope in self.op.keys(): raise SchemaError('duplicated key found: ' + new_scope) self.op[new_scope] = obj
from __future__ import absolute_import from ..scan import Dispatcher from ..errs import SchemaError from ..spec.v3_0_0.objects import Operation from ..utils import scope_compose from ..consts import private class TypeReduce(object): """ Type Reducer, collect Operation & Model spreaded in Resources put in a global accessible place. """ class Disp(Dispatcher): pass def __init__(self, sep=private.SCOPE_SEPARATOR): self.op = {} self.__sep = sep @Disp.register([Operation]) def _op(self, path, obj, _): scope = obj.tags[0] if obj.tags and len(obj.tags) > 0 else None name = obj.operationId if obj.operationId else None # in swagger 2.0, both 'operationId' and 'tags' are optional. # When 'operationId' is empty, it causes 'scope_compose' return something # duplicated with other Operations with the same tag. if not name: return new_scope = scope_compose(scope, name, sep=self.__sep) if new_scope: if new_scope in self.op.keys(): raise SchemaError('duplicated key found: ' + new_scope) self.op[new_scope] = obj
Fix test, get username etc from env vars
package fi.helsinki.cs.tmc.cli.tmcstuff; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import fi.helsinki.cs.tmc.cli.Application; import fi.helsinki.cs.tmc.core.TmcCore; import fi.helsinki.cs.tmc.core.domain.Course; import org.junit.Before; import org.junit.Test; import java.util.Locale; public class TmcUtilTest { @Test public void findCouseIfItExists() { Application app; Course course; app = new Application(); app.createTmcCore(new Settings()); course = TmcUtil.findCourse(app.getTmcCore(), "demo"); assertNotNull(course); } @Test public void returnNullIfCourseWontExist() { Application app; Course course; app = new Application(); app.createTmcCore(new Settings()); course = TmcUtil.findCourse(app.getTmcCore(), "afuwhf"); assertNull(course); } }
package fi.helsinki.cs.tmc.cli.tmcstuff; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import fi.helsinki.cs.tmc.cli.Application; import fi.helsinki.cs.tmc.core.TmcCore; import fi.helsinki.cs.tmc.core.domain.Course; import org.junit.Before; import org.junit.Test; import java.util.Locale; public class TmcUtilTest { @Test public void findCouseIfItExists() { Application app; Course course; app = new Application(); course = TmcUtil.findCourse(app.getTmcCore(), "demo"); assertNotNull(course); } @Test public void returnNullIfCourseWontExist() { Application app; Course course; app = new Application(); course = TmcUtil.findCourse(app.getTmcCore(), "afuwhf"); assertNull(course); } }
Switch to ES5 style import
'use strict'; const path = require('path'); const gulp = require('gulp'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const plumber = require('gulp-plumber'); const babel = require('gulp-babel'); const del = require('del'); const run = require('gulp-run-command').default // Initialize the babel transpiler so ES2015 files gets compiled // when they're loaded require('babel-core/register'); gulp.task('static', () => gulp.src('**/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()) ); gulp.task('watch', () => { gulp.watch(['lib/**/*.js', 'test/**'], ['test']); }); gulp.task('test-coverage', [run('npm i nyc')]) gulp.task('test', ['test-coverage']) gulp.task('babel', ['clean'], () => gulp.src('lib/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist')) ); gulp.task('clean', () => del('dist')); gulp.task('prepublish', ['babel']); gulp.task('default', ['static', 'test']);
'use strict'; const path = require('path'); const gulp = require('gulp'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const plumber = require('gulp-plumber'); const babel = require('gulp-babel'); const del = require('del'); import run from "gulp-run-command"; // Initialize the babel transpiler so ES2015 files gets compiled // when they're loaded require('babel-core/register'); gulp.task('static', () => gulp.src('**/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()) ); gulp.task('watch', () => { gulp.watch(['lib/**/*.js', 'test/**'], ['test']); }); gulp.task('test-coverage', [run('npm i nyc')]) gulp.task('test', ['test-coverage']) gulp.task('babel', ['clean'], () => gulp.src('lib/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist')) ); gulp.task('clean', () => del('dist')); gulp.task('prepublish', ['babel']); gulp.task('default', ['static', 'test']);
Make network name and slug unique
import os from django.conf import settings from django.db import models from . import tenant if 'DJANGO_TENANT' in os.environ: tenant._set_for_tenant(os.environ['DJANGO_TENANT']) else: tenant._set_default() tenant._patch_table_names() class Tenant(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) network_name = models.CharField(max_length=20, unique=True) slug = models.SlugField(unique=True) @property def network_url(self): if settings.DEBUG: return 'http://%s.localhost:8080' % self.slug else: # Do the Site import here to avoid messing up the # monkeypatching of _meta.db_table from django.contrib.sites.models import Site return 'http://%s.%s' % (self.slug, Site.objects.get_current())
import os from django.conf import settings from django.db import models from . import tenant if 'DJANGO_TENANT' in os.environ: tenant._set_for_tenant(os.environ['DJANGO_TENANT']) else: tenant._set_default() tenant._patch_table_names() class Tenant(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) network_name = models.CharField(max_length=20) slug = models.SlugField() @property def network_url(self): if settings.DEBUG: return 'http://%s.localhost:8080' % self.slug else: # Do the Site import here to avoid messing up the # monkeypatching of _meta.db_table from django.contrib.sites.models import Site return 'http://%s.%s' % (self.slug, Site.objects.get_current())
Add close method to Raw class Fixes #10
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): """Clean up after ourselves when leaving the context manager.""" self.close() def close(self): """Free the underlying raw representation.""" libraw.libraw_close(self.data) def process(self, options=None): """ Unpack and process the raw data into something more usable. """ libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): libraw.libraw_close(self.data) def process(self, options=None): libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
Change cleanroom to use inner class.
import java.util.ArrayList; import java.lang.*; import java.math.BigDecimal; public class Student { int testVariable = 0; int __cleanVariable = 1; public int foo() { int ret = 4711 + testVariable; __cleanIteratorClass iterator = new __cleanIteratorClass(); return ret + iterator.getCleanVar(); } public double bar() { return 4711.0815 + testVariable; } public String baz() { return "I am nice."; } public String foobar() { return "I am dangerous."; } public static Object getNull() { return null; } public static String doNull() { return ""; } public static void recur(int i) { if(i > 0) recur(i-1); } public static void recur(int i, double d) { if(i > 0) recur(i-1); } public static void ioob() { int a[] = new int[10]; a[a.length + 32]++; } public Student() { } public Student(int x) { } private class __cleanIteratorClass { public int getCleanVar() { return __cleanVariable - 23; } } }
import java.util.ArrayList; import java.lang.*; import java.math.BigDecimal; public class Student { int testVariable = 0; int __cleanVariable = 0; public int foo() { return 4711 + __cleanVariable + testVariable; } public double bar() { return 4711.0815 + testVariable; } public String baz() { return "I am nice."; } public String foobar() { return "I am dangerous."; } public static Object getNull() { return null; } public static String doNull() { return ""; } public static void recur(int i) { if(i > 0) recur(i-1); } public static void recur(int i, double d) { if(i > 0) recur(i-1); } public static void ioob() { int a[] = new int[10]; a[a.length + 32]++; } public Student() { } public Student(int x) { } }
Fix issue that photo-scroller no longer works. This is caused by update to Bootstrap assets in Yii2.
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace app\assets; use yii\web\AssetBundle; /** * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class PropertyDetailAsset extends AssetBundle { public $sourcePath = '@app/views/property'; public $css = [ //'detail.css' ]; public $js = [ 'https://maps.googleapis.com/maps/api/js?key=AIzaSyD8Ls8RLsCalFAdQ48dPFQL-dEsgs0mF_E&libraries=geometry&sensor=false', 'map_helper.js', 'detail.js' ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapPluginAsset', ]; }
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace app\assets; use yii\web\AssetBundle; /** * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class PropertyDetailAsset extends AssetBundle { public $sourcePath = '@app/views/property'; public $css = [ //'detail.css' ]; public $js = [ 'https://maps.googleapis.com/maps/api/js?key=AIzaSyD8Ls8RLsCalFAdQ48dPFQL-dEsgs0mF_E&libraries=geometry&sensor=false', 'map_helper.js', 'detail.js' ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; }
ZON-3163: Hide elasticsearch fields of elasticsearch is not selected as query type.
(function ($) { var FIELDS = { 'centerpage': 'referenced_cp', 'channel': 'query', 'topicpage': 'referenced_topicpage', 'query': 'raw_query', 'elasticsearch-query': 'elasticsearch_raw_query', }; var show_matching_field = function(container, current_type) { $(Object.keys(FIELDS)).each( function(i, key) { var field = FIELDS[key]; var method = field == FIELDS[current_type] ? 'show' : 'hide'; var target = $('.fieldname-' + field, container).closest('fieldset'); target[method](); }); }; $(document).bind('fragment-ready', function(event) { var type_select = $('.fieldname-automatic_type select', event.__target); if (! type_select.length) { return; } show_matching_field(event.__target, type_select.val()); type_select.on( 'change', function() { show_matching_field(event.__target, $(this).val()); }); }); }(jQuery));
(function ($) { var FIELDS = { 'centerpage': 'referenced_cp', 'channel': 'query', 'topicpage': 'referenced_topicpage', 'query': 'raw_query' }; var show_matching_field = function(container, current_type) { $(['referenced_cp', 'query', 'referenced_topicpage', 'raw_query']).each( function(i, field) { var method = field == FIELDS[current_type] ? 'show' : 'hide'; var target = $('.fieldname-' + field, container).closest('fieldset'); target[method](); }); }; $(document).bind('fragment-ready', function(event) { var type_select = $('.fieldname-automatic_type select', event.__target); if (! type_select.length) { return; } show_matching_field(event.__target, type_select.val()); type_select.on( 'change', function() { show_matching_field(event.__target, $(this).val()); }); }); }(jQuery));
Remove brute and inconvinient star import
# need to install python-opencv, pygame, numpy, scipy, PIL import sys import pygame from pygame.locals import QUIT, KEYDOWN import opencv #this is important for capturing/displaying images from opencv import highgui def get_image(camera): img = highgui.cvQueryFrame(camera) # Add the line below if you need it (Ubuntu 8.04+) # im = opencv.cvGetMat(im) # convert Ipl image to PIL image return opencv.adaptors.Ipl2PIL(img) def render_flipped_camera(): camera = highgui.cvCreateCameraCapture(0) fps = 30.0 pygame.init() pygame.display.set_mode((640, 480)) pygame.display.set_caption("WebCam Demo") screen = pygame.display.get_surface() while True: events = pygame.event.get() for event in events: if event.type == QUIT or event.type == KEYDOWN: sys.exit(0) im = get_image(camera) pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode) screen.blit(pg_img, (0, 0)) pygame.display.flip() pygame.time.delay(int(1000 * 1.0/fps)) if __name__ == "__main__": render_flipped_camera()
# need to install python-opencv, pygame, numpy, scipy, PIL import sys import pygame from pygame.locals import * import opencv #this is important for capturing/displaying images from opencv import highgui def get_image(camera): img = highgui.cvQueryFrame(camera) # Add the line below if you need it (Ubuntu 8.04+) # im = opencv.cvGetMat(im) # convert Ipl image to PIL image return opencv.adaptors.Ipl2PIL(img) def render_flipped_camera(): camera = highgui.cvCreateCameraCapture(0) fps = 30.0 pygame.init() pygame.display.set_mode((640, 480)) pygame.display.set_caption("WebCam Demo") screen = pygame.display.get_surface() while True: events = pygame.event.get() for event in events: if event.type == QUIT or event.type == KEYDOWN: sys.exit(0) im = get_image(camera) pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode) screen.blit(pg_img, (0, 0)) pygame.display.flip() pygame.time.delay(int(1000 * 1.0/fps)) if __name__ == "__main__": render_flipped_camera()
Add conditional to sample java file
public class BasicArithmatic { private static final int constant = 10; public static int casualMethod() { return 1; } public static void main(String args) { int a = 4; int b = 2 + casualMethod(); if (true) { b += 1; } int sum = a + b; int product = a*b; int difference = a -b; int addImmediate = a + 2; int subImmediate = a - 2; //int addConstant = b * constant; //addConstant += 2; int multiplyImmediate = b * 0x05; int parenthesis = a + ( a + b ); int pemdasFull = (a + b) * 3 - 10; int pemdasFullAlternate = a + b * (3 - 10); int multipleParenthis = 1 + (a + (b - 5) * 2) * 7; //multiplyImmediate = multiplyImmediate << 1; //multiplyImmediate++; //boolean test = true | false; //CasualMethod(); //Sum(a, b); // DO NOT LEX /* Do not lex */ /* * Do not lex 2 */ // /**/ Do not lex 3 /* * * // */ // Strings are currently unsupported // String s = "/*LexAstring" + lex + "LexAstring*/ LexAstring"; } }
public class BasicArithmatic { private static final int constant = 10; public static int casualMethod() { return 1; } public static void main(String args) { int a = 4; int b = 2 + casualMethod(); int sum = a + b; int product = a*b; int difference = a -b; int addImmediate = a + 2; int subImmediate = a - 2; //int addConstant = b * constant; //addConstant += 2; int multiplyImmediate = b * 0x05; int parenthesis = a + ( a + b ); int pemdasFull = (a + b) * 3 - 10; int pemdasFullAlternate = a + b * (3 - 10); int multipleParenthis = 1 + (a + (b - 5) * 2) * 7; //multiplyImmediate = multiplyImmediate << 1; //multiplyImmediate++; //boolean test = true | false; //CasualMethod(); //Sum(a, b); // DO NOT LEX /* Do not lex */ /* * Do not lex 2 */ // /**/ Do not lex 3 /* * * // */ // Strings are currently unsupported // String s = "/*LexAstring" + lex + "LexAstring*/ LexAstring"; } }
Fix bug that closes stdout
package qpx import ( "bytes" "encoding/json" "io" "net/http" "os" ) func Cheapest(origin, destination, date string) (to tripOption, err error) { var ( res *http.Response f io.WriteCloser resp response buf = bytes.NewBuffer(nil) ) payload := newRequest(origin, destination, date) if f, err = logfile(); err != nil { return } defer func() { if f != os.Stdout { f.Close() } }() w := io.MultiWriter(buf, f) if err = json.NewEncoder(w).Encode(payload); err != nil { return } if res, err = http.Post(endpoint, "application/json", buf); err != nil { return } f.Write([]byte("===========================\n")) tee := io.TeeReader(res.Body, f) if err = json.NewDecoder(tee).Decode(&resp); err != nil { return } res.Body.Close() resp.sort() to = resp.Cheapest() return }
package qpx import ( "bytes" "encoding/json" "io" "net/http" ) func Cheapest(origin, destination, date string) (to tripOption, err error) { var ( res *http.Response f io.WriteCloser resp response buf = bytes.NewBuffer(nil) ) payload := newRequest(origin, destination, date) if f, err = logfile(); err != nil { return } defer f.Close() w := io.MultiWriter(buf, f) if err = json.NewEncoder(w).Encode(payload); err != nil { return } if res, err = http.Post(endpoint, "application/json", buf); err != nil { return } f.Write([]byte("===========================\n")) tee := io.TeeReader(res.Body, f) if err = json.NewDecoder(tee).Decode(&resp); err != nil { return } res.Body.Close() resp.sort() to = resp.Cheapest() return }
Remove image with link & media icons
// ==UserScript== // @name SFcomic Viewer // @namespace // @version 0.2.1 // @description Auto load comic picture. // @author AntonioTsai // @match http://comic.sfacg.com/* // @include http://comic.sfacg.com/* // @grant none // @downloadURL https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js // ==/UserScript== /** * picAy: The array store all image's url of the volume * hosts: The array store possible host * getHost(): Get the current host index */ (() => { const imgTable = document.querySelector("table tbody"); const tempTr = document.createElement("tr"); // Remove original image & social media icon imgTable.querySelectorAll('td').forEach((currentValue) => { currentValue.remove(); }) // generate all images for (var i = 0; i < picCount; i++) { var imgTr = tempTr.cloneNode(true); imgTr.appendChild(document.createElement("img")); imgTr.children[0].children[0].src = picAy[i]; imgTable.appendChild(imgTr); } })();
// ==UserScript== // @name SFcomic Viewer // @namespace // @version 0.2.1 // @description Auto load comic picture. // @author AntonioTsai // @match http://comic.sfacg.com/* // @include http://comic.sfacg.com/* // @grant none // @downloadURL https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js // ==/UserScript== /** * picAy: The array store all image's url of the volume * hosts: The array store possible host * getHost(): Get the current host index */ (() => { const imgTable = document.querySelector("table tbody"); const tempTr = document.createElement("tr"); // remove original image & social media icon var tr = document.querySelector("tr"); tr.parentElement.removeChild(tr); // generate all images for (var i = 0; i < picCount; i++) { var imgTr = tempTr.cloneNode(true); imgTr.appendChild(document.createElement("img")); imgTr.children[0].children[0].src = picAy[i]; imgTable.appendChild(imgTr); } })();
Modify not to push state to history on posting message.
define([ 'underscore', 'controllers/ApplicationController', 'models/Thread', 'models/Message', 'utils/Utils' ], function(_, ApplicationController, Thread, Message, Utils) { var MessageController = Utils.inherit(ApplicationController, function(networkAgent) { ApplicationController.call(this, networkAgent); }); MessageController.prototype.create = function(args, format) { var self = this; Message.new(args).exists(function(exists) { Message.create(args, function(message, error) { if (error) { throw new Error("Failed to create message:", error); } Utils.debug("Created or updated message:", message.id); if (!exists) { Utils.debug("Spreading message:", message.id); self._networkAgent.spreadMessage(message.toJson()); } self._response(format, { html: function() { WebRtcBbs.context.routing.to('/thread/show', {threadId: args.threadId}, true); } }); }); }); }; return MessageController; });
define([ 'underscore', 'controllers/ApplicationController', 'models/Thread', 'models/Message', 'utils/Utils' ], function(_, ApplicationController, Thread, Message, Utils) { var MessageController = Utils.inherit(ApplicationController, function(networkAgent) { ApplicationController.call(this, networkAgent); }); MessageController.prototype.create = function(args, format) { var self = this; Message.new(args).exists(function(exists) { Message.create(args, function(message, error) { if (error) { throw new Error("Failed to create message:", error); } Utils.debug("Created or updated message:", message.id); if (!exists) { Utils.debug("Spreading message:", message.id); self._networkAgent.spreadMessage(message.toJson()); } self._response(format, { html: function() { WebRtcBbs.context.routing.to('/thread/show', {threadId: args.threadId}); } }); }); }); }; return MessageController; });
Modify presentation of CSS strings
'use strict'; function CSSStyleDeclaration(inline) { if (inline) { inline.trim().split(';').forEach(function(statement) { var parts = statement.split(':'); if (parts.length !== 2) { return; } this[parts[0].trim()] = parts[1].trim(); }, this); } } CSSStyleDeclaration.prototype.getPropertyValue = function(name) { if (Object.hasOwnProperty.call(this, name)) { return this[name]; } return null; }; CSSStyleDeclaration.prototype.setProperty = function(name, value) { if (name in this && !Object.hasOwnProperty.call(this, name)) { return; } this[name] = value.trim(); }; CSSStyleDeclaration.prototype.toString = function() { var str = Object.keys(this).map(function(name) { return name + ':' + this[name]; }, this).join(';'); if (str) { str += ';'; } return str; }; module.exports = CSSStyleDeclaration;
'use strict'; function CSSStyleDeclaration(inline) { if (inline) { inline.trim().split(';').forEach(function(statement) { var parts = statement.split(':'); if (parts.length !== 2) { return; } this[parts[0].trim()] = parts[1].trim(); }, this); } } CSSStyleDeclaration.prototype.getPropertyValue = function(name) { if (Object.hasOwnProperty.call(this, name)) { return this[name]; } return null; }; CSSStyleDeclaration.prototype.setProperty = function(name, value) { if (name in this && !Object.hasOwnProperty.call(this, name)) { return; } this[name] = value.trim(); }; CSSStyleDeclaration.prototype.toString = function() { return Object.keys(this).map(function(name) { return name + ': ' + this[name]; }, this).join(';'); }; module.exports = CSSStyleDeclaration;
Remove trailing slashes, add origin url to responses
import flask import flask_caching import flask_cors import main import slack app = flask.Flask(__name__) cache = flask_caching.Cache(app, config={"CACHE_TYPE": "simple"}) cors = flask_cors.CORS(app, resources={r"/*": {"origins": "*"}}) app.register_blueprint(slack.blueprint, url_prefix="/api/slack") @app.route("/api") @cache.cached(timeout=10800) def list_entities(): return flask.jsonify({"entities": ["restaurant"], "url": flask.url_for("list_entities", _external=True)}) @app.route("/api/restaurant") @cache.cached(timeout=10800) def list_restaurants(): return flask.jsonify({"restaurants": main.list_restaurants(), "url": flask.url_for("list_restaurants", _external=True)}) @app.route("/api/restaurant/<name>") @cache.cached(timeout=10800) def get_restaurant(name): data = dict(main.get_restaurant(name)) if not data: abort(status=404) data["menu"] = [{"dish": entry} for entry in data["menu"]] return flask.jsonify({"restaurant": data, "url": flask.url_for("get_restaurant", name=name, _external=True)})
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main import slack app = Flask(__name__) cache = Cache(app, config={"CACHE_TYPE": "simple"}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) app.register_blueprint(slack.blueprint, url_prefix="/api/slack") @app.route("/api/") @cache.cached(timeout=10800) def list_entities(): return jsonify({"entities": ["restaurant"]}) @app.route("/api/restaurant/") @cache.cached(timeout=10800) def list_restaurants(): return jsonify({"restaurants": main.list_restaurants()}) @app.route("/api/restaurant/<name>/") @cache.cached(timeout=10800) def get_restaurant(name): data = dict(main.get_restaurant(name)) if not data: abort(status=404) data["menu"] = [{"dish": entry} for entry in data["menu"]] return jsonify({"restaurant": data})
Use clear cart method from satchless https://github.com/mirumee/satchless/commit/3acaa8f6a27d9ab259a2d66fc3f7416a18fab1ad This reverts commit 2ad16c44adb20e9ba023e873149d67068504c34c.
from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item import ItemList, ClassifyingPartitioner from ..product.models import DigitalShip class ShippedGroup(ItemList): ''' Group for shippable products. ''' pass class DigitalGroup(ItemList): ''' Group for digital products. ''' pass class CartPartitioner(ClassifyingPartitioner): ''' Dividing cart into groups. ''' def classify(self, item): if isinstance(item.product, DigitalShip): return 'digital' return 'shippable' def get_partition(self, classifier, items): if classifier == 'digital': return DigitalGroup(items) return ShippedGroup(items) class Cart(cart.Cart): ''' Contains cart items. Serialized instance of cart is saved into django session. ''' timestamp = None billing_address = None def __unicode__(self): return pgettext( 'Shopping cart', 'Your cart (%(cart_count)s)') % {'cart_count': self.count()}
from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item import ItemList, ClassifyingPartitioner from ..product.models import DigitalShip class ShippedGroup(ItemList): ''' Group for shippable products. ''' pass class DigitalGroup(ItemList): ''' Group for digital products. ''' pass class CartPartitioner(ClassifyingPartitioner): ''' Dividing cart into groups. ''' def classify(self, item): if isinstance(item.product, DigitalShip): return 'digital' return 'shippable' def get_partition(self, classifier, items): if classifier == 'digital': return DigitalGroup(items) return ShippedGroup(items) class Cart(cart.Cart): ''' Contains cart items. Serialized instance of cart is saved into django session. ''' timestamp = None billing_address = None def __unicode__(self): return pgettext( 'Shopping cart', 'Your cart (%(cart_count)s)') % {'cart_count': self.count()} def clear(self): self._state = []
Trim whitespace from banner text before checking
(function (GOVUK) { "use strict"; var sendVirtualPageView = function() { var $element = $(this); var url = $element.data('url'); if (GOVUK.analytics && url){ GOVUK.analytics.trackPageview(url); } }; GOVUK.GDM.analytics.virtualPageViews = function() { var $flashMessage; $('[data-analytics=trackPageView]').each(sendVirtualPageView); if (GOVUK.GDM.analytics.location.pathname().match(/^\/suppliers\/opportunities\/\d+\/ask-a-question/) !== null) { $flashMessage = $('.banner-success-without-action .banner-message'); if ($flashMessage.text().replace(/^\s+|\s+$/g, '').match(/^Your question has been sent/) !== null) { GOVUK.analytics.trackPageview(GOVUK.GDM.analytics.location.href() + '?submitted=true'); } } }; })(window.GOVUK);
(function (GOVUK) { "use strict"; var sendVirtualPageView = function() { var $element = $(this); var url = $element.data('url'); if (GOVUK.analytics && url){ GOVUK.analytics.trackPageview(url); } }; GOVUK.GDM.analytics.virtualPageViews = function() { var $flashMessage; $('[data-analytics=trackPageView]').each(sendVirtualPageView); if (GOVUK.GDM.analytics.location.pathname().match(/^\/suppliers\/opportunities\/\d+\/ask-a-question/) !== null) { $flashMessage = $('.banner-success-without-action .banner-message'); if ($flashMessage.text().match(/^Your question has been sent/) !== null) { GOVUK.analytics.trackPageview(GOVUK.GDM.analytics.location.href() + '?submitted=true'); } } }; })(window.GOVUK);
Set default text when no description found
package fr.free.nrw.commons.nearby; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import fr.free.nrw.commons.R; import fr.free.nrw.commons.ViewHolder; import fr.free.nrw.commons.utils.ResourceUtils; public class NearbyViewHolder implements ViewHolder<Place> { @BindView(R.id.tvName) TextView tvName; @BindView(R.id.tvDesc) TextView tvDesc; @BindView(R.id.distance) TextView distance; @BindView(R.id.icon) ImageView icon; public NearbyViewHolder(View view) { ButterKnife.bind(this, view); } @Override public void bindModel(Context context, Place place) { // Populate the data into the template view using the data object tvName.setText(place.name); String description = place.description; if ( description == null || description.isEmpty() || description.equals("?")) { description = "No Description Found"; } tvDesc.setText(description); distance.setText(place.distance); icon.setImageResource(ResourceUtils.getDescriptionIcon(place.description)); } }
package fr.free.nrw.commons.nearby; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import fr.free.nrw.commons.R; import fr.free.nrw.commons.ViewHolder; import fr.free.nrw.commons.utils.ResourceUtils; public class NearbyViewHolder implements ViewHolder<Place> { @BindView(R.id.tvName) TextView tvName; @BindView(R.id.tvDesc) TextView tvDesc; @BindView(R.id.distance) TextView distance; @BindView(R.id.icon) ImageView icon; public NearbyViewHolder(View view) { ButterKnife.bind(this, view); } @Override public void bindModel(Context context, Place place) { // Populate the data into the template view using the data object tvName.setText(place.name); tvDesc.setText(place.description); distance.setText(place.distance); icon.setImageResource(ResourceUtils.getDescriptionIcon(place.description)); } }
Return result and whitespace fixes.
package interdroid.vdb.persistence.ui; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import interdroid.vdb.R; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceActivity; public class VdbPreferences extends PreferenceActivity { private static final Logger logger = LoggerFactory.getLogger(VdbPreferences.class); public static final String PREFERENCES_NAME = "interdroid.vdb_preferences"; // If you change these change the android:key value in vdb_preferences.xml public static final String PREF_SHARING_ENABLED = "sharingEnabled"; public static final String PREF_NAME = "name"; public static final String PREF_EMAIL = "email"; // TODO: Add listener to synch toggle and start and stop service based on that. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.vdb_preferences); logger.debug("Storing preferences to: " + getPreferenceManager().getSharedPreferencesName()); SharedPreferences prefs = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE); if (prefSet(prefs, PREF_NAME) && prefSet(prefs, PREF_EMAIL)) { setResult(RESULT_OK); } else { setResult(RESULT_CANCELED); } } private boolean prefSet(SharedPreferences prefs, String prefName) { // Has preference which is not null or the empty string return prefs.contains(prefName) && null != prefs.getString(prefName, null) && !"".equals(prefs.getString(prefName, "")); } }
package interdroid.vdb.persistence.ui; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import interdroid.vdb.R; import android.os.Bundle; import android.preference.PreferenceActivity; public class VdbPreferences extends PreferenceActivity { private static final Logger logger = LoggerFactory .getLogger(VdbPreferences.class); public static final String PREFERENCES_NAME = "interdroid.vdb_preferences"; // If you change these change the android:key value in vdb_preferences.xml public static final String PREF_SHARING_ENABLED = "sharingEnabled"; public static final String PREF_NAME = "name"; public static final String PREF_EMAIL = "email"; // TODO: Add listener to synch toggle and start and stop service based on that. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.vdb_preferences); logger.debug("Storing preferences to: " + getPreferenceManager().getSharedPreferencesName()); } }
Add another example radio station: '4 Ever Zeppelin'.
exports.stations = { "4 Ever Floyd": "http://67.205.85.183:5500", "4 Ever Zeppelin": "http://173.236.59.82:8330", "Feeling Floyd": "http://Streaming23.radionomy.com/FeelingFloyd", "KFRC": "http://2133.live.streamtheworld.com:80/KFRCFMCMP3", ".977 The Comedy Channel": "http://icecast3.977music.com/comedy" }; exports.random = function() { var keys = Object.keys(exports.stations); var key = keys[Math.floor(Math.random()*keys.length)]; return { name: key, url: exports.stations[key] }; } exports.fromName = function(name) { var regexp = new RegExp(name, "i"); for (var i in exports.stations) { if (regexp.test(i)) { return { name: i, url: exports.stations[i] }; } } }
exports.stations = { "4 Ever Floyd": "http://67.205.85.183:5500", "Feeling Floyd": "http://Streaming23.radionomy.com/FeelingFloyd", "KFRC": "http://2133.live.streamtheworld.com:80/KFRCFMCMP3", ".977 The Comedy Channel": "http://icecast3.977music.com/comedy" }; exports.random = function() { var keys = Object.keys(exports.stations); var key = keys[Math.floor(Math.random()*keys.length)]; return { name: key, url: exports.stations[key] }; } exports.fromName = function(name) { var regexp = new RegExp(name, "i"); for (var i in exports.stations) { if (regexp.test(i)) { return { name: i, url: exports.stations[i] }; } } }
Change to generic discord user to support N chats
package discord import ( "strings" "github.com/bwmarrin/discordgo" ) type dsMessage struct { *discordgo.Message session *discordgo.Session } func (d dsMessage) GroupID() string { return "discord" } func (d dsMessage) UserName() string { return d.Author.Username } func (d dsMessage) UserID() string { return d.Author.ID } func (d dsMessage) MessageID() string { return d.ID } func (d dsMessage) Text() string { modifiedText := d.Content for _, mention := range d.Mentions { replaceStr := "<@" + mention.ID + ">" modifiedText = strings.Replace(modifiedText, replaceStr, "@"+mention.Username, -1) } return modifiedText } func (d dsMessage) UserType() string { if d.Type == discordgo.MessageTypeDefault { return "user" } else { return "other" } }
package discord import ( "strings" "github.com/bwmarrin/discordgo" ) type dsMessage struct { *discordgo.Message session *discordgo.Session } func (d dsMessage) GroupID() string { return d.ChannelID } func (d dsMessage) UserName() string { return d.Author.Username } func (d dsMessage) UserID() string { return d.Author.ID } func (d dsMessage) MessageID() string { return d.ID } func (d dsMessage) Text() string { modifiedText := d.Content for _, mention := range d.Mentions { replaceStr := "<@" + mention.ID + ">" modifiedText = strings.Replace(modifiedText, replaceStr, "@"+mention.Username, -1) } return modifiedText } func (d dsMessage) UserType() string { if d.Type == discordgo.MessageTypeDefault { return "user" } else { return "other" } }
Make services only receive their related configs
from __future__ import absolute_import from os.path import abspath from os.path import dirname from flask import Flask, request import yaml import utils.config from services import find_services from comms import find_and_load_comms CONFIG_FOLDER = dirname(dirname(abspath(__file__))) application = Flask(__name__) @application.route('/<service>', methods=['GET', 'POST']) def receive_webhook(service): config = utils.config.load_config(CONFIG_FOLDER) services = find_services(config) comms = find_and_load_comms(config) print services print comms return services[service]( request, request.get_json(), comms, config[service] ).execute() if __name__ == '__main__': application.run(debug=True, host='0.0.0.0')
from __future__ import absolute_import from os.path import abspath from os.path import dirname from flask import Flask, request import yaml import utils.config from services import find_services from comms import find_and_load_comms CONFIG_FOLDER = dirname(dirname(abspath(__file__))) application = Flask(__name__) @application.route('/<service>', methods=['GET', 'POST']) def receive_webhook(service): config = utils.config.load_config(CONFIG_FOLDER) services = find_services(config) comms = find_and_load_comms(config) print services print comms return services[service]( request, request.get_json(), comms, config ).execute() if __name__ == '__main__': application.run(debug=True, host='0.0.0.0')
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var postcss = require('postcss') var cssstats = require('cssstats') var module = require('tachyons-display/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-display/tachyons-display.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_display.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/display/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/layout/display/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var postcss = require('postcss') var cssstats = require('cssstats') var display = require('tachyons-display/package.json') var displayCss = fs.readFileSync('node_modules/tachyons-display/tachyons-display.min.css', 'utf8') var displayObj = cssstats(displayCss) var displaySize = filesize(displayObj.gzipSize) var srcCSS = fs.readFileSync('./src/_display.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/display/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ displayVersion: display.version, displaySize: displaySize, displayObj: displayObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/layout/display/index.html', html)
Remove proxy configs for UxApplications
Ext.define('OppUI.view.uxDashboard.uxapplications.UxApplicationsModel', { extend: 'Ext.app.ViewModel', alias: 'viewmodel.uxapplications', data: { total: 10, totalApps: 20, activeTestsPerPage: 30, failures: 40, passing: 50 }, stores: { remoteUxApplications: { model: 'OppUI.model.uxDashboard.UxApplications', autoLoad: true, proxy: { type: 'ajax', url: 'https://localhost/uxsvc/v1/wpt/navigation', reader: { type: 'json' } }, listeners: { load: 'onRemoteUxApplicationsLoad' } } } });
Ext.define('OppUI.view.uxDashboard.uxapplications.UxApplicationsModel', { extend: 'Ext.app.ViewModel', alias: 'viewmodel.uxapplications', data: { total: 10, totalApps: 20, activeTestsPerPage: 30, failures: 40, passing: 50 }, stores: { remoteUxApplications: { model: 'OppUI.model.uxDashboard.UxApplications', autoLoad: true, proxy: { type: 'ajax', //url: 'http://roadrunner.roving.com/uxsvc/v2/rrux/wptNav', url: 'https://localhost/uxsvc/v1/wpt/navigation', cors: true, useDefaultXhrHeader: false, reader: { type: 'json' } }, listeners: { load: 'onRemoteUxApplicationsLoad' } } } });
Load localization file for the plugin
<?php /* Plugin Name: WooCommerce Komoju Gateway Plugin URI: https://komoju.com Description: Extends WooCommerce with Komoju gateway. Version: 0.1 Author: Komoju Author URI: https://komoju.com */ add_action('plugins_loaded', 'woocommerce_komoju_init', 0); function woocommerce_komoju_init() { if ( !class_exists( 'WC_Payment_Gateway' ) ) return; /** * Localisation */ load_textdomain( 'woocommerce', WP_PLUGIN_DIR.'/'.dirname( plugin_basename( __FILE__ ) ).'/lang/ja_JP.mo' ); require_once 'class-wc-gateway-komoju.php'; /** * Add the Gateway to WooCommerce **/ function woocommerce_add_komoju_gateway($methods) { $methods[] = 'WC_Gateway_Komoju'; return $methods; } add_filter('woocommerce_payment_gateways', 'woocommerce_add_komoju_gateway' ); }
<?php /* Plugin Name: WooCommerce Komoju Gateway Plugin URI: https://komoju.com Description: Extends WooCommerce with Komoju gateway. Version: 0.1 Author: Komoju Author URI: https://komoju.com */ add_action('plugins_loaded', 'woocommerce_komoju_init', 0); function woocommerce_komoju_init() { if ( !class_exists( 'WC_Payment_Gateway' ) ) return; /** * Localisation */ //load_plugin_textdomain('wc-komoju', false, dirname( plugin_basename( __FILE__ ) ) . '/languages'); require_once 'class-wc-gateway-komoju.php'; /** * Add the Gateway to WooCommerce **/ function woocommerce_add_komoju_gateway($methods) { $methods[] = 'WC_Gateway_Komoju'; return $methods; } add_filter('woocommerce_payment_gateways', 'woocommerce_add_komoju_gateway' ); }
Add positive test for search
# This Source Code Form is subjectfrom django import forms to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.home import HomePage class TestAvailableTasks(): @pytest.mark.nondestructive def test_assign_tasks(self, base_url, selenium, nonrepeatable_assigned_task, task, new_user): home_page = HomePage(selenium, base_url).open() home_page.login(new_user) available_tasks_page = home_page.click_available_tasks() # Check if assignable task is found home_page.search_for_task(task.name) assert len(available_tasks_page.available_tasks) home_page.search_for_task(nonrepeatable_assigned_task.name) assert len(available_tasks_page.available_tasks) == 0
# This Source Code Form is subjectfrom django import forms to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.home import HomePage class TestAvailableTasks(): @pytest.mark.nondestructive def test_assign_tasks(self, base_url, selenium, nonrepeatable_assigned_task, new_user): home_page = HomePage(selenium, base_url).open() home_page.login(new_user) available_tasks_page = home_page.click_available_tasks() home_page.search_for_task(nonrepeatable_assigned_task.name) assert len(available_tasks_page.available_tasks) == 0
Fix compile error due to class rename.
/* * Copyright 2013 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.api.internal.tasks.testing; import org.gradle.api.Task; import org.gradle.api.reporting.ConfigurableReport; import org.gradle.api.reporting.DirectoryReport; import org.gradle.api.reporting.internal.TaskGeneratedSingleDirectoryReport; import org.gradle.api.reporting.internal.TaskReportContainer; import org.gradle.api.tasks.testing.TestReports; public class DefaultTestReports extends TaskReportContainer<ConfigurableReport> implements TestReports { public DefaultTestReports(Task task) { super(ConfigurableReport.class, task); add(TaskGeneratedSingleDirectoryReport.class, "junitXml", task, null); add(TaskGeneratedSingleDirectoryReport.class, "html", task, "index.html"); } public DirectoryReport getHtml() { return (DirectoryReport) getByName("html"); } public DirectoryReport getJunitXml() { return (DirectoryReport) getByName("junitXml"); } }
/* * Copyright 2013 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.api.internal.tasks.testing; import org.gradle.api.Task; import org.gradle.api.reporting.ConfigureableReport; import org.gradle.api.reporting.DirectoryReport; import org.gradle.api.reporting.internal.TaskGeneratedSingleDirectoryReport; import org.gradle.api.reporting.internal.TaskReportContainer; import org.gradle.api.tasks.testing.TestReports; public class DefaultTestReports extends TaskReportContainer<ConfigureableReport> implements TestReports { public DefaultTestReports(Task task) { super(ConfigureableReport.class, task); add(TaskGeneratedSingleDirectoryReport.class, "junitXml", task, null); add(TaskGeneratedSingleDirectoryReport.class, "html", task, "index.html"); } public DirectoryReport getHtml() { return (DirectoryReport) getByName("html"); } public DirectoryReport getJunitXml() { return (DirectoryReport) getByName("junitXml"); } }
Change cache-control from 60s expired to 86.400 (1 day)
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ // <![CDATA[ $(document).ready(function() { $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh setInterval(function() { $('#pjax_total').load('https://reserv.solusi-integral.co.id/pajax/pjax_total'); $('#pjax_green').load('https://reserv.solusi-integral.co.id/pajax/pjax_green'); $('#pjax_status').load('https://reserv.solusi-integral.co.id/pajax/pjax_status'); $('#pjax_person').load('https://reserv.solusi-integral.co.id/pajax/pjax_person'); $('#pjax_last6').load('https://reserv.solusi-integral.co.id/pajax/pjax_last6'); $('#pjax_today').load('https://reserv.solusi-integral.co.id/pajax/pjax_today'); $('#pjax_today2').load('https://reserv.solusi-integral.co.id/pajax/pjax_today'); }, 1234); // the "3000" here refers to the time to refresh the div. it is in milliseconds. }); // ]]>
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ // <![CDATA[ $(document).ready(function() { $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh setInterval(function() { $('#pjax_total').load('https://reserv.solusi-integral.co.id/index.php/pajax/pjax_total'); $('#pjax_green').load('https://reserv.solusi-integral.co.id/index.php/pajax/pjax_green'); $('#pjax_status').load('https://reserv.solusi-integral.co.id/index.php/pajax/pjax_status'); $('#pjax_person').load('https://reserv.solusi-integral.co.id/index.php/pajax/pjax_person'); $('#pjax_last6').load('https://reserv.solusi-integral.co.id/index.php/pajax/pjax_last6'); $('#pjax_today').load('https://reserv.solusi-integral.co.id/index.php/pajax/pjax_today'); $('#pjax_today2').load('https://reserv.solusi-integral.co.id/index.php/pajax/pjax_today'); }, 1234); // the "3000" here refers to the time to refresh the div. it is in milliseconds. }); // ]]>
CLI: Fix 'qunit' require error on Node 10 if qunit.json exists If the project using QUnit has a local qunit.json file in the repository root, then the CLI was unable to find the 'qunit' package. Instead, it first found a local 'qunit.json' file. This affected an ESLint plugin with a 'qunit' preset file. This bug was fixed in Node 12, and thus only affects Node 10 for us. The bug is also specific to require.resolve(). Regular use of require() was not affected and always correctly found the local package. (A local file would only be considered if the require started with dot-slash like `./qunit`.) Ref https://github.com/nodejs/node/issues/35367. Fixes https://github.com/qunitjs/qunit/issues/1484.
// Depending on the exact usage, QUnit could be in one of several places, this // function handles finding it. module.exports = function requireQUnit( resolve = require.resolve ) { try { // First we attempt to find QUnit relative to the current working directory. const localQUnitPath = resolve( "qunit", { // Support: Node 10. Explicitly check "node_modules" to avoid a bug. // Fixed in Node 12+. See https://github.com/nodejs/node/issues/35367. paths: [ process.cwd() + "/node_modules", process.cwd() ] } ); delete require.cache[ localQUnitPath ]; return require( localQUnitPath ); } catch ( e ) { try { // Second, we use the globally installed QUnit delete require.cache[ resolve( "../../qunit/qunit" ) ]; // eslint-disable-next-line node/no-missing-require, node/no-unpublished-require return require( "../../qunit/qunit" ); } catch ( e ) { if ( e.code === "MODULE_NOT_FOUND" ) { // Finally, we use the local development version of QUnit delete require.cache[ resolve( "../../dist/qunit" ) ]; // eslint-disable-next-line node/no-missing-require, node/no-unpublished-require return require( "../../dist/qunit" ); } throw e; } } };
// Depending on the exact usage, QUnit could be in one of several places, this // function handles finding it. module.exports = function requireQUnit( resolve = require.resolve ) { try { // First we attempt to find QUnit relative to the current working directory. const localQUnitPath = resolve( "qunit", { paths: [ process.cwd() ] } ); delete require.cache[ localQUnitPath ]; return require( localQUnitPath ); } catch ( e ) { try { // Second, we use the globally installed QUnit delete require.cache[ resolve( "../../qunit/qunit" ) ]; // eslint-disable-next-line node/no-missing-require, node/no-unpublished-require return require( "../../qunit/qunit" ); } catch ( e ) { if ( e.code === "MODULE_NOT_FOUND" ) { // Finally, we use the local development version of QUnit delete require.cache[ resolve( "../../dist/qunit" ) ]; // eslint-disable-next-line node/no-missing-require, node/no-unpublished-require return require( "../../dist/qunit" ); } throw e; } } };
Mark test_type_inference test as expected failure
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): @unittest.expectedFailure def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
from __future__ import print_function from numba import vectorize, jit, bool_, double, int_, float_, typeof, int8 import numba.unittest_support as unittest import numpy as np def add(a, b): return a + b def func(dtypeA, dtypeB): A = np.arange(10, dtype=dtypeA) B = np.arange(10, dtype=dtypeB) return typeof(vector_add(A, B)) class TestVectTypeInfer(unittest.TestCase): def test_type_inference(self): global vector_add vector_add = vectorize([ bool_(double, int_), double(double, double), float_(double, float_), ])(add) cfunc = jit(func) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype('i')), int8[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float64)), double[:]) self.assertEqual(cfunc(np.dtype(np.float64), np.dtype(np.float32)), float_[:]) if __name__ == '__main__': unittest.main()
Fix base dir in router
var fs = require('fs-extra'); var path = require('path'); var serveStatic = require('serve-static'); var finalhandler = require('finalhandler'); module.exports = function(options) { options = options || {}; var rcfile = path.join(options.cwd || process.cwd(), '.webmodulesrc'); var rc = fs.existsSync(rcfile) ? JSON.parse(fs.readFileSync(rcfile)) : {}; var base = path.join(process.cwd(), options.base || rc.directory || 'web_modules'); var runtimedir = serveStatic(path.normalize(path.join(__dirname, '..', '..'))); var moduledir = serveStatic(base); return function webmodules(req, res, next) { if( arguments.length <= 2 ) next = finalhandler(req, res); //console.log('req', req.url); if( req.url.startsWith('/webmodules/') ) { req.url = req.url.substring('/webmodules/'.length); runtimedir(req, res, next); } else { moduledir(req, res, next); } }; };
var fs = require('fs-extra'); var path = require('path'); var serveStatic = require('serve-static'); var finalhandler = require('finalhandler'); module.exports = function(options) { options = options || {}; var rcfile = path.join(options.cwd || process.cwd(), '.webmodulesrc'); var rc = fs.existsSync(rcfile) ? JSON.parse(fs.readFileSync(rcfile)) : {}; var base = options.base || rc.directory || path.join(process.cwd(), 'web_modules'); var runtimedir = serveStatic(path.normalize(path.join(__dirname, '..', '..'))); var moduledir = serveStatic(base); return function webmodules(req, res, next) { if( arguments.length <= 2 ) next = finalhandler(req, res); //console.log('req', req.url); if( req.url.startsWith('/webmodules/') ) { req.url = req.url.substring('/webmodules/'.length); runtimedir(req, res, next); } else { moduledir(req, res, next); } }; };
Add name to Departure resource
from __future__ import unicode_literals from ...models import Address, AddOn, DepartureRoom, PP2aPrice from ..base import Product from .tour_dossier import TourDossier from .departure_component import DepartureComponent class Departure(Product): _resource_name = 'departures' _is_listable = True _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'name', 'availability', 'flags', 'nearest_start_airport', 'nearest_finish_airport', 'product_line', 'sku', 'requirements', ] _date_fields = ['start_date', 'finish_date'] _date_time_fields_utc = ['date_created', 'date_last_modified'] _date_time_fields_local = ['latest_arrival_time', 'earliest_departure_time'] _resource_fields = [('tour', 'Tour'), ('tour_dossier', TourDossier)] _resource_collection_fields = [ ('components', DepartureComponent), ] _model_fields = [('start_address', Address), ('finish_address', Address)] _model_collection_fields = [ ('addons', AddOn), ('rooms', DepartureRoom), ('lowest_pp2a_prices', PP2aPrice), ] _deprecated_fields = ['add_ons']
from __future__ import unicode_literals from ...models import Address, AddOn, DepartureRoom, PP2aPrice from ..base import Product from .tour_dossier import TourDossier from .departure_component import DepartureComponent class Departure(Product): _resource_name = 'departures' _is_listable = True _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'availability', 'flags', 'nearest_start_airport', 'nearest_finish_airport', 'product_line', 'sku', 'requirements', ] _date_fields = ['start_date', 'finish_date'] _date_time_fields_utc = ['date_created', 'date_last_modified'] _date_time_fields_local = ['latest_arrival_time', 'earliest_departure_time'] _resource_fields = [('tour', 'Tour'), ('tour_dossier', TourDossier)] _resource_collection_fields = [ ('components', DepartureComponent), ] _model_fields = [('start_address', Address), ('finish_address', Address)] _model_collection_fields = [ ('addons', AddOn), ('rooms', DepartureRoom), ('lowest_pp2a_prices', PP2aPrice), ] _deprecated_fields = ['add_ons']
Disable printing of API parameters which could leak private info and were generally not useful Change-Id: I8a8a8d10799df4f61e4465fe60b6c7efbefbd962
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def __init__(self, *args, **kwargs): super(TestRequest, self).__init__(0, *args, **kwargs) def _get_cache_dir(self): path = os.path.join(os.path.split(__file__)[0], 'apicache') self._make_dir(path) return path def _expired(self, dt): return False def submit(self): cached_available = self._load_cache() if not cached_available: print str(self) return super(TestRequest, self).submit() def patch_request(): pywikibot.data.api.Request = TestRequest def unpatch_request(): pywikibot.data.api.Request = _original_Request
TEST: Work aound failing Nightwatch test
'use strict'; var log = require('../modules/log'); exports.command = function(scenario, callback) { var client = this; this.perform(function() { log.command('Processing Scope diagnosis - scenario: ' + scenario.title); client .waitForElementPresent('body.js-enabled', 3000, function() { console.log(' - Waiting for page to fully load'); }) .assert.urlContains('/scope/diagnosis', ' - Scope diagnosis URL is correct') .assert.containsText('h1', 'Choose the area you most need help with', ' - Scope diagnosis page title is correct') .useXpath() ; scenario.nodes.forEach(function(node) { var xpath = '//a[starts-with(normalize-space(.), "' + node + '")]'; client .waitForElementPresent(xpath, 3000, ' • node ‘' + node + '’ visible') .pause(50) // KLUDGE: Wait a bit to ensure element is accessible before being clicked .click(xpath, function() { console.log(' • node ‘' + node + '’ clicked'); }); }); client.useCss(); }); if (typeof callback === 'function') { callback.call(client); } return client; };
'use strict'; var log = require('../modules/log'); exports.command = function(scenario, callback) { var client = this; this.perform(function() { log.command('Processing Scope diagnosis - scenario: ' + scenario.title); client .waitForElementPresent('body.js-enabled', 3000, function() { console.log(' - Waiting for page to fully load'); }) .assert.urlContains('/scope/diagnosis', ' - Scope diagnosis URL is correct') .assert.containsText('h1', 'Choose the area you most need help with', ' - Scope diagnosis page title is correct') .useXpath() ; scenario.nodes.forEach(function(node) { var xpath = '//a[starts-with(normalize-space(.), "' + node + '")]'; client .waitForElementPresent(xpath, 3000, ' • node ‘' + node + '’ visible') .click(xpath, function() { console.log(' • node ‘' + node + '’ clicked'); }); }); client.useCss(); }); if (typeof callback === 'function') { callback.call(client); } return client; };
Make test works with make and bazel
# Copyright 2018 The Sonnet 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. # ============================================================================ """Tests for time_two ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.platform import test try: from tensorflow_time_two.python.ops import time_two_ops except ImportError: import time_two_ops class TimeTwoTest(test.TestCase): def testTimeTwo(self): with self.test_session(): self.assertAllClose( time_two_ops.time_two([[1, 2], [3, 4]]).eval(), np.array([[2, 4], [6, 8]])) if __name__ == '__main__': test.main()
# Copyright 2018 The Sonnet 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. # ============================================================================ """Tests for time_two ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.platform import test from time_two_ops import time_two class TimeTwoTest(test.TestCase): def testTimeTwo(self): with self.test_session(): self.assertAllClose( time_two([[1, 2], [3, 4]]).eval(), np.array([[2, 4], [6, 8]])) if __name__ == '__main__': test.main()
Add time/space complexity; revise var's
from __future__ import absolute_import from __future__ import print_function from __future__ import division def sum_list_recur(a_list): """Sum list by recursion. Time complexity: O(n), where n is the list length. Space complexity: O(n). """ if len(a_list) == 1: return a_list[0] else: return a_list[0] + sum_list_recur(a_list[1:]) def sum_list_dp(a_list): """Sum list by bottom-up dynamic programming. Time complexity: O(n). Space complexity: O(1). """ s = 0 for x in a_list: s += x return s def main(): import time import random a_list = [random.randint(0, 1000) for _ in range(100)] start_time = time.time() print('By recursion: {}'.format(sum_list_recur(a_list))) print('Time: {}'.format(time.time() - start_time)) start_time = time.time() print('By DP: {}'.format(sum_list_dp(a_list))) print('Time: {}'.format(time.time() - start_time)) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def sum_list_iter(num_ls): """Sum number list by for loop.""" _sum = 0 for num in num_ls: _sum += num return _sum def sum_list_recur(num_ls): """Sum number list by recursion.""" if len(num_ls) == 1: return num_ls[0] else: return num_ls[0] + sum_list_recur(num_ls[1:]) def main(): import time num_ls = range(100) start_time = time.time() print('By iteration: {}'.format(sum_list_iter(num_ls))) print('Time: {}'.format(time.time() - start_time)) start_time = time.time() print('By recursion: {}'.format(sum_list_recur(num_ls))) print('Time: {}'.format(time.time() - start_time)) if __name__ == '__main__': main()
Add package dependencies for printing and testing Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='pycc', version='0.0.1', url='https://github.com/kevinconway/pycc', license=license, description='Python code optimizer..', author='Kevin Conway', author_email='kevinjacobconway@gmail.com', long_description=readme, classifiers=[], packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']), requires=['astkit', 'pytest'], entry_points={ 'console_scripts': [ 'pycc-lint = pycc.cli.lint:main', 'pycc-transform = pycc.cli.transform:main', 'pycc-compile = pycc.cli.compile:main', ], }, )
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='pycc', version='0.0.1', url='https://github.com/kevinconway/pycc', license=license, description='Python code optimizer..', author='Kevin Conway', author_email='kevinjacobconway@gmail.com', long_description=readme, classifiers=[], packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']), requires=['astkit'], entry_points = { 'console_scripts': [ 'pycc-lint = pycc.cli.lint:main', 'pycc-transform = pycc.cli.transform:main', 'pycc-compile = pycc.cli.compile:main', ], }, )
Handle true/false as well as True/False arguments
''' Utilities for scripts ''' import sys __all__ = ['parse_args'] def parse_args(num_args, allowed_params, msg, string_args=set()): msg += '\nAllowed arguments and default values:\n' for k, v in allowed_params.iteritems(): msg += '\n %s = %s' % (k, v) if len(sys.argv)<=num_args: print msg exit(1) params = {} for spec in sys.argv[num_args+1:]: name, val = spec.split('=') if name not in string_args: if val.lower()=='true': val = 'True' elif val.lower()=='false': val = 'False' val = eval(val) params[name] = val for k in params.keys(): if k not in allowed_params: print msg exit(1) for k, v in allowed_params.iteritems(): if k not in params: params[k] = v return sys.argv[1:num_args+1], params
''' Utilities for scripts ''' import sys __all__ = ['parse_args'] def parse_args(num_args, allowed_params, msg, string_args=set()): msg += '\nAllowed arguments and default values:\n' for k, v in allowed_params.iteritems(): msg += '\n %s = %s' % (k, v) if len(sys.argv)<=num_args: print msg exit(1) params = {} for spec in sys.argv[num_args+1:]: name, val = spec.split('=') if name not in string_args: val = eval(val) params[name] = val for k in params.keys(): if k not in allowed_params: print msg exit(1) for k, v in allowed_params.iteritems(): if k not in params: params[k] = v return sys.argv[1:num_args+1], params
Disable Edge test (not available in all operating systems in CI)
/* * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.edge; import org.junit.Before; import org.junit.BeforeClass; import org.openqa.selenium.edge.EdgeDriver; import io.github.bonigarcia.wdm.WebDriverManager; import io.github.bonigarcia.wdm.test.base.BrowserTestParent; /** * Test with Microsoft Edge. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.3.0 */ @Ignore("Edge not available in CI for all operating systems") public class EdgeTest extends BrowserTestParent { @BeforeClass public static void setupClass() { WebDriverManager.edgedriver().setup(); } @Before public void setupTest() { driver = new EdgeDriver(); } }
/* * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia.wdm.test.edge; import org.junit.Before; import org.junit.BeforeClass; import org.openqa.selenium.edge.EdgeDriver; import io.github.bonigarcia.wdm.WebDriverManager; import io.github.bonigarcia.wdm.test.base.BrowserTestParent; /** * Test with Microsoft Edge. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.3.0 */ public class EdgeTest extends BrowserTestParent { @BeforeClass public static void setupClass() { WebDriverManager.edgedriver().setup(); } @Before public void setupTest() { driver = new EdgeDriver(); } }
Refactor report item factory, simplify switch statement
<?php namespace PhpSpec\Formatter\Html; use PhpSpec\Event\ExampleEvent; use PhpSpec\Formatter\Presenter\PresenterInterface; use PhpSpec\Formatter\Template as TemplateInterface; class ReportItemFactory { private $template; public function __construct(TemplateInterface $template) { $this->template = $template ?: new Template; } public function create(ExampleEvent $event, PresenterInterface $presenter = null) { switch($event->getResult()) { case ExampleEvent::PASSED: return new ReportPassedItem($this->template, $event); case ExampleEvent::PENDING: return new ReportPendingItem($this->template, $event); case ExampleEvent::FAILED: case ExampleEvent::BROKEN: return new ReportFailedItem($this->template, $event, $presenter); default: throw $this->invalidResultException($event->getResult()); } } private function invalidResultException($result) { throw new InvalidExampleResultException( "Unrecognised example result $result" ); } }
<?php namespace PhpSpec\Formatter\Html; use PhpSpec\Event\ExampleEvent; use PhpSpec\Formatter\Presenter\PresenterInterface; use PhpSpec\Formatter\Template as TemplateInterface; class ReportItemFactory { private $template; public function __construct(TemplateInterface $template) { $this->template = $template ?: new Template; } public function create(ExampleEvent $event, PresenterInterface $presenter = null) { switch(true) { case $event->getResult() === ExampleEvent::PASSED: return new ReportPassedItem($this->template, $event); case $event->getResult() === ExampleEvent::PENDING: return new ReportPendingItem($this->template, $event); case $event->getResult() === ExampleEvent::FAILED: case $event->getResult() === ExampleEvent::BROKEN: return new ReportFailedItem($this->template, $event, $presenter); default: throw $this->invalidResultException($event->getResult()); } } private function invalidResultException($result) { throw new InvalidExampleResultException( "Unrecognised example result $result" ); } }
Use proper method to determine system uptime. Fixes https://github.com/dittert/pyprobe/issues/9
# coding=utf-8 from datetime import datetime import psutil from pyprobe.sensors import * __author__ = 'Dirk Dittert' class UptimeSensor(BaseSensor): KIND = u'uptime' def define(self, configuration): result = SensorDescription(u"Laufzeit", self.KIND) result.description = u"Monitort die Laufzeit eines Geräts." return result def execute(self, sensorid, host, parameters, configuration): uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time()) result = SensorResult(sensorid) channel = SensorChannel(u"System-Laufzeit", ModeType.FLOAT, ValueType.TIME_SECONDS, uptime.total_seconds()) result.channel.append(channel) return result
# coding=utf-8 from datetime import datetime import psutil from pyprobe.sensors import * __author__ = 'Dirk Dittert' class UptimeSensor(BaseSensor): KIND = u'uptime' def define(self, configuration): result = SensorDescription(u"Laufzeit", self.KIND) result.description = u"Monitort die Laufzeit eines Geräts." return result def execute(self, sensorid, host, parameters, configuration): uptime = datetime.now() - datetime.fromtimestamp(psutil.get_boot_time()) result = SensorResult(sensorid) channel = SensorChannel(u"System-Laufzeit", ModeType.FLOAT, ValueType.TIME_SECONDS, uptime.total_seconds()) result.channel.append(channel) return result
Update deployment process to use frozen requirements.
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('bower install') run('npm install') run('ember build --environment=production') virtualenv('pip install -r /var/www/twweb/requirements-frozen.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) sudo('/usr/sbin/service twweb-sync-listener restart', shell=False) sudo('/usr/sbin/service twweb-log-consumer restart', shell=False) sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) local('git checkout development')
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('bower install') run('npm install') run('ember build --environment=production') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) sudo('/usr/sbin/service twweb-sync-listener restart', shell=False) sudo('/usr/sbin/service twweb-log-consumer restart', shell=False) sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) local('git checkout development')
Add medical_physician requirement to medical_appointment
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Appointment', 'summary': 'Add Appointment concept to medical_physician', 'version': '9.0.1.0.0', 'author': 'LasLabs, Odoo Community Association (OCA)', 'category': 'Medical', 'depends': [ 'medical_base_history', 'medical_physician', ], 'data': [ 'views/medical_appointment_view.xml', 'views/medical_menu.xml', 'security/ir.model.access.csv', 'security/medical_security.xml', 'data/medical_appointment_data.xml', 'data/medical_appointment_sequence.xml', ], 'website': 'https://laslabs.com', 'licence': 'AGPL-3', 'installable': True, 'auto_install': False, }
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Appointment', 'summary': 'Add Appointment concept to medical_physician', 'version': '9.0.1.0.0', 'author': 'LasLabs, Odoo Community Association (OCA)', 'category': 'Medical', 'depends': [ 'medical_base_history', 'medical', ], 'data': [ 'views/medical_appointment_view.xml', 'views/medical_menu.xml', 'security/ir.model.access.csv', 'security/medical_security.xml', 'data/medical_appointment_data.xml', 'data/medical_appointment_sequence.xml', ], 'website': 'https://laslabs.com', 'licence': 'AGPL-3', 'installable': True, 'auto_install': False, }
Deal with str/bytes mismatch in python 3
import sys import unittest import ocookie.httplib_adapter from tests import app py3 = sys.version_info[0] == 3 if py3: import http.client as httplib def to_bytes(text): return text.encode('utf8') else: import httplib def to_bytes(text): return text port = 5040 app.run(port) class HttplibAdapterTest(unittest.TestCase): def test_cookies(self): conn = httplib.HTTPConnection('localhost', port) conn.request('GET', '/set') response = conn.getresponse() self.assertEqual(to_bytes('success'), response.read()) cookies = ocookie.httplib_adapter.parse_response_cookies(response) self.assertEqual(1, len(cookies)) cookie = cookies[0] self.assertEqual('visited', cookie.name) self.assertEqual('yes', cookie.value) if __name__ == '__main__': unittest.main()
import sys import unittest import ocookie.httplib_adapter from tests import app py3 = sys.version_info[0] == 3 if py3: import http.client as httplib else: import httplib port = 5040 app.run(port) class HttplibAdapterTest(unittest.TestCase): def test_cookies(self): conn = httplib.HTTPConnection('localhost', port) conn.request('GET', '/set') response = conn.getresponse() self.assertEqual('success', response.read()) cookies = ocookie.httplib_adapter.parse_response_cookies(response) self.assertEqual(1, len(cookies)) cookie = cookies[0] self.assertEqual('visited', cookie.name) self.assertEqual('yes', cookie.value) if __name__ == '__main__': unittest.main()
Add requests dependency, bump to 0.0.4
try: from setuptools import setup except ImportError: from distutils.core import setup version = "0.0.4" setup( name="pyopen", version=version, author="Tim O'Donnell", author_email="timodonnell@gmail.com", packages=["pyopen", "pyopen.loaders"], url="https://github.com/timodonnell/pyopen", license="Apache License", description="launch an interactive ipython session with specified files opened and parsed", long_description=open('README.rst').read(), download_url='https://github.com/timodonnell/pyopen/tarball/%s' % version, entry_points={ 'console_scripts': [ 'pyopen = pyopen.command:run', ] }, classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Developers", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", ], install_requires=[ "humanize", "traitlets", "six", "xlrd", "requests", "pandas>=0.16.1", "nose>=1.3.1", ] )
try: from setuptools import setup except ImportError: from distutils.core import setup version = "0.0.3" setup( name="pyopen", version=version, author="Tim O'Donnell", author_email="timodonnell@gmail.com", packages=["pyopen", "pyopen.loaders"], url="https://github.com/timodonnell/pyopen", license="Apache License", description="launch an interactive ipython session with specified files opened and parsed", long_description=open('README.rst').read(), download_url='https://github.com/timodonnell/pyopen/tarball/%s' % version, entry_points={ 'console_scripts': [ 'pyopen = pyopen.command:run', ] }, classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Developers", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", ], install_requires=[ "humanize", "traitlets", "six", "xlrd", "pandas>=0.16.1", "nose>=1.3.1", ] )
Add converter before blueprint registration
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oa = OAuth() lm = LoginManager() lm.login_view = "main.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oa.init_app(app) from app.converters import WordClassConverter app.url_map.converters["word_class"] = WordClassConverter from app.views.main import main from app.views.oauth import oauth app.register_blueprint(main) app.register_blueprint(oauth) return app
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oa = OAuth() lm = LoginManager() lm.login_view = "main.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oa.init_app(app) from app.views.main import main from app.views.oauth import oauth app.register_blueprint(main) app.register_blueprint(oauth) from app.converters import WordClassConverter app.url_map.converters["word_class"] = WordClassConverter return app
Integrate integer test function into instantiation Ref #23
"""Creates the station class""" #import request_integer_in_range from request_integer_in_range class Station: """ Each train station is an instance of the Station class. Methods: __init__: creates a new stations request_integer_in_range : requests an integer in a range """ def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing): self.capacity = request_integer_in_range("Enter the station capacity between 10 and 10000: ", 10, 10000) self.escalators = request_integer_in_range("Enter an odd number of escalators between 1 and 7: ", 1, 7) self.train_wait = request_integer_in_range("Enter the wait time between trains in seconds between 60 and 1800 ", 60, 1800) self.travelors_arriving = request_integer_in_range("Enter the number of people exiting the train between 1 and 500: ", 1, 500) self.travelors_departing = request_integer_in_range("Enter the number of people waiting for the train between 1 and 500: ", 1, 500)
"""Creates the station class""" #import ask_user from ask_user #import int_check from int_check #import reasonable_check from reasonable_check class Station: """ Each train station is an instance of the Station class. Methods: __init__: creates a new stations total_station_pop: calculates total station population ask_user(prompt, lower_range, upper_range): function to get input, maybe it should live somewhere else? """ def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing): self.capacity = user.says("Enter the max capacity of the station between" lower "and" upper) self.escalators = user.says("Enter the number of escalators in the station between" lower "and" upper) self.train_wait = user.says("Enter the wait time between trains in seconds between" lower "and" upper) self.travelors_arriving = user.says("How many people just exited the train? between" lower "and" upper) self.travelors_departing = user.says("How many people are waiting for the train? between" lower "and" upper)
Fix the download URL to match the version number.
#coding:utf-8 import sys from distutils.core import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['tests/'] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) setup( name='fantasy_data', version='1.1.3', description='FantasyData Python', author='Fantasy Football Calculator', author_email='support@fantasyfootballcalculator.com', url='https://fantasyfootballcalculator.com/fantasydata-python', packages=['fantasy_data'], keywords=['fantasy', 'sports', 'football', 'nba'], install_requires=[ "requests", "six", ], tests_require=['pytest'], cmdclass = {'test': PyTest}, download_url='https://github.com/ffcalculator/fantasydata-python/archive/v1.1.3.tar.gz' )
#coding:utf-8 import sys from distutils.core import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['tests/'] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) setup( name='fantasy_data', version='1.1.2', description='FantasyData Python', author='Fantasy Football Calculator', author_email='support@fantasyfootballcalculator.com', url='https://fantasyfootballcalculator.com/fantasydata-python', packages=['fantasy_data'], keywords=['fantasy', 'sports', 'football', 'nba'], install_requires=[ "requests", "six", ], tests_require=['pytest'], cmdclass = {'test': PyTest}, download_url='https://github.com/ffcalculator/fantasydata-python/archive/v1.1.1.tar.gz' )
Add eslint-disable-next-line comments to get rid of excessively pedantic react/no-array-index-key errors.
import React from 'react'; import css from './Breadcrumbs.css'; const propTypes = { links: React.PropTypes.array, }; function Breadcrumbs(props) { const links = props.links.map((link, i) => { // eslint-disable-next-line react/no-array-index-key const linkElem = <li key={`breadcrumb_${i}`}><a href={link.path}>{link.label}</a></li>; // eslint-disable-next-line react/no-array-index-key const dividerElem = <li key={`divider${i}`}>{'>'}</li>; if (i !== props.links.length - 1) { return (linkElem + dividerElem); } return linkElem; }); return ( <ul className={css.navBreadcrumbs}> {links} </ul> ); } Breadcrumbs.propTypes = propTypes; export default Breadcrumbs;
import React from 'react'; import css from './Breadcrumbs.css'; const propTypes = { links: React.PropTypes.array, }; function Breadcrumbs(props) { const links = props.links.map((link, i) => { const linkElem = <li key={`breadcrumb_${i}`}><a href={link.path}>{link.label}</a></li>; const dividerElem = <li key={`divider${i}`}>{'>'}</li>; if (i !== props.links.length - 1) { return (linkElem + dividerElem); } return linkElem; }); return ( <ul className={css.navBreadcrumbs}> {links} </ul> ); } Breadcrumbs.propTypes = propTypes; export default Breadcrumbs;
Remove babelHelper and add global
/** * Created by godsong on 16/7/7. */ var injectedGlobals = [ 'define', 'require', 'document', 'bootstrap', 'register', 'render', '__d', '__r', '__DEV__', '__weex_define__', '__weex_bootstrap__', '__weex_document__', '__weex_viewmodel__', '__weex_options__', '__weex_data__', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'global' ]; const bundleWrapper = 'function __weex_bundle_entry__('+injectedGlobals.join(',')+'){'; const rearRegexp = /\/\/#\s*sourceMappingURL|$/; module.exports = function (code,sourceUrl) { var match=/(^\s*\/\/.+)\n/.exec(code); var anno=''; if(match){ anno='$$frameworkFlag["'+sourceUrl+'"]="'+match[1].replace(/"/g,'\\"')+'";'; } return anno+bundleWrapper + code.replace(rearRegexp, '}\n$&'); }
/** * Created by godsong on 16/7/7. */ var injectedGlobals = [ 'define', 'require', 'document', 'bootstrap', 'register', 'render', '__d', '__r', '__DEV__', '__weex_define__', '__weex_bootstrap__', '__weex_document__', '__weex_viewmodel__', '__weex_options__', '__weex_data__', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'babelHelpers' ]; const bundleWrapper = 'function __weex_bundle_entry__('+injectedGlobals.join(',')+'){'; const rearRegexp = /\/\/#\s*sourceMappingURL|$/; module.exports = function (code,sourceUrl) { var match=/(^\s*\/\/.+)\n/.exec(code); var anno=''; if(match){ anno='$$frameworkFlag["'+sourceUrl+'"]="'+match[1].replace(/"/g,'\\"')+'";'; } return anno+bundleWrapper + code.replace(rearRegexp, '}\n$&'); }
Add after Garbage Collection memory statistics to status pages.
package html import ( "fmt" "github.com/Symantec/Dominator/lib/format" "io" "runtime" "syscall" "time" ) var startTime time.Time = time.Now() func writeHeader(writer io.Writer) { fmt.Fprintf(writer, "Start time: %s<br>\n", startTime) uptime := time.Since(startTime) fmt.Fprintf(writer, "Uptime: %s<br>\n", uptime) var rusage syscall.Rusage syscall.Getrusage(syscall.RUSAGE_SELF, &rusage) cpuTime := rusage.Utime.Sec + rusage.Stime.Sec fmt.Fprintf(writer, "CPU Time: %d%%<br>\n", cpuTime*100/int64(uptime.Seconds())) var memStatsBeforeGC, memStatsAfterGC runtime.MemStats runtime.ReadMemStats(&memStatsBeforeGC) runtime.GC() runtime.ReadMemStats(&memStatsAfterGC) fmt.Fprintf(writer, "Allocated memory: %s (%s after GC)<br>\n", format.FormatBytes(memStatsBeforeGC.Alloc), format.FormatBytes(memStatsAfterGC.Alloc)) fmt.Fprintf(writer, "System memory: %s (%s after GC)<br>\n", format.FormatBytes(memStatsBeforeGC.Sys), format.FormatBytes(memStatsAfterGC.Sys)) }
package html import ( "fmt" "github.com/Symantec/Dominator/lib/format" "io" "runtime" "syscall" "time" ) var startTime time.Time = time.Now() func writeHeader(writer io.Writer) { fmt.Fprintf(writer, "Start time: %s<br>\n", startTime) uptime := time.Since(startTime) fmt.Fprintf(writer, "Uptime: %s<br>\n", uptime) var rusage syscall.Rusage syscall.Getrusage(syscall.RUSAGE_SELF, &rusage) cpuTime := rusage.Utime.Sec + rusage.Stime.Sec fmt.Fprintf(writer, "CPU Time: %d%%<br>\n", cpuTime*100/int64(uptime.Seconds())) var memStats runtime.MemStats runtime.ReadMemStats(&memStats) fmt.Fprintf(writer, "Allocated memory: %s<br>\n", format.FormatBytes(memStats.Alloc)) }
Add a filter for membership_type.
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import AdminPasswordChangeForm from tastypie.admin import ApiKeyInline from tastypie.models import ApiKey from .forms import UserCreationForm, UserChangeForm from .models import User, Membership class MembershipInline(admin.StackedInline): model = Membership extra = 0 readonly_fields = ('created', 'updated') class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm change_password_form = AdminPasswordChangeForm inlines = BaseUserAdmin.inlines + [ApiKeyInline, MembershipInline] class MembershipAdmin(admin.ModelAdmin): list_display = ( '__str__', 'created', 'updated' ) date_hierarchy = 'created' search_fields = ['creator__username'] list_filter = ['membership_type'] class ApiKeyAdmin(admin.ModelAdmin): list_display = ('user', 'created', ) date_hierarchy = 'created' admin.site.register(User, UserAdmin) admin.site.register(Membership, MembershipAdmin) try: admin.site.unregister(ApiKey) except admin.sites.NotRegistered: pass finally: admin.site.register(ApiKey, ApiKeyAdmin)
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import AdminPasswordChangeForm from tastypie.admin import ApiKeyInline from tastypie.models import ApiKey from .forms import UserCreationForm, UserChangeForm from .models import User, Membership class MembershipInline(admin.StackedInline): model = Membership extra = 0 readonly_fields = ('created', 'updated') class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm change_password_form = AdminPasswordChangeForm inlines = BaseUserAdmin.inlines + [ApiKeyInline, MembershipInline] class MembershipAdmin(admin.ModelAdmin): list_display = ( '__str__', 'created', 'updated' ) date_hierarchy = 'created' search_fields = ['creator__username'] class ApiKeyAdmin(admin.ModelAdmin): list_display = ('user', 'created', ) date_hierarchy = 'created' admin.site.register(User, UserAdmin) admin.site.register(Membership, MembershipAdmin) try: admin.site.unregister(ApiKey) except admin.sites.NotRegistered: pass finally: admin.site.register(ApiKey, ApiKeyAdmin)
Add the last pressure value.
package data type WsError struct { Code int `json:"code"` Msg string `json:"msg"` } type WsEvent struct { Id int `json:"id"` Type string `json:"type"` Channel string `json:"channel"` Text string `json:"text"` Ok bool `json:"ok"` ReplyTo int `json:"reply_to"` Ts string `json:"ts"` Error WsError `json:"error"` Url string `json:"url"` User string `json:"user"` } type IpInfo struct { Ip string `json:"ip"` } type WeatherInfo struct { Temp float32 `json:"temp"` Pressure float32 `json:"pressure"` Day bool `json:"day"` Humidity float32 `json:"humid"` Lux float32 `json:"lux"` LastPressure float32 `json:"lastPressure"` } type RtmResponse struct { Url string `json:"url"` } type WsMessage struct { Msg string } type SlackUser struct { User string Channel string }
package data type WsError struct { Code int `json:"code"` Msg string `json:"msg"` } type WsEvent struct { Id int `json:"id"` Type string `json:"type"` Channel string `json:"channel"` Text string `json:"text"` Ok bool `json:"ok"` ReplyTo int `json:"reply_to"` Ts string `json:"ts"` Error WsError `json:"error"` Url string `json:"url"` User string `json:"user"` } type IpInfo struct { Ip string `json:"ip"` } type WeatherInfo struct { Temp float32 `json:"temp"` Pressure float32 `json:"pressure"` Day bool `json:"day"` Humidity float32 `json:"humid"` Lux float32 `json:"lux"` } type RtmResponse struct { Url string `json:"url"` } type WsMessage struct { Msg string } type SlackUser struct { User string Channel string }
Remove plain 'django-admin-sortable' from requirements This is only required to test migrations, not for new installs.
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from aldryn_faq import __version__ REQUIREMENTS = [ 'aldryn-apphooks-config', 'aldryn-reversion', 'aldryn-search', # 'django-admin-sortable', 'django-admin-sortable2>=0.5.0', 'django-parler', 'django-sortedm2m', ] CLASSIFIERS = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Application Frameworks', ] setup( name='aldryn-faq', version=__version__, description='FAQ addon for django CMS', author='Divio AG', author_email='info@divio.ch', url='https://github.com/aldryn/aldryn-faq', packages=find_packages(), license='LICENSE.txt', platforms=['OS Independent'], install_requires=REQUIREMENTS, classifiers=CLASSIFIERS, include_package_data=True, zip_safe=False )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from aldryn_faq import __version__ REQUIREMENTS = [ 'aldryn-apphooks-config', 'aldryn-reversion', 'aldryn-search', 'django-admin-sortable', 'django-admin-sortable2>=0.5.0', 'django-parler', 'django-sortedm2m', ] CLASSIFIERS = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Application Frameworks', ] setup( name='aldryn-faq', version=__version__, description='FAQ addon for django CMS', author='Divio AG', author_email='info@divio.ch', url='https://github.com/aldryn/aldryn-faq', packages=find_packages(), license='LICENSE.txt', platforms=['OS Independent'], install_requires=REQUIREMENTS, classifiers=CLASSIFIERS, include_package_data=True, zip_safe=False )
Remove ServiceFilter from view since it's not needed. Service only has name and json
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import ScratchOrgInstance from mrbelvedereci.cumulusci.models import Service from rest_framework import viewsets class OrgViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Orgs """ serializer_class = OrgSerializer queryset = Org.objects.all() filter_class = OrgFilter class ScratchOrgInstanceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing ScratchOrgInstances """ serializer_class = ScratchOrgInstanceSerializer queryset = ScratchOrgInstance.objects.all() filter_class = ScratchOrgInstanceFilter class ServiceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Services """ serializer_class = ServiceSerializer queryset = Service.objects.all()
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter from mrbelvedereci.cumulusci.filters import ServiceFilter from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import ScratchOrgInstance from mrbelvedereci.cumulusci.models import Service from rest_framework import viewsets class OrgViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Orgs """ serializer_class = OrgSerializer queryset = Org.objects.all() filter_class = OrgFilter class ScratchOrgInstanceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing ScratchOrgInstances """ serializer_class = ScratchOrgInstanceSerializer queryset = ScratchOrgInstance.objects.all() filter_class = ScratchOrgInstanceFilter class ServiceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Services """ serializer_class = ServiceSerializer queryset = Service.objects.all() filter_class = ServiceFilter