text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update to new (unburned) webhook.site URL
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name' } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(() => webhook.notify(challenge, 'https://webhook.site/#!/e3b07c99-fd53-4799-aa18-984f71009f8c')).to.not.throw() }) }) })
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name' } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(() => webhook.notify(challenge, 'https://webhook.site/46beb3e9-df8f-495b-98b9-abf0d4ae38a0')).to.not.throw() }) }) })
Fix permission check in `UserContentAction::validateBulkRevert()`
<?php namespace wcf\data\user; use wcf\system\edit\EditHistoryManager; use wcf\system\WCF; /** * Executes actions on user generated content. * * @author Tim Duesterhus * @copyright 2001-2015 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package com.woltlab.wcf * @subpackage data.user * @category Community Framework */ class UserContentAction extends UserAction { /** * Checks permissions to bulk revert. */ public function validateBulkRevert() { WCF::getSession()->checkPermissions(array('admin.content.canBulkRevertContentChanges')); } /** * Bulk reverts changes made to history saving objects. */ public function bulkRevert() { $this->readInteger('timeframe', true); if (!$this->parameters['timeframe']) { $this->parameters['timeframe'] = 86400 * 7; } EditHistoryManager::getInstance()->bulkRevert($this->objectIDs, $this->parameters['timeframe']); } }
<?php namespace wcf\data\user; use wcf\system\edit\EditHistoryManager; use wcf\system\WCF; /** * Executes actions on user generated content. * * @author Tim Duesterhus * @copyright 2001-2015 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package com.woltlab.wcf * @subpackage data.user * @category Community Framework */ class UserContentAction extends UserAction { /** * Checks permissions to bulk revert. */ public function validateBulkRevert() { WCF::getSession()->checkPermissions('admin.content.canBulkRevertContentChanges'); } /** * Bulk reverts changes made to history saving objects. */ public function bulkRevert() { $this->readInteger('timeframe', true); if (!$this->parameters['timeframe']) { $this->parameters['timeframe'] = 86400 * 7; } EditHistoryManager::getInstance()->bulkRevert($this->objectIDs, $this->parameters['timeframe']); } }
Add a trailing slash to the paginated talk list
from django.conf.urls import patterns, url, include from rest_framework import routers from wafer.talks.views import ( Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks, TalksViewSet) router = routers.DefaultRouter() router.register(r'talks', TalksViewSet) urlpatterns = patterns( '', url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'), url(r'^page/(?P<page>\d+)/$', UsersTalks.as_view(), name='wafer_users_talks_page'), url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'), url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'), url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(), name='wafer_talk_edit'), url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(), name='wafer_talk_delete'), url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'), url(r'^api/', include(router.urls)), )
from django.conf.urls import patterns, url, include from rest_framework import routers from wafer.talks.views import ( Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks, TalksViewSet) router = routers.DefaultRouter() router.register(r'talks', TalksViewSet) urlpatterns = patterns( '', url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'), url(r'^page/(?P<page>\d+)$', UsersTalks.as_view(), name='wafer_users_talks_page'), url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'), url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'), url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(), name='wafer_talk_edit'), url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(), name='wafer_talk_delete'), url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'), url(r'^api/', include(router.urls)), )
Change embeded struct CensusData's error structure
// The census package is used to query data from the census API. // // It's centered more so around data from Planetside 2 package census import ( "strings" ) var BaseURL = "http://census.daybreakgames.com/" var BaseURLOld = "http://census.soe.com/" func init() { //BaseURL = BaseURLOld } // CensusData is a struct that contains various metadata that a Census request can have. type CensusData struct { Error string `json:"error"` } // NewCensus returns a new census object given your service ID func NewCensus(ServiceID string, Namespace string) *Census { c := new(Census) c.serviceID = ServiceID c.namespace = Namespace return c } // Census is the main object you use to query data type Census struct { serviceID string namespace string } func (c *Census) CleanNamespace() string { if strings.Contains(c.namespace, ":") { return strings.Split(c.namespace, ":")[0] } return c.namespace } func (c *Census) IsEU() bool { if strings.Contains(c.namespace, "eu") { return true } return false }
// The census package is used to query data from the census API. // // It's centered more so around data from Planetside 2 package census import ( "strings" ) var BaseURL = "http://census.daybreakgames.com/" var BaseURLOld = "http://census.soe.com/" func init() { //BaseURL = BaseURLOld } // CensusData is a struct that contains various metadata that a Census request can have. type CensusData struct { Error string `json:"error"` } func (c *CensusData) Error() string { return c.error } // NewCensus returns a new census object given your service ID func NewCensus(ServiceID string, Namespace string) *Census { c := new(Census) c.serviceID = ServiceID c.namespace = Namespace return c } // Census is the main object you use to query data type Census struct { serviceID string namespace string } func (c *Census) CleanNamespace() string { if strings.Contains(c.namespace, ":") { return strings.Split(c.namespace, ":")[0] } return c.namespace } func (c *Census) IsEU() bool { if strings.Contains(c.namespace, "eu") { return true } return false }
Remove phar:// from file path
<?php namespace falkirks\simplewarp\utils; use pocketmine\plugin\PharPluginLoader; use pocketmine\plugin\PluginBase; use pocketmine\utils\Utils; class ChecksumVerify { const POGGIT_ENDPOINT = "https://poggit.pmmp.io/get.sha1/"; /** * WARNING! This is a blocking function that performs a web request. */ public static function isValid(PluginBase $pluginBase){ $url = ChecksumVerify::POGGIT_ENDPOINT . $pluginBase->getDescription()->getName() . "/" . $pluginBase->getDescription()->getVersion(); $hash = Utils::getURL($url); if($pluginBase->getPluginLoader() instanceof PharPluginLoader){ $reflect = new \ReflectionClass($pluginBase); $method = $reflect->getMethod("getFile"); $method->setAccessible(true); $file = $method->invoke($pluginBase); $method->setAccessible(false); $check = sha1_file(str_replace("phar://", "", $file)); return $check === $hash; } return false; } }
<?php namespace falkirks\simplewarp\utils; use pocketmine\plugin\PharPluginLoader; use pocketmine\plugin\PluginBase; use pocketmine\utils\Utils; class ChecksumVerify { const POGGIT_ENDPOINT = "https://poggit.pmmp.io/get.sha1/"; /** * WARNING! This is a blocking function that performs a web request. */ public static function isValid(PluginBase $pluginBase){ $url = ChecksumVerify::POGGIT_ENDPOINT . $pluginBase->getDescription()->getName() . "/" . $pluginBase->getDescription()->getVersion(); $hash = Utils::getURL($url); if($pluginBase->getPluginLoader() instanceof PharPluginLoader){ $reflect = new \ReflectionClass($pluginBase); $method = $reflect->getMethod("getFile"); $method->setAccessible(true); $file = $method->invoke($pluginBase); $method->setAccessible(false); $check = sha1_file($file); return $check === $hash; } return false; } }
Add cacheable flag to webpack loader.
// This loader replaces each require(*.coffee) by require(./noco-loader.js!*.coffee) // and compile the result to JS. // Its purpose is to avoid adding any code in the webpack.config.js of the parent project. var coffee = require('coffee-script'); var path = __filename.replace(/\\/g,'/'); var exp = RegExp(/require([\(,',",\s]*)(.*\.coffee[\),',",\s]*)/g) var has_coffee_config = false; module.exports = function(source, map) { var matches = source.match(exp); if(matches != null){ for (i = 0; i < matches.length; i++) { var match = matches[i]; if(match.indexOf('!') != -1){continue}; var replace = match.replace(exp,'require$1' + path + '!$2'); source = source.replace(match,replace); } } if(/(^|\n)var /.test(source)) has_coffee_config = true; if(!has_coffee_config) source = coffee.compile(source); this.cacheable(true) this.callback(null, source, map); };
// This loader replaces each require(*.coffee) by require(./noco-loader.js!*.coffee) // and compile the result to JS. // Its purpose is to avoid adding any code in the webpack.config.js of the parent project. var coffee = require('coffee-script'); var path = __filename.replace(/\\/g,'/'); var exp = RegExp(/require([\(,',",\s]*)(.*\.coffee[\),',",\s]*)/g) var has_coffee_config = false; module.exports = function(source, map) { var matches = source.match(exp); if(matches != null){ for (i = 0; i < matches.length; i++) { var match = matches[i]; if(match.indexOf('!') != -1){continue}; var replace = match.replace(exp,'require$1' + path + '!$2'); source = source.replace(match,replace); } } if(/(^|\n)var /.test(source)) has_coffee_config = true; if(!has_coffee_config) source = coffee.compile(source); this.callback(null, source, map); };
Replace missing Mongo to MongoClient
package org.jongo.util; import com.mongodb.MongoClient; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import com.mongodb.DB; import com.mongodb.Mongo; public class EmbeddedMongoRule implements TestRule { private static DB db; public static MongoClient getMongo() { return MongoHolder.getInstance(); } public static DB getTestDatabase() { return db; } public EmbeddedMongoRule() { setUpTestDatabase(); } public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { before(description); try { base.evaluate(); } finally { after(); } } }; } protected void before(Description description) throws Exception { setUpTestDatabase(); } protected void after() { tearDownTestDatabase(); } public void setUpTestDatabase(){ if(db == null) { db = getMongo().getDB("test_" + System.nanoTime()); } } public void tearDownTestDatabase(){ if (db != null) { db.dropDatabase(); db = null; } } }
package org.jongo.util; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import com.mongodb.DB; import com.mongodb.Mongo; public class EmbeddedMongoRule implements TestRule { private static DB db; public static Mongo getMongo() { return MongoHolder.getInstance(); } public static DB getTestDatabase() { return db; } public EmbeddedMongoRule() { setUpTestDatabase(); } public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { before(description); try { base.evaluate(); } finally { after(); } } }; } protected void before(Description description) throws Exception { setUpTestDatabase(); } protected void after() { tearDownTestDatabase(); } public void setUpTestDatabase(){ if(db == null) { db = getMongo().getDB("test_" + System.nanoTime()); } } public void tearDownTestDatabase(){ if (db != null) { db.dropDatabase(); db = null; } } }
Fix unit test for essentia dissonance
#! /usr/bin/env python from unit_timeside import unittest, TestRunner from timeside.plugins.decoder.file import FileDecoder from timeside.core import get_processor from timeside.core.tools.test_samples import samples class TestEssentiaDissonance(unittest.TestCase): def setUp(self): self.analyzer = get_processor('essentia_dissonance')() def testOnC4Scale(self): "runs on C4 scale" self.source = samples["C4_scale.wav"] def tearDown(self): decoder = FileDecoder(self.source) (decoder | self.analyzer).run() self.assertAlmostEqual(self.analyzer.results['essentia_dissonance'].data_object.value.mean(), 0.16, places=2) if __name__ == '__main__': unittest.main(testRunner=TestRunner())
#! /usr/bin/env python from unit_timeside import unittest, TestRunner from timeside.plugins.decoder.file import FileDecoder from timeside.core import get_processor from timeside.core.tools.test_samples import samples class TestEssentiaDissonance(unittest.TestCase): def setUp(self): self.analyzer = get_processor('essentia_dissonance')() def testOnC4Scale(self): "runs on C4 scale" self.source = samples["C4_scale.wav"] def tearDown(self): decoder = FileDecoder(self.source) (decoder | self.analyzer).run() self.assertAlmostEqual(self.analyzer.results['essentia_dissonance'].data_object.value.mean(), 0.18, places=2) if __name__ == '__main__': unittest.main(testRunner=TestRunner())
Allow mixed in PHP 8 for manipulation
<?php namespace Psalm\Type\Atomic; class TMixed extends \Psalm\Type\Atomic { /** @var bool */ public $from_loop_isset = false; public function __construct(bool $from_loop_isset = false) { $this->from_loop_isset = $from_loop_isset; } public function __toString(): string { return 'mixed'; } public function getKey(bool $include_extra = true): string { return 'mixed'; } /** * @param array<string> $aliased_classes */ public function toPhpString( ?string $namespace, array $aliased_classes, ?string $this_class, int $php_major_version, int $php_minor_version ): ?string { return $php_major_version >= 8 ? 'mixed' : null; } public function canBeFullyExpressedInPhp(int $php_major_version, int $php_minor_version): bool { return $php_major_version >= 8; } public function getAssertionString(): string { return 'mixed'; } }
<?php namespace Psalm\Type\Atomic; class TMixed extends \Psalm\Type\Atomic { /** @var bool */ public $from_loop_isset = false; public function __construct(bool $from_loop_isset = false) { $this->from_loop_isset = $from_loop_isset; } public function __toString(): string { return 'mixed'; } public function getKey(bool $include_extra = true): string { return 'mixed'; } /** * @param array<string> $aliased_classes */ public function toPhpString( ?string $namespace, array $aliased_classes, ?string $this_class, int $php_major_version, int $php_minor_version ): ?string { return null; } public function canBeFullyExpressedInPhp(int $php_major_version, int $php_minor_version): bool { return false; } public function getAssertionString(): string { return 'mixed'; } }
Add pythonic way to concatenate strings.
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import argparse def get_metric(host, port, metric): response = urllib2.urlopen( 'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port) ) data = json.load(response) # print json.dumps(data, indent=4, sort_keys=True) try: print data[metric] except KeyError: print "ZBX_NOT_SUPPORTED" if __name__ == '__main__': arg_parser = argparse.ArgumentParser( description='Mesos metrics') arg_parser.add_argument( '-H', '--host', help="Specify host or ip address", required=True) arg_parser.add_argument( '-p', '--port', help="Specify mesos api port", required=True) arg_parser.add_argument( '-m', '--metric', help="Specify metric's name", required=True) arguments = arg_parser.parse_args() get_metric(arguments.host, arguments.port, arguments.metric)
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import argparse def get_metric(host, port, metric): response = urllib2.urlopen( 'http://' + host + ':' + port + '/metrics/snapshot') data = json.load(response) # print json.dumps(data, indent=4, sort_keys=True) try: print data[metric] except KeyError: print "ZBX_NOT_SUPPORTED" if __name__ == '__main__': arg_parser = argparse.ArgumentParser( description='Mesos metrics') arg_parser.add_argument( '-H', '--host', help="Specify host or ip address", required=True) arg_parser.add_argument( '-p', '--port', help="Specify mesos api port", required=True) arg_parser.add_argument( '-m', '--metric', help="Specify metric's name", required=True) arguments = arg_parser.parse_args() get_metric(arguments.host, arguments.port, arguments.metric)
Remove whitespace & use same order as in readme
#!/usr/bin/env node var argv = process.argv.splice(2) var log = require('./helpers/log.js') var whitelist = ['build', 'run', 'test', 'lint', 'setup'] if (argv.length === 0 || argv[0] === 'help') { console.log('abc [command]') console.log('') console.log('Commands:') console.log(' setup Creates the directories and files for the whole project to run.') console.log(' build Compiles the source files from src/ into a build/ directory.') console.log(' test Runs the test files in the tests/ directory.') console.log(' lint Checks if your code is consistent and follows best practices.') console.log(' run src/file.js Runs a specified file.') console.log(' help This help page you are looking at!') process.exit(0) } if (whitelist.indexOf(argv[0]) === -1) { log.error('Command `' + argv[0] + '` does not exist') process.exit(1) } var callback = require('./' + argv[0] + '.js') callback.apply(null, argv.splice(1))
#!/usr/bin/env node var argv = process.argv.splice(2) var log = require('./helpers/log.js') var whitelist = ['build', 'run', 'test', 'lint', 'setup'] if (argv.length === 0 || argv[0] === 'help') { console.log('abc [command]\n\nCommands:') console.log(' build Compiles the source files from src/ into a build/ directory. ') console.log(' run src/file.js Runs a specified file.') console.log(' test Runs the test files in the tests/ directory.') console.log(' lint Checks if your code is consistent and follows best practices. ') console.log(' setup Creates the directories and files for the whole project to run.') console.log(' help This help page you are looking at!') process.exit(0) } if (whitelist.indexOf(argv[0]) === -1) { log.error('Command `' + argv[0] + '` does not exist') process.exit(1) } var callback = require('./' + argv[0] + '.js') callback.apply(null, argv.splice(1))
Change anchor placement to avoid flash
(function($) { // SVG polyfill svg4everybody(); // Deep anchor links for headings anchors.options = { placement: 'left', visible: 'touch', icon: '#' } anchors.add('.post h3, .post h4, .post h5, post h6, .page h3, .page h4, .page h5, page h6, .archive-overview h3, .archive-overview h4'); anchors.remove('.comment header > h4'); // Smooth scrolling links in comments $('.comment_reply').click(function(e) { var $el = $(this); var target, replyTo; target = '#reply'; replyTo = $el.attr("id").replace(/serendipity_reply_/g, ""); $("#serendipity_replyTo").val(replyTo); $('html, body').animate({ scrollTop: $(target).offset().top }, 250); e.preventDefault(); }); // Move comment preview $('#c').insertAfter('#feedback'); })(jQuery);
(function($) { // SVG polyfill svg4everybody(); // Deep anchor links for headings anchors.options = { placement: 'right', visible: 'touch', icon: '#' } anchors.add('.post h3, .post h4, .post h5, post h6, .page h3, .page h4, .page h5, page h6, .archive-overview h3, .archive-overview h4'); anchors.remove('.comment header > h4'); // Smooth scrolling links in comments $('.comment_reply').click(function(e) { var $el = $(this); var target, replyTo; target = '#reply'; replyTo = $el.attr("id").replace(/serendipity_reply_/g, ""); $("#serendipity_replyTo").val(replyTo); $('html, body').animate({ scrollTop: $(target).offset().top }, 250); e.preventDefault(); }); // Move comment preview $('#c').insertAfter('#feedback'); })(jQuery);
Stop ID should be string so zeros don't get truncated
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBusWatchListsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('bus_watch_lists', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->string('bus_stop_id'); $table->string('name'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('bus_watch_lists'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBusWatchListsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('bus_watch_lists', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->integer('bus_stop_id'); $table->string('name'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('bus_watch_lists'); } }
Allow ol-mapbox-style to import from ol/style/Style etc.
const fs = require('fs'); const path = require('path'); const cases = path.join(__dirname, 'cases'); const caseDirs = fs.readdirSync(cases).filter((name) => { let exists = true; try { fs.accessSync(path.join(cases, name, 'main.js')); } catch (err) { exists = false; } return exists; }); const entry = {}; caseDirs.forEach((c) => { entry[`cases/${c}/main`] = `./cases/${c}/main.js`; }); module.exports = { context: __dirname, target: 'web', entry: entry, devtool: 'source-map', stats: 'minimal', module: { rules: [ { test: /\.js$/, use: { loader: path.join( __dirname, '../../examples/webpack/worker-loader.js' ), }, include: [path.join(__dirname, '../../src/ol/worker')], }, ], }, resolve: { alias: { // ol-mapbox-style imports ol/style/Style etc ol: path.join(__dirname, '..', '..', 'src', 'ol'), }, }, };
const fs = require('fs'); const path = require('path'); const cases = path.join(__dirname, 'cases'); const caseDirs = fs.readdirSync(cases).filter((name) => { let exists = true; try { fs.accessSync(path.join(cases, name, 'main.js')); } catch (err) { exists = false; } return exists; }); const entry = {}; caseDirs.forEach((c) => { entry[`cases/${c}/main`] = `./cases/${c}/main.js`; }); module.exports = { context: __dirname, target: 'web', entry: entry, devtool: 'source-map', stats: 'minimal', module: { rules: [ { test: /\.js$/, use: { loader: path.join( __dirname, '../../examples/webpack/worker-loader.js' ), }, include: [path.join(__dirname, '../../src/ol/worker')], }, ], }, };
Add Ability to forward Post Data
var url = require('url') var HttpClient = function() {} HttpClient.prototype.fetch = function (requestOptions) { var self = this; var urlSplit = url.parse(requestOptions.url); var isHttps = urlSplit.protocol === 'https:' var http = require(isHttps ? 'https' : 'http'); var options = { hostname: urlSplit.hostname, port: urlSplit.port || (isHttps ? 443 : 80), path: urlSplit.path, method: requestOptions.method, headers: requestOptions.headers }; return new Promise(function(resolve, reject) { var req = http.request(options, function(res) { var statusCode = res.statusCode; var contentType = res.headers['content-type']; var responseData = ''; res.on('data', function (chunk) { responseData += chunk; }); res.on('end', function() { resolve({status: statusCode, type: contentType, data: responseData}); }); res.on('error', function () { reject('Unable to load data from request.'); }); }); if (requestOptions.body) { req.write(requestOptions.body); } req.end() }); } module.exports = HttpClient
var url = require('url') var HttpClient = function() {} HttpClient.prototype.fetch = function (requestOptions) { var self = this; var urlSplit = url.parse(requestOptions.url); var isHttps = urlSplit.protocol === 'https:' var http = require(isHttps ? 'https' : 'http'); var options = { hostname: urlSplit.hostname, port: urlSplit.port || (isHttps ? 443 : 80), path: urlSplit.path, method: requestOptions.method, headers: requestOptions.headers }; return new Promise(function(resolve, reject) { var req = http.request(options, function(res) { var statusCode = res.statusCode; var contentType = res.headers['content-type']; var responseData = ''; res.on('data', function (chunk) { responseData += chunk; }); res.on('end', function() { resolve({status: statusCode, type: contentType, data: responseData}); }); res.on('error', function () { reject('Unable to load data from request.'); }); }); req.end() }); } module.exports = HttpClient
Fix for pip 10.0 and later
import pip import xblog from setuptools import setup from setuptools import find_packages try: # for pip >= 10 from pip._internal.req import parse_requirements except ImportError: # for pip <= 9.0.3 from pip.req import parse_requirements REQUIREMENTS_FILE = "xblog/requirements.txt" requirements = [str(ir.req) for ir in parse_requirements(REQUIREMENTS_FILE, session=pip.download.PipSession())] setup( name='django-xblog', version=xblog.__version__, description="A full-featured blogging application for your Django site", long_description=open('README.md').read(), keywords='django, blog, weblog, bootstrap, metaWeblog, wordpress', author=xblog.__author__, author_email=xblog.__email__, url=xblog.__url__, packages=find_packages(), classifiers=[ 'Framework :: Django :: 1.8', 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: BSD License', ], license=xblog.__license__, include_package_data=True, zip_safe=False, install_requires=requirements, )
from setuptools import setup from setuptools import find_packages from pip.req import parse_requirements import pip import xblog REQUIREMENTS_FILE = "xblog/requirements.txt" requirements = [str(ir.req) for ir in parse_requirements(REQUIREMENTS_FILE, session=pip.download.PipSession())] setup( name='django-xblog', version=xblog.__version__, description="A full-featured blogging application for your Django site", long_description=open('README.md').read(), keywords='django, blog, weblog, bootstrap, metaWeblog, wordpress', author=xblog.__author__, author_email=xblog.__email__, url=xblog.__url__, packages=find_packages(), classifiers=[ 'Framework :: Django :: 1.8', 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: BSD License', ], license=xblog.__license__, include_package_data=True, zip_safe=False, install_requires=requirements, )
Add debug to form in test
<?php namespace MediaMonks\SonataMediaBundle\Tests\Functional; class ImageProviderTest extends AbstractProviderTestAbstract { public function testImage() { $provider = 'image'; $crawler = $this->client->request('GET', self::BASE_PATH.'create?provider='.$provider); $form = $crawler->selectButton('Create')->form(); $this->assertSonataFormValues( $form, [ 'provider' => $provider, ] ); $this->setFormBinaryContent($form, $this->getFixturesPath().'monk.jpg'); echo $form->getMethod() . PHP_EOL; print_r($form->getPhpFiles()); print_r($form->getPhpValues()); $crawler = $this->client->submit($form); $form = $crawler->selectButton('Update')->form(); $this->assertSonataFormValues($form, ['title' => 'monk']); $this->client->request('GET', self::BASE_PATH.'list'); $this->assertContains('monk', $this->client->getResponse()->getContent()); $this->assertNumberOfFilesInPath(1, $this->getMediaPathPrivate()); } }
<?php namespace MediaMonks\SonataMediaBundle\Tests\Functional; class ImageProviderTest extends AbstractProviderTestAbstract { public function testImage() { $provider = 'image'; $crawler = $this->client->request('GET', self::BASE_PATH.'create?provider='.$provider); $form = $crawler->selectButton('Create')->form(); $this->assertSonataFormValues( $form, [ 'provider' => $provider, ] ); $this->setFormBinaryContent($form, $this->getFixturesPath().'monk.jpg'); $crawler = $this->client->submit($form); $form = $crawler->selectButton('Update')->form(); $this->assertSonataFormValues($form, ['title' => 'monk']); $this->client->request('GET', self::BASE_PATH.'list'); $this->assertContains('monk', $this->client->getResponse()->getContent()); $this->assertNumberOfFilesInPath(1, $this->getMediaPathPrivate()); } }
Use sudo to change db user password.
from argyle.base import upload_template from fabric.api import sudo, task @task def create_db_user(username, password=None, flags=None): """Create a databse user.""" flags = flags or u'-D -A -R' sudo(u'createuser %s %s' % (flags, username), user=u'postgres') if password: change_db_user_password(username, password) @task def excute_query(query, db=None, flags=None, use_sudo=False): """Execute remote psql query.""" flags = flags or u'' if db: flags = u"%s -d %s" % (flags, db) command = u'psql %s -c "%s"' % (flags, query) if use_sudo: sudo(command, user='postgres') else: run(command) @task def change_db_user_password(username, password): """Change a db user's password.""" sql = "ALTER USER %s WITH PASSWORD '%s'" % (username, password) excute_query(sql, use_sudo=True) @task def create_db(name, owner=None, encoding=u'UTF-8'): """Create a Postgres database.""" flags = u'' if encoding: flags = u'-E %s' % encoding if owner: flags = u'%s -O %s' % (flags, owner) sudo('createdb %s %s' % (flags, name), user='postgres')
from argyle.base import upload_template from fabric.api import sudo, task @task def create_db_user(username, password=None, flags=None): """Create a databse user.""" flags = flags or u'-D -A -R' sudo(u'createuser %s %s' % (flags, username), user=u'postgres') if password: change_db_user_password(username, password) @task def excute_query(query, db=None, flags=None, use_sudo=False): """Execute remote psql query.""" flags = flags or u'' if db: flags = u"%s -d %s" % (flags, db) command = u'psql %s -c "%s"' % (flags, query) if use_sudo: sudo(command, user='postgres') else: run(command) @task def change_db_user_password(username, password): """Change a db user's password.""" sql = "ALTER USER %s WITH PASSWORD '%s'" % (username, password) excute_query(sql) @task def create_db(name, owner=None, encoding=u'UTF-8'): """Create a Postgres database.""" flags = u'' if encoding: flags = u'-E %s' % encoding if owner: flags = u'%s -O %s' % (flags, owner) sudo('createdb %s %s' % (flags, name), user='postgres')
FIX fiscal position no source tax
from openerp import models, api, fields class account_fiscal_position(models.Model): _inherit = 'account.fiscal.position' @api.v7 def map_tax(self, cr, uid, fposition_id, taxes, context=None): result = super(account_fiscal_position, self).map_tax( cr, uid, fposition_id, taxes, context=context) print 'fposition_id', fposition_id if fposition_id: taxes_without_src_ids = [ x.tax_dest_id.id for x in fposition_id.tax_ids if not x.tax_src_id] result = set(result) | set(taxes_without_src_ids) return list(result) @api.v8 # noqa def map_tax(self, taxes): result = super(account_fiscal_position, self).map_tax(taxes) taxes_without_src_ids = [ x.tax_dest_id.id for x in self.tax_ids if not x.tax_src_id] result += result.browse(taxes_without_src_ids) return result class account_fiscal_position_tax(models.Model): _inherit = 'account.fiscal.position.tax' tax_src_id = fields.Many2one(required=False)
from openerp import models, api, fields class account_fiscal_position(models.Model): _inherit = 'account.fiscal.position' @api.v7 def map_tax(self, cr, uid, fposition_id, taxes, context=None): result = super(account_fiscal_position, self).map_tax( cr, uid, fposition_id, taxes, context=context) taxes_without_src_ids = [ x.tax_dest_id.id for x in fposition_id.tax_ids if not x.tax_src_id] result = set(result) | set(taxes_without_src_ids) return list(result) @api.v8 # noqa def map_tax(self, taxes): result = super(account_fiscal_position, self).map_tax(taxes) taxes_without_src_ids = [ x.tax_dest_id.id for x in self.tax_ids if not x.tax_src_id] result += result.browse(taxes_without_src_ids) return result class account_fiscal_position_tax(models.Model): _inherit = 'account.fiscal.position.tax' tax_src_id = fields.Many2one(required=False)
Fix hierarchical/inherit issue with styles for Tooltip
package io.bisq.gui.components; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; public class HyperlinkWithIcon extends Hyperlink { public HyperlinkWithIcon(String text) { this(text, AwesomeIcon.INFO_SIGN); } public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) { super(text); Label icon = new Label(); AwesomeDude.setIcon(icon, awesomeIcon); icon.setMinWidth(20); icon.setOpacity(0.7); icon.getStyleClass().add("hyperlink"); setGraphic(icon); setContentDisplay(ContentDisplay.RIGHT); tooltipProperty().addListener((observable, oldValue, newValue) -> newValue.setStyle("-fx-text-fill: -bs-black")); } }
package io.bisq.gui.components; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; public class HyperlinkWithIcon extends Hyperlink { public HyperlinkWithIcon(String text) { this(text, AwesomeIcon.INFO_SIGN); } public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) { super(text); Label icon = new Label(); AwesomeDude.setIcon(icon, awesomeIcon); icon.setMinWidth(20); icon.setOpacity(0.7); icon.getStyleClass().add("hyperlink"); setGraphic(icon); setContentDisplay(ContentDisplay.RIGHT); } }
Correct the packaging of packages on winsys modified setup.py
from distutils.core import setup import winsys if __name__ == '__main__': setup ( name='WinSys', version=winsys.__version__, url='http://code.google.com/p/winsys', download_url='http://timgolden.me.uk/python/downloads/winsys', license='MIT', author='Tim Golden', author_email='mail@timgolden.me.uk', description='Python tools for the Windows sysadmin', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: Windows', 'Programming Language :: Python', 'Topic :: Utilities', ], platforms='win32', packages=['winsys', 'winsys.test', 'winsys._security', 'winsys.extras'], )
from distutils.core import setup import winsys if __name__ == '__main__': setup ( name='WinSys', version=winsys.__version__, url='http://svn.timgolden.me.uk/winsys', download_url='http://timgolden.me.uk/python/downloads', license='MIT', author='Tim Golden', author_email='mail@timgolden.me.uk', description='Python tools for the Windows sysadmin', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: Windows', 'Programming Language :: Python', 'Topic :: Utilities', ], platforms='win32', packages=['winsys'], )
Fix pep8 error with new newline Change-Id: I47b12c62eb1653bcbbe552464aab72c486bbd1cc
#! /usr/bin/env python # Copyright Lajos Katona # # 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. def selection_brute(mylist, t): for i, l in enumerate(mylist): if t == l: return i return 0 def selection_pythonic(mylist, t): return mylist.index(t) if __name__ == '__main__': mylist = [1, 2, 3, 4, 5] print(selection_brute(mylist, 4)) print(selection_pythonic(mylist, 4))
#! /usr/bin/env python # Copyright Lajos Katona # # 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. def selection_brute(mylist, t): for i, l in enumerate(mylist): if t == l: return i return 0 def selection_pythonic(mylist, t): return mylist.index(t) if __name__ == '__main__': mylist = [1, 2, 3, 4, 5] print(selection_brute(mylist, 4)) print(selection_pythonic(mylist, 4))
Fix to make site packages more generic in tests
from datetime import datetime from django.conf import settings from django.test import TestCase from package.tests import data, initial_data from searchv2.utils import remove_prefix, clean_title class UtilFunctionTest(TestCase): def setUp(self): self.values = [] for value in ["-me",".me","/me","_me"]: value = "{0}{1}".format(settings.PACKAGINATOR_SEARCH_PREFIX, value) self.values.append(value) def test_remove_prefix(self): for value in self.values: self.assertEqual(remove_prefix(value), "me") def test_clean_title(self): test_value = "{0}me".format(settings.PACKAGINATOR_SEARCH_PREFIX) for value in self.values: self.assertEqual(clean_title(value), test_value)
from datetime import datetime from django.test import TestCase from package.tests import data, initial_data from searchv2.utils import remove_prefix, clean_title class UtilFunctionTest(TestCase): def test_remove_prefix(self): values = ["django-me","django.me","django/me","django_me"] for value in values: self.assertEqual(remove_prefix(value), "me") def test_clean_title(self): values = ["django-me","django.me","django/me","django_me"] for value in values: self.assertEqual(clean_title(value), "djangome")
Fix 'class DataverseFile' to handle old and new response format Tests were failing after swith to new server/version
from __future__ import absolute_import from dataverse.utils import sanitize class DataverseFile(object): def __init__(self, dataset, name, file_id=None): self.dataset = dataset self.name = sanitize(name) self.id = file_id self.download_url = '{0}/access/datafile/{1}'.format( dataset.connection.native_base_url, self.id ) edit_media_base = '{0}/edit-media/file/{1}' self.edit_media_uri = edit_media_base.format( dataset.connection.sword_base_url, self.id ) @classmethod def from_json(cls, dataset, json): try: name = json['dataFile']['filename'] file_id = json['dataFile']['id'] except KeyError: name = json['datafile']['name'] file_id = json['datafile']['id'] return cls(dataset, name, file_id)
from __future__ import absolute_import from dataverse.utils import sanitize class DataverseFile(object): def __init__(self, dataset, name, file_id=None): self.dataset = dataset self.name = sanitize(name) self.id = file_id self.download_url = '{0}/access/datafile/{1}'.format( dataset.connection.native_base_url, self.id ) edit_media_base = '{0}/edit-media/file/{1}' self.edit_media_uri = edit_media_base.format( dataset.connection.sword_base_url, self.id ) @classmethod def from_json(cls, dataset, json): name = json['datafile']['name'] file_id = json['datafile']['id'] return cls(dataset, name, file_id)
Fix parrot variant on 1.17
package protocolsupport.protocol.typeremapper.entity.format.metadata.types.living.tameable; import protocolsupport.protocol.typeremapper.entity.format.metadata.object.value.NetworkEntityMetadataObjectIndexValueNoOpTransformer; import protocolsupport.protocol.typeremapper.entity.format.metadata.types.base.TameableNetworkEntityMetadataFormatTransformerFactory; import protocolsupport.protocol.types.networkentity.metadata.NetworkEntityMetadataObjectIndex; import protocolsupport.protocol.utils.ProtocolVersionsHelper; public class ParrotNetworkEntityMetadataFormatTransformerFactory extends TameableNetworkEntityMetadataFormatTransformerFactory { public static final ParrotNetworkEntityMetadataFormatTransformerFactory INSTANCE = new ParrotNetworkEntityMetadataFormatTransformerFactory(); protected ParrotNetworkEntityMetadataFormatTransformerFactory() { add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 19), ProtocolVersionsHelper.UP_1_17); add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 18), ProtocolVersionsHelper.RANGE__1_15__1_16_4); add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 17), ProtocolVersionsHelper.ALL_1_14); add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 15), ProtocolVersionsHelper.RANGE__1_12__1_13_2); } }
package protocolsupport.protocol.typeremapper.entity.format.metadata.types.living.tameable; import protocolsupport.protocol.typeremapper.entity.format.metadata.object.value.NetworkEntityMetadataObjectIndexValueNoOpTransformer; import protocolsupport.protocol.typeremapper.entity.format.metadata.types.base.TameableNetworkEntityMetadataFormatTransformerFactory; import protocolsupport.protocol.types.networkentity.metadata.NetworkEntityMetadataObjectIndex; import protocolsupport.protocol.utils.ProtocolVersionsHelper; public class ParrotNetworkEntityMetadataFormatTransformerFactory extends TameableNetworkEntityMetadataFormatTransformerFactory { public static final ParrotNetworkEntityMetadataFormatTransformerFactory INSTANCE = new ParrotNetworkEntityMetadataFormatTransformerFactory(); protected ParrotNetworkEntityMetadataFormatTransformerFactory() { add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 18), ProtocolVersionsHelper.UP_1_17); add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 18), ProtocolVersionsHelper.RANGE__1_15__1_16_4); add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 17), ProtocolVersionsHelper.ALL_1_14); add(new NetworkEntityMetadataObjectIndexValueNoOpTransformer(NetworkEntityMetadataObjectIndex.Parrot.VARIANT, 15), ProtocolVersionsHelper.RANGE__1_12__1_13_2); } }
Add some tiny docstring to the unicode method
import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): """ :rtype: str or unicode """ return self.markdown_text
import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): return self.markdown_text
Fix InspectorMemoryTest.testGetDOMStats to have consistent behaviour on CrOS and desktop versions of Chrome. Starting the browser in CrOS requires navigating through an initial setup that does not leave us with a tab at "chrome://newtab". This workaround runs the test in a new tab on all platforms for consistency. BUG=235634 TEST=InspectorMemoryTest.testGetDOMStats passes on cros and system NOTRY=true Review URL: https://chromiumcodereview.appspot.com/14672002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@197490 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'unittest_data') self._browser.SetHTTPServerDirectories(unittest_data_dir) # Due to an issue with CrOS, we create a new tab here rather than # using self._tab to get a consistent starting page on all platforms tab = self._browser.tabs.New() tab.Navigate( self._browser.http_server.UrlOf('dom_counter_sample.html')) tab.WaitForDocumentReadyStateToBeComplete() counts = tab.dom_stats self.assertEqual(counts['document_count'], 2) self.assertEqual(counts['node_count'], 18) self.assertEqual(counts['event_listener_count'], 2)
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'unittest_data') self._browser.SetHTTPServerDirectories(unittest_data_dir) self._tab.Navigate( self._browser.http_server.UrlOf('dom_counter_sample.html')) self._tab.WaitForDocumentReadyStateToBeComplete() counts = self._tab.dom_stats self.assertEqual(counts['document_count'], 1) self.assertEqual(counts['node_count'], 14) self.assertEqual(counts['event_listener_count'], 2)
Refactor test example with syllable breaks - no doubt there will be disagreements & ambiguities, but at least we can assert what the code can/should be doing more precisely
'use strict'; let mocha = require('mocha'); let should = require('should'); //apply the plugin const syllables = require('../../src/index.js'); const nlp = require('nlp_compromise'); nlp.plugin(syllables); describe('syllables', function() { //americanize it it('verify syllables for term', function(done) { let tests = [ 'sud den ly', 'con sti pa tion', 'di a bo lic', 'fa ted', 'ge ne tic', 'i mi ta ted', 'tree', 'ci vi lised', // 'fate', // 'fates', // 'deviled', // 'horse', ]; tests.forEach(function(word_with_syllable_breaks) { let s = nlp.term(word_with_syllable_breaks.replace(/ /g, '')).syllables(); s.join(' ').should.equal(word_with_syllable_breaks); }); done(); }); });
'use strict'; let mocha = require('mocha'); let should = require('should'); //apply the plugin const syllables = require('../../src/index.js'); const nlp = require('nlp_compromise'); nlp.plugin(syllables); describe('syllables', function() { //americanize it it('count syllables for term', function(done) { let tests = [ ['suddenly', 3], ['constipation', 4], ['diabolic', 4], ['fated', 2], ['genetic', 3], ['imitated', 4], ['tree', 1], ['civilised', 3], // ['fate', 1], // ['fates', 1], // ['deviled', 3], // ['horse', 1] ]; tests.forEach(function(a) { let t = nlp.term(a[0]); t.syllables().length.should.equal(a[1]); }); done(); }); });
Revert "Revert "import BS sources"" This reverts commit 1bd13ac67152b33f974ce32402100a0f651c3091.
/* * This is the main entry point. * * You can import other modules here, including external packages. When bundling using rollup you can mark those modules as external and have them excluded or, if they have a jsnext:main entry in their package.json (like this package does), let rollup bundle them into your dist file. * * IMPORTANT NOTE: If you are ultimately creating an iife/self executing bundle for the browser, be sure to: * import 'babel-polyfill' * * at your application entry point. This is necessary for browsers that do not yet support some ES2015 runtime necessities such as Symbol. We do this in `index-iife.js` for our iife rollup bundle. */ import 'babel-polyfill' // Bootstrap components import 'bootstrap/js/src/alert' import 'bootstrap/js/src/button' import 'bootstrap/js/src/carousel' import 'bootstrap/js/src/collapse' import 'bootstrap/js/src/dropdown' import 'bootstrap/js/src/modal' import 'bootstrap/js/src/popover' import 'bootstrap/js/src/scrollspy' import 'bootstrap/js/src/tab' import 'bootstrap/js/src/tooltip' import 'bootstrap/js/src/util' // invalidComponentMatches is currently disabled due to https://github.com/rollup/rollup/issues/428#issuecomment-170066452 import './checkbox' import './checkboxInline' import './collapseInline' import './file' import './radio' import './radioInline' import './select' import './switch' import './text' import './textarea' import './drawer' import './ripples' import './autofill' import './bootstrapMaterialDesign'
/* * This is the main entry point. * * You can import other modules here, including external packages. When bundling using rollup you can mark those modules as external and have them excluded or, if they have a jsnext:main entry in their package.json (like this package does), let rollup bundle them into your dist file. * * IMPORTANT NOTE: If you are ultimately creating an iife/self executing bundle for the browser, be sure to: * import 'babel-polyfill' * * at your application entry point. This is necessary for browsers that do not yet support some ES2015 runtime necessities such as Symbol. We do this in `index-iife.js` for our iife rollup bundle. */ import 'babel-polyfill' // Bootstrap components import 'bootstrap/dist/js/bootstrap' // invalidComponentMatches is currently disabled due to https://github.com/rollup/rollup/issues/428#issuecomment-170066452 import './checkbox' import './checkboxInline' import './collapseInline' import './file' import './radio' import './radioInline' import './select' import './switch' import './text' import './textarea' import './drawer' import './ripples' import './autofill' import './bootstrapMaterialDesign'
Fix the previous commit =)
const DEFAULT_VALUES = { atomicNumber : 1, chemicalSymbol : 'H', name : 'Hydrogen' }; const ELEMENTS_VALUE = { 'hydrogen' : { name : 'Hydrogen', atomicNumber : 1, chemicalSymbol : 'H' }, 'helium' : { name : 'Helium', atomicNumber : 2, chemicalSymbol : 'He' } } /* Represents an atomic element according to the Mendeleiev periodic table. */ class Element { constructor(name = DEFAULT_VALUES.name, atomicNumber = DEFAULT_VALUES.atomicNumber, chemicalSymbol = DEFAULT_VALUES.chemicalSymbol) { this.name = name; this.atomicNumber = atomicNumber; this.chemicalSymbol = chemicalSymbol; } static create(name) { let n = ELEMENTS_VALUE[name].name; let atomicNumber = ELEMENTS_VALUE[name].atomicNumber; let chemicalSymbol = ELEMENTS_VALUE[name].chemicalSymbol; return new Element(n, atomicNumber, chemicalSymbol); } } export default Element;
const DEFAULT_VALUES = { atomicNumber : 1, chemicalSymbol : 'H', name : 'Hydrogen' }; const ELEMENTS_VALUE = { 'hydrogen' : { name : 'Hydrogen', atomicNumber : 1, chemicalSymbol : 'H' }, 'helium' : { name : 'Helium', atomicNumber : 2, chemicalSymbol : 'He' } } class Element { constructor(name = DEFAULT_VALUES.name, atomicNumber = DEFAULT_VALUES.atomicNumber, chemicalSymbol = DEFAULT_VALUES.chemicalSymbol) { this.name = name; this.atomicNumber = atomicNumber; this.chemicalSymbol = chemicalSymbol; } static create(name) { let n = ELEMENTS_VALUE[name].name; let atomicNumber = ELEMENTS_VALUE[name].atomicNumber; let chemicalSymbol = ELEMENTS_VALUE[name].chemicalSymbol; return new Element(n, atomicNumber, chemicalSymbol); } } export default Element;
Update css for save button.
$('#dripbot-title').css({ "display": "inline-block", "margin-right": "20px" }); $('#dripbot').css({ "text-align": "left" }); $('#dripbot-toggle.stop').css({ "background-color": "#e9656d", "color": "white", "margin-top": "-10px" }); $('#dripbot ul li p').css({ "margin-bottom":"5px", "margin-right": "40px", "display": "inline-block" }); $('img#dripbot-logo').css({ "margin-bottom": "10px", "margin-right": "5px" }); $('div#dripbot-update').css({ "background-color": "#47a447", "padding": "10px" }); $('div#dripbot-update h1').css({ "font-weight": "800", }); $('#save-button').css({ "background-color": "#47a447", "color": "white", "margin-left": "20px" })
$('#dripbot-title').css({ "display": "inline-block", "margin-right": "20px" }); $('#dripbot').css({ "text-align": "left" }); $('#dripbot-toggle.stop').css({ "background-color": "#e9656d", "color": "white", "margin-top": "-10px" }); $('#dripbot ul li p').css({ "margin-bottom":"5px", "margin-right": "40px", "display": "inline-block" }); $('img#dripbot-logo').css({ "margin-bottom": "10px", "margin-right": "5px" }); $('div#dripbot-update').css({ "background-color": "#47a447", "padding": "10px" }); $('div#dripbot-update h1').css({ "font-weight": "800", });
Drop usageof fluent interface on mocking Psalm is not failing now !
<?php declare(strict_types=1); namespace ProxyManagerTest\Exception; use PHPUnit\Framework\TestCase; use ProxyManager\Exception\FileNotWritableException; use Webimpress\SafeWriter\Exception\ExceptionInterface as FileWriterException; /** * Tests for {@see \ProxyManager\Exception\FileNotWritableException} * * @covers \ProxyManager\Exception\FileNotWritableException * @group Coverage */ final class FileNotWritableExceptionTest extends TestCase { public function testFromPrevious() : void { $previousExceptionMock = $this->getMockBuilder(FileWriterException::class); $previousExceptionMock->enableOriginalConstructor(); $previousExceptionMock->setConstructorArgs(['Previous exception message']); $previousException = $previousExceptionMock->getMock(); $exception = FileNotWritableException::fromPrevious($previousException); self::assertSame('Previous exception message', $exception->getMessage()); self::assertSame($previousException, $exception->getPrevious()); } }
<?php declare(strict_types=1); namespace ProxyManagerTest\Exception; use PHPUnit\Framework\TestCase; use ProxyManager\Exception\FileNotWritableException; use Webimpress\SafeWriter\Exception\ExceptionInterface as FileWriterException; /** * Tests for {@see \ProxyManager\Exception\FileNotWritableException} * * @covers \ProxyManager\Exception\FileNotWritableException * @group Coverage */ final class FileNotWritableExceptionTest extends TestCase { public function testFromPrevious() : void { $previous = $this->getMockBuilder(FileWriterException::class) ->enableOriginalConstructor() ->setConstructorArgs(['Previous exception message']) ->getMock(); $exception = FileNotWritableException::fromPrevious($previous); self::assertSame('Previous exception message', $exception->getMessage()); self::assertSame($previous, $exception->getPrevious()); } }
Handle 'end' event in the right way
const Duplex = require('stream').Duplex; const Transform = require('stream').Transform; const JlTransform = require('./JlTransform'); class JlTransformsChain extends Transform { constructor(streams) { super({ objectMode: true }); this.inputType = JlTransform.ANY; this.outputType = JlTransform.ANY; this.firstStream = streams[0]; this.lastStream = streams[streams.length - 1]; for (let i = 0; i < streams.length - 1; i++) { streams[i].pipe(streams[i + 1]); } this.lastStream.on('end', () => { this.push(null); }); this.lastStream.on('data', (d) => { if (!this.push(d)) { this.lastStream.pause(); } }); this.lastStream.on('error', e => { this.emit('error', e); }); } _transform(chunk, encoding, callback) { this.firstStream.write(chunk, encoding, callback); } _flush(cb) { this.lastStream.once('end', cb); this.firstStream.end(); } _read(...args) { super._read(...args); if (this.lastStream.isPaused()) { this.lastStream.resume(); } } } module.exports = JlTransformsChain;
const Duplex = require('stream').Duplex; const Transform = require('stream').Transform; const JlTransform = require('./JlTransform'); class JlTransformsChain extends Transform { constructor(streams) { super({ objectMode: true }); this.inputType = JlTransform.ANY; this.outputType = JlTransform.ANY; this.firstStream = streams[0]; this.lastStream = streams[streams.length - 1]; for (let i = 0; i < streams.length - 1; i++) { streams[i].pipe(streams[i + 1]); } this.lastStream.on('end', () => { this.emit('end'); }); this.lastStream.on('data', (d) => { if (!this.push(d)) { this.lastStream.pause(); } }); this.lastStream.on('error', e => { this.emit('error', e); }); } _transform(chunk, encoding, callback) { this.firstStream.write(chunk, encoding, callback); } _flush(cb) { this.lastStream.once('end', cb); this.firstStream.end(); } _read(...args) { super._read(...args); if (this.lastStream.isPaused()) { this.lastStream.resume(); } } } module.exports = JlTransformsChain;
Use data-bgset instead of data-bg. https://github.com/aFarkas/lazysizes/issues/101
<?php // [1] Regular background image; resized thumb (thumbs.dev.width) ?> <?php if($lazyload == false && c::get('resrc') == false): ?> style="background-image:url(<?php echo $thumburl; ?>);"<?php if($class): echo ' class="' . $class . '"'; endif; ?> <?php endif; ?> <?php // [2] Lazyload image; resized thumb (thumbs.dev.width) ?> <?php if($lazyload == true && c::get('resrc') == false): ?> data-bg="<?php echo $thumburl; ?>" class="BgImage lazyload<?php if($class): echo ' ' . $class; endif; ?>" <?php endif; ?> <?php // [3] Lazyload + resrc image; full size thumb (let resrc resize and optimize the biggest possible thumb!) ?> <?php if($lazyload == true && c::get('resrc') == true): ?> data-sizes="auto" data-bgset="<?php echo 'http://' . c::get('resrc.plan') . '/s=w{width}/o={quality}/' . $thumburl; ?>" class="BgImage lazyload<?php if($class): echo ' ' . $class; endif; ?>" <?php endif; ?>
<?php // [1] Regular background image; resized thumb (thumbs.dev.width) ?> <?php if($lazyload == false && c::get('resrc') == false): ?> style="background-image:url(<?php echo $thumburl; ?>);"<?php if($class): echo ' class="' . $class . '"'; endif; ?> <?php endif; ?> <?php // [2] Lazyload image; resized thumb (thumbs.dev.width) ?> <?php if($lazyload == true && c::get('resrc') == false): ?> data-bg="<?php echo $thumburl; ?>" class="BgImage lazyload<?php if($class): echo ' ' . $class; endif; ?>" <?php endif; ?> <?php // [3] Lazyload + resrc image; full size thumb (let resrc resize and optimize the biggest possible thumb!) ?> <?php if($lazyload == true && c::get('resrc') == true): ?> data-sizes="auto" data-bg="<?php echo 'http://' . c::get('resrc.plan') . '/s=w{width}/o={quality}/' . $thumburl; ?>" class="BgImage lazyload<?php if($class): echo ' ' . $class; endif; ?>" <?php endif; ?>
[TASK] Add sorting to faqs table
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFaqsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('polyfaq_faqs', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('title')->default(''); $table->text('content')->default(''); $table->integer('sorting')->default(0); $table->morphs('faqable'); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('polyfaq_faqs', function (Blueprint $table) { $table->drop(); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFaqsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('polyfaq_faqs', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('title')->default(''); $table->text('content')->default(''); $table->morphs('faqable'); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('polyfaq_faqs', function (Blueprint $table) { $table->drop(); }); } }
Make test variable names a little more specific
package reuseport import ( "context" "net" "testing" "github.com/stretchr/testify/require" ) func testDialFromListeningPort(t *testing.T, network string) { lc := net.ListenConfig{ Control: Control, } ctx := context.Background() ll, err := lc.Listen(ctx, network, "localhost:0") require.NoError(t, err) rl, err := lc.Listen(ctx, network, "localhost:0") require.NoError(t, err) d := net.Dialer{ LocalAddr: ll.Addr(), Control: Control, } c, err := d.Dial(network, rl.Addr().String()) require.NoError(t, err) c.Close() } func TestDialFromListeningPort(t *testing.T) { testDialFromListeningPort(t, "tcp") } func TestDialFromListeningPortTcp6(t *testing.T) { testDialFromListeningPort(t, "tcp6") }
package reuseport import ( "context" "net" "testing" "github.com/stretchr/testify/require" ) func testDialFromListeningPort(t *testing.T, network string) { lc := net.ListenConfig{ Control: Control, } ctx := context.Background() l1, err := lc.Listen(ctx, network, "localhost:0") require.NoError(t, err) l2, err := lc.Listen(ctx, network, "localhost:0") require.NoError(t, err) d := net.Dialer{ LocalAddr: l1.Addr(), Control: Control, } c, err := d.Dial(network, l2.Addr().String()) require.NoError(t, err) c.Close() } func TestDialFromListeningPort(t *testing.T) { testDialFromListeningPort(t, "tcp") }
Use relative imports in the package.
#!/usr/bin/env python2 '''Resize images using the FFT FFTresize resizes images using zero-padding in the frequency domain. ''' from numpy import zeros as _zeros from . import fftinterp from . import imutils __author__ = 'Mansour Moufid' __copyright__ = 'Copyright 2013, Mansour Moufid' __license__ = 'ISC' __version__ = '0.2' __email__ = 'mansourmoufid@gmail.com' __status__ = 'Development' def resize(filename, factor=1.5): '''Resize an image by zero-padding in the frequency domain. Return the filename of the resized image. ''' img = imutils.read(filename) nchannels = imutils.channels(img) if nchannels == 1: new = fftinterp.interp2(img, factor) else: new = None for i in range(nchannels): rgb = img[:, :, i] newrgb = fftinterp.interp2(rgb, factor) if new is None: newsize = list(newrgb.shape) newsize.append(imutils.channels(img)) new = _zeros(tuple(newsize)) new[:, :, i] = newrgb return imutils.save(new, filename) if '__main__' in __name__: pass
#!/usr/bin/env python2 '''Resize images using the FFT FFTresize resizes images using zero-padding in the frequency domain. ''' from fftinterp import interp2 import imutils from numpy import zeros as _zeros __author__ = 'Mansour Moufid' __copyright__ = 'Copyright 2013, Mansour Moufid' __license__ = 'ISC' __version__ = '0.2' __email__ = 'mansourmoufid@gmail.com' __status__ = 'Development' def resize(filename, factor=1.5): '''Resize an image by zero-padding in the frequency domain. Return the filename of the resized image. ''' img = imutils.read(filename) nchannels = imutils.channels(img) if nchannels == 1: new = interp2(img, factor) else: new = None for i in range(nchannels): rgb = img[:, :, i] newrgb = interp2(rgb, factor) if new is None: newsize = list(newrgb.shape) newsize.append(imutils.channels(img)) new = _zeros(tuple(newsize)) new[:, :, i] = newrgb return imutils.save(new, filename) if '__main__' in __name__: pass
Add support for json decoding
<?php require_once __DIR__.'/../vendor/autoload.php'; use Silex\Application; use Eyewitness\Router; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\ParameterBag; include __DIR__.'/config.php'; // Basic App Setup Stuff $app = new Application(); $app['debug'] = $debug; $router = new Router($app); // Register service providers include __DIR__.'/../src/EyeWitness/registerProviders.php'; $app->before(function (Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); $app->mount('/api/', $router->setApiRoutes()); $app->run();
<?php require_once __DIR__.'/../vendor/autoload.php'; use Silex\Application; use Eyewitness\Router; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\ParameterBag; include __DIR__.'/config.php'; // Basic App Setup Stuff $app = new Application(); $app['debug'] = $debug; $router = new Router($app); // Register service providers include __DIR__.'/../src/EyeWitness/registerProviders.php'; $app->before(function (Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); $app->mount('/', $router->setBasicRoutes()); $app->run();
Add data to log in liveClipping
<?php /** * @package plugins.cuePoints * @subpackage Scheduler */ class KLiveClippingCopyCuePointEngine extends KLiveToVodCopyCuePointEngine { //override set status to HANDLED as LiveToVod engine protected static function postProcessCuePoints($copiedCuePointIds) {} protected function shouldCopyCuePoint($cuePoint) { $cuePointStartTime = $this->getOffsetForTimestamp($cuePoint->createdAt * 1000, false); $cuePointEndTime = $this->getOffsetForTimestamp($cuePoint->calculatedEndTime * 1000, false); KalturaLog::debug("Checking times to know if copy is needed for id[". $cuePoint->id ."]: start- [$cuePointStartTime], end- [$cuePointEndTime], calculatedEndTime - " . $cuePoint->calculatedEndTime); if ($cuePointStartTime < 0 && is_null($cuePoint->calculatedEndTime)) return true; //if cue point started before the clip but end afterward (no next cue point) return ($cuePointStartTime >= 0 || $cuePointEndTime > 0); } public function getCuePointFilter($entryId, $status = CuePointStatus::READY) { $statuses = array(CuePointStatus::READY, CuePointStatus::HANDLED); $filter = parent::getCuePointFilter($entryId, implode(",",$statuses)); return $filter; } }
<?php /** * @package plugins.cuePoints * @subpackage Scheduler */ class KLiveClippingCopyCuePointEngine extends KLiveToVodCopyCuePointEngine { //override set status to HANDLED as LiveToVod engine protected static function postProcessCuePoints($copiedCuePointIds) {} protected function shouldCopyCuePoint($cuePoint) { $cuePointStartTime = $this->getOffsetForTimestamp($cuePoint->createdAt * 1000, false); $cuePointEndTime = $this->getOffsetForTimestamp($cuePoint->calculatedEndTime * 1000, false); KalturaLog::debug("Checking times to know if copy is needed: start [$cuePointStartTime] end [$cuePointEndTime]"); if ($cuePointStartTime < 0 && is_null($cuePoint->calculatedEndTime)) return true; //if cue point started before the clip but end afterward (no next cue point) return ($cuePointStartTime >= 0 || $cuePointEndTime > 0); } public function getCuePointFilter($entryId, $status = CuePointStatus::READY) { $statuses = array(CuePointStatus::READY, CuePointStatus::HANDLED); $filter = parent::getCuePointFilter($entryId, implode(",",$statuses)); return $filter; } }
Fix settings update when unknown theme is stored
"use strict"; import socket from "../socket"; import upload from "../upload"; import store from "../store"; socket.once("configuration", function(data) { store.commit("serverConfiguration", data); // 'theme' setting depends on serverConfiguration.themes so // settings cannot be applied before this point store.dispatch("settings/applyAll"); if (data.fileUpload) { upload.initialize(); } // If localStorage contains a theme that does not exist on this server, switch // back to its default theme. const currentTheme = data.themes.find((t) => t.name === store.state.settings.theme); if (currentTheme === undefined) { store.dispatch("settings/update", {name: "theme", value: data.defaultTheme, sync: true}); } else if (currentTheme.themeColor) { document.querySelector('meta[name="theme-color"]').content = currentTheme.themeColor; } if (document.body.classList.contains("public")) { window.addEventListener("beforeunload", (e) => { e.preventDefault(); e.returnValue = "Are you sure you want to navigate away from this page?"; }); } });
"use strict"; import socket from "../socket"; import upload from "../upload"; import store from "../store"; socket.once("configuration", function(data) { store.commit("serverConfiguration", data); // 'theme' setting depends on serverConfiguration.themes so // settings cannot be applied before this point store.dispatch("settings/applyAll"); if (data.fileUpload) { upload.initialize(); } // If localStorage contains a theme that does not exist on this server, switch // back to its default theme. const currentTheme = data.themes.find((t) => t.name === store.state.settings.theme); if (currentTheme === undefined) { store.commit("settings/update", {name: "theme", value: data.defaultTheme, sync: true}); } else if (currentTheme.themeColor) { document.querySelector('meta[name="theme-color"]').content = currentTheme.themeColor; } if (document.body.classList.contains("public")) { window.addEventListener("beforeunload", (e) => { e.preventDefault(); e.returnValue = "Are you sure you want to navigate away from this page?"; }); } });
Remove obsolete requirement of pyexiv2.
#! /usr/bin/python from distutils.core import setup try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2.x from distutils.command.build_py import build_py import photo import re DOCLINES = photo.__doc__.split("\n") DESCRIPTION = DOCLINES[0] LONG_DESCRIPTION = "\n".join(DOCLINES[2:]) VERSION = photo.__version__ AUTHOR = photo.__author__ m = re.match(r"^(.*?)\s*<(.*)>$", AUTHOR) (AUTHOR_NAME, AUTHOR_EMAIL) = m.groups() if m else (AUTHOR, None) setup( name = "photo", version = VERSION, description = DESCRIPTION, long_description = LONG_DESCRIPTION, author = AUTHOR_NAME, author_email = AUTHOR_EMAIL, license = "Apache-2.0", requires = ["yaml"], packages = ["photo", "photo.qt"], scripts = ["photoidx.py", "imageview.py"], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Development Status :: 3 - Alpha", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", ], cmdclass = {'build_py': build_py}, )
#! /usr/bin/python from distutils.core import setup try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2.x from distutils.command.build_py import build_py import photo import re DOCLINES = photo.__doc__.split("\n") DESCRIPTION = DOCLINES[0] LONG_DESCRIPTION = "\n".join(DOCLINES[2:]) VERSION = photo.__version__ AUTHOR = photo.__author__ m = re.match(r"^(.*?)\s*<(.*)>$", AUTHOR) (AUTHOR_NAME, AUTHOR_EMAIL) = m.groups() if m else (AUTHOR, None) setup( name = "photo", version = VERSION, description = DESCRIPTION, long_description = LONG_DESCRIPTION, author = AUTHOR_NAME, author_email = AUTHOR_EMAIL, license = "Apache-2.0", requires = ["yaml", "pyexiv2"], packages = ["photo", "photo.qt"], scripts = ["photoidx.py", "imageview.py"], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Development Status :: 3 - Alpha", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", ], cmdclass = {'build_py': build_py}, )
Use gmpy2 instead of numpy
#!/usr/bin/env python # vim: set fileencoding=UTF-8 : import gmpy2 from gmpy2 import mpq, mpfr def ulp(v): return mpq(2) ** v.as_mantissa_exp()[1] def round(mode): def decorator(f): def wrapped(v1, v2): with gmpy2.local_context(round=mode): return f(v1, v2) return wrapped return decorator if __name__ == '__main__': gmpy2.set_context(gmpy2.ieee(32)) print float(ulp(mpfr('0.1'))) mult = lambda x, y: x * y args = [mpfr('0.3'), mpfr('2.6')] print round(gmpy2.RoundDown)(mult)(*args) print round(gmpy2.RoundUp)(mult)(*args)
#!/usr/bin/env python # vim: set fileencoding=UTF-8 : import numpy as np def get_exponent(v): if isinstance(v, np.float32): mask, shift, offset = 0x7f800000, 23, 127 else: raise NotImplementedError('The value v can only be of type np.float32') return ((v.view('i') & mask) >> shift) - offset def ulp(v): if isinstance(v, np.float16): prec = 11 elif isinstance(v, np.float32): prec = 24 elif isinstance(v, np.float64): prec = 53 return 2 ** (get_exponent(v) - prec) def round(v, m='Nearest'): pass if __name__ == '__main__': v = np.float32('2.5') print get_exponent(v) print ulp(v)
Add version to PHP70 dependency
import Dependency from './Dependency' /** * The base class for defining your application's dependencies and installation * proceedures. */ export default class Php70 extends Dependency { default() { this.dependencyName = 'PHP 7.0' this.dependencyLink = 'http://php.net/' this.dependencyDocumentation = 'http://php.net/docs.php' this.dependencyDescription = "PHP is a popular general-purpose scripting language that is especially suited to web development." this.command = 'php -v' this.expectedOutput = /PHP 7\.0/i this.required = true } mac() { this.installCommand = 'brew install php70' this.uninstallCommand = 'brew uninstall php70' } }
import Dependency from './Dependency' /** * The base class for defining your application's dependencies and installation * proceedures. */ export default class Php70 extends Dependency { default() { this.dependencyName = 'Php' this.dependencyLink = 'http://php.net/' this.dependencyDocumentation = 'http://php.net/docs.php' this.dependencyDescription = "PHP is a popular general-purpose scripting language that is especially suited to web development." this.command = 'php -v' this.expectedOutput = /PHP 7\.0/i this.required = true } mac() { this.installCommand = 'brew install php70' this.uninstallCommand = 'brew uninstall php70' } }
Add argument to generation to create doctype
var _ = require('lodash'); var builder = require('xmlbuilder'); var utils = require('./utils'); var generate = require('./generate'); var parse = require('./parse'); function XMLSchema(schema) { this.schema = schema; } // Create a xml string from a schema XMLSchema.prototype.generate = function(value, options, doctype) { options = _.defaults(options || {}, { version: '1.0', encoding: 'UTF-8', standalone: false, pretty: false }); var xml = builder.create(this.schema.tag, { version: options.version, encoding: options.encoding, standalone: options.standalone }, doctype); generate.applySchema(xml, this.schema, value || {}); return xml.end({ pretty: options.pretty }); }; // Parse a xml tring XMLSchema.prototype.parse = function(xml) { return parse.applySchema(xml, this.schema); }; module.exports = XMLSchema;
var _ = require('lodash'); var builder = require('xmlbuilder'); var utils = require('./utils'); var generate = require('./generate'); var parse = require('./parse'); function XMLSchema(schema) { this.schema = schema; } // Create a xml string from a schema XMLSchema.prototype.generate = function(value, options) { options = _.defaults(options || {}, { version: '1.0', encoding: 'UTF-8', standalone: false, pretty: false }); var xml = builder.create(this.schema.tag, { version: options.version, encoding: options.encoding, standalone: options.standalone }); generate.applySchema(xml, this.schema, value || {}); return xml.end({ pretty: options.pretty }); }; // Parse a xml tring XMLSchema.prototype.parse = function(xml) { return parse.applySchema(xml, this.schema); }; module.exports = XMLSchema;
Update tests up to status code change
'use strict'; var expect = require('expect.js'); exports.successResponseCallback = function successResponseCallback(cb, close) { return function testSuccessResp(res) { res.setEncoding('utf8'); expect(res.statusCode).to.be(200); expect(res.headers['content-type']).to.be('text/javascript; charset=utf-8'); expect(res.headers['cache-control']).to.be('no-cache'); res.on('data', function (chunk) { expect(chunk).to.be.a('string'); expect(chunk).to.not.be.empty(); }); res.on('close', cb); res.on('end', function () { if (close) close(cb); else cb(); }); } }; exports.failureResponseCallback = function failureResponseCallback(cb, close) { return function testFailureResp(res) { res.setEncoding('utf8'); expect(res.statusCode).to.be(200); res.on('data', function (chunk) { expect(chunk).to.be.a('string'); expect(chunk).to.contain('Cannot require'); }); res.on('close', cb); res.on('end', function () { if (close) close(cb); else cb(); }); } };
'use strict'; var expect = require('expect.js'); exports.successResponseCallback = function successResponseCallback(cb, close) { return function testSuccessResp(res) { res.setEncoding('utf8'); expect(res.statusCode).to.be(200); expect(res.headers['content-type']).to.be('text/javascript; charset=utf-8'); expect(res.headers['cache-control']).to.be('no-cache'); res.on('data', function (chunk) { expect(chunk).to.be.a('string'); expect(chunk).to.not.be.empty(); }); res.on('close', cb); res.on('end', function () { if (close) close(cb); else cb(); }); } }; exports.failureResponseCallback = function failureResponseCallback(cb, close) { return function testFailureResp(res) { res.setEncoding('utf8'); expect(res.statusCode).to.be(500); res.on('data', function (chunk) { expect(chunk).to.be.a('string'); expect(chunk).to.contain('Cannot require'); }); res.on('close', cb); res.on('end', function () { if (close) close(cb); else cb(); }); } };
Enable domain config only for sqlserver
import mysql from './mysql'; import postgresql from './postgresql'; import sqlserver from './sqlserver'; import cassandra from './cassandra'; /** * List of supported database clients */ export const CLIENTS = [ { key: 'mysql', name: 'MySQL', defaultPort: 3306, disabledFeatures: [ 'server:schema', 'server:domain', ], }, { key: 'postgresql', name: 'PostgreSQL', defaultDatabase: 'postgres', defaultPort: 5432, disabledFeatures: [ 'server:domain', ], }, { key: 'sqlserver', name: 'Microsoft SQL Server', defaultPort: 1433, }, { key: 'cassandra', name: 'Cassandra', defaultPort: 9042, disabledFeatures: [ 'server:ssl', 'server:socketPath', 'server:user', 'server:password', 'server:schema', 'server:domain', 'scriptCreateTable', 'cancelQuery', ], }, ]; export default { mysql, postgresql, sqlserver, cassandra, };
import mysql from './mysql'; import postgresql from './postgresql'; import sqlserver from './sqlserver'; import cassandra from './cassandra'; /** * List of supported database clients */ export const CLIENTS = [ { key: 'mysql', name: 'MySQL', defaultPort: 3306, disabledFeatures: [ 'server:schema', ], }, { key: 'postgresql', name: 'PostgreSQL', defaultDatabase: 'postgres', defaultPort: 5432, }, { key: 'sqlserver', name: 'Microsoft SQL Server', defaultPort: 1433, }, { key: 'cassandra', name: 'Cassandra', defaultPort: 9042, disabledFeatures: [ 'server:ssl', 'server:socketPath', 'server:user', 'server:password', 'server:schema', 'scriptCreateTable', 'cancelQuery', ], }, ]; export default { mysql, postgresql, sqlserver, cassandra, };
Remove buildnumber from version when tag
var jsonfile = require('jsonfile'); // Read in the file to be patched var file = process.argv[2]; // e.g. '../src/MyProject/project.json' if (!file) console.log("No filename provided"); console.log("File: " + file); // Read in the build version (this is provided by the CI server) var version = process.argv[3]; // e.g. '1.0.0-master-10' var tag = process.argv[4]; // e.g. '', or '1.0.0-rc1' if (!version) console.log("No version provided"); var lastDash = version.lastIndexOf("-"); var buildNumber = version.substring(lastDash + 1, version.length); var num = "00000000" + parseInt(buildNumber); buildNumber = num.substr(num.length-5); if (tag) { // Turn version into tag version = tag; } else { version = version.substring(0, lastDash) + '-' + buildNumber; } jsonfile.readFile(file, function (err, project) { console.log("Version: " + version); // Patch the project.version project.version = version; jsonfile.writeFile(file, project, {spaces: 2}, function(err) { if (err) console.error(err); }); })
var jsonfile = require('jsonfile'); // Read in the file to be patched var file = process.argv[2]; // e.g. '../src/MyProject/project.json' if (!file) console.log("No filename provided"); console.log("File: " + file); // Read in the build version (this is provided by the CI server) var version = process.argv[3]; // e.g. '1.0.0-master-10' var tag = process.argv[4]; // e.g. '', or '1.0.0-rc1' if (!version) console.log("No version provided"); var lastDash = version.lastIndexOf("-"); var buildNumber = version.substring(lastDash + 1, version.length); var num = "00000000" + parseInt(buildNumber); buildNumber = num.substr(num.length-5); if (tag) { // Turn version into tag + '-' + buildnumber version = tag + '-' + buildNumber; } else { version = version.substring(0, lastDash) + '-' + buildNumber; } jsonfile.readFile(file, function (err, project) { console.log("Version: " + version); // Patch the project.version project.version = version; jsonfile.writeFile(file, project, {spaces: 2}, function(err) { if (err) console.error(err); }); })
Use system module to get command line arguments
/** * PhantomJS-based web performance metrics collector * * Usage: * node phantomas.js * --url=<page to check> * --debug * --verbose * * @version 0.2 */ // parse script arguments var args = require("system").args, params = require('./lib/args').parse(args), phantomas = require('./core/phantomas').phantomas; // run phantomas var instance = new phantomas(params); // add 3rd party modules instance.addModule('assetsTypes'); instance.addModule('cacheHits'); instance.addModule('cookies'); instance.addModule('domComplexity'); //instance.addModule('domQueries'); // FIXME: jQuery mockup generates random issues instance.addModule('domains'); instance.addModule('headers'); instance.addModule('requestsStats'); instance.addModule('localStorage'); instance.addModule('waterfall'); instance.addModule('windowPerformance'); // and finally - run it! instance.run();
/** * PhantomJS-based web performance metrics collector * * Usage: * node phantomas.js * --url=<page to check> * --debug * --verbose * * @version 0.2 */ // parse script arguments var params = require('./lib/args').parse(phantom.args), phantomas = require('./core/phantomas').phantomas; // run phantomas var instance = new phantomas(params); // add 3rd party modules instance.addModule('assetsTypes'); instance.addModule('cacheHits'); instance.addModule('cookies'); instance.addModule('domComplexity'); //instance.addModule('domQueries'); // FIXME: jQuery mockup generates random issues instance.addModule('domains'); instance.addModule('headers'); instance.addModule('requestsStats'); instance.addModule('localStorage'); instance.addModule('waterfall'); instance.addModule('windowPerformance'); // and finally - run it! instance.run();
Create root page for api.openresolve.com
import os from flask import Flask, jsonify from flask_restful import Api from dns.resolver import Resolver from flask_cors import CORS dns_resolver = Resolver() def create_app(config_name): app = Flask(__name__) if config_name == 'dev': app.config.from_object('resolverapi.config.DevelopmentConfig') else: app.config.from_object('resolverapi.config.BaseConfig') # Get nameservers from environment variable or default to OpenDNS resolvers if os.environ.get('RESOLVERS'): app.config['RESOLVERS'] = [addr.strip() for addr in os.environ.get('RESOLVERS').split(',')] # Respond with Access-Control-Allow-Origin headers. Use * to accept all if os.environ.get('CORS_ORIGIN'): CORS(app, origins=os.environ.get('CORS_ORIGIN')) dns_resolver.lifetime = 3.0 from resolverapi.endpoints import ReverseLookup from resolverapi.endpoints import LookupRecordType api = Api(app) api.add_resource(ReverseLookup, '/reverse/<ip>') api.add_resource(LookupRecordType, '/<rdtype>/<domain>') @app.route('/') def root(): """Provide user a link to the main page. Also this route acts as a health check, returns 200.""" return jsonify({'message': "Check out www.openresolve.com for usage."}), 200 return app
import os from flask import Flask from flask_restful import Api from dns.resolver import Resolver from flask_cors import CORS dns_resolver = Resolver() def create_app(config_name): app = Flask(__name__) if config_name == 'dev': app.config.from_object('resolverapi.config.DevelopmentConfig') else: app.config.from_object('resolverapi.config.BaseConfig') # Get nameservers from environment variable or default to OpenDNS resolvers if os.environ.get('RESOLVERS'): app.config['RESOLVERS'] = [addr.strip() for addr in os.environ.get('RESOLVERS').split(',')] # Respond with Access-Control-Allow-Origin headers. Use * to accept all if os.environ.get('CORS_ORIGIN'): CORS(app, origins=os.environ.get('CORS_ORIGIN')) dns_resolver.lifetime = 3.0 from resolverapi.endpoints import ReverseLookup from resolverapi.endpoints import LookupRecordType api = Api(app) api.add_resource(ReverseLookup, '/reverse/<ip>') api.add_resource(LookupRecordType, '/<rdtype>/<domain>') @app.route('/') def root(): """Health check. No data returned. Just 200.""" return '', 200 return app
Add rowspan and colspan attribute bindings Added rowspan and colspan attribute bindings for table header.
import Ember from 'ember'; import layout from './template'; const { computed } = Ember; export default Ember.Component.extend({ attributeBindings: ['rowspan', 'colspan'], layout: layout, tagName: 'th', classNameBindings: ['sortType', 'isSortable:sortable', 'isActiveColumn:active'], isSortable: false, bindSort: function () { var sort = this.get('sort'), component = this; if (sort) { this.set('isSortable', true); this.$().bind('click', function () { component.toggleOrderBy(); }); } // Initial Sort if (this.get('sortType')) { this.send('sortBy'); } }.on('didInsertElement'), unBindSort: function () { this.$().unbind('click'); }.on('willDestroyElement'), // Computed Properties isActiveColumn: computed('parentView.activeColumn', { get: function () { return this.get('parentView.activeColumn') === this; } }), toggleOrderBy: function () { var sortType = this.get('sortType') || 'asc'; this.set('sortType', (sortType === 'asc') ? 'desc' : 'asc'); this.send('sortBy'); }, // Actions actions:{ sortBy: function () { this.get('parentView').send('onSort', this); } } });
import Ember from 'ember'; import layout from './template'; const { computed } = Ember; export default Ember.Component.extend({ layout: layout, tagName: 'th', classNameBindings: ['sortType', 'isSortable:sortable', 'isActiveColumn:active'], isSortable: false, bindSort: function () { var sort = this.get('sort'), component = this; if (sort) { this.set('isSortable', true); this.$().bind('click', function () { component.toggleOrderBy(); }); } // Initial Sort if (this.get('sortType')) { this.send('sortBy'); } }.on('didInsertElement'), unBindSort: function () { this.$().unbind('click'); }.on('willDestroyElement'), // Computed Properties isActiveColumn: computed('parentView.activeColumn', { get: function () { return this.get('parentView.activeColumn') === this; } }), toggleOrderBy: function () { var sortType = this.get('sortType') || 'asc'; this.set('sortType', (sortType === 'asc') ? 'desc' : 'asc'); this.send('sortBy'); }, // Actions actions:{ sortBy: function () { this.get('parentView').send('onSort', this); } } });
Throw on non-int array lenghts
'use strict'; const EasyObjectValue = require('../values/EasyObjectValue'); const ObjectValue = require('../values/ObjectValue'); const ArrayValue = require('../values/ArrayValue'); const CompletionRecord = require('../CompletionRecord'); class ArrayObject extends EasyObjectValue { *call(thiz, args, s) { if ( args.length === 1 && args[0].jsTypeName === 'number' ) { let len = args[0].toNative(); if ( len != len>>0 ) { return yield CompletionRecord.makeRangeError(this.realm, "Invalid array length"); } let result = ArrayValue.make([], s.realm); yield * result.set('length', args[0]); return result; } return ArrayValue.make(args, s.realm); } callPrototype(realm) { return realm.ArrayPrototype; } constructorFor(realm) { return realm.ArrayPrototype; } //objPrototype(realm) { return realm.Function; } static *isArray(thiz, args) { if ( args.length < 1 ) return EasyObjectValue.false; return EasyObjectValue.fromNative(args[0] instanceof ArrayValue); } } module.exports = ArrayObject;
'use strict'; const EasyObjectValue = require('../values/EasyObjectValue'); const ObjectValue = require('../values/ObjectValue'); const ArrayValue = require('../values/ArrayValue'); class ArrayObject extends EasyObjectValue { *call(thiz, args, s) { if ( args.length === 1 && args[0].jsTypeName === 'number' ) { let result = ArrayValue.make([], s.realm); yield * result.set('length', args[0]); return result; } return ArrayValue.make(args, s.realm); } callPrototype(realm) { return realm.ArrayPrototype; } constructorFor(realm) { return realm.ArrayPrototype; } //objPrototype(realm) { return realm.Function; } static *isArray(thiz, args) { if ( args.length < 1 ) return EasyObjectValue.false; return EasyObjectValue.fromNative(args[0] instanceof ArrayValue); } } module.exports = ArrayObject;
Change for local pid prefix
package org.jsoftware.tjconsole.local; import com.sun.tools.attach.VirtualMachine; /** * Check if tools.jar is available * Receive local java PIDs * Try to load agent for JMX * @author szalik */ public class ProcessListManagerLoader { public static final String LOCAL_PREFIX = "LOCAL:"; private static ProcessListManager processListManager; public static boolean isToolsJarAvailable() { try { Class.forName("com.sun.tools.attach.VirtualMachine"); return true; } catch (ClassNotFoundException e) { return false; } } public static ProcessListManager getProcessListManager() throws ToolsNotAvailableException { if (! isToolsJarAvailable()) { throw new ToolsNotAvailableException(); } synchronized (ProcessListManagerLoader.class) { if (processListManager == null) { processListManager = new ProcessListManager(); } return processListManager; } } /** * @param url url to check * @return true if url string is local process url */ public static boolean isLocalProcess(String url) { return url.startsWith(LOCAL_PREFIX); } }
package org.jsoftware.tjconsole.local; import com.sun.tools.attach.VirtualMachine; /** * Check if tools.jar is available * Receive local java PIDs * Try to load agent for JMX * @author szalik */ public class ProcessListManagerLoader { public static final String LOCAL_PREFIX = "LOCAL "; private static ProcessListManager processListManager; public static boolean isToolsJarAvailable() { try { Class.forName("com.sun.tools.attach.VirtualMachine"); return true; } catch (ClassNotFoundException e) { return false; } } public static ProcessListManager getProcessListManager() throws ToolsNotAvailableException { if (! isToolsJarAvailable()) { throw new ToolsNotAvailableException(); } synchronized (ProcessListManagerLoader.class) { if (processListManager == null) { processListManager = new ProcessListManager(); } return processListManager; } } /** * @param url url to check * @return true if url string is local process url */ public static boolean isLocalProcess(String url) { return url.startsWith(LOCAL_PREFIX); } }
Switch example to geojson primitives
/** * Takes a bounding box and returns a new bounding box with a size expanded or contracted * by a factor of X. * * @module turf/size * @category measurement * @param {Array<number>} bbox a bounding box * @param {number} factor the ratio of the new bbox to the input bbox * @return {Array<number>} the resized bbox * @example * var bbox = [0, 0, 10, 10] * * var resized = turf.size(bbox, 2); * * var features = { * "type": "FeatureCollection", * "features": [ * turf.bboxPolygon(bbox), * turf.bboxPolygon(resized) * ] * }; * * //=features */ module.exports = function(bbox, factor){ var currentXDistance = (bbox[2] - bbox[0]); var currentYDistance = (bbox[3] - bbox[1]); var newXDistance = currentXDistance * factor; var newYDistance = currentYDistance * factor; var xChange = newXDistance - currentXDistance; var yChange = newYDistance - currentYDistance; var lowX = bbox[0] - (xChange / 2); var lowY = bbox[1] - (yChange / 2); var highX = (xChange / 2) + bbox[2]; var highY = (yChange / 2) + bbox[3]; var sized = [lowX, lowY, highX, highY]; return sized; }
/** * Takes a bounding box and returns a new bounding box with a size expanded or contracted * by a factor of X. * * @module turf/size * @category measurement * @param {Array<number>} bbox a bounding box * @param {number} factor the ratio of the new bbox to the input bbox * @return {Array<number>} the resized bbox * @example * var bbox = [0, 0, 10, 10] * * var resized = turf.size(bbox, 2); * * var features = turf.featurecollection([ * turf.bboxPolygon(bbox), * turf.bboxPolygon(resized)]); * * //=features */ module.exports = function(bbox, factor){ var currentXDistance = (bbox[2] - bbox[0]); var currentYDistance = (bbox[3] - bbox[1]); var newXDistance = currentXDistance * factor; var newYDistance = currentYDistance * factor; var xChange = newXDistance - currentXDistance; var yChange = newYDistance - currentYDistance; var lowX = bbox[0] - (xChange / 2); var lowY = bbox[1] - (yChange / 2); var highX = (xChange / 2) + bbox[2]; var highY = (yChange / 2) + bbox[3]; var sized = [lowX, lowY, highX, highY]; return sized; }
Support for variable number of layers
import numpy as np from scipy.special import expit from sklearn import ensemble def get_activations(exp_data, w, b): exp_data = np.transpose(exp_data) prod = exp_data.dot(w) prod_with_bias = prod + b return( expit(prod_with_bias) ) # Order of *args: first all the weights and then all the biases def run_random_forest(exp_data, labels, weights, biases, n_layers=None): assert len(exp_data) == len(labels) # I think they should be already transposed when running the code. Will see act = exp_data#.T # Using ternary operator for shortness n = n_layers if n_layers else len(weights) for i in range(n): print('Weights and biases for layer: ' + str(i+1)) print np.asarray(weights[i]).shape, np.asarray(biases[i]).shape act = get_activations(act.T, weights[i], biases[i]) rf = ensemble.RandomForestClassifier(n_estimators=1000, oob_score=True, max_depth=5) rfit = rf.fit(act, labels) print('OOB score: %.2f\n' % rfit.oob_score_)
import numpy as np # import pandas as pd # import sys from scipy.special import expit from sklearn import ensemble def get_activations(exp_data, w, b): exp_data = np.transpose(exp_data) prod = exp_data.dot(w) prod_with_bias = prod + b return( expit(prod_with_bias) ) # Order of *args: first all the weights and then all the biases def run_random_forest(nHLayers, exp_data, labels, *args): print len(args[0]), len(args[0][0]), len(args[0][1]) print len(args[0][2]) print "NewLine!\n", len(args[0][3]) print "NewLine!\n", len(args[0][4]) assert len(exp_data) == len(labels) # I think they should be already transposed when running the code. Will see act = exp_data#.T for i in range(nHLayers): print('Weights and biases for layer: ' + str(i+1)) print np.asarray(args[0][i]).shape, np.asarray(args[0][nHLayers + i]).shape act = get_activations(act.T, args[0][i], args[0][nHLayers + i]) rf = ensemble.RandomForestClassifier(n_estimators=1000, oob_score=True, max_depth=5) rfit = rf.fit(act, labels) print('OOB score: %.2f\n' % rfit.oob_score_)
Change how the test asserts a file has been deleted. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@63 c7a0535c-eda6-11de-83d8-6d5adf01d787
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.cli; import static org.junit.Assert.assertTrue; import java.io.File; import org.junit.After; import org.junit.Test; public class ClassListReaderFactoryTest { private File classListFile; @Test public void testDefaultReturnedReaderIsPlainTextClassListReader() throws Exception { classListFile = new File("somePlainTextFile.txt"); assertTrue(classListFile.createNewFile()); ClassListToReportCollector collector = new ClassListReaderFactory(classListFile).createReader(); assertTrue("Should be a plain text reader.", collector instanceof PlainTextClassListToReportReader); } @After public void tearDown() { if (classListFile != null) { assertTrue(classListFile.delete()); } } }
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.cli; import static org.junit.Assert.assertTrue; import java.io.File; import org.junit.After; import org.junit.Test; public class ClassListReaderFactoryTest { private File classListFile; @Test public void testDefaultReturnedReaderIsPlainTextClassListReader() throws Exception { classListFile = new File("somePlainTextFile.txt"); classListFile.createNewFile(); ClassListToReportCollector collector = new ClassListReaderFactory(classListFile).createReader(); assertTrue("Should be a plain text reader.", collector instanceof PlainTextClassListToReportReader); } @After public void tearDown() { if (classListFile != null) classListFile.delete(); } }
Stop calling unregisterWorkqueue which was removed in gerrit Change-Id: I9e60c229bab42b893c565196ce058000c647783e
// Copyright (C) 2017 The Android Open Source Project // // 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.googlesource.gerrit.plugins.webhooks; import java.util.concurrent.ScheduledThreadPoolExecutor; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.extensions.events.LifecycleListener; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; class ExecutorProvider implements Provider<ScheduledThreadPoolExecutor>, LifecycleListener { private WorkQueue.Executor executor; @Inject ExecutorProvider(WorkQueue workQueue, Configuration cfg, @PluginName String name) { executor = workQueue.createQueue(cfg.getThreadPoolSize(), name); } @Override public void start() { // do nothing } @Override public void stop() { executor.shutdown(); executor = null; } @Override public ScheduledThreadPoolExecutor get() { return executor; } }
// Copyright (C) 2017 The Android Open Source Project // // 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.googlesource.gerrit.plugins.webhooks; import java.util.concurrent.ScheduledThreadPoolExecutor; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.extensions.events.LifecycleListener; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; class ExecutorProvider implements Provider<ScheduledThreadPoolExecutor>, LifecycleListener { private WorkQueue.Executor executor; @Inject ExecutorProvider(WorkQueue workQueue, Configuration cfg, @PluginName String name) { executor = workQueue.createQueue(cfg.getThreadPoolSize(), name); } @Override public void start() { // do nothing } @Override public void stop() { executor.shutdown(); executor.unregisterWorkQueue(); executor = null; } @Override public ScheduledThreadPoolExecutor get() { return executor; } }
tests/basics: Add test for throw into yield-from with normal return. This test was found by missing coverage of a branch in py/nativeglue.c.
def gen(): try: yield 1 except ValueError as e: print("got ValueError from upstream!", repr(e.args)) yield "str1" raise TypeError def gen2(): print((yield from gen())) g = gen2() print(next(g)) print(g.throw(ValueError)) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # passing None as second argument to throw g = gen2() print(next(g)) print(g.throw(ValueError, None)) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # passing an exception instance as second argument to throw g = gen2() print(next(g)) print(g.throw(ValueError, ValueError(123))) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # thrown value is caught and then generator returns normally def gen(): try: yield 123 except ValueError: print('ValueError') # return normally after catching thrown exception def gen2(): yield from gen() yield 789 g = gen2() print(next(g)) print(g.throw(ValueError))
def gen(): try: yield 1 except ValueError as e: print("got ValueError from upstream!", repr(e.args)) yield "str1" raise TypeError def gen2(): print((yield from gen())) g = gen2() print(next(g)) print(g.throw(ValueError)) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # passing None as second argument to throw g = gen2() print(next(g)) print(g.throw(ValueError, None)) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # passing an exception instance as second argument to throw g = gen2() print(next(g)) print(g.throw(ValueError, ValueError(123))) try: print(next(g)) except TypeError: print("got TypeError from downstream!")
Add normal field to test model
from django.db.models import loading from django.contrib.gis.db import models from django.contrib.gis.geos import GEOSGeometry from mapentity.models import MapEntityMixin class MushroomSpot(models.Model): name = models.CharField(max_length=100, default='Empty') serialized = models.CharField(max_length=200, null=True, default=None) """geom as python attribute""" @property def geom(self): if self.serialized is None: return None return GEOSGeometry(self.serialized) class WeatherStation(models.Model): geom = models.PointField(null=True, default=None, srid=2154) objects = models.GeoManager() class DummyModel(MapEntityMixin, models.Model): @classmethod def get_jsonlist_url(self): return '' @classmethod def get_generic_detail_url(self): return '' @classmethod def get_add_url(self): return '' @classmethod def get_update_url(self): return '' @classmethod def get_delete_url(self): return '' loading.cache.loaded = False
from django.db.models import loading from django.contrib.gis.db import models from django.contrib.gis.geos import GEOSGeometry from mapentity.models import MapEntityMixin class MushroomSpot(models.Model): serialized = models.CharField(max_length=200, null=True, default=None) """geom as python attribute""" @property def geom(self): if self.serialized is None: return None return GEOSGeometry(self.serialized) class WeatherStation(models.Model): geom = models.PointField(null=True, default=None, srid=2154) objects = models.GeoManager() class DummyModel(MapEntityMixin, models.Model): @classmethod def get_jsonlist_url(self): return '' @classmethod def get_generic_detail_url(self): return '' @classmethod def get_add_url(self): return '' @classmethod def get_update_url(self): return '' @classmethod def get_delete_url(self): return '' loading.cache.loaded = False
Add a failing test for objects with quoted keys.
import check from './support/check'; describe('objects', () => { it('adds curly braces immediately around a single-line object', () => { check(` a b: c, d: e `, ` a({b: c, d: e}); `); }); it.skip('indents and loosely wraps multi-line objects if needed', () => { check(` a: b c: d `, ` ({ a: b, c: d }); `); }); it.skip('adds curly braces loosely around a nested-object', () => { check(` a: b: c `, ` ({ a: { b: c } }); `); }); it.skip('uses concise methods for functions in objects', () => { check(` a: -> true b : -> false `, ` ({ a() { return true; }, b() { return false; } }); `); }); it.skip('handles quoted strings as keys', () => { check(` write 301, '', 'Location': pathname+'/' `, ` write(301, '', {'Location': pathname+'/'}); `); }); });
import check from './support/check'; describe('objects', () => { it('adds curly braces immediately around a single-line object', () => { check(` a b: c, d: e `, ` a({b: c, d: e}); `); }); it.skip('indents and loosely wraps multi-line objects if needed', () => { check(` a: b c: d `, ` ({ a: b, c: d }); `); }); it.skip('adds curly braces loosely around a nested-object', () => { check(` a: b: c `, ` ({ a: { b: c } }); `); }); it.skip('uses concise methods for functions in objects', () => { check(` a: -> true b : -> false `, ` ({ a() { return true; }, b() { return false; } }); `); }); });
Clarify functionality of JournalledInsertNode by simplifying code
package org.apache.calcite.adapter.jdbc; import io.pivotal.beach.calcite.programs.BasicForcedRule; import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder; import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.TableModify.Operation; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rel.logical.LogicalTableModify; /** * Created by tzoloc on 11/25/16. */ public class JournalledInsertRule implements BasicForcedRule { @Override public RelNode apply(RelNode originalRel, JdbcRelBuilderFactory relBuilderFactory) { if (!(originalRel instanceof LogicalTableModify)) { return null; } LogicalTableModify tableModify = (LogicalTableModify) originalRel; if (!tableModify.getOperation().equals(Operation.INSERT)) { return null; } if (!(tableModify.getInput() instanceof LogicalProject)) { return null; } // Bypass the projection tableModify.replaceInput(0, tableModify.getInput(0).getInput(0)); return tableModify; } }
package org.apache.calcite.adapter.jdbc; import io.pivotal.beach.calcite.programs.BasicForcedRule; import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder; import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.TableModify.Operation; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rel.logical.LogicalTableModify; /** * Created by tzoloc on 11/25/16. */ public class JournalledInsertRule implements BasicForcedRule { @Override public RelNode apply(RelNode originalRel, JdbcRelBuilderFactory relBuilderFactory) { if (!(originalRel instanceof LogicalTableModify)) { return null; } LogicalTableModify tableModify = (LogicalTableModify) originalRel; if (!tableModify.getOperation().equals(Operation.INSERT)) { return null; } if (!(tableModify.getInput() instanceof LogicalProject)) { return null; } return LogicalTableModify.create( tableModify.getTable(), tableModify.getCatalogReader(), ((LogicalProject) tableModify.getInput()).getInput(), Operation.INSERT, null, //List < String > updateColumnList, null, //List < RexNode > sourceExpressionList, tableModify.isFlattened() ); } }
Fix service provider import path
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Jenssegers\Rollbar\RollbarServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // } /** * Register any application services. * * @return void */ public function register() { $this->app->bind( 'Illuminate\Contracts\Auth\Registrar', 'App\Services\Registrar' ); if ($this->app->environment() == 'local') { $this->app->register('Laracasts\Generators\GeneratorsServiceProvider'); $this->app->register('Barryvdh\Debugbar\ServiceProvider'); $this->app->register('Potsky\LaravelLocalizationHelpers\LaravelLocalizationHelpersServiceProvider'); } if ($this->app->environment() != 'testing') { $this->app->register(RollbarServiceProvider::class); } } }
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // } /** * Register any application services. * * @return void */ public function register() { $this->app->bind( 'Illuminate\Contracts\Auth\Registrar', 'App\Services\Registrar' ); if ($this->app->environment() == 'local') { $this->app->register('Laracasts\Generators\GeneratorsServiceProvider'); $this->app->register('Barryvdh\Debugbar\ServiceProvider'); $this->app->register('Potsky\LaravelLocalizationHelpers\LaravelLocalizationHelpersServiceProvider'); } if ($this->app->environment() != 'testing') { $this->app->register(Jenssegers\Rollbar\RollbarServiceProvider::class); } } }
Fix in/active state of check item
import Item from './item'; export default class CheckItem extends Item { constructor() { super(); this._root .classed('check', true) .styles({ 'cursor': 'pointer' }); this._check = this .icon() .class('ion-ios-circle-outline') .size('1.5em'); this._check .root() .styles({ 'width': '1.75em' }); } _click() { const cancel = this._model === null || this._disabled === true; if (cancel === true) { return; } const value = this._model.get(this._name); const action = typeof value === 'undefined' || value.indexOf(this._value) === -1; this._model.add(this._name, this._value, action); } _set(setEvent) { if (setEvent.name !== this._name) { return; } const value = setEvent.value; const checked = typeof value !== 'undefined' && value.indexOf(this._value) > -1; if (checked === true) { this._check.class('ion-ios-checkmark'); } else { this._check.class('ion-ios-circle-outline'); } } }
import Item from './item'; export default class CheckItem extends Item { constructor() { super(); this._root .classed('check', true) .styles({ 'cursor': 'pointer' }); this._check = this .icon() .class('ion-ios-circle-outline') .size('1.5em'); this._check .root() .styles({ 'width': '1.75em' }); } _click() { const cancel = this._model === null || this._disabled === true; if (cancel === true) { return; } const value = this._model.get(this._name); const action = typeof value === 'undefined' || value.indexOf(this._value) === -1; this._model.add(this._name, this._value, action); } _set(setEvent) { if (setEvent.name !== this._name) { return; } const value = setEvent.value; const checked = typeof value !== 'undefined' && value.indexOf(this._value) > -1; if (checked === true) { this._check.class('ion-ios-circle-outline'); } else { this._check.class('ion-ios-checkmark'); } } }
UP-4802: Add since annotation to getImageCaptions
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * 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.apereo.portal.portlets.backgroundpreference; import javax.portlet.ActionRequest; import javax.portlet.PortletRequest; /** * Strategy for selecting different background image sets based on some criteria such as theme, user agent, etc. * * @author James Wennmacher, jwennmacher@unicon.net */ public interface BackgroundSetSelectionStrategy { String[] getImageSet(PortletRequest req); String[] getImageThumbnailSet(PortletRequest req); /** * @since 4.3.2 */ String[] getImageCaptions(PortletRequest req); String getSelectedImage(PortletRequest req); String getBackgroundContainerSelector(PortletRequest req); void setSelectedImage(ActionRequest req, String backgroundImage); }
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * 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.apereo.portal.portlets.backgroundpreference; import javax.portlet.ActionRequest; import javax.portlet.PortletRequest; /** * Strategy for selecting different background image sets based on some criteria such as theme, user agent, etc. * * @author James Wennmacher, jwennmacher@unicon.net */ public interface BackgroundSetSelectionStrategy { String[] getImageSet(PortletRequest req); String[] getImageThumbnailSet(PortletRequest req); String[] getImageCaptions(PortletRequest req); String getSelectedImage(PortletRequest req); String getBackgroundContainerSelector(PortletRequest req); void setSelectedImage(ActionRequest req, String backgroundImage); }
Declare default timezone in controllers which use date function
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Stations extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('stationsFetcher'); date_default_timezone_set('Europe/Zagreb'); } public function _remap($method) { $trainNo = intval($method); if ($trainNo > 0) { $this->_stations($trainNo); } else { show_error('400 Bad Request', 400); } } private function _stations($trainNo) { $data = $this->stationsfetcher->getStations($trainNo); $data['generated_time'] = date('H:i'); $json = json_encode($data); $this->output->set_header('Cache-Control: no-cache, must-revalidate'); $this->output->set_header('Pragma: no-cache'); if ($this->input->get('callback')) { $this->output->set_content_type('application/javascript'); $this->output->set_output("{$this->input->get('callback')}($json)"); } else { $this->output->set_content_type('application/json'); $this->output->set_output($json); } } }
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Stations extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('stationsFetcher'); } public function _remap($method) { $trainNo = intval($method); if ($trainNo > 0) { $this->_stations($trainNo); } else { show_error('400 Bad Request', 400); } } private function _stations($trainNo) { $data = $this->stationsfetcher->getStations($trainNo); $data['generated_time'] = date('H:i'); $json = json_encode($data); $this->output->set_header('Cache-Control: no-cache, must-revalidate'); $this->output->set_header('Pragma: no-cache'); if ($this->input->get('callback')) { $this->output->set_content_type('application/javascript'); $this->output->set_output("{$this->input->get('callback')}($json)"); } else { $this->output->set_content_type('application/json'); $this->output->set_output($json); } } }
Use new back-end sample's path instead of url
class ApiClient { constructor(baseUrl) { this.baseUrl = baseUrl; } getSamples() { let apiClient = this; return fetch(`${apiClient.baseUrl}/samples`) .then((response) => { if (response.status === 200) { return response.json(); } throw new Error(`Server replied with ${response.status}`); }) .then((json) => json.samples.map((data) => { /* eslint-disable no-param-reassign */ // Javascript's timestamp uses milliseconds data.mtime = 1000 * data.mtime; // Convert path to an absolute url data.url = apiClient.baseUrl + '/samples/' + data.path; return data; /* eslint-enable no-param-reassign */ })); } } export default ApiClient;
class ApiClient { constructor(baseUrl) { this.baseUrl = baseUrl; } getSamples() { return fetch(`${this.baseUrl}/samples`) .then((response) => { if (response.status === 200) { return response.json(); } throw new Error(`Server replied with ${response.status}`); }) .then((json) => json.samples.map((data) => { /* eslint-disable no-param-reassign */ // Javascript's timestamp uses milliseconds data.mtime = 1000 * data.mtime; return data; /* eslint-enable no-param-reassign */ })); } } export default ApiClient;
Use es6 imports instead of require
import {run} from '@cycle/xstream-run'; import {makeDOMDriver, div} from '@cycle/dom'; import xs from 'xstream'; import Scratchpad from './src/scratchpad'; const startingCode = ` import {run} from '@cycle/xstream-run'; import {makeDOMDriver, div, button} from '@cycle/dom'; import _ from 'lodash'; import xs from 'xstream'; function main ({DOM}) { const add$ = DOM .select('.add') .events('click') .map(ev => 1); const count$ = add$ .fold((total, change) => total + change, 0) return { DOM: count$.map(count => div('.counter', [ 'Count: ' + count, button('.add', 'Add') ]) ) }; } const sources = { DOM: makeDOMDriver('.app') } // Normally you need to call Cycle.run, but Tricycle handles that for you! // If you want to try this out locally, just uncomment this code. // // Cycle.run(main, sources); `; function main ({DOM}) { const props = xs.of({code: startingCode}); const scratchpad = Scratchpad(DOM, props); return { DOM: scratchpad.DOM }; } run(main, { DOM: makeDOMDriver('.tricycle') });
import {run} from '@cycle/xstream-run'; import {makeDOMDriver, div} from '@cycle/dom'; import xs from 'xstream'; import Scratchpad from './src/scratchpad'; const startingCode = ` const Cycle = require('@cycle/xstream-run'); const {makeDOMDriver, div, button} = require('@cycle/dom'); const _ = require('lodash'); const xs = require('xstream'); function main ({DOM}) { const add$ = DOM .select('.add') .events('click') .map(ev => 1); const count$ = add$ .fold((total, change) => total + change, 0) return { DOM: count$.map(count => div('.counter', [ 'Count: ' + count, button('.add', 'Add') ]) ) }; } const sources = { DOM: makeDOMDriver('.app') } // Normally you need to call Cycle.run, but Tricycle handles that for you! // If you want to try this out locally, just uncomment this code. // // Cycle.run(main, sources); `; function main ({DOM}) { const props = xs.of({code: startingCode}); const scratchpad = Scratchpad(DOM, props); return { DOM: scratchpad.DOM }; } run(main, { DOM: makeDOMDriver('.tricycle') });
Add a test for ``Enum.__repr__``; ``spiralgalaxygame.sentinel`` now has full coverage.
import unittest from spiralgalaxygame.sentinel import Sentinel, Enum class SentinelTests (unittest.TestCase): def setUp(self): self.s = Sentinel('thingy') def test_name(self): self.assertIs(self.s.name, 'thingy') def test_repr(self): self.assertEqual(repr(self.s), '<Sentinel thingy>') def test_identity_by_name(self): s2 = Sentinel('th' + 'ingy') # `+` to avoid string interning. self.assertIs(s2, self.s) class EnumTests (unittest.TestCase): def setUp(self): self.e = Enum('red', 'green', 'blue') def test_repr(self): self.assertEqual(repr(self.e), '<Enum blue, green, red>') def test_iter_and_members_are_sentinels(self): for member in self.e: self.assertIsInstance(member, Sentinel) def test_member_as_attr_and_in_operator(self): self.assertIn(self.e.green, self.e)
import unittest from spiralgalaxygame.sentinel import Sentinel, Enum class SentinelTests (unittest.TestCase): def setUp(self): self.s = Sentinel('thingy') def test_name(self): self.assertIs(self.s.name, 'thingy') def test_repr(self): self.assertEqual(repr(self.s), '<Sentinel thingy>') def test_identity_by_name(self): s2 = Sentinel('th' + 'ingy') # `+` to avoid string interning. self.assertIs(s2, self.s) class EnumTests (unittest.TestCase): def setUp(self): self.e = Enum('red', 'green', 'blue') def test_iter_and_members_are_sentinels(self): for member in self.e: self.assertIsInstance(member, Sentinel) def test_member_as_attr_and_in_operator(self): self.assertIn(self.e.green, self.e)
Fix bug in admin_module checking
from tinydb import TinyDB, Query class BotModule: name = '' # name of your module description = '' # description of its function help_text = '' # help text for explaining how to do things trigger_string = '' # string to listen for as trigger has_background_loop = False listen_for_reaction = False loaded_modules = [] admin_modules = ['370934086111330308', '372729159933362177'] trigger_char = '!' # char preceding trigger string module_version = '0.0.0' def __init__(self): self.module_db = TinyDB('./modules/databases/' + self.name) async def parse_command(self, message, client): raise NotImplementedError("Parse function not implemented in module:" + self.name) async def background_loop(self, client): raise NotImplementedError("background_loop function not implemented in module:" + self.name) async def on_reaction_add(self, reaction, client, user): raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name) async def on_reaction_remove(self, reaction, client, user): raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
from tinydb import TinyDB, Query class BotModule: name = '' # name of your module description = '' # description of its function help_text = '' # help text for explaining how to do things trigger_string = '' # string to listen for as trigger has_background_loop = False listen_for_reaction = False loaded_modules = [] admin_modules = [370934086111330308, 372729159933362177] trigger_char = '!' # char preceding trigger string module_version = '0.0.0' def __init__(self): self.module_db = TinyDB('./modules/databases/' + self.name) async def parse_command(self, message, client): raise NotImplementedError("Parse function not implemented in module:" + self.name) async def background_loop(self, client): raise NotImplementedError("background_loop function not implemented in module:" + self.name) async def on_reaction_add(self, reaction, client, user): raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name) async def on_reaction_remove(self, reaction, client, user): raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
Add Rector with PHP 7.3
<?php /** @noinspection PhpFullyQualifiedNameUsageInspection */ declare(strict_types=1); use Rector\Core\Configuration\Option; use Rector\Set\ValueObject\SetList; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { // get parameters $parameters = $containerConfigurator->parameters(); // Define what rule sets will be applied $containerConfigurator->import(SetList::PHP_70); $containerConfigurator->import(SetList::PHP_71); $containerConfigurator->import(SetList::PHP_72); $containerConfigurator->import(SetList::PHP_73); // get services (needed for register a single rule) // $services = $containerConfigurator->services(); // register a single rule // $services->set(\Rector\Php74\Rector\Property\TypedPropertyRector::class); };
<?php /** @noinspection PhpFullyQualifiedNameUsageInspection */ declare(strict_types=1); use Rector\Core\Configuration\Option; use Rector\Set\ValueObject\SetList; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { // get parameters $parameters = $containerConfigurator->parameters(); // Define what rule sets will be applied $containerConfigurator->import(SetList::PHP_70); $containerConfigurator->import(SetList::PHP_71); $containerConfigurator->import(SetList::PHP_72); // get services (needed for register a single rule) // $services = $containerConfigurator->services(); // register a single rule // $services->set(\Rector\Php74\Rector\Property\TypedPropertyRector::class); };
Declare Python 3 support, bump version.
# -*- coding: utf-8 -*- from setuptools import setup VERSION = '0.6' setup( name='conllu', packages=["conllu"], version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/conllu/', download_url='https://github.com/EmilStenstrom/conllu/archive/%s.zip' % VERSION, install_requires=[], tests_require=["nose>=1.3.7", "flake8>=3.0.4"], test_suite="nose.collector", keywords=['conllu', 'conll', 'conllu-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Operating System :: OS Independent", ], )
# -*- coding: utf-8 -*- from setuptools import setup VERSION = '0.5' setup( name='conllu', packages=["conllu"], version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/conllu/', download_url='https://github.com/EmilStenstrom/conllu/archive/%s.zip' % VERSION, install_requires=[], tests_require=["nose>=1.3.7", "flake8>=3.0.4"], test_suite="nose.collector", keywords=['conllu', 'conll', 'conllu-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Operating System :: OS Independent", ], )
book-store: Use book price constant in calculation
BOOK_PRICE = 8 def _group_price(size): discounts = [0, .05, .1, .2, .25] if not (0 < size <= 5): raise ValueError('size must be in 1..' + len(discounts)) return BOOK_PRICE * size * (1 - discounts[size - 1]) def calculate_total(books, price_so_far=0.): if not books: return price_so_far groups = list(set(books)) min_price = float('inf') for i in range(len(groups)): remaining_books = books[:] for v in groups[:i + 1]: remaining_books.remove(v) price = calculate_total(remaining_books, price_so_far + _group_price(i + 1)) min_price = min(min_price, price) return min_price
BOOK_PRICE = 8 def _group_price(size): discounts = [0, .05, .1, .2, .25] if not (0 < size <= 5): raise ValueError('size must be in 1..' + len(discounts)) return 8 * size * (1 - discounts[size - 1]) def calculate_total(books, price_so_far=0.): if not books: return price_so_far groups = list(set(books)) min_price = float('inf') for i in range(len(groups)): remaining_books = books[:] for v in groups[:i + 1]: remaining_books.remove(v) price = calculate_total(remaining_books, price_so_far + _group_price(i + 1)) min_price = min(min_price, price) return min_price
Fix oauth2 revoke URI, new URL doesn't seem to work
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client library for using OAuth2, especially with Google APIs.""" __version__ = '4.1.3' GOOGLE_AUTH_URI = 'https://accounts.google.com/o/oauth2/v2/auth' GOOGLE_DEVICE_URI = 'https://oauth2.googleapis.com/device/code' GOOGLE_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke' GOOGLE_TOKEN_URI = 'https://oauth2.googleapis.com/token' GOOGLE_TOKEN_INFO_URI = 'https://oauth2.googleapis.com/tokeninfo'
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client library for using OAuth2, especially with Google APIs.""" __version__ = '4.1.3' GOOGLE_AUTH_URI = 'https://accounts.google.com/o/oauth2/v2/auth' GOOGLE_DEVICE_URI = 'https://oauth2.googleapis.com/device/code' GOOGLE_REVOKE_URI = 'https://oauth2.googleapis.com/revoke' GOOGLE_TOKEN_URI = 'https://oauth2.googleapis.com/token' GOOGLE_TOKEN_INFO_URI = 'https://oauth2.googleapis.com/tokeninfo'
Change boolean to reporter for block with dropdowns
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ['r', '%m.k', 'k', 'heady'] ], menus: { k: ['headx', 'heady', 'righthandx', 'righthandy'] } }; ext.my_first_block = function() { console.log("hello, world."); }; ext.power = function(base, exponent) { return Math.pow(base, exponent); }; ext.k = function(m) { switch(m){ case 'headx': return 1; case 'heady': return 2; case 'righthandx': return 3; case 'righthandy': return 4; } }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ['b', '%m.k', 'k', 'heady'] ], menus: { k: ['headx', 'heady', 'righthandx', 'righthandy'] } }; ext.my_first_block = function() { console.log("hello, world."); }; ext.power = function(base, exponent) { return Math.pow(base, exponent); }; ext.k = function(m) { switch(m){ case 'headx': return true; case 'heady': return true; case 'righthandx': return false; case 'righthandy': return false; } }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
Fix undefined error if sourcemaps option not defined
var StubGenerator = require('./stub-generator'); var CachingBrowserify = require('./caching-browserify'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-browserify', included: function(app){ this.app = app; this.options = { root: this.app.project.root, browserifyOptions: app.project.config(app.env).browserify || {}, enableSourcemap: app.options.sourcemaps ? app.options.sourcemaps.indexOf('js') > -1 : false, fullPaths: app.env !== 'production' }; app.import('browserify/browserify.js'); if (app.importWhitelistFilters) { app.importWhitelistFilters.push(function(moduleName){ return moduleName.slice(0,4) === 'npm:'; }); } }, postprocessTree: function(type, tree){ if (type !== 'js'){ return tree; } return mergeTrees([ tree, new CachingBrowserify(new StubGenerator(tree), this.options) ]); } };
var StubGenerator = require('./stub-generator'); var CachingBrowserify = require('./caching-browserify'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-browserify', included: function(app){ this.app = app; this.options = { root: this.app.project.root, browserifyOptions: app.project.config(app.env).browserify || {}, enableSourcemap: app.options.sourcemaps.indexOf('js') > -1, fullPaths: app.env !== 'production' }; app.import('browserify/browserify.js'); if (app.importWhitelistFilters) { app.importWhitelistFilters.push(function(moduleName){ return moduleName.slice(0,4) === 'npm:'; }); } }, postprocessTree: function(type, tree){ if (type !== 'js'){ return tree; } return mergeTrees([ tree, new CachingBrowserify(new StubGenerator(tree), this.options) ]); } };
Use new send() function arguments
/*jslint node: true */ var path = require('path'); var logger = require('loge'); var send = require('send'); var Router = require('regex-router'); var roots = { static: path.join(__dirname, '..', 'static'), templates: path.join(__dirname, '..', 'templates'), }; var R = new Router(function(req, res) { res.die(404, 'Cannot find resource at ' + req.url); }); var serve = function(req, res, root, path) { send(req, path, {root: root}) .on('error', function(err) { res.die(err.status || 500, 'send error: ' + err.message); }) .on('directory', function() { res.die(404, 'No resource at: ' + req.url); }) .pipe(res); }; R.get(/^\/static\/([^?]+)(\?|$)/, function(req, res, m) { serve(req, res, roots.static, m[1]); }); R.get(/^\/templates\/([^?]+)(\?|$)/, function(req, res, m) { serve(req, res, roots.templates, m[1]); }); R.get('/favicon.ico', function(req, res) { serve(req, res, roots.static, 'favicon.ico'); }); module.exports = R.route.bind(R);
/*jslint node: true */ var path = require('path'); var logger = require('loge'); var send = require('send'); var Router = require('regex-router'); var roots = { static: path.join(__dirname, '..', 'static'), templates: path.join(__dirname, '..', 'templates'), }; var R = new Router(function(req, res) { res.die(404, 'Cannot find resource at ' + req.url); }); var serve = function(req, res, root, path) { send(req, path).root(root) .on('error', function(err) { res.die(err.status || 500, 'send error: ' + err.message); }) .on('directory', function() { res.die(404, 'No resource at: ' + req.url); }) .pipe(res); }; R.get(/^\/static\/([^?]+)(\?|$)/, function(req, res, m) { serve(req, res, roots.static, m[1]); }); R.get(/^\/templates\/([^?]+)(\?|$)/, function(req, res, m) { serve(req, res, roots.templates, m[1]); }); R.get('/favicon.ico', function(req, res) { serve(req, res, roots.static, 'favicon.ico'); }); module.exports = R.route.bind(R);
Fix an issue that tables not be removed in end of each test
# -*- coding: utf-8 -*- import json import os import pytest from pyroonga.odm.table import tablebase, TableBase from pyroonga.tests import utils FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture') FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json') @pytest.fixture def Table(request): class TableBaseForTest(TableBase): @utils.classproperty def __tablename__(cls): if not getattr(cls, '_tablename', None): cls._tablename = utils.gen_unique_tablename() def remove_table(): utils.sendquery('table_remove %s' % cls._tablename) request.addfinalizer(remove_table) return cls._tablename Tbl = tablebase(cls=TableBaseForTest) return Tbl @pytest.fixture def fixture1(): with open(FIXTURE_PATH % 1) as f: return json.load(f) @pytest.fixture def fixture2(): with open(FIXTURE_PATH % 2) as f: return json.load(f)
# -*- coding: utf-8 -*- import json import os import pytest from pyroonga.odm.table import tablebase, TableBase from pyroonga.tests import utils FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture') FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json') @pytest.fixture def Table(request): class TableBaseForTest(TableBase): @utils.classproperty def __tablename__(cls): if not getattr(cls, '_tablename', None): cls._tablename = utils.gen_unique_tablename() return cls._tablename Tbl = tablebase(cls=TableBaseForTest) def remove_table(): utils.sendquery('table_remove %s' % Tbl.__tablename__) request.addfinalizer(remove_table) return Tbl @pytest.fixture def fixture1(): with open(FIXTURE_PATH % 1) as f: return json.load(f) @pytest.fixture def fixture2(): with open(FIXTURE_PATH % 2) as f: return json.load(f)
Use a placeholder string instead of a README. Until I work out why README.rst isn't being included, use this.
import setuptools REQUIREMENTS = [ "docopt==0.6.1", "feedparser==5.1.3", "jabberbot==0.15", "xmpppy==0.5.0rc1", ] if __name__ == "__main__": setuptools.setup( name="dudebot", version="0.0.7", author="Sujay Mansingh", author_email="sujay.mansingh@gmail.com", packages=setuptools.find_packages(), scripts=[], url="https://github.com/sujaymansingh/dudebot", license="LICENSE.txt", description="A really simple framework for chatroom bots", long_description="View the github page (https://github.com/sujaymansingh/dudebot) for more details.", install_requires=REQUIREMENTS )
import setuptools REQUIREMENTS = [ "docopt==0.6.1", "feedparser==5.1.3", "jabberbot==0.15", "xmpppy==0.5.0rc1", ] if __name__ == "__main__": setuptools.setup( name="dudebot", version="0.0.7", author="Sujay Mansingh", author_email="sujay.mansingh@gmail.com", packages=setuptools.find_packages(), package_data={ "dudebot": ["README.rst"] }, scripts=[], url="https://github.com/sujaymansingh/dudebot", license="LICENSE.txt", description="A really simple framework for chatroom bots", long_description="View the github page (https://github.com/sujaymansingh/dudebot) for more details.", install_requires=REQUIREMENTS )
Remove getDriverName method call from the exception message
<?php namespace Maghead\TableParser; use InvalidArgumentException; use Magsql\Driver\BaseDriver; use Magsql\Driver\MySQLDriver; use Magsql\Driver\PgSQLDriver; use Magsql\Driver\SQLiteDriver; use Maghead\Runtime\Connection; class TableParser { public static function create(Connection $c, BaseDriver $d) { if ($d instanceof MySQLDriver) { return new MysqlTableParser($c, $d); } else if ($d instanceof PgSQLDriver) { return new PgsqlTableParser($c, $d); } else if ($d instanceof SQLiteDriver) { return new SqliteTableParser($c, $d); } // This is not going to happen throw new InvalidArgumentException("table parser driver does not support {$d::ID} currently."); } }
<?php namespace Maghead\TableParser; use InvalidArgumentException; use Magsql\Driver\BaseDriver; use Magsql\Driver\MySQLDriver; use Magsql\Driver\PgSQLDriver; use Magsql\Driver\SQLiteDriver; use Maghead\Runtime\Connection; class TableParser { public static function create(Connection $c, BaseDriver $d) { if ($d instanceof MySQLDriver) { return new MysqlTableParser($c, $d); } else if ($d instanceof PgSQLDriver) { return new PgsqlTableParser($c, $d); } else if ($d instanceof SQLiteDriver) { return new SqliteTableParser($c, $d); } // This is not going to happen throw new InvalidArgumentException("table parser driver does not support {$d->getDriverName()} currently."); } }
Fix issue with null timestamps on campaign object. These are sometimes null, causing an issue calling the date formatting method. Why? :(
<?php namespace Northstar\Http\Transformers; use Northstar\Models\Campaign; use League\Fractal\TransformerAbstract; class CampaignTransformer extends TransformerAbstract { /** * @param Campaign $campaign * @return array */ public function transform(Campaign $campaign) { return [ 'drupal_id' => $campaign->drupal_id, 'reportback_id' => $campaign->reportback_id, 'reportback_source' => $campaign->reportback_source, 'reportback_data' => $campaign->reportback_data, 'signup_id' => $campaign->signup_id, 'signup_source' => $campaign->signup_source, 'signup_group' => $campaign->signup_group, // @TODO: Sometimes these aren't set... why? 'updated_at' => $campaign->updated_at ? $campaign->updated_at->toISO8601String() : null, 'created_at' => $campaign->created_at ? $campaign->created_at->toISO8601String() : null, ]; } }
<?php namespace Northstar\Http\Transformers; use Northstar\Models\Campaign; use League\Fractal\TransformerAbstract; class CampaignTransformer extends TransformerAbstract { /** * @param Campaign $campaign * @return array */ public function transform(Campaign $campaign) { return [ 'drupal_id' => $campaign->drupal_id, 'reportback_id' => $campaign->reportback_id, 'reportback_source' => $campaign->reportback_source, 'reportback_data' => $campaign->reportback_data, 'signup_id' => $campaign->signup_id, 'signup_source' => $campaign->signup_source, 'signup_group' => $campaign->signup_group, ]; } }
[Refactoring] Split the function for call and wait processes
import chain from './chain'; import {clone} from './utils'; function vq(el, props, opts = null) { if (!el || !props) throw new Error('Must have two or three args'); if (!opts) { if (!('p' in props && 'o' in props)) { throw new Error('2nd arg must have `p` and `o` property when only two args is given'); } opts = props.o; props = props.p; } // use `props` as progress callback if it is a function if (typeof props === 'function') { opts.progress = props; props = { tween: [1, 0] }; } // Avoid changing original props and opts // vq may mutate these values internally props = clone(props); opts = clone(opts); return chain(el, props, opts); } vq.sequence = function sequence(seq) { if (seq.length === 0) return; const head = unify(seq[0]); const tail = seq.slice(1); return head(() => sequence(tail)); }; function unify(fn) { return function(done) { if (typeof fn !== 'function') return done(); if (fn.length > 0) { // Ensure there is a callback function as 1st argument return fn(done); } const res = fn(); // Wait until the function is terminated if the returned value is thenable if (res && typeof res.then === 'function') { return res.then(done); } return done(); }; } module.exports = vq;
import chain from './chain'; import {clone} from './utils'; function vq(el, props, opts = null) { if (!el || !props) throw new Error('Must have two or three args'); if (!opts) { if (!('p' in props && 'o' in props)) { throw new Error('2nd arg must have `p` and `o` property when only two args is given'); } opts = props.o; props = props.p; } // use `props` as progress callback if it is a function if (typeof props === 'function') { opts.progress = props; props = { tween: [1, 0] }; } // Avoid changing original props and opts // vq may mutate these values internally props = clone(props); opts = clone(opts); return chain(el, props, opts); } vq.sequence = function sequence(seq) { const head = seq[0]; const tail = seq.slice(1); if (typeof head !== 'function') return; if (head.length > 0) { // Ensure there is a callback function as 1st argument return head(function() { sequence(tail); }); } const res = head(); // Wait until the head function is terminated if the returned value is thenable if (res && typeof res.then === 'function') { return res.then(() => sequence(tail)); } return sequence(tail); }; module.exports = vq;
Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@1782 78cadc50-ecff-11dd-a971-7dbc132099af
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
Fix main fn to not rethrow
// Core coroutine runner function run(coroutine) { return new Promise(function (resolve, reject) { (function next(value, exception) { var result; try { result = exception ? coroutine.throw(value) : coroutine.next(value); } catch (error) { return reject(error); } if (result.done) return resolve(result.value); Promise.resolve(result.value).then(next, function(error) { next(error, true); }); })(); }); } function isGeneratorFunction(obj) { return obj && obj.constructor && 'GeneratorFunction' == obj.constructor.name; } // Throw error in next event turn function raise(error) { if (!error) return; setImmediate(function() { throw error; }); } // Run coroutine and raise exception on failure function copromise(coroutine) { if (isGeneratorFunction(coroutine)) { coroutine = coroutine(); } return run(coroutine); } copromise.exec = function exec(coroutine) { return run(coroutine).catch(copromise.raise); }; module.exports = copromise;
// Core coroutine runner function run(coroutine) { return new Promise(function (resolve, reject) { (function next(value, exception) { var result; try { result = exception ? coroutine.throw(value) : coroutine.next(value); } catch (error) { return reject(error); } if (result.done) return resolve(result.value); Promise.resolve(result.value).then(next, function(error) { next(error, true); }); })(); }); } function isGeneratorFunction(obj) { return obj && obj.constructor && 'GeneratorFunction' == obj.constructor.name; } // Throw error in next event turn function raise(error) { if (!error) return; setImmediate(function() { throw error; }); } // Run coroutine and raise exception on failure function copromise(coroutine) { if (isGeneratorFunction(coroutine)) { coroutine = coroutine(); } return run(coroutine).catch(copromise.raise); } copromise.exec = function exec(coroutine) { return run(coroutine).catch(copromise.raise); }; module.exports = copromise;
Remove multilanguage picture titles since they pollute all other picture entities
<?php namespace MssPhp\Schema\Response; use JMS\Serializer\Annotation\AccessType; use JMS\Serializer\Annotation\Type; class Picture { /** * @AccessType("public_method") * @Type("string") */ public $url; public function getUrl() { return $this->url; } public function setUrl($url) { $this->url = str_replace('https://www.easymailing.eu', 'https://www.bookingsuedtirol.com', $url); } /** * @Type("integer") */ public $time; /** * @Type("string") */ public $title; /** * @Type("string") */ public $copyright; }
<?php namespace MssPhp\Schema\Response; use JMS\Serializer\Annotation\AccessType; use JMS\Serializer\Annotation\Type; class Picture { /** * @AccessType("public_method") * @Type("string") */ public $url; public function getUrl() { return $this->url; } public function setUrl($url) { $this->url = str_replace('https://www.easymailing.eu', 'https://www.bookingsuedtirol.com', $url); } /** * @Type("integer") */ public $time; /** * @Type("string") */ public $title; /** * @Type("string") */ public $copyright; /** * @Type("string") */ public $title_deu; /** * @Type("string") */ public $title_ita; /** * @Type("string") */ public $title_eng; /** * @Type("string") */ public $title_spa; /** * @Type("string") */ public $title_fra; /** * @Type("string") */ public $title_rus; /** * @Type("string") */ public $title_dan; }
Update error handling and provide better error message
var async = require('async'), boom = require('boom'), defaultData = {'success' : true}; function Series(arr) { this.arr = arr; Validate(arr); } function Validate(arr) { var len = arr.length; while(len--) { if(typeof arr[len] !== 'function') { throw new Error('Arguments passed in hapi-next must be functions'); } } } Series.prototype.execute = function(request,reply) { if(!request) { throw new Error('Request can\'t be empty.'); return; } if(!reply) { throw new Error('Reply can\'t be empty.'); return; } var arr = this.arr; async.series(arr.map(function(func) { return function(cb) { func.call({},request,reply,function(err) { if(err) { return cb(err); } cb(); }); } }),function(err,results) { if(err) { reply(boom.badData(err)); } reply.data = reply.data || defaultData; reply(reply.data); }); }; module.exports = Series;
var async = require('async'), boom = require('boom'), defaultData = {'success' : true}; function Series(arr) { this.arr = arr; } function Validate(arr) { var len = arr.length; while(len--) { if(typeof arr[len] !== 'function') { throw new Error('') } } } Series.prototype.execute = function(request,reply) { if(!request) { throw new Error('Request can\'t be empty.'); return; } if(!reply) { throw new Error('Reply can\'t be empty.'); return; } var arr = this.arr; async.series(arr.map(function(func) { return function(cb) { func.call({},request,reply,function(err) { if(err) { return cb(err); } cb(); }); } }),function(err,results) { if(err) { reply(boom.badData(err)); } reply.data = reply.data || defaultData; reply(reply.data); }); }; module.exports = Series;
Make title in archive page link to article.
<article <?php post_class(); ?>> <header> <?php if (($posts[0]->post_type != 'faq') && ($posts[0]->post_type != 'service')) : ?> <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php else: ?> <?php $content_class = "large_text_display"; ?> <a class="archive_title" href="<?=the_permalink()?>"><h2 class="entry-title"><?php the_title(); ?></h2></a> <?php endif ?> <?php if ($posts[0]->post_type == 'post') get_template_part('templates/entry-meta'); ?> </header> <div class="entry-summary <?php echo $content_class ? $content_class : '' ?> "> <?php the_content(); ?> </div> </article>
<article <?php post_class(); ?>> <header> <?php if (($posts[0]->post_type != 'faq') && ($posts[0]->post_type != 'service')) : ?> <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php else: ?> <?php $content_class = "large_text_display"; ?> <h2 class="entry-title"><?php the_title(); ?></h2> <?php endif ?> <?php if ($posts[0]->post_type == 'post') get_template_part('templates/entry-meta'); ?> </header> <div class="entry-summary <?php echo $content_class ? $content_class : '' ?> "> <?php the_content(); ?> </div> </article>
Add password handling to default factory.
from django.contrib.auth.models import User import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', 'password') user = super(UserFactory, cls)._prepare(create=False, **kwargs) user.set_password(password) user.raw_password = password if create: user.save() return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
from django.contrib.auth.models import User from django.test import TestCase import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
Fix app after updating to PHP 7.4
<?php namespace App\Exceptions; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Validation\ValidationException; use Laravel\Lumen\Exceptions\Handler as ExceptionHandler; use Symfony\Component\HttpKernel\Exception\HttpException; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ AuthorizationException::class, HttpException::class, ModelNotFoundException::class, ValidationException::class, ]; /** * Report or log an exception. * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(\Throwable $e) { parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, \Throwable $e) { return parent::render($request, $e); } }
<?php namespace App\Exceptions; use Exception; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Validation\ValidationException; use Laravel\Lumen\Exceptions\Handler as ExceptionHandler; use Symfony\Component\HttpKernel\Exception\HttpException; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ AuthorizationException::class, HttpException::class, ModelNotFoundException::class, ValidationException::class, ]; /** * Report or log an exception. * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { return parent::render($request, $e); } }
Extend Phi expression to work with more than 2 values
from .base import SimSootExpr import logging l = logging.getLogger('angr.engines.soot.expressions.phi') class SimSootExpr_Phi(SimSootExpr): def __init__(self, expr, state): super(SimSootExpr_Phi, self).__init__(expr, state) def _execute(self): locals_option = [self._translate_value(v) for v in self.expr.values] values = [] for local in locals_option: value = self.state.memory.load(local, none_if_missing=True) if value is not None: values.append(value) if len(values) == 0: l.warning("Couldn't find a value of Phi expression in memory.") return if len(values) > 2: l.warning("Found multiple values of Phi expression in memory.") self.expr = values[-1]
from .base import SimSootExpr class SimSootExpr_Phi(SimSootExpr): def __init__(self, expr, state): super(SimSootExpr_Phi, self).__init__(expr, state) def _execute(self): if len(self.expr.values) != 2: import ipdb; ipdb.set_trace(); v1, v2 = [self._translate_value(v) for v in self.expr.values] v = self.expr = self.state.memory.load(v1, none_if_missing=True) if v is None: v = self.expr = self.state.memory.load(v2, none_if_missing=True) if v is None: import ipdb; ipdb.set_trace(); self.expr = v
Return error if no items could be fetched
'use strict'; var cheerio = require('cheerio'); var got = require('got'); /** * w3counter API * * @param {String} type * @param {Function} cb * @api public */ module.exports = function (type, cb) { var types = { browser: 'Web Browsers', country: 'Countries', os: 'Operating Systems', res: 'Screen Resolutions' }; var method = types[type]; var ret = []; got('http://www.w3counter.com/globalstats.php', function (err, data) { if (err) { return cb(err); } var $ = cheerio.load(data); $('th').filter(function () { return this.text() === method; }).parent().nextAll('.item').each(function () { ret.push({ item: this.text(), percent: $(this).next('.pct').text() }); }); if (ret.length === 0) { return cb(new Error('Couldn\'t get any ' + method.toLowerCase())); } cb(null, ret); }); };
'use strict'; var cheerio = require('cheerio'); var got = require('got'); /** * w3counter API * * @param {String} type * @param {Function} cb * @api public */ module.exports = function (type, cb) { var types = { browser: 'Web Browsers', country: 'Countries', os: 'Operating Systems', res: 'Screen Resolutions' }; var method = types[type]; var ret = []; got('http://www.w3counter.com/globalstats.php', function (err, data) { if (err) { return cb(err); } var $ = cheerio.load(data); $('th').filter(function () { return this.text() === method; }).parent().nextAll('.item').each(function () { ret.push({ item: this.text(), percent: $(this).next('.pct').text() }); }); if (ret.length === 0) { return cb('Couldn\'t get any ' + method.toLowerCase()); } cb(null, ret); }); };
Fix StyleKeeper context after ES6 conversion `this.context` is inaccessible in the constructor unless you pass the arguments to the component constructor (the second arg is context)
/* @flow */ import React, {Component} from 'react'; import StyleKeeper from '../style-keeper'; export default class StyleSheet extends Component { // $FlowStaticPropertyWarning static contextTypes = { _radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper) }; constructor() { super(...arguments); this.state = this._getCSSState(); } componentDidMount() { this._subscription = this.context._radiumStyleKeeper.subscribe( this._onChange ); this._onChange(); } componentWillUnmount() { if (this._subscription) { this._subscription.remove(); } } _getCSSState(): {css: string} { return {css: this.context._radiumStyleKeeper.getCSS()}; } _onChange() { this.setState(this._getCSSState()); } render(): ReactElement { return ( <style dangerouslySetInnerHTML={{__html: this.state.css}} /> ); } }
/* @flow */ import React, {Component} from 'react'; import StyleKeeper from '../style-keeper'; export default class StyleSheet extends Component { // $FlowStaticPropertyWarning static contextTypes = { _radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper) }; constructor() { super(); this.state = this._getCSSState(); } componentDidMount() { this._subscription = this.context._radiumStyleKeeper.subscribe( this._onChange ); this._onChange(); } componentWillUnmount() { if (this._subscription) { this._subscription.remove(); } } _getCSSState(): {css: string} { return {css: this.context._radiumStyleKeeper.getCSS()}; } _onChange() { this.setState(this._getCSSState()); } render(): ReactElement { return ( <style dangerouslySetInnerHTML={{__html: this.state.css}} /> ); } }
Remove line replace laravel namespace
<?php namespace Caffeinated\Modules\Console; use Module; use Illuminate\Support\Str; use Illuminate\Filesystem\Filesystem; use Symfony\Component\Console\Input\InputArgument; use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand; abstract class GeneratorCommand extends LaravelGeneratorCommand { /** * Parse the name and format according to the root namespace. * * @param string $name * @return string */ protected function parseName($name) { $rootNamespace = config('modules.namespace'); if (Str::startsWith($name, $rootNamespace)) { return $name; } if (Str::contains($name, '/')) { $name = str_replace('/', '\\', $name); } return $this->parseName($this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name); } /** * Get the destination class path. * * @param string $name * @return string */ protected function getPath($name) { $rootNamespace = config('modules.namespace'); $name = str_replace($rootNamespace, '', $name); return module_path().'/'.str_replace('\\', '/', $name).'.php'; } }
<?php namespace Caffeinated\Modules\Console; use Module; use Illuminate\Support\Str; use Illuminate\Filesystem\Filesystem; use Symfony\Component\Console\Input\InputArgument; use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand; abstract class GeneratorCommand extends LaravelGeneratorCommand { /** * Parse the name and format according to the root namespace. * * @param string $name * @return string */ protected function parseName($name) { $rootNamespace = config('modules.namespace'); if (Str::startsWith($name, $rootNamespace)) { return $name; } if (Str::contains($name, '/')) { $name = str_replace('/', '\\', $name); } return $this->parseName($this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name); } /** * Get the destination class path. * * @param string $name * @return string */ protected function getPath($name) { $rootNamespace = config('modules.namespace'); $name = str_replace($this->laravel->getNamespace(), '', $name); $name = str_replace($rootNamespace, '', $name); return module_path().'/'.str_replace('\\', '/', $name).'.php'; } }
:white_check_mark: Test for inclusion of icon data.
const minecraftItems = require('../') const tap = require('tap') const testItem = (test, item, name) => { test.type(item, 'object') test.equal(item.name, name) test.notEqual(typeof item.id, 'undefined', 'items should have an id property') test.notEqual(typeof item.type, 'undefined', 'items should have a type property') test.notEqual(typeof item.meta, 'undefined', 'items should have a meta property') test.notEqual(typeof item.icon, 'undefined', 'items should have a icon property') test.end() } tap.test('should be able to get an item by numeric type', t => { testItem(t, minecraftItems.get(1), 'Stone') }) tap.test('should be able to get an item by string type', t => { testItem(t, minecraftItems.get('1'), 'Stone') }) tap.test('should be able to get an item by string type & subType', t => { testItem(t, minecraftItems.get('1:0'), 'Stone') }) tap.test('should be able to get an item by name', t => { testItem(t, minecraftItems.get('Stone'), 'Stone') }) tap.test('should be able to get an item by name with case insensitivity', t => { testItem(t, minecraftItems.get('stoNe'), 'Stone') })
const minecraftItems = require('../') const tap = require('tap') const testItem = (test, item, name) => { test.type(item, 'object') test.equal(item.name, name) test.end() } tap.test('should be able to get an item by numeric type', t => { testItem(t, minecraftItems.get(1), 'Stone') }) tap.test('should be able to get an item by string type', t => { testItem(t, minecraftItems.get('1'), 'Stone') }) tap.test('should be able to get an item by string type & subType', t => { testItem(t, minecraftItems.get('1:0'), 'Stone') }) tap.test('should be able to get an item by name', t => { testItem(t, minecraftItems.get('Stone'), 'Stone') }) tap.test('should be able to get an item by name with case insensitivity', t => { testItem(t, minecraftItems.get('stoNe'), 'Stone') })
Use test parent class inheritance to avoid boiler plate code.
package com.oneandone.snmpman; import org.snmp4j.smi.OctetString; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.testng.Assert.assertTrue; public class SnmpmanAgentTest extends AbstractSnmpmanTest { @Test public void testSnmpAgentSetupWithCommunityContext() { final List<OctetString> contexts = new ArrayList<>(); final List<SnmpmanAgent> snmpmanAgents = snmpman.getAgents(); for (final SnmpmanAgent agent : snmpmanAgents) { agent.registerManagedObjects(); contexts.addAll(Arrays.asList(agent.getServer().getContexts())); } assertTrue(contexts.contains(new OctetString("9"))); assertTrue(contexts.contains(new OctetString("42"))); } }
package com.oneandone.snmpman; import org.snmp4j.smi.OctetString; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.testng.Assert.assertTrue; public class SnmpmanAgentTest { private Snmpman snmpman; @BeforeMethod public void startSnmpman() { snmpman = Snmpman.start(new File("src/test/resources/configuration/configuration.yaml")); } @Test public void testSnmpAgentSetupWithCommunityContext() { final List<OctetString> contexts = new ArrayList<>(); final List<SnmpmanAgent> snmpmanAgents = snmpman.getAgents(); for (final SnmpmanAgent agent : snmpmanAgents) { agent.registerManagedObjects(); contexts.addAll(Arrays.asList(agent.getServer().getContexts())); } assertTrue(contexts.contains(new OctetString("9"))); assertTrue(contexts.contains(new OctetString("42"))); } @AfterMethod public void stopSnmpman() { if (snmpman != null) { snmpman.stop(); } } }
Fix unnamed SQL parameters not being escaped (api)
const util = require('util'); const mysql = require('mysql'); // Open the database connection. const db = mysql.createConnection({ host: process.env['DB_HOST'], port: process.env['DB_PORT'], user: process.env['DB_USER'], password: process.env['DB_PASS'], database: process.env['DB_NAME'], multipleStatements: true }); // Add support for named parameters in queries. db.config.queryFormat = (query, values) => { if (!values) return query; // Keep unnamed parameter support. if (Array.isArray(values)) { let i = 0; return query.replace(/\?/g, () => db.escape(values[i++])); } return query.replace(/:(\w+)/g, (match, key) => db.escape(values[key])); }; // Promisify query function for async/await. db.query = util.promisify(db.query); module.exports = db;
const util = require('util'); const mysql = require('mysql'); // Open the database connection. const db = mysql.createConnection({ host: process.env['DB_HOST'], port: process.env['DB_PORT'], user: process.env['DB_USER'], password: process.env['DB_PASS'], database: process.env['DB_NAME'], multipleStatements: true }); // Add support for named parameters in queries. db.config.queryFormat = (query, values) => { if (!values) return query; // Keep unnamed parameter support. if (Array.isArray(values)) { let i = 0; return query.replace(/\?/g, () => values[i++]); } return query.replace(/:(\w+)/g, (match, key) => db.escape(values[key] || '')); }; // Promisify query function for async/await. db.query = util.promisify(db.query); module.exports = db;
Use === instead of ==
'use strict'; module.exports = class PivotBuffer { constructor(size) { this.size = size; this.$buffer = new Buffer(size); this.$buffer.fill(0); this.$curSize = 0; } append(buffer) { if (buffer.length === 0) { return; } if (buffer.length >= this.size) { // buffer being appended is longer than buffer size buffer.copy(this.$buffer, 0, buffer.length - this.size); } else { // rotate current buffer var leftover = this.size - buffer.length; this.$buffer.copy(this.$buffer, 0, this.size - leftover); // copy the new buffer to the current one buffer.copy(this.$buffer, leftover); } this.$curSize = Math.min(this.size, this.$curSize + buffer.length); } get value() { return this.$curSize != this.size ? this.$buffer.slice(this.size - this.$curSize) // truncate the buffer if it was not yet filled up : this.$buffer; } get length() { return this.$curSize; } };
'use strict'; module.exports = class PivotBuffer { constructor(size) { this.size = size; this.$buffer = new Buffer(size); this.$buffer.fill(0); this.$curSize = 0; } append(buffer) { if (buffer.length == 0) { return; } if (buffer.length >= this.size) { // buffer being appended is longer than buffer size buffer.copy(this.$buffer, 0, buffer.length - this.size); } else { // rotate current buffer var leftover = this.size - buffer.length; this.$buffer.copy(this.$buffer, 0, this.size - leftover); // copy the new buffer to the current one buffer.copy(this.$buffer, leftover); } this.$curSize = Math.min(this.size, this.$curSize + buffer.length); } get value() { return this.$curSize != this.size ? this.$buffer.slice(this.size - this.$curSize) // truncate the buffer if it was not yet filled up : this.$buffer; } get length() { return this.$curSize; } };
Fix typo after file renaming
/* global fetch */ import React from 'react'; import 'whatwg-fetch'; export default class UserStatisticsPage extends React.Component { constructor(props) { super(props); this.state = { successRate: 0 }; this.getUserStatistics(); } getUserStatistics() { fetch(`api/statistics/${this.props.username}`, { credentials: 'same-origin' }) .then(response => response.json()) .then(data => this.setState({ successRate: data })) .catch(ex => console.log('Fel vid hämtning av användarstatistik', ex)); } render() { return ( <div className="text-center"> <h2>Din totala svarsprocent är {this.state.successRate}%</h2> </div> ); } } UserStatisticsPage.propTypes = { username: React.PropTypes.string.isRequired };
/* global fetch */ import React from 'react'; import 'whatwg-fetch'; export default class UserStatisticPage extends React.Component { constructor(props) { super(props); this.state = { successRate: 0 }; this.getUserStatistics(); } getUserStatistics() { fetch(`api/statistics/${this.props.username}`, { credentials: 'same-origin' }) .then(response => response.json()) .then(data => this.setState({ successRate: data })) .catch(ex => console.log('Fel vid hämtning av användarstatistik', ex)); } render() { return ( <div className="text-center"> <h2>Din totala svarsprocent är {this.state.successRate}%</h2> </div> ); } } UserStatisticPage.propTypes = { username: React.PropTypes.string.isRequired };
Fix endpoint url generation for graphiql
<?php declare(strict_types=1); namespace LotGD\Crate\GraphQL\AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; class GraphiQLController extends Controller { /** * Main controller action.$ * * This method either displays a landing page informing the user that this is * a graphql interface or submits the query to the real controller that manages * graphql queries. * @Route("/") * @param Request $request * @return type */ public function indexAction() { return $this->render( $this->getParameter('overblog_graphql.graphiql_template'), [ 'endpoint' => $this->generateUrl('lotgd_crate_graphql_app_graph_endpoint'), 'versions' => [ 'graphiql' => $this->getParameter('overblog_graphql.versions.graphiql'), 'react' => $this->getParameter('overblog_graphql.versions.react'), ], ] ); } }
<?php declare(strict_types=1); namespace LotGD\Crate\GraphQL\AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; class GraphiQLController extends Controller { /** * Main controller action.$ * * This method either displays a landing page informing the user that this is * a graphql interface or submits the query to the real controller that manages * graphql queries. * @Route("/") * @param Request $request * @return type */ public function indexAction() { return $this->render( $this->getParameter('overblog_graphql.graphiql_template'), [ 'endpoint' => $this->generateUrl('lotgd_crate_www_app_graph_endpoint'), 'versions' => [ 'graphiql' => $this->getParameter('overblog_graphql.versions.graphiql'), 'react' => $this->getParameter('overblog_graphql.versions.react'), ], ] ); } }
Add setGrid and resetGrid functions
#!/usr/bin/env python def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): row = grid[i] rowstr = '' for j in row: rowstr += str(j)+' ' print(rowstr) def serializeGrid(grid): numRow = len(grid) numCol = len(grid[0]) gridstr = '' for j in range(0,numCol): for i in range(0,numRow): gridstr += str(grid[i][j]) return gridstr def setGrid(grid, setlist, rowoffset, coloffset): for entry in setlist: grid[entry[0]+rowoffset][entry[1]+coloffset] = 1 return grid def resetGrid(grid, setlist, rowoffset, coloffset): for entry in setlist: grid[entry[0]+rowoffset][entry[1]+coloffset] = 0 return grid
#!/usr/bin/env python def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): row = grid[i] rowstr = '' for j in row: rowstr += str(j)+' ' print(rowstr) def serializeGrid(grid): numRow = len(grid) numCol = len(grid[0]) gridstr = '' for j in range(0,numCol): for i in range(0,numRow): gridstr += str(grid[i][j]) return gridstr
Fix use of escape characters in "set terminal title" segment. Escape characters were incorrect for non-BASH shells.
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\033]0;%n@%m: %~\007' else: import socket set_title = '\033]0;%s@%s: %s\007' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\\e]0;%n@%m: %~\\a' else: import socket set_title = '\\e]0;%s@%s: %s\\a' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
Store variables for signal status Former-commit-id: e4d925bcfd4543eb9dc309091b0098b3c8e6ccd5
/** * Get the network speed from zebedee/ping endpoint and output the network health **/ function networkStatus(ping) { var $good = $('.icon-status--good'), $ok = $('.icon-status--ok'), $poor = $('.icon-status--poor'), $veryPoor = $('.icon-status--very-poor'); if (ping > 0 && ping < 100) { $('.icon-status div').css({"opacity": "1.0"}); } else if (ping >= 100 && ping < 200) { $good.css({"opacity": "0.2"}); $ok.css({"opacity": "1.0"}); $poor.css({"opacity": "1.0"}); $veryPoor.css({"opacity": "1.0"}); } else if (ping >= 200 && ping < 300) { $good.css({"opacity": "0.2"}); $ok.css({"opacity": "0.2"}); $poor.css({"opacity": "1.0"}); $veryPoor.css({"opacity": "1.0"}); } else if (ping >= 300) { $good.css({"opacity": "0.2"}); $ok.css({"opacity": "0.2"}); $poor.css({"opacity": "0.2"}); $veryPoor.css({"opacity": "1.0"}); } }
/** * Get the network speed from zebedee/ping endpoint and output the network health **/ function networkStatus(ping) { if (ping > 0 && ping < 100) { $('.icon-status div').css({"opacity": "1.0"}); } else if (ping >= 100 && ping < 200) { $('.icon-status--good').css({"opacity": "0.2"}); $('.icon-status--ok').css({"opacity": "1.0"}); $('.icon-status--poor').css({"opacity": "1.0"}); $('.icon-status--very-poor').css({"opacity": "1.0"}); } else if (ping >= 200 && ping < 300) { $('.icon-status--good').css({"opacity": "0.2"}); $('.icon-status--ok').css({"opacity": "0.2"}); $('.icon-status--poor').css({"opacity": "1.0"}); $('.icon-status--very-poor').css({"opacity": "1.0"}); } else if (ping >= 300) { $('.icon-status--good').css({"opacity": "0.2"}); $('.icon-status--ok').css({"opacity": "0.2"}); $('.icon-status--poor').css({"opacity": "0.2"}); $('.icon-status--very-poor').css({"opacity": "1.0"}); } }