text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix an issue where the sort function weren't included in the fkit module.
'use strict'; var util = require('./util'); /** * FKit treats both arrays and strings as *lists*: an array is a list of * elements, and a string is a list of characters. * * Representing strings as lists may be a novel concept for some JavaScript * users, but it is quite common in other languages. This seemingly simple * abstractions yields a great deal of power: it allows you to apply the same * list combinators to both arrays and strings. * * @summary Working with Lists * * @module fkit/list * @mixes module:fkit/list/base * @mixes module:fkit/list/build * @mixes module:fkit/list/fold * @mixes module:fkit/list/map * @mixes module:fkit/list/search * @mixes module:fkit/list/set * @mixes module:fkit/list/sort * @mixes module:fkit/list/sublist * @mixes module:fkit/list/zip * @author Josh Bassett */ module.exports = util.extend({}, [ require('./list/base'), require('./list/build'), require('./list/fold'), require('./list/map'), require('./list/search'), require('./list/set'), require('./list/sort'), require('./list/sublist'), require('./list/zip'), ]);
'use strict'; var util = require('./util'); /** * FKit treats both arrays and strings as *lists*: an array is a list of * elements, and a string is a list of characters. * * Representing strings as lists may be a novel concept for some JavaScript * users, but it is quite common in other languages. This seemingly simple * abstractions yields a great deal of power: it allows you to apply the same * list combinators to both arrays and strings. * * @summary Working with Lists * * @module fkit/list * @mixes module:fkit/list/base * @mixes module:fkit/list/build * @mixes module:fkit/list/fold * @mixes module:fkit/list/map * @mixes module:fkit/list/search * @mixes module:fkit/list/set * @mixes module:fkit/list/sublist * @mixes module:fkit/list/zip * @author Josh Bassett */ module.exports = util.extend({}, [ require('./list/base'), require('./list/build'), require('./list/fold'), require('./list/map'), require('./list/search'), require('./list/set'), require('./list/sublist'), require('./list/zip'), ]);
Check warningCount as well as errorCount http://eslint.org/docs/developer-guide/nodejs-api#executeonfiles "The errorCount and warningCount give the exact number of errors and warnings respectively on the given file."
'use strict'; const colors = require('ansicolors'); const pluralize = require('pluralize'); const CLIEngine = require('eslint').CLIEngine; class ESLinter { constructor(brunchConfig) { this.config = (brunchConfig && brunchConfig.plugins && brunchConfig.plugins.eslint) || {}; this.warnOnly = (this.config.warnOnly === true); this.pattern = this.config.pattern || /^app[\/\\].*\.js?$/; this.engineOptions = this.config.config || {}; this.linter = new CLIEngine(this.engineOptions); } lint(data, path) { const result = this.linter.executeOnText(data, path).results[0]; const errorCount = result.errorCount; const warningCount = result.warningCount; if (errorCount === 0 && warningCount === 0) { return Promise.resolve(); } const errorMsg = result.messages.map(error => { return `${colors.blue(error.message)} (${error.line}:${error.column})`; }); errorMsg.unshift(`ESLint detected ${errorCount} ${(pluralize('problem', errorCount))}:`); let msg = errorMsg.join('\n'); if (this.warnOnly) { msg = `warn: ${msg}`; } return (msg ? Promise.reject(msg) : Promise.resolve()); } } ESLinter.prototype.brunchPlugin = true; ESLinter.prototype.type = 'javascript'; ESLinter.prototype.extension = 'js'; module.exports = ESLinter;
'use strict'; const colors = require('ansicolors'); const pluralize = require('pluralize'); const CLIEngine = require('eslint').CLIEngine; class ESLinter { constructor(brunchConfig) { this.config = (brunchConfig && brunchConfig.plugins && brunchConfig.plugins.eslint) || {}; this.warnOnly = (this.config.warnOnly === true); this.pattern = this.config.pattern || /^app[\/\\].*\.js?$/; this.engineOptions = this.config.config || {}; this.linter = new CLIEngine(this.engineOptions); } lint(data, path) { const result = this.linter.executeOnText(data, path).results[0]; const errorCount = result.errorCount; if (errorCount === 0) { return Promise.resolve(); } const errorMsg = result.messages.map(error => { return `${colors.blue(error.message)} (${error.line}:${error.column})`; }); errorMsg.unshift(`ESLint detected ${errorCount} ${(pluralize('problem', errorCount))}:`); let msg = errorMsg.join('\n'); if (this.warnOnly) { msg = `warn: ${msg}`; } return (msg ? Promise.reject(msg) : Promise.resolve()); } } ESLinter.prototype.brunchPlugin = true; ESLinter.prototype.type = 'javascript'; ESLinter.prototype.extension = 'js'; module.exports = ESLinter;
Remove user from db connection string
# -*- coding: utf-8 -*- from flask import Flask import os import psycopg2 from contextlib import closing DB_SCHEMA = """ DROP TABLE IF EXISTS entries; CREATE TABLE entries ( id serial PRIMARY KEY, title VARCHAR (127) NOT NULL, text TEXT NOT NULL, created TIMESTAMP NOT NULL ) """ app = Flask(__name__) app.config['DATABASE'] = os.environ.get( 'DATABASE_URL', 'dbname=learning_journal' ) def connect_db(): """Return a connection to the configured database""" return psycopg2.connect(app.config['DATABASE']) def init_db(): """Initialize the database using DB_SCHEMA WARNING: executing this function will drop existing tables. """ with closing(connect_db()) as db: db.cursor().execute(DB_SCHEMA) db.commit() @app.route('/') def hello(): return u'Hello world!' if __name__ == '__main__': app.run(debug=True)
# -*- coding: utf-8 -*- from flask import Flask import os import psycopg2 from contextlib import closing DB_SCHEMA = """ DROP TABLE IF EXISTS entries; CREATE TABLE entries ( id serial PRIMARY KEY, title VARCHAR (127) NOT NULL, text TEXT NOT NULL, created TIMESTAMP NOT NULL ) """ app = Flask(__name__) app.config['DATABASE'] = os.environ.get( 'DATABASE_URL', 'dbname=learning_journal user=miked, lfritts' ) def connect_db(): """Return a connection to the configured database""" return psycopg2.connect(app.config['DATABASE']) def init_db(): """Initialize the database using DB_SCHEMA WARNING: executing this function will drop existing tables. """ with closing(connect_db()) as db: db.cursor().execute(DB_SCHEMA) db.commit() @app.route('/') def hello(): return u'Hello world!' if __name__ == '__main__': app.run(debug=True)
Change tabular to 4 spaces
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
[fix] Check for lack of host header.
var union = require('union'), ecstatic = require('ecstatic'); var port = process.env.PORT || 8080; // // ### redirect(res) // World's simplest redirect function // function redirect(res) { var url = 'http://2015.empirenode.org', body = '<p>301. Redirecting to <a href="' + url + '">' + url + '</a></p>'; res.writeHead(301, { 'content-type': 'text/html', location: url }); res.end(body); } var server = union.createServer({ before: [ function (req, res) { var host = req.headers.host || '', parts = host.split('.'); console.log('%s - %s%s', req.method, host, req.url); if (process.env.NODE_ENV === 'production' && (parts.length !== 3 || parts[0] === 'www')) { return redirect(res); } res.emit('next'); }, ecstatic({ root: __dirname + '/public', defaultExt: true }), function (req, res) { return redirect(res); } ] }); server.listen(port, function () { console.log('Listening on %s', port); });
var union = require('union'), ecstatic = require('ecstatic'); var port = process.env.PORT || 8080; // // ### redirect(res) // World's simplest redirect function // function redirect(res) { var url = 'http://2015.empirenode.org', body = '<p>301. Redirecting to <a href="' + url + '">' + url + '</a></p>'; res.writeHead(301, { 'content-type': 'text/html', location: url }); res.end(body); } var server = union.createServer({ before: [ function (req, res) { var host = req.headers.host, parts = host.split('.'); console.log('%s - %s%s', req.method, host, req.url); if (process.env.NODE_ENV === 'production' && (parts.length !== 3 || parts[0] === 'www')) { return redirect(res); } res.emit('next'); }, ecstatic({ root: __dirname + '/public', defaultExt: true }), function (req, res) { return redirect(res); } ] }); server.listen(port, function () { console.log('Listening on %s', port); });
Fix a problem where else rendering is messed up when an if is inside an if
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.jdeparser; import static org.jboss.jdeparser.Tokens.$KW; import java.io.IOException; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ class ElseJBlock extends BasicJBlock { ElseJBlock(final ImplJIf _if) { this(_if, Braces.IF_MULTILINE); } ElseJBlock(final ImplJIf _if, final Braces braces) { super(_if.getParent(), braces); } void write(final SourceFileWriter writer, final FormatPreferences.Space beforeBrace, final Braces braces) throws IOException { writer.write(FormatPreferences.Space.BEFORE_KEYWORD_ELSE); writer.write($KW.ELSE); super.write(writer, beforeBrace, braces); } }
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.jdeparser; import static org.jboss.jdeparser.Tokens.$KW; import java.io.IOException; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ class ElseJBlock extends BasicJBlock { ElseJBlock(final ImplJIf _if) { this(_if, Braces.IF_MULTILINE); } ElseJBlock(final ImplJIf _if, final Braces braces) { super(_if.getParent(), braces); } public void write(final SourceFileWriter writer) throws IOException { writeComments(writer); writer.write(FormatPreferences.Space.BEFORE_KEYWORD_ELSE); writer.write($KW.ELSE); super.write(writer, FormatPreferences.Space.BEFORE_BRACE_ELSE); } }
Allow to override kwargs of filter
from django.views import generic class FilteredListView(generic.ListView): """List view with support for filtering and sorting via django-filter. Usage: Set filter_set to your django_filters.FilterSet definition. Use view.filter.form in the template to access the filter form. Note: Always call super().get_queryset() when customizing get_queryset() to include the filter functionality. """ filter_set = None def filter_kwargs(self): default_kwargs = { 'data': self.request.GET, 'request': self.request, 'queryset': super().get_queryset() } return default_kwargs def filter(self): return self.filter_set( **self.filter_kwargs() ) def get_queryset(self): qs = self.filter().qs return qs
from django.views import generic class FilteredListView(generic.ListView): """List view with support for filtering and sorting via django-filter. Usage: Set filter_set to your django_filters.FilterSet definition. Use view.filter.form in the template to access the filter form. Note: Always call super().get_queryset() when customizing get_queryset() to include the filter functionality. """ filter_set = None def filter(self): return self.filter_set( self.request.GET, request=self.request ) def get_queryset(self): qs = self.filter().qs return qs
Optimize production builds by passing in NODE_ENV React contains a lot of debugging machinery that is being run throughout development. This should always be stripped out in production in order to make the application more performant. The most simple way to do this is with the built-in Webpack EnvironmentPlugin that will make the environment variables given available to the script and make React strip out debugging calls when NODE_ENV is not set to “development”. There is a more advanced way of achieving the same with the DefinePlugin, but this power is not needed here. The DefinePlugin has the added benefit of allowing you to define your own “globals” and make use of them in the script. new webpack.DefinePlugin({ '__DEV__': JSON.stringify(false), '__MY_OTHER_GLOBAL__': 'A nice value', 'process.env.NODE_ENV': JSON.stringify('production') })
var path = require('path'); var webpack = require('webpack'); module.exports = { context: __dirname + "/src", entry: "./jsx/main.jsx", output: { path: path.join(__dirname, 'build'), filename: 'js/app.js' }, resolve: { extensions: ['', '.js', '.jsx'], modulesDirectories: ["src/jsx", "node_modules"] }, module: { loaders: [ { exclude: /node_modules/, test: /\.jsx?$/, loader: "babel-loader", query: { cacheDirectory: true, presets: ['es2015', 'react'] } }, { test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$|\.wav$|\.mp3$/, loader: "file" }, { test: /\.html$/, loader: "file?name=[name].[ext]", }, { test: /\.sass$/, loaders: ["style", "css", "sass?indentedSyntax"] } ] }, // context: path.join(__dirname, 'build'), plugins: [ new webpack.EnvironmentPlugin('NODE_ENV') ] };
var path = require('path'); module.exports = { context: __dirname + "/src", entry: "./jsx/main.jsx", output: { path: path.join(__dirname, 'build'), filename: 'js/app.js' }, resolve: { extensions: ['', '.js', '.jsx'], modulesDirectories: ["src/jsx", "node_modules"] }, module: { loaders: [ { exclude: /node_modules/, test: /\.jsx?$/, loader: "babel-loader", query: { cacheDirectory: true, presets: ['es2015', 'react'] } }, { test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$|\.wav$|\.mp3$/, loader: "file" }, { test: /\.html$/, loader: "file?name=[name].[ext]", }, { test: /\.sass$/, loaders: ["style", "css", "sass?indentedSyntax"] } ] }, // context: path.join(__dirname, 'build'), plugins: [ ] };
Check number of arguments instead of val existence
var extend = require('extend'); var Plom = function(options) { this.options = options || {}; this.data = this.options.data || {}; } Plom.extend = function(object) { var NewPlom = function(options) { this.options = options || {}; this.data = this.options.data || {}; if(this.initialize) { this.initialize(options); } }; object = object || null; NewPlom.prototype = extend({}, this.prototype, object); NewPlom.extend = this.extend.bind(this); return NewPlom; }; Plom.prototype.set = function(key, val) { var argsLength = Array.prototype.slice.call(arguments).length; if (argsLength === 2) { this.data[key] = val; return this; } this.data = key; return this; }; Plom.prototype.get = function(key) { if(key) { return this.data[key]; } return this.data; }; module.exports = Plom;
var extend = require('extend'); var Plom = function(options) { this.options = options || {}; this.data = this.options.data || {}; } Plom.extend = function(object) { var NewPlom = function(options) { this.options = options || {}; this.data = this.options.data || {}; if(this.initialize) { this.initialize(options); } }; object = object || null; NewPlom.prototype = extend({}, this.prototype, object); NewPlom.extend = this.extend.bind(this); return NewPlom; }; Plom.prototype.set = function(key, val) { if(typeof val !== 'undefined') { this.data[key] = val; return this; } this.data = key; return this; }; Plom.prototype.get = function(key) { if(key) { return this.data[key]; } return this.data; }; module.exports = Plom;
Set the RBAC role hierarchy to 10 levels by default.
// Copyright 2017 The casbin Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package model import ( "log" "github.com/casbin/casbin/rbac" ) // Assertion represents an expression in a section of the model. // For example: r = sub, obj, act type Assertion struct { Key string Value string Tokens []string Policy [][]string RM *rbac.RoleManager } func (ast *Assertion) buildRoleLinks() { ast.RM = rbac.NewRoleManager(10) for _, rule := range ast.Policy { if len(rule) == 2 { ast.RM.AddLink(rule[0], rule[1]) } else if len(rule) == 3 { ast.RM.AddLink(rule[0], rule[1], rule[2]) } } log.Print("Role links for: " + ast.Key) ast.RM.PrintRoles() }
// Copyright 2017 The casbin Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package model import ( "log" "github.com/casbin/casbin/rbac" ) // Assertion represents an expression in a section of the model. // For example: r = sub, obj, act type Assertion struct { Key string Value string Tokens []string Policy [][]string RM *rbac.RoleManager } func (ast *Assertion) buildRoleLinks() { ast.RM = rbac.NewRoleManager(1) for _, rule := range ast.Policy { if len(rule) == 2 { ast.RM.AddLink(rule[0], rule[1]) } else if len(rule) == 3 { ast.RM.AddLink(rule[0], rule[1], rule[2]) } } log.Print("Role links for: " + ast.Key) ast.RM.PrintRoles() }
Remove print statements for syncdb receivers
from django.db.models.signals import post_syncdb from django.conf import settings from accounts import models def ensure_core_accounts_exists(sender, **kwargs): create_source_account() create_sales_account() create_expired_account() def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') models.Account.objects.get_or_create(name=name) def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') models.Account.objects.get_or_create(name=name) def create_source_account(): # Create a source account if one does not exist if not hasattr(settings, 'ACCOUNTS_SOURCE_NAME'): return # We only create the source account if there are no accounts already # created. if models.Account.objects.all().count() > 0: return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') models.Account.objects.get_or_create(name=name, credit_limit=None) post_syncdb.connect(ensure_core_accounts_exists, sender=models)
from django.db.models.signals import post_syncdb from django.conf import settings from accounts import models def ensure_core_accounts_exists(sender, **kwargs): create_source_account() create_sales_account() create_expired_account() def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') __, created = models.Account.objects.get_or_create(name=name) if created: print "Created sales account '%s'" % name def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') __, created = models.Account.objects.get_or_create(name=name) if created: print "Created expired account '%s'" % name def create_source_account(): # Create a source account if one does not exist if not hasattr(settings, 'ACCOUNTS_SOURCE_NAME'): return # We only create the source account if there are no accounts already # created. if models.Account.objects.all().count() > 0: return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') __, created = models.Account.objects.get_or_create(name=name, credit_limit=None) if created: print "Created source account '%s'" % name post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Sort the staff by their order attr
<?php defined('C5_EXECUTE') or die("Access Denied."); Loader::model('user_list'); $av = Loader::helper('concrete/avatar'); $ul = new UserList(); $ul->filterByGroup('Staff'); $ul->sortBy('ak_order','asc'); $content = $controller->getContent(); print $content; ?> <ul class="ccm-staff-list"> <?php foreach($ul->get(100) as $staffMember) { ?> <li> <?php if($avatar = $av->getImagePath($staffMember)) { ?> <div class='u-avatar' style='background-image:url(<?=$avatar?>)'></div> <?php } else { ?> <div class='u-avatar placeholder<?=ord($staffMember->getUserID()) % 3?>'></div> <?php } ?> <div class='ccm-staff-list-details'> <h3><?="{$staffMember->getAttribute('first_name')} {$staffMember->getAttribute('last_name')}, " . ($staffMember->getAttribute('job_title') ?: 'Jane\'s Walk');?></h3> <a href="mailto:<?=($email = $staffMember->getUserEmail())?>"><?=$email?></a> <p class='ccm-staff-list-bio'><?=$staffMember->getAttribute('bio')?></p> </div> </li> <?php } ?> </ul>
<?php defined('C5_EXECUTE') or die("Access Denied."); Loader::model('user_list'); $av = Loader::helper('concrete/avatar'); $ul = new UserList(); $ul->filterByGroup('Staff'); $ul->sortBy('uName'); $content = $controller->getContent(); print $content; ?> <ul class="ccm-staff-list"> <?php foreach($ul->get(100) as $staffMember) { ?> <li> <?php if($avatar = $av->getImagePath($staffMember)) { ?> <div class='u-avatar' style='background-image:url(<?=$avatar?>)'></div> <?php } else { ?> <div class='u-avatar placeholder<?=ord($staffMember->getUserID()) % 3?>'></div> <?php } ?> <div class='ccm-staff-list-details'> <h3><?="{$staffMember->getAttribute('first_name')} {$staffMember->getAttribute('last_name')}, " . ($staffMember->getAttribute('job_title') ?: 'Jane\'s Walk');?></h3> <a href="mailto:<?=($email = $staffMember->getUserEmail())?>"><?=$email?></a> <p class='ccm-staff-list-bio'><?=$staffMember->getAttribute('bio')?></p> </div> </li> <?php } ?> </ul>
Docs: Update createInstance documentation to be more clear Former-commit-id: c79279a20551c2cac39e2b2d74a8941914b62d98 Former-commit-id: 935f0112079632ec2940db2ca281707f2007815f
<?php namespace Concrete\Core\Foundation\Service; use \Concrete\Core\Application\Application; class ProviderList { public function __construct(Application $app) { $this->app = $app; } /** * Loads and registers a class ServiceProvider class. * @param string $class * @return void */ public function registerProvider($class) { $this->createInstance($class)->register(); } /** * Creates an instance of the passed class string, override this to change how providers are instantiated * * @param string $class The class name * @return \Concrete\Core\Foundation\Service\Provider */ protected function createInstance($class) { return new $class($this->app); } /** * Registers an array of service group classes. * @param array $groups * @return void */ public function registerProviders($groups) { foreach($groups as $group) { $this->registerProvider($group); } } /** * We are not allowed to serialize $this->app */ public function __sleep() { unset($this->app); } }
<?php namespace Concrete\Core\Foundation\Service; use \Concrete\Core\Application\Application; class ProviderList { public function __construct(Application $app) { $this->app = $app; } /** * Loads and registers a class ServiceProvider class. * @param string $class * @return void */ public function registerProvider($class) { $this->createInstance($class)->register(); } /** * Class for creating an instance of a passed class string, override this to add extra functionality * * @param string $class The class name * @return \Concrete\Core\Foundation\Service\Provider */ protected function createInstance($class) { return new $class($this->app); } /** * Registers an array of service group classes. * @param array $groups * @return void */ public function registerProviders($groups) { foreach($groups as $group) { $this->registerProvider($group); } } /** * We are not allowed to serialize $this->app */ public function __sleep() { unset($this->app); } }
Set minimum query length to 10 nts The shortest length that the nhmmer alphabet guesser will work on is 10.
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ # minimum query sequence length MIN_LENGTH = 10 # maximum query sequence length MAX_LENGTH = 10000 # Redis results expiration time EXPIRATION = 60*60*24*7 # seconds # maximum time to run nhmmer MAX_RUN_TIME = 60*60 # seconds # full path to query files QUERY_DIR = '' # full path to results files RESULTS_DIR = '' # full path to nhmmer executable NHMMER_EXECUTABLE = '' # full path to sequence database SEQDATABASE = ''
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ # minimum query sequence length MIN_LENGTH = 11 # maximum query sequence length MAX_LENGTH = 10000 # Redis results expiration time EXPIRATION = 60*60*24*7 # seconds # maximum time to run nhmmer MAX_RUN_TIME = 60*60 # seconds # full path to query files QUERY_DIR = '' # full path to results files RESULTS_DIR = '' # full path to nhmmer executable NHMMER_EXECUTABLE = '' # full path to sequence database SEQDATABASE = ''
Switch to example to localhost uppy-server
import { Core, Dummy, Dashboard, GoogleDrive, Webcam, Tus10, MetaData, Informer } from '../src/index.js' // import ru_RU from '../src/locales/ru_RU.js' // import MagicLog from '../src/plugins/MagicLog' const uppy = new Core({debug: true, autoProceed: false}) .use(Dashboard, {trigger: '#uppyModalOpener', inline: false}) .use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'}) .use(Dummy, {target: Dashboard}) .use(Webcam, {target: Dashboard}) // .use(ProgressBar, {target: Dashboard}) .use(Tus10, {endpoint: 'http://master.tus.io:8080/files/', resume: false}) .use(Informer, {target: Dashboard}) .use(MetaData, { fields: [ { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' }, { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' } ] }) uppy.run() // uppy.emit('informer', 'Smile!', 'info', 2000) uppy.on('core:success', (fileCount) => { console.log(fileCount) }) document.querySelector('#uppyModalOpener').click()
import { Core, Dummy, Dashboard, GoogleDrive, Webcam, Tus10, MetaData, Informer } from '../src/index.js' // import ru_RU from '../src/locales/ru_RU.js' // import MagicLog from '../src/plugins/MagicLog' const uppy = new Core({debug: true, autoProceed: false}) .use(Dashboard, {trigger: '#uppyModalOpener', inline: false}) .use(GoogleDrive, {target: Dashboard, host: 'http://ya.ru'}) .use(Dummy, {target: Dashboard}) .use(Webcam, {target: Dashboard}) // .use(ProgressBar, {target: Dashboard}) .use(Tus10, {endpoint: 'http://master.tus.io:8080/files/', resume: false}) .use(Informer, {target: Dashboard}) .use(MetaData, { fields: [ { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' }, { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' } ] }) uppy.run() // uppy.emit('informer', 'Smile!', 'info', 2000) uppy.on('core:success', (fileCount) => { console.log(fileCount) }) document.querySelector('#uppyModalOpener').click()
Include test for invalid input
<?php namespace Zend\Romans\View\Helper; use PHPUnit\Framework\TestCase; use Zend\View\Helper\HelperInterface; /** * Roman Test */ class RomanTest extends TestCase { /** * {@inheritdoc} */ protected function setUp() { $this->helper = new Roman(); } /** * Test Instance Of */ public function testInstanceOf() { $this->assertInstanceOf(HelperInterface::class, $this->helper); } /** * Test Roman */ public function testRoman() { $this->assertSame('N', ($this->helper)(0)); $this->assertSame('I', ($this->helper)(1)); $this->assertSame('CDLXIX', ($this->helper)(469)); $this->assertSame('MCMXCIX', ($this->helper)(1999)); } /** * Test Roman with Invalid Value */ public function testRomanWithInvalidValue() { $this->assertNull(($this->helper)('-1')); } }
<?php namespace Zend\Romans\View\Helper; use PHPUnit\Framework\TestCase; use Zend\View\Helper\HelperInterface; /** * Roman Test */ class RomanTest extends TestCase { /** * {@inheritdoc} */ protected function setUp() { $this->helper = new Roman(); } /** * Test Instance Of */ public function testInstanceOf() { $this->assertInstanceOf(HelperInterface::class, $this->helper); } /** * Test Roman */ public function testRoman() { $this->assertSame('N', ($this->helper)(0)); $this->assertSame('I', ($this->helper)(1)); $this->assertSame('CDLXIX', ($this->helper)(469)); $this->assertSame('MCMXCIX', ($this->helper)(1999)); } }
Add documentation for 8ball command
# Copyright (c) 2013-2014 Molly White # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from plugins.util import command from random import choice @command("8ball", "8-ball") def eightball(m): """Returns 8-ball advice.""" #- !8ball [question] #- #- ```irc #- < GorillaWarfare> !8ball #- < GorillaBot> Most likely. #- ``` #- #- Returns a magic 8 ball response. with open(m.bot.base_path + '/plugins/responses/8ball.txt', 'r') as replies: lines = replies.read().splitlines() m.bot.private_message(m.location, choice(lines))
# Copyright (c) 2013-2014 Molly White # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from plugins.util import command from random import choice @command("8ball", "8-ball") def eightball(m): """Returns 8-ball advice.""" with open(m.bot.base_path + '/plugins/responses/8ball.txt', 'r') as replies: lines = replies.read().splitlines() m.bot.private_message(m.location, choice(lines))
Fix a possible deadlock in unit tests after an error Summary: After certain types of errors, we may deadlock when trying to destroy test databases. Specifically, we still have connections open to, say, `phabricator_unittest_abasonaknlbaklnasb_herald` (or whatever) and MySQL sometimes (not sure exactly when?) waits for them before destorying the database. Test Plan: - Added `$m = null; $m->method()` to a fixture test to force a fatal. - Saw consistent deadlock, with `storage destroy` never exiting. - Added `--trace` to the `storage destroy` command and made it use `phutil_passthru()` so I could see what was happening. - Saw it hang on some arbitrary database. - Conneced to MySQL, used `show full processlist;` to see what was wrong. - Saw the `DROP DATABASE ...` command waiting for locks to release on the database, and other connections still open. - Applied patch. - Saw consistent success. - Used `storage destroy --unittest-fixtures` to clean up extra databases. Reviewers: chad Reviewed By: chad Differential Revision: https://secure.phabricator.com/D14875
<?php /** * Used by unit tests to build storage fixtures. */ final class PhabricatorStorageFixtureScopeGuard extends Phobject { private $name; public function __construct($name) { $this->name = $name; execx( 'php %s upgrade --force --no-adjust --namespace %s', $this->getStorageBinPath(), $this->name); PhabricatorLiskDAO::pushStorageNamespace($name); // Destructor is not called with fatal error. register_shutdown_function(array($this, 'destroy')); } public function destroy() { PhabricatorLiskDAO::popStorageNamespace(); // NOTE: We need to close all connections before destroying the databases. // If we do not, the "DROP DATABASE ..." statements may hang, waiting for // our connections to close. PhabricatorLiskDAO::closeAllConnections(); execx( 'php %s destroy --force --namespace %s', $this->getStorageBinPath(), $this->name); } private function getStorageBinPath() { $root = dirname(phutil_get_library_root('phabricator')); return $root.'/scripts/sql/manage_storage.php'; } }
<?php /** * Used by unit tests to build storage fixtures. */ final class PhabricatorStorageFixtureScopeGuard extends Phobject { private $name; public function __construct($name) { $this->name = $name; execx( 'php %s upgrade --force --no-adjust --namespace %s', $this->getStorageBinPath(), $this->name); PhabricatorLiskDAO::pushStorageNamespace($name); // Destructor is not called with fatal error. register_shutdown_function(array($this, 'destroy')); } public function destroy() { PhabricatorLiskDAO::popStorageNamespace(); execx( 'php %s destroy --force --namespace %s', $this->getStorageBinPath(), $this->name); } private function getStorageBinPath() { $root = dirname(phutil_get_library_root('phabricator')); return $root.'/scripts/sql/manage_storage.php'; } }
Reformat and correct keyPress call
package com.opera.core.systems; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.opera.core.systems.scope.protos.SystemInputProtos.ModifierPressed; public class QuickWidgetTest extends DesktopTestBase { @Test public void testSomething() { driver.waitStart(); List<ModifierPressed> modifiers = new ArrayList<ModifierPressed>(); modifiers.add(ModifierPressed.CTRL); driver.keyPress("t", modifiers); System.out.println("Done keypress"); // driver.waitForWindowShown(""); // driver.close(); int win_id = driver.waitForWindowShown(""); System.out.println("Window shown = " + win_id); System.out.println("Window name = " + driver.getWindowName(win_id)); // FIXME add asserts List<QuickWindow> windows = driver.getWindowList(); QuickWindow window = driver.getWindow("Document window"); List<QuickWidget> list = driver.getQuickWidgetList("Document window"); } }
package com.opera.core.systems; import java.util.List; import org.junit.Test; import com.opera.core.systems.scope.protos.SystemInputProtos.ModifierPressed; public class QuickWidgetTest extends DesktopTestBase { @Test public void testSomething(){ driver.waitStart(); // driver.operaDesktopAction("Open url in new page", "1"); driver.keyPress("t", ModifierPressed.CTRL); System.out.println("Done keypress"); //driver.waitForWindowShown(""); //driver.close(); int win_id = driver.waitForWindowShown(""); System.out.println("Window shown = " + win_id); System.out.println("Window name = " + driver.getWindowName(win_id)); List<QuickWindow> windows = driver.getWindowList(); QuickWindow window = driver.getWindow("Document window"); List<QuickWidget> list = driver.getQuickWidgetList("Document window"); } }
Throw ValidationError for invalid form, drop get_query_form()
from rest_framework.exceptions import ValidationError class ModelSerializerMixin(object): """Provides generic model serializer classes to views.""" model_serializer_class = None def get_serializer_class(self): if self.serializer_class: return self.serializer_class class DefaultSerializer(self.model_serializer_class): class Meta: model = self.queryset.model return DefaultSerializer class QueryFormMixin(object): """Provides form based handling of GET or POST requests.""" query_form_class = None def clean_params(self): """Returns a validated form dict from Request parameters.""" form = self.query_form_class( self.request.query_params or self.request.data, self.request.FILES or None) if form.is_valid(): return form.cleaned_data raise ValidationError(form.errors)
class ModelSerializerMixin(object): """Provides generic model serializer classes to views.""" model_serializer_class = None def get_serializer_class(self): if self.serializer_class: return self.serializer_class class DefaultSerializer(self.model_serializer_class): class Meta: model = self.queryset.model return DefaultSerializer class QueryFormMixin(object): """Provides form based handling of GET or POST requests.""" query_form_class = None def get_query_form(self): """Returns a bound form instance.""" return self.query_form_class( self.request.query_params or self.request.data, self.request.FILES or None) def clean_params(self): """Returns a validated form dict or an empty dict.""" form = self.get_query_form() return form.cleaned_data if form.is_valid() else {}
Fix assert.match integration test helper
/** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ var assert = require('assert'); assert.match = function assertMatches(string, matcher, message) { assert.ok(string.match(matcher), message || 'Expected ' + string + ' to match ' + matcher); }; assert.contains = function assertContains(list, matcher, message) { var found = false; for (var i in list) { if (!list.hasOwnProperty(i)) continue; if (typeof matcher === 'function') { found = matcher(list[i]); } else { found = (list[i] === matcher); } if (found) return; } assert.fail(list, matcher, message, 'does not contain'); }; assert.compare = function assertComparison(actual, operator, expected, message) { var compare = actual + ' ' + operator + ' ' + expected; assert.ok(eval(compare), message || compare); } module.exports = { assert: assert };
/** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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. */ var assert = require('assert'); assert.match = function assertMatches(string, matcher, message) { assert.ok(expected.match(matcher), message || 'Expected ' + string + ' to match ' + matcher); }; assert.contains = function assertContains(list, matcher, message) { var found = false; for (var i in list) { if (!list.hasOwnProperty(i)) continue; if (typeof matcher === 'function') { found = matcher(list[i]); } else { found = (list[i] === matcher); } if (found) return; } assert.fail(list, matcher, message, 'does not contain'); }; assert.compare = function assertComparison(actual, operator, expected, message) { var compare = actual + ' ' + operator + ' ' + expected; assert.ok(eval(compare), message || compare); } module.exports = { assert: assert };
Switch to Double DQN as the default algorithm.
"""Configuration data for training or evaluating a reinforcement learning agent. """ import agents def get_config(): config = { 'game': 'BreakoutDeterministic-v3', 'agent_type': agents.DoubleDeepQLearner, 'history_length': 4, 'training_steps': 50000000, 'training_freq': 4, 'num_eval_episodes': 30, 'max_steps_per_eval_episode': 135000, 'eval_freq': 150000, 'initial_replay_size': 50000, 'epsilon_start': 1.0, 'epsilon_end': 0.01, 'epsilon_decay_steps': 1000000, 'eval_epsilon': 0.001, 'screen_dims': (84, 84), 'reward_processing': 'clip', 'discount_factor': 0.99, 'learning_rate': 0.00025, 'rms_scale': 0.95, 'rms_constant': 0.01, 'error_clipping': 1.0, 'target_update_freq': 30000, 'memory_capacity': 1000000, 'batch_size': 32, 'summary_freq': 50000, } return config
"""Configuration data for training or evaluating a reinforcement learning agent. """ import agents def get_config(): config = { 'game': 'BreakoutDeterministic-v3', 'agent_type': agents.DeepQLearner, 'history_length': 4, 'training_steps': 50000000, 'training_freq': 4, 'num_eval_episodes': 30, 'max_steps_per_eval_episode': 135000, 'eval_freq': 150000, 'initial_replay_size': 50000, 'epsilon_start': 1.0, 'epsilon_end': 0.1, 'epsilon_decay_steps': 1000000, 'eval_epsilon': 0.05, 'screen_dims': (84, 84), 'reward_processing': 'clip', 'discount_factor': 0.99, 'learning_rate': 0.00025, 'rms_scale': 0.95, 'rms_constant': 0.01, 'error_clipping': 1.0, 'target_update_freq': 10000, 'memory_capacity': 1000000, 'batch_size': 32, 'summary_freq': 50000, } return config
Update URL, need to set dev version on GitHub.
""" Flask-Script -------------- Flask support for writing external scripts. Links ````` * `documentation <http://packages.python.org/Flask-Script>`_ """ from setuptools import setup setup( name='Flask-Script', version='0.3.2', url='http://github.com/rduplain/flask-script', license='BSD', author='Dan Jacob', author_email='danjac354@gmail.com', maintainer='Ron DuPlain', maintainer_email='ron.duplain@gmail.com', description='Scripting support for Flask', long_description=__doc__, packages=['flaskext'], namespace_packages=['flaskext'], test_suite='nose.collector', zip_safe=False, platforms='any', install_requires=[ 'Flask', 'argparse', ], tests_require=[ 'nose', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
""" Flask-Script -------------- Flask support for writing external scripts. Links ````` * `documentation <http://packages.python.org/Flask-Script>`_ * `development version <http://bitbucket.org/danjac/flask-Script/get/tip.gz#egg=Flask-Script-dev>`_ """ from setuptools import setup setup( name='Flask-Script', version='0.3.2', url='http://bitbucket.org/danjac/flask-script', license='BSD', author='Dan Jacob', author_email='danjac354@gmail.com', maintainer='Ron DuPlain', maintainer_email='ron.duplain@gmail.com', description='Scripting support for Flask', long_description=__doc__, packages=['flaskext'], namespace_packages=['flaskext'], test_suite='nose.collector', zip_safe=False, platforms='any', install_requires=[ 'Flask', 'argparse', ], tests_require=[ 'nose', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Add use strict to stub controller
"use strict"; let db = require('./db.js'), express = require('express'), router = express.Router(); function convertBase62ToId(base62) { let chars = base62.split(''); return chars.reduce(function(sum, char) { if (/[0-9]/.test(char)) return sum += parseInt(char); else if (/[a-z]/.test(char)) return sum += char.charCodeAt(0) - 87; else return sum += char.charCodeAt(0) - 29; }, 0); } router.get('/:stub', function(req, res) { db.one('select * from urls where id = $1;', convertBase62ToId(req.params.stub)) .then(function(data) { res.redirect(301, data.url); }) .catch(function(error) { console.log('Error: ' + error); res.sendStatus(404); }); }); router.get('/', function(req, res) { res.render('index'); }); module.exports = router;
let db = require('./db.js'), express = require('express'), router = express.Router(); function convertBase62ToId(base62) { let chars = base62.split(''); return chars.reduce(function(sum, char) { if (/[0-9]/.test(char)) return sum += parseInt(char); else if (/[a-z]/.test(char)) return sum += char.charCodeAt(0) - 87; else return sum += char.charCodeAt(0) - 29; }, 0); } router.get('/:stub', function(req, res) { db.one('select * from urls where id = $1;', convertBase62ToId(req.params.stub)) .then(function(data) { res.redirect(301, data.url); }) .catch(function(error) { console.log('Error: ' + error); res.sendStatus(404); }); }); router.get('/', function(req, res) { res.render('index'); }); module.exports = router;
Remove ES6 template strings for node 0.10+ compatibility
var assert = require('chai').assert; var fun = require('../lib/utils').stripStackOverflow; describe('stripStackOverflow', function() { it('should not strip -f parameters in the title', function () { var title = 'monitoring - How does the "tail" command\'s "-f" parameter ...'; assert.equal(fun(title), title); }); it('should strip Unix & Linux Stack Exchange', function() { assert.equal( fun('table - combine text files column-wise - Unix & Linux Stack Exchange'), 'table - combine text files column-wise' ); }); it('should strip Unix', function() { assert.equal( fun('table - combine text files column-wise - Unix ...'), 'table - combine text files column-wise' ); }); it('should preserve titles with one dash on the left', function() { assert.equal( fun('table - combine text files columnwise'), 'table - combine text files columnwise' ); }); it('should strip titles with one dash on the right', function() { assert.equal( fun('How to merge all (text) files in a directory into one? - Unix & Linux'), 'How to merge all (text) files in a directory into one?' ); }); });
var assert = require('chai').assert; var fun = require('../lib/utils').stripStackOverflow; describe('stripStackOverflow', function() { it('should not strip -f parameters in the title', function () { var title = `monitoring - How does the "tail" command's "-f" parameter ...`; assert.equal(fun(title), title); }); it('should strip Unix & Linux Stack Exchange', function() { assert.equal( fun('table - combine text files column-wise - Unix & Linux Stack Exchange'), 'table - combine text files column-wise' ); }); it('should strip Unix', function() { assert.equal( fun('table - combine text files column-wise - Unix ...'), 'table - combine text files column-wise' ); }); it('should preserve titles with one dash on the left', function() { assert.equal( fun('table - combine text files columnwise'), 'table - combine text files columnwise' ); }); it('should strip titles with one dash on the right', function() { assert.equal( fun('How to merge all (text) files in a directory into one? - Unix & Linux'), 'How to merge all (text) files in a directory into one?' ); }); });
Set package version to 0.4.2
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 2) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 1) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
Fix parameter syntax in CreateReleation modified: lib/create_relation.js
'use strict'; var U = require('lodash'); var DynamoDB = require('./dynamodb'); function CreateRelation() {} module.exports = CreateRelation; CreateRelation.create = function createCreateRelation(spec) { var obj = new CreateRelation(); return obj.initialize(spec); }; U.extend(CreateRelation.prototype, { initialize: function (spec) { Object.defineProperties(this, { dynamodb: { value: spec.dynamodb } }); return this; }, parameters: function (subjectId, objectId) { return { Item: DynamoDB.serializeRelation({ subject: subjectId, object: objectId }), TableName: this.dynamodb.relationTable(), ConditionExpression: 'attribute_not_exists(subject) AND ' + 'attribute_not_exists(object)' // Potentially useful parameters: // ReturnConsumedCapacity // ReturnItemCollectionMetrics }; }, create: function (subjectId, objectId) { return this.dynamodb .putItem(this.parameters(subjectId, objectId)) .then(U.constant(true)); } });
'use strict'; var U = require('lodash'); var DynamoDB = require('./dynamodb'); function CreateRelation() {} module.exports = CreateRelation; CreateRelation.create = function createCreateRelation(spec) { var obj = new CreateRelation(); return obj.initialize(spec); }; U.extend(CreateRelation.prototype, { initialize: function (spec) { Object.defineProperties(this, { dynamodb: { value: spec.dynamodb } }); return this; }, parameters: function (subject, object) { return { Item: DynamoDB.serializeRelation({ subject: subject, object: object }), TableName: this.dynamodb.relationTable(), ConditionExpression: 'attribute_not_exists(subject) AND ' + 'attribute_not_exists(object)' // Potentially useful parameters: // ReturnConsumedCapacity // ReturnItemCollectionMetrics }; }, create: function (subject, object) { return this.dynamodb .putItem(this.parameters(subject, object)) .then(U.constant(true)); } });
Update socket URL for production use.
var socket = io('http://was.geht.im.hackspace.siegen.so:13374'); var elems = document.getElementsByClassName("status"); socket.on('status', function (data) { console.log(data); for (var i = 0; i < elems.length; i++) { var elem = elems[i]; var key = elem.getAttribute("data-key"); var unit = elem.getAttribute("data-unit"); var value = data[key]; if (value != undefined) { elem.innerHTML = value + " " + unit; } } var body = document.body; var img = document.getElementById("lock_image"); var data_fields = document.getElementById("data"); if (data["state"] == "open") { body.style.background = "#00FF00"; img.setAttribute("src", "assets/images/open.svg"); data_fields.style.color = "#00FF00"; } else { body.style.background = "#FF0000"; img.setAttribute("src", "assets/images/closed.svg"); data_fields.style.color = "#FF0000"; } });
var socket = io('http://localhost:13374'); var elems = document.getElementsByClassName("status"); socket.on('status', function (data) { console.log(data); for (var i = 0; i < elems.length; i++) { var elem = elems[i]; var key = elem.getAttribute("data-key"); var unit = elem.getAttribute("data-unit"); var value = data[key]; if (value != undefined) { elem.innerHTML = value + " " + unit; } } var body = document.body; var img = document.getElementById("lock_image"); var data_fields = document.getElementById("data"); if (data["state"] == "open") { body.style.background = "#00FF00"; img.setAttribute("src", "assets/images/open.svg"); data_fields.style.color = "#00FF00"; } else { body.style.background = "#FF0000"; img.setAttribute("src", "assets/images/closed.svg"); data_fields.style.color = "#FF0000"; } });
Add Content-Length header to Aphront file responses. Summary: Provide a Content-Length header so that browsers can estimate time remaining for file downloads. Test Plan: Tested on our local phabricator install. Reviewers: epriestley Reviewed By: epriestley CC: aran, Korvin Differential Revision: https://secure.phabricator.com/D6107
<?php /** * @group aphront */ final class AphrontFileResponse extends AphrontResponse { private $content; private $mimeType; private $download; public function setDownload($download) { $download = preg_replace('/[^A-Za-z0-9_.-]/', '_', $download); if (!strlen($download)) { $download = 'untitled_document.txt'; } $this->download = $download; return $this; } public function getDownload() { return $this->download; } public function setMimeType($mime_type) { $this->mimeType = $mime_type; return $this; } public function getMimeType() { return $this->mimeType; } public function setContent($content) { $this->content = $content; return $this; } public function buildResponseString() { return $this->content; } public function getHeaders() { $headers = array( array('Content-Type', $this->getMimeType()), array('Content-Length', strlen($this->content)), ); if (strlen($this->getDownload())) { $headers[] = array('X-Download-Options', 'noopen'); $filename = $this->getDownload(); $headers[] = array( 'Content-Disposition', 'attachment; filename='.$filename, ); } $headers = array_merge(parent::getHeaders(), $headers); return $headers; } }
<?php /** * @group aphront */ final class AphrontFileResponse extends AphrontResponse { private $content; private $mimeType; private $download; public function setDownload($download) { $download = preg_replace('/[^A-Za-z0-9_.-]/', '_', $download); if (!strlen($download)) { $download = 'untitled_document.txt'; } $this->download = $download; return $this; } public function getDownload() { return $this->download; } public function setMimeType($mime_type) { $this->mimeType = $mime_type; return $this; } public function getMimeType() { return $this->mimeType; } public function setContent($content) { $this->content = $content; return $this; } public function buildResponseString() { return $this->content; } public function getHeaders() { $headers = array( array('Content-Type', $this->getMimeType()), ); if (strlen($this->getDownload())) { $headers[] = array('X-Download-Options', 'noopen'); $filename = $this->getDownload(); $headers[] = array( 'Content-Disposition', 'attachment; filename='.$filename, ); } $headers = array_merge(parent::getHeaders(), $headers); return $headers; } }
Fix comment for bucket deletion
// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND. // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html // Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create S3 service object s3 = new AWS.S3({apiVersion: '2006-03-01'}); // Create params for S3.createBucket var bucketParams = { Bucket : 'BUCKET_NAME', }; // call S3 to delete the bucket s3.deleteBucket(bucketParams, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND. // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html // Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create S3 service object s3 = new AWS.S3({apiVersion: '2006-03-01'}); // Create params for S3.createBucket var bucketParams = { Bucket : 'BUCKET_NAME', }; // call S3 to create the bucket s3.deleteBucket(bucketParams, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Update clusterconfig-provider binary to use logrusx.JSONFormatter
package main import ( "time" log "github.com/Sirupsen/logrus" logx "github.com/cerana/cerana/pkg/logrusx" "github.com/cerana/cerana/provider" "github.com/cerana/cerana/providers/clusterconf" flag "github.com/spf13/pflag" ) func main() { log.SetFormatter(&logx.JSONFormatter{}) config := clusterconf.NewConfig(nil, nil) flag.DurationP("dataset-ttl", "d", time.Minute, "ttl for dataset usage heartbeats") flag.DurationP("bundle-ttl", "b", time.Minute, "ttl for bundle usage heartbeats") flag.DurationP("node-ttl", "o", time.Minute, "ttl for node heartbeats") flag.Parse() dieOnError(config.LoadConfig()) dieOnError(config.SetupLogging()) server, err := provider.NewServer(config.Config) dieOnError(err) c := clusterconf.New(config, server.Tracker()) dieOnError(err) c.RegisterTasks(server) if len(server.RegisteredTasks()) != 0 { dieOnError(server.Start()) server.StopOnSignal() } else { log.Warn("no registered tasks, exiting") } } func dieOnError(err error) { if err != nil { log.Fatal("encountered an error during startup") } }
package main import ( "time" log "github.com/Sirupsen/logrus" logx "github.com/cerana/cerana/pkg/logrusx" "github.com/cerana/cerana/provider" "github.com/cerana/cerana/providers/clusterconf" flag "github.com/spf13/pflag" ) func main() { log.SetFormatter(&logx.MistifyFormatter{}) config := clusterconf.NewConfig(nil, nil) flag.DurationP("dataset-ttl", "d", time.Minute, "ttl for dataset usage heartbeats") flag.DurationP("bundle-ttl", "b", time.Minute, "ttl for bundle usage heartbeats") flag.DurationP("node-ttl", "o", time.Minute, "ttl for node heartbeats") flag.Parse() dieOnError(config.LoadConfig()) dieOnError(config.SetupLogging()) server, err := provider.NewServer(config.Config) dieOnError(err) c := clusterconf.New(config, server.Tracker()) dieOnError(err) c.RegisterTasks(server) if len(server.RegisteredTasks()) != 0 { dieOnError(server.Start()) server.StopOnSignal() } else { log.Warn("no registered tasks, exiting") } } func dieOnError(err error) { if err != nil { log.Fatal("encountered an error during startup") } }
Add a register method for plugins
package io.github.Cnly.BusyInv.BusyInv; import io.github.Cnly.BusyInv.BusyInv.listeners.BusyListener; import org.bukkit.Bukkit; import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; public class BusyInv extends JavaPlugin { private static BusyInv instance; @Override public void onEnable() { instance = this; Bukkit.getPluginManager().registerEvents(new BusyListener(), this); } @Override public void onDisable() { HandlerList.unregisterAll(this); } public static void registerFor(JavaPlugin jp) { Bukkit.getPluginManager().registerEvents(new BusyListener(), jp); } public static BusyInv getInstance() { return instance; } }
package io.github.Cnly.BusyInv.BusyInv; import io.github.Cnly.BusyInv.BusyInv.listeners.BusyListener; import org.bukkit.Bukkit; import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; public class BusyInv extends JavaPlugin { private static BusyInv instance; @Override public void onEnable() { instance = this; Bukkit.getPluginManager().registerEvents(new BusyListener(), this); } @Override public void onDisable() { HandlerList.unregisterAll(this); } public static BusyInv getInstance() { return instance; } }
Fix mostUrgentSubject query to not use r.row in subquery
var r = require('rethinkdb'); // Number of seconds after which Reddit will archive an article // (180 days): https://github.com/reddit/reddit/commit/b7b24d2e9fa06ba37ea78e0275dce86d95158e64 var archiveLimit = 180 * 24 * 60 * 60; exports.mostUrgentSubject = r.table('subjects') .between(r.now().sub(archiveLimit),r.now(),{index:'article_created'}) .orderBy(function(subject){ var staleness = subject('last_checked').sub(r.now()); var age = subject('article_created').sub(r.now()); return staleness.div(age); }).limit(1).merge(function(subject){ return { forfeits: r.table('forfeits').getAll( subject('name'),{index: 'subject'}) .filter(function(forfeit){ return r.not(forfeit('withdrawn').default(false))}) .merge(function(forfeit){ return { reply_klaxons: r.table('klaxons').getAll( forfeit('id'),{index:'forfeits'}) .map(function(klaxon){return klaxon('reply')}) .coerceTo('array') }; }).coerceTo('array') }; })(0).default(null);
var r = require('rethinkdb'); // Number of seconds after which Reddit will archive an article // (180 days): https://github.com/reddit/reddit/commit/b7b24d2e9fa06ba37ea78e0275dce86d95158e64 var archiveLimit = 180 * 24 * 60 * 60; exports.mostUrgentSubject = r.table('subjects') .between(r.now().sub(archiveLimit),r.now(),{index:'article_created'}) .orderBy(function(subject){ var staleness = subject('last_checked').sub(r.now()); var age = subject('article_created').sub(r.now()); return staleness.div(age); }).limit(1).merge(function(subject){ return { forfeits: r.table('forfeits').getAll( subject('name'),{index: 'subject'}) .filter(r.not(r.row('withdrawn').default(false))) .merge(function(forfeit){ return { reply_klaxons: r.table('klaxons').getAll( forfeit('id'),{index:'forfeits'}) .map(r.row('reply')).coerceTo('array') }; }).coerceTo('array') }; })(0).default(null);
Add the ability to specify a tag
// MIT license, see: https://github.com/tjcrowder/simple-snippets-console/blob/master/LICENSE var snippet = { version: "1.1", // Writes out the given text in a monospaced paragraph tag, escaping // & and < so they aren't rendered as HTML. log: function(msg, tag) { var elm = document.createElement(tag || "p"); elm.style.fontFamily = "monospace"; elm.style.margin = "2px 0 2px 0"; if (Object.prototype.toString.call(msg) === "[object Array]") { msg = msg.join(); } else if (typeof object === "object") { msg = msg === null ? "null" : JSON.stringify(msg); } elm.innerHTML = msg.replace(/&/g, '&amp;').replace(/</g, '&lt;'); document.body.appendChild(elm); }, // Writes out the given HTML at the end of the body, // exactly as-is logHTML: function(html) { document.body.insertAdjacentHTML("beforeend", html); } };
// MIT license, see: https://github.com/tjcrowder/simple-snippets-console/blob/master/LICENSE var snippet = { version: "1.0", // Writes out the given text in a monospaced paragraph tag, escaping // & and < so they aren't rendered as HTML. log: function(msg) { if (Object.prototype.toString.call(msg) === "[object Array]") { msg = msg.join(); } else if (typeof object === "object") { msg = msg === null ? "null" : JSON.stringify(msg); } document.body.insertAdjacentHTML( 'beforeend', '<p style="font-family: monospace; margin: 2px 0 2px 0">' + msg.replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</p>' ); }, // Writes out the given HTML at the end of the body, // exactly as-is logHTML: function(html) { document.body.insertAdjacentHTML("beforeend", html); } };
Remove agenda view from calendar
import React from 'react'; import BigCalendar from 'react-big-calendar'; import moment from 'moment'; import 'react-big-calendar/lib/css/react-big-calendar.css' BigCalendar.setLocalizer( BigCalendar.momentLocalizer(moment) ); // TODO take in events as props let Calendar = React.createClass({ render(){ console.log(this.props); return ( <div style={{height: '80vh', width: '90vw', margin:'0 auto', marginTop: '20px'}}> <BigCalendar events={this.props.events} timeslots={2} views={['month', 'day', 'week']} onSelectEvent={event => alert(event.title)} defaultDate={new Date()} /> </div> ) } }) export default Calendar;
import React from 'react'; import BigCalendar from 'react-big-calendar'; import moment from 'moment'; import 'react-big-calendar/lib/css/react-big-calendar.css' BigCalendar.setLocalizer( BigCalendar.momentLocalizer(moment) ); // TODO take in events as props let Calendar = React.createClass({ render(){ console.log(this.props); return ( <div style={{height: '80vh', width: '90vw', margin:'0 auto', marginTop: '20px'}}> <BigCalendar events={this.props.events} timeslots={2} onSelectEvent={event => alert(event.title)} defaultDate={new Date()} /> </div> ) } }) export default Calendar;
Allow whitespace after multiline code open dash
<?php namespace Phug\Lexer\Scanner; use Phug\Lexer\ScannerInterface; use Phug\Lexer\State; use Phug\Lexer\Token\CodeToken; use Phug\Lexer\Token\TextToken; class CodeScanner implements ScannerInterface { public function scan(State $state) { $reader = $state->getReader(); if (!$reader->match('-[ \t]*')) { return; } /** @var CodeToken $token */ $token = $state->createToken(CodeToken::class); $reader->consume(); //Single-line code foreach ($state->scan(TextScanner::class) as $textToken) { //Trim the text as expressions usually would yield $state->endToken($token); if ($textToken instanceof TextToken) { $textToken->setValue(trim($textToken->getValue())); yield $textToken; } return; } //Multi-line code $token->setIsBlock(true); yield $state->endToken($token); foreach ($state->scan(MultilineScanner::class) as $token) { yield $token; } } }
<?php namespace Phug\Lexer\Scanner; use Phug\Lexer\ScannerInterface; use Phug\Lexer\State; use Phug\Lexer\Token\CodeToken; use Phug\Lexer\Token\TextToken; class CodeScanner implements ScannerInterface { public function scan(State $state) { $reader = $state->getReader(); if (!$reader->peekChar('-')) { return; } /** @var CodeToken $token */ $token = $state->createToken(CodeToken::class); $reader->consume(); //Single-line code foreach ($state->scan(TextScanner::class) as $textToken) { //Trim the text as expressions usually would yield $state->endToken($token); if ($textToken instanceof TextToken) { $textToken->setValue(trim($textToken->getValue())); yield $textToken; } return; } //Multi-line code $token->setIsBlock(true); yield $state->endToken($token); foreach ($state->scan(MultilineScanner::class) as $token) { yield $token; } } }
Fix division by zero is not possible
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; class Category extends Model { use HasFactory; protected $table = 'categories'; protected $fillable = [ 'label', 'parent_category_id', 'budgeted', 'user_id', ]; public function getSpentAttribute() { $spent = 0; foreach ($this->transactions()->get() as $transaction) { if ($transaction->inflow) { $spent -= $transaction->amount; } else { $spent += $transaction->amount; } } return $spent; } public function getProgressAttribute() { if ($this->budgeted == 0) { // no progress with no budget return 0; } return round(($this->spent / $this->budgeted) * 100); } public function transactions() { return $this->hasMany(Transaction::class); } }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; class Category extends Model { use HasFactory; protected $table = 'categories'; protected $fillable = [ 'label', 'parent_category_id', 'budgeted', 'user_id', ]; public function getSpentAttribute() { $spent = 0; foreach ($this->transactions()->get() as $transaction) { if ($transaction->inflow) { $spent -= $transaction->amount; } else { $spent += $transaction->amount; } } return $spent; } public function getProgressAttribute() { return round(($this->spent / $this->budgeted) * 100); } public function transactions() { return $this->hasMany(Transaction::class); } }
Add int detection to interpreting results
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read().replace('.. :changelog:', '') requirements = [ # TODO: put package requirements here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='pash', version='1.1.2', description="Module for interacting with os.subprocess easily.", long_description=readme + '\n\n' + history, author="Ian McFarlane", author_email='iansmcfarlane@gmail.com', url='https://github.com/iansmcf/pash', py_modules = ['pash'], include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='pash', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', ], test_suite='tests', tests_require=test_requirements )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read().replace('.. :changelog:', '') requirements = [ # TODO: put package requirements here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='pash', version='1.1.1', description="Module for interacting with os.subprocess easily.", long_description=readme + '\n\n' + history, author="Ian McFarlane", author_email='iansmcfarlane@gmail.com', url='https://github.com/iansmcf/pash', py_modules = ['pash'], include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='pash', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', ], test_suite='tests', tests_require=test_requirements )
Add method to access an element of save-button
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var dom = app.dom || require('../dom.js'); var SidebarToggleButton = app.SidebarToggleButton || require('./sidebar-toggle-button.js'); var ContentHeader = helper.inherits(function(props) { ContentHeader.super_.call(this); this.element = this.prop(props.element); this.sidebarToggleButton = this.prop(new SidebarToggleButton({ element: this.sidebarToggleButtonElement(), collapser: props.sidebarCollapser, expander: props.sidebarExpander })); this.sidebarToggleButton().registerTapListener(); }, jCore.Component); ContentHeader.prototype.sidebarToggleButtonElement = function() { return dom.child(this.element(), 0); }; ContentHeader.prototype.loadButtonElement = function() { return dom.child(this.element(), 1); }; ContentHeader.prototype.saveButtonElement = function() { return dom.child(this.element(), 2); }; ContentHeader.prototype.redraw = function() { this.sidebarToggleButton().redraw(); }; if (typeof module !== 'undefined' && module.exports) module.exports = ContentHeader; else app.ContentHeader = ContentHeader; })(this.app || (this.app = {}));
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var dom = app.dom || require('../dom.js'); var SidebarToggleButton = app.SidebarToggleButton || require('./sidebar-toggle-button.js'); var ContentHeader = helper.inherits(function(props) { ContentHeader.super_.call(this); this.element = this.prop(props.element); this.sidebarToggleButton = this.prop(new SidebarToggleButton({ element: this.sidebarToggleButtonElement(), collapser: props.sidebarCollapser, expander: props.sidebarExpander })); this.sidebarToggleButton().registerTapListener(); }, jCore.Component); ContentHeader.prototype.sidebarToggleButtonElement = function() { return dom.child(this.element(), 0); }; ContentHeader.prototype.loadButtonElement = function() { return dom.child(this.element(), 1); }; ContentHeader.prototype.redraw = function() { this.sidebarToggleButton().redraw(); }; if (typeof module !== 'undefined' && module.exports) module.exports = ContentHeader; else app.ContentHeader = ContentHeader; })(this.app || (this.app = {}));
Add function bind for iOS
(function() { window.PointerEventShim = { clone: function(inSink, inSource) { var p$ = [].slice.call(arguments, 1); for (var i=0, p; p=p$[i]; i++) { if (p) { var g, s; for (var n in p) { //inSink[n] = p[n]; /* fixme: sigh, copy getters/setters */ g = p.__lookupGetter__(n), s = p.__lookupSetter__(n); if (g) { inSink.__defineGetter__(n, g); } else { inSink[n] = p[n]; } if (s) { inSink.__defineSetter__(n, s); } } } } return inSink; }, }; if (!Function.prototype.bind) { Function.prototype.bind = function(scope) { var _this = this; return function() { return _this.apply(scope, arguments); } } } })();
(function() { window.PointerEventShim = { clone: function(inSink, inSource) { var p$ = [].slice.call(arguments, 1); for (var i=0, p; p=p$[i]; i++) { if (p) { var g, s; for (var n in p) { //inSink[n] = p[n]; /* fixme: sigh, copy getters/setters */ g = p.__lookupGetter__(n), s = p.__lookupSetter__(n); if (g) { inSink.__defineGetter__(n, g); } else { inSink[n] = p[n]; } if (s) { inSink.__defineSetter__(n, s); } } } } return inSink; }, }; })();
Fix typo in orm transformer
<?php namespace FOQ\ElasticaBundle\Doctrine\ORM; use FOQ\ElasticaBundle\Doctrine\AbstractElasticaToModelTransformer; use Elastica_Document; use Doctrine\ORM\Query; /** * Maps Elastica documents with Doctrine objects * This mapper assumes an exact match between * elastica documents ids and doctrine object ids */ class ElasticaToModelTransformer extends AbstractElasticaToModelTransformer { /** * Fetch objects for theses identifier values * * @param string $class the model class * @param string $identifierField like 'id' * @param array $identifierValues ids values * @param Boolean $hydrate whether or not to hydrate the objects, false returns arrays * @return array of objects or arrays */ protected function findByIdentifiers($class, $identifierField, array $identifierValues, $hydrate) { if (empty($identifierValues)) { return array(); } $hydrationMode = $hydrate ? Query::HYDRATE_OBJECT : Query::HYDRATE_ARRAY; $qb = $this->objectManager ->getRepository($class) ->createQueryBuilder('o'); $qb->where($qb->expr()->in('o.'.$identifierField, $identifierValues)); return $qb->getQuery()->setHydrationMode($hydrationMode)->execute(); } }
<?php namespace FOQ\ElasticaBundle\Doctrine\ORM; use FOQ\ElasticaBundle\Doctrine\AbstractElasticaToModelTransformer; use Elastica_Document; use Doctrine\ORM\Query; /** * Maps Elastica documents with Doctrine objects * This mapper assumes an exact match between * elastica documents ids and doctrine object ids */ class ElasticaToModelTransformer extends AbstractElasticaToModelTransformer { /** * Fetch objects for theses identifier values * * @param string $class the model class * @param string $identifierField like 'id' * @param array $identifierValues ids values * @param Boolean $hydrate whether or not to hydrate the objects, false returns arrays * @return array of objects or arrays */ protected function findByIdentifiers($class, $identifierField, array $identifierValues, $hydrate) { if (empty($identifierValues)) { return array(); } $hydratationMode = $hydrate ? Query::HYDRATE_OBJECT : Query::HYDRATE_ARRAY; $qb = $this->objectManager ->getRepository($class) ->createQueryBuilder('o'); $qb->where($qb->expr()->in('o.'.$identifierField, $identifierValues)); return $qb->getQuery()->setHydrationMode($hydrationMode)->execute(); } }
Use Query struct for searchString method
package main import ( "bytes" "fmt" "log" "net/http" "strings" ) const baseURL = "https://api.github.com/search/repositories" type Query struct { Q string Lang string Limit int } func escapeSearch(s string) string { return strings.Replace(s, " ", "+", -1) } func searchString(q Query) string { var buffer bytes.Buffer buffer.WriteString(baseURL) fmt.Println(q) if q.Q == "" { log.Fatal("You must enter a search query") } query := fmt.Sprintf("?q=%s", escapeSearch(q.Q)) buffer.WriteString(query) // return fmt.Sprintf("%s?q=%s+language:assembly&sort=stars&order=desc", baseURL, q) return buffer.String() } func requestSearch(url string, client http.Client) (r *http.Response, e error) { res, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } res.Header.Set("Accept", "application/vnd.github.preview") return client.Do(res) } func main() { fmt.Println(searchString(Query{"foo bar", "", 0})) }
package main import ( "bytes" "fmt" "log" "net/http" "strings" ) const baseURL = "https://api.github.com/search/repositories" func escapeSearch(s string) string { return strings.Replace(s, " ", "+", -1) } func searchString(q string, lang string, limit int) string { var buffer bytes.Buffer buffer.WriteString(baseURL) if q == "" { log.Fatal("You must enter a search query") } query := fmt.Sprintf("?q=%s", escapeSearch(q)) buffer.WriteString(query) // return fmt.Sprintf("%s?q=%s+language:assembly&sort=stars&order=desc", baseURL, q) return buffer.String() } func requestSearch(url string, client http.Client) (r *http.Response, e error) { res, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } res.Header.Set("Accept", "application/vnd.github.preview") return client.Do(res) } func main() { fmt.Println(searchString("foo bar", "", 0)) }
Use property instead of name for meta tags
<?php if ($content_type = Controller::$view->mime_type): ?> <?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?> <meta http-equiv="Content-Type" content="<?php echo $content_type ?>"> <?php endif; ?> <?php if ($author = Backend::getConfig('application.author')): ?> <meta name="author" content="<?php echo $author ?>"> <?php endif; ?> <?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?> <meta name="description" content="<?php echo $meta_description ?>"> <?php endif; ?> <meta name="generator" content="backend-php.net"> <?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?> <meta name="keywords" content="<?php echo $keywords ?>"> <?php endif; ?> <?php if (!empty($meta_values) && is_array($meta_values)): ?> <?php foreach($meta_values as $name => $value): ?> <meta property="<?php echo $name ?>" value="<?php echo $value ?>"/> <?php endforeach; ?> <?php endif; ?>
<?php if ($content_type = Controller::$view->mime_type): ?> <?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?> <meta http-equiv="Content-Type" content="<?php echo $content_type ?>"> <?php endif; ?> <?php if ($author = Backend::getConfig('application.author')): ?> <meta name="author" content="<?php echo $author ?>"> <?php endif; ?> <?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?> <meta name="description" content="<?php echo $meta_description ?>"> <?php endif; ?> <meta name="generator" content="backend-php.net"> <?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?> <meta name="keywords" content="<?php echo $keywords ?>"> <?php endif; ?> <?php if (!empty($meta_values) && is_array($meta_values)): ?> <?php foreach($meta_values as $name => $value): ?> <meta name="<?php echo $name ?>" value="<?php echo $value ?>"> <?php endforeach; ?> <?php endif; ?>
Set up reading lines from file, print count for testing purposes
import sqlite3 as sql import os import sys import logging import benchmark # bmVerify(['final_r7', 'final_r8'], filepath="/home/ysun/disambig/newcode/all/", outdir = "/home/ayu/results_v2/") # Text Files txt_file = 'benchmark_errors.txt' opened_file = open(txt_file, 'U') log_file = 'benchmark_results.log' # Logging logging.basicConfig(filename=log_file, level=logging.DEBUG) open(log_file, "w") # Set Up SQL Connections con = sql.connect('invnum_N_zardoz_with_invpat.sqlite3') with con: con_cur = con.cursor() logging.info("Beginning to query database") con_cur.execute("CREATE INDEX IF NOT EXISTS index_invnum ON invpat (Invnum)"); con_cur.execute("CREATE INDEX IF NOT EXISTS index_lastname ON invpat (Lastname)"); con_cur.execute("CREATE INDEX IF NOT EXISTS index_firstname ON invpat (Firstname)"); count = 0 errors = 0 success = 0 while True: line_read = opened_file.readline() # print line_read if not line_read: print "EXITING" break count = count + 1 if count%100 == 0: print "starting patent", count
import sqlite3 as sql import os import sys import logging import benchmark # bmVerify(['final_r7', 'final_r8'], filepath="/home/ysun/disambig/newcode/all/", outdir = "/home/ayu/results_v2/") # Text Files txt_file = 'benchmark_errors.txt' opened_file = open(txt_file, 'U') log_file = 'benchmark_results.log' # Logging logging.basicConfig(filename=log_file, level=logging.DEBUG) open(log_file, "w") # Set Up SQL Connections con = sql.connect('invnum_N_zardoz_with_invpat.sqlite3') with con: con_cur = con.cursor() logging.info("Beginning to query database") con_cur.execute("CREATE INDEX IF NOT EXISTS index_invnum ON invpat (Invnum)"); con_cur.execute("CREATE INDEX IF NOT EXISTS index_lastname ON invpat (Lastname)"); con_cur.execute("CREATE INDEX IF NOT EXISTS index_firstname ON invpat (Firstname)"); count = 0 errors = 0 success = 0
Add missing return of Event methods
class Event: def __init__(self, bot, data): self.bot = bot self.data = data def post_message(self, text, channel=None): if channel is None: channel = self.data['channel'] return self.bot.post_message(text, channel) def add_reaction(self, emoji, channel=None, timestamp=None): if channel is None: channel = self.data['channel'] if timestamp is None: timestamp = self.data['ts'] return self.bot.add_reaction(emoji, channel, timestamp) def remove_reaction(self, emoji, channel=None, timestamp=None): if channel is None: channel = self.data['channel'] if timestamp is None: timestamp = self.data['ts'] return self.bot.remove_reaction(emoji, channel, timestamp)
class Event: def __init__(self, bot, data): self.bot = bot self.data = data def post_message(self, text, channel=None): if channel is None: channel = self.data['channel'] self.bot.post_message(text, channel) def add_reaction(self, emoji, channel=None, timestamp=None): if channel is None: channel = self.data['channel'] if timestamp is None: timestamp = self.data['ts'] self.bot.add_reaction(emoji, channel, timestamp) def remove_reaction(self, emoji, channel=None, timestamp=None): if channel is None: channel = self.data['channel'] if timestamp is None: timestamp = self.data['ts'] self.bot.remove_reaction(emoji, channel, timestamp)
Add description to the table and populate it with two categories
"""create category table Revision ID: 47dd43c1491 Revises: 27bf0aefa49d Create Date: 2013-05-21 10:41:43.548449 """ # revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), sa.Column('description', sa.Text, nullable=False), sa.Column('created', sa.Text, default=make_timestamp), ) # Add two categories query = 'INSERT INTO category (name, short_name, description) VALUES (\'Thinking\', \'thinking\', \'Applications where you can help using your skills\')' op.execute(query) query = 'INSERT INTO category (name, short_name, description) VALUES (\'Sensing\', \'sensing\', \'Applications where you can help gathering data\')' op.execute(query) def downgrade(): op.drop_table('category')
"""create category table Revision ID: 47dd43c1491 Revises: 27bf0aefa49d Create Date: 2013-05-21 10:41:43.548449 """ # revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), sa.Column('created', sa.Text, default=make_timestamp), ) def downgrade(): op.drop_table('category')
Add default argument when looking up sentry dsn setting
import os import logging from django.conf import settings log = logging.getLogger(__name__) def static(request): "Shorthand static URLs. In debug mode, the JavaScript is not minified." static_url = settings.STATIC_URL prefix = 'src' if settings.DEBUG else 'min' return { 'CSS_URL': os.path.join(static_url, 'stylesheets/css'), 'IMAGES_URL': os.path.join(static_url, 'images'), 'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix), } def alamut(request): return { 'ALAMUT_URL': settings.ALAMUT_URL, } def sentry(request): SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None) if SENTRY_PUBLIC_DSN: return { 'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN } log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
import os import logging from django.conf import settings log = logging.getLogger(__name__) def static(request): "Shorthand static URLs. In debug mode, the JavaScript is not minified." static_url = settings.STATIC_URL prefix = 'src' if settings.DEBUG else 'min' return { 'CSS_URL': os.path.join(static_url, 'stylesheets/css'), 'IMAGES_URL': os.path.join(static_url, 'images'), 'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix), } def alamut(request): return { 'ALAMUT_URL': settings.ALAMUT_URL, } def sentry(request): SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN') if SENTRY_PUBLIC_DSN: return { 'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN } log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
Update offline bat cache after adding a bat
package peergos.server; import peergos.server.storage.auth.*; import peergos.shared.storage.auth.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.*; public class OfflineBatCache implements BatCave { private final BatCave target; private final BatCache cache; public OfflineBatCache(BatCave target, BatCache cache) { this.target = target; this.cache = cache; } @Override public Optional<Bat> getBat(BatId id) { return target.getBat(id); } @Override public CompletableFuture<List<BatWithId>> getUserBats(String username, byte[] auth) { return Futures.asyncExceptionally( () -> target.getUserBats(username, auth).thenApply(bats -> { cache.setUserBats(username, bats); return bats; }), t -> cache.getUserBats(username)); } @Override public CompletableFuture<Boolean> addBat(String username, BatId id, Bat bat, byte[] auth) { return target.addBat(username, id, bat, auth).thenApply(res -> { getUserBats(username, (byte[])null); // update cache return res; }); } }
package peergos.server; import peergos.server.storage.auth.*; import peergos.shared.storage.auth.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.*; public class OfflineBatCache implements BatCave { private final BatCave target; private final BatCache cache; public OfflineBatCache(BatCave target, BatCache cache) { this.target = target; this.cache = cache; } @Override public Optional<Bat> getBat(BatId id) { return target.getBat(id); } @Override public CompletableFuture<List<BatWithId>> getUserBats(String username, byte[] auth) { return Futures.asyncExceptionally( () -> target.getUserBats(username, auth).thenApply(bats -> { cache.setUserBats(username, bats); return bats; }), t -> cache.getUserBats(username)); } @Override public CompletableFuture<Boolean> addBat(String username, BatId id, Bat bat, byte[] auth) { return target.addBat(username, id, bat, auth); } }
Add Zend_Log Test - Logging to a database (reformatting)
<?php class LogTest extends PHPUnit_Framework_TestCase { public function testDbLogger() { $databaseAdapter = Zend_Db::factory( 'PDO_SQLITE', array( 'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite' ) ); $databaseTableName = 'logs'; $columnMapping = array('message' => 'message'); $log = new Zend_Log(); $log->addWriter(new Zend_Log_Writer_Db($databaseAdapter, $databaseTableName, $columnMapping)); $log->info('Info Message'); } }
<?php class LogTest extends PHPUnit_Framework_TestCase { public function testDbLogger() { $log = new Zend_Log(); $dbWriter = new Zend_Log_Writer_Db( Zend_Db::factory( 'PDO_SQLITE', array( 'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite' ) ), 'logs', array( 'message' => 'message' ) ); $log->addWriter($dbWriter); $log->info('Info Message'); } }
Set no-op entries as tombstones.
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.atomix.copycat.server.storage.entry; import io.atomix.catalyst.serializer.SerializeWith; import io.atomix.catalyst.util.ReferenceManager; /** * No-op entry. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ @SerializeWith(id=223) public class NoOpEntry extends TimestampedEntry<NoOpEntry> { public NoOpEntry() { } public NoOpEntry(ReferenceManager<Entry<?>> referenceManager) { super(referenceManager); } @Override public boolean isTombstone() { return true; } @Override public String toString() { return String.format("%s[index=%d, term=%d, timestamp=%s]", getClass().getSimpleName(), getIndex(), getTerm(), getTimestamp()); } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.atomix.copycat.server.storage.entry; import io.atomix.catalyst.serializer.SerializeWith; import io.atomix.catalyst.util.ReferenceManager; /** * No-op entry. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ @SerializeWith(id=223) public class NoOpEntry extends TimestampedEntry<NoOpEntry> { public NoOpEntry() { } public NoOpEntry(ReferenceManager<Entry<?>> referenceManager) { super(referenceManager); } @Override public String toString() { return String.format("%s[index=%d, term=%d, timestamp=%s]", getClass().getSimpleName(), getIndex(), getTerm(), getTimestamp()); } }
Revert "Revert "Revert "I don't know what changed""" This reverts commit 9831a5f3e60457ac87b1b4a83000b0aee5a027b8.
<?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--[if lt IE 8]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'roots'); ?> </div> <![endif]--> <?php get_template_part('templates/header-top-navbar'); ?> <div class="content-detail container"> <div class="row" role="document"> <?php if (roots_display_sidebar()) : ?> <aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary"> <?php include roots_sidebar_path(); ?> </aside> <!-- /.sidebar.<?php echo roots_sidebar_class(); ?> --> <?php endif; ?> <main class="main <?php echo roots_main_class(); ?>" role="main"> <div class="content-area"> <?php include roots_template_path(); ?> </div> <!-- /.content-area --> </main> <!-- /.main.<?php echo roots_main_class(); ?> --> </div> <!-- /.row --> </div> <!-- /.content-detail.container --> <?php get_template_part('templates/footer'); ?> </body> </html>
<?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--[if lt IE 8]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'roots'); ?> </div> <![endif]--> <?php get_template_part('templates/header-top-navbar'); ?> <div class="body-wrap"> <div class="container"> <div class="row" role="document"> <main class="main <?php echo roots_main_class(); ?>" role="main"> <?php include roots_template_path(); ?> </main><!-- /.main --> <?php if (roots_display_sidebar()) : ?> <aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary"> <?php include roots_sidebar_path(); ?> </aside><!-- /.sidebar --> <?php endif; ?> </div><!-- /.content --> </div><!-- /.wrap --> <?php get_template_part('templates/footer'); ?> </body> </html>
Revert "[GH-4308] Temporary disable all tests with extensions" This reverts commit 0cbe0a7152891c4bd0e846a7c76bebcf47ab8cec.
package io.syndesis.qe; import com.codeborne.selenide.Configuration; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.junit.BeforeClass; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( features = "classpath:features", tags = {"not @wip", "not @manual", "not @deprecated", "not @disabled"}, format = {"pretty", "html:target/cucumber/cucumber-html", "junit:target/cucumber/cucumber-junit.xml", "json:target/cucumber/cucumber-report.json"} ) public class CucumberTest extends TestSuiteParent { @BeforeClass public static void setupCucumber() { //set up Selenide Configuration.timeout = TestConfiguration.getConfigTimeout() * 1000; Configuration.collectionsTimeout = Configuration.timeout; //We will now use custom web driver //Configuration.browser = TestConfiguration.syndesisBrowser(); Configuration.browser = "io.syndesis.qe.CustomWebDriverProvider"; Configuration.browserSize= "1920x1080"; } }
package io.syndesis.qe; import org.junit.BeforeClass; import org.junit.runner.RunWith; import com.codeborne.selenide.Configuration; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "classpath:features", tags = {"not @wip", "not @manual", "not @deprecated", "not @disabled", "not @extension"}, format = {"pretty", "html:target/cucumber/cucumber-html", "junit:target/cucumber/cucumber-junit.xml", "json:target/cucumber/cucumber-report.json"} ) public class CucumberTest extends TestSuiteParent { @BeforeClass public static void setupCucumber() { //set up Selenide Configuration.timeout = TestConfiguration.getConfigTimeout() * 1000; Configuration.collectionsTimeout = Configuration.timeout; //We will now use custom web driver //Configuration.browser = TestConfiguration.syndesisBrowser(); Configuration.browser = "io.syndesis.qe.CustomWebDriverProvider"; Configuration.browserSize= "1920x1080"; } }
Add example commands for the Systeminfo api Currently the api documentation does not include example commands. It would be very friendly for our users to have some example commands to follow and use the api. This patch adds examples to the Systeminfo section of the api documentation. Change-Id: Ic3d56d207db696100754a5a1fd5764f2f3f0a7f3
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. from oslo_config import cfg from pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. Example:: curl https://my.example.org/api/v1/systeminfo """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. from oslo_config import cfg from pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
Adjust route to add result_id, not _id...
var express = require('express'); var router = express.Router(); var mongoose = require('../models/mongoose'); const config = require('../config'); // Redis const Redis = require('ioredis'); var redis_client = new Redis(config.redis_connection); // routes that end with jobs // ---------------------------------------------------- // These are redis-based queries // route to return all current requests (GET http://localhost:3000/api/requests) router.route('/jobs/submit') // add a request for a process to launch (accessed at PUT api/requests) .put(function(req, res) { let request = req.body.request; // Add _id to process is not present if (! request.process.result_id) { request.process.result_id = new mongoose.mongo.ObjectId(); } console.log("REQUEST", request); redis_client.lpush('RAPD_JOBS', JSON.stringify(request), function(err, queue_length) { if (err) { console.error(err); res.status(500).json({ success: false, error: err }); } else { console.log('Job added to RAPD_JOBS queue length:', queue_length); res.status(200).json({ success: true, queue_length: queue_length }); } }); }); // End .put(function(req,res) { module.exports = router;
var express = require('express'); var router = express.Router(); var mongoose = require('../models/mongoose'); const config = require('../config'); // Redis const Redis = require('ioredis'); var redis_client = new Redis(config.redis_connection); // routes that end with jobs // ---------------------------------------------------- // These are redis-based queries // route to return all current requests (GET http://localhost:3000/api/requests) router.route('/jobs/submit') // add a request for a process to launch (accessed at PUT api/requests) .put(function(req, res) { let request = req.body.request; // Add _id to process is not present if (! request.process._id) { request.process._id = new mongoose.mongo.ObjectId(); } console.log("REQUEST", request); redis_client.lpush('RAPD_JOBS', JSON.stringify(request), function(err, queue_length) { if (err) { console.error(err); res.status(500).json({ success: false, error: err }); } else { console.log('Job added to RAPD_JOBS queue length:', queue_length); res.status(200).json({ success: true, queue_length: queue_length }); } }); }); // End .put(function(req,res) { module.exports = router;
Update analyzer definition access to type field
'use strict'; export default class AnalyzerConfigFormController { constructor($log) { 'ngInject'; this.$log = $log; this.rateUnits = ['Day', 'Month']; this.formData = {}; } $onInit() { this.$log.log( 'onInit of AnalyzerConfigFormController', this.definition, this.analyzer ); const { name, configuration } = this.analyzer; this.formData = { name, configuration }; } typeOf(config) { return `${config.multi ? 'multi-' : ''}${config.type}`; } addOption(config) { let defaultValues = { string: null, number: 0, boolean: true }; this.analyzer.configuration[config.name].push(defaultValues[config.type]); } }
'use strict'; export default class AnalyzerConfigFormController { constructor($log) { 'ngInject'; this.$log = $log; this.rateUnits = ['Day', 'Month']; this.formData = {}; } $onInit() { this.$log.log( 'onInit of AnalyzerConfigFormController', this.definition, this.analyzer ); const { name, configuration } = this.analyzer; this.formData = { name, configuration }; } typeOf(config) { return `${config.multi ? 'multi-' : ''}${config.tpe}`; } addOption(config) { let defaultValues = { string: null, number: 0, boolean: true }; this.analyzer.configuration[config.name].push(defaultValues[config.tpe]); } }
Add `jade` to the list of inputformats for Pug
'use strict'; var pug = require('pug'); exports.name = 'pug'; exports.inputFormats = ['pug', 'jade']; exports.outputFormat = 'html'; exports.compile = function (source, options) { var fn = pug.compile(source, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileClient = function (source, options) { return pug.compileClientWithDependenciesTracked(source, options); }; exports.compileFile = function (path, options) { var fn = pug.compileFile(path, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileFileClient = function (path, options) { var fs = require('fs'); // There is no compileFileClientWithDependenciesTracked so gotta do it // manually. options = options || {}; options.filename = options.filename || path; return exports.compileClient(fs.readFileSync(path, 'utf8'), options); };
'use strict'; var pug = require('pug'); exports.name = 'pug'; exports.outputFormat = 'html'; exports.compile = function (source, options) { var fn = pug.compile(source, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileClient = function (source, options) { return pug.compileClientWithDependenciesTracked(source, options); }; exports.compileFile = function (path, options) { var fn = pug.compileFile(path, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileFileClient = function (path, options) { var fs = require('fs'); // There is no compileFileClientWithDependenciesTracked so gotta do it // manually. options = options || {}; options.filename = options.filename || path; return exports.compileClient(fs.readFileSync(path, 'utf8'), options); };
Add a context to the fixture translations
import json import codecs import tempfile from django.core.management.commands.makemessages import Command as BaseCommand class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'), ('geo', 'geo_data.json'), ] def handle(self, *args, **kwargs): with tempfile.NamedTemporaryFile(dir='bluebottle', suffix='.py') as temp: for app, file in self.fixtures: with open('bluebottle/{}/fixtures/{}'.format(app, file)) as fixture_file: for string in [ fixture['fields']['name'].encode('utf-8') for fixture in json.load(fixture_file)]: temp.write('pgettext("{}-fixtures", "{}")\n'.format(app, string)) temp.flush() return super(Command, self).handle(*args, **kwargs)
import json import codecs import tempfile from django.core.management.commands.makemessages import Command as BaseCommand class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'), ('geo', 'geo_data.json'), ] def handle(self, *args, **kwargs): strings = [] for app, file in self.fixtures: with open('bluebottle/{}/fixtures/{}'.format(app, file)) as fixture_file: strings += [fixture['fields']['name'].encode('utf-8') for fixture in json.load(fixture_file)] with tempfile.NamedTemporaryFile(dir='bluebottle', suffix='.py') as temp: temp.write('\n'.join(['gettext("{}")'.format(string) for string in strings])) temp.flush() return super(Command, self).handle(*args, **kwargs)
Update up to changes in es5-ext
'use strict'; var compose = require('es5-ext/function/#/compose') , write = process.stdout.write.bind(process.stdout) , chars = '-\\|/' , l = chars.length , p; p = { next: 0, write: write, throbbed: false, ontick: function () { if (this.throbbed) { write('\u0008'); } else { this.throbbed = true; } this.write(chars[this.next++ % l]); }, onstop: function () { if (this.throbbed) { write('\u0008'); this.next = 0; this.throbbed = false; } } }; module.exports = function (interval, formatting) { var o = Object.create(p); if (formatting) { o.write = compose.call(write, formatting); } interval.on('tick', o.ontick.bind(o)); interval.on('stop', o.onstop.bind(o)); };
'use strict'; var chain = require('es5-ext/function/#/chain') , write = process.stdout.write.bind(process.stdout) , chars = '-\\|/' , l = chars.length , p; p = { next: 0, write: write, throbbed: false, ontick: function () { if (this.throbbed) { write('\u0008'); } else { this.throbbed = true; } this.write(chars[this.next++ % l]); }, onstop: function () { if (this.throbbed) { write('\u0008'); this.next = 0; this.throbbed = false; } } }; module.exports = function (interval, formatting) { var o = Object.create(p); if (formatting) { o.write = chain.call(formatting, write); } interval.on('tick', o.ontick.bind(o)); interval.on('stop', o.onstop.bind(o)); };
Change param name to match parent
<?php declare(strict_types=1); namespace Doctrine\Bundle\MongoDBBundle\Tests\Mapping\Driver; use Doctrine\Bundle\MongoDBBundle\Mapping\Driver\XmlDriver; class XmlDriverTest extends AbstractDriverTest { /** * @return string */ protected function getFileExtension() { return '.mongodb.xml'; } /** * @return string */ protected function getFixtureDir() { return __DIR__ . '/Fixtures/xml'; } /** * @return XmlDriver */ protected function getDriver(array $paths = []) { return new XmlDriver($paths, $this->getFileExtension()); } }
<?php declare(strict_types=1); namespace Doctrine\Bundle\MongoDBBundle\Tests\Mapping\Driver; use Doctrine\Bundle\MongoDBBundle\Mapping\Driver\XmlDriver; class XmlDriverTest extends AbstractDriverTest { /** * @return string */ protected function getFileExtension() { return '.mongodb.xml'; } /** * @return string */ protected function getFixtureDir() { return __DIR__ . '/Fixtures/xml'; } /** * @return XmlDriver */ protected function getDriver(array $prefixes = []) { return new XmlDriver($prefixes, $this->getFileExtension()); } }
Fix number of bills test
from tests import PMGTestCase from tests.fixtures import dbfixture, BillData, BillTypeData class TestBillAPI(PMGTestCase): def setUp(self): super(TestBillAPI, self).setUp() self.fx = dbfixture.data(BillTypeData, BillData) self.fx.setup() def test_total_bill(self): """ Viewing all private member bills """ res = self.client.get("bill/", base_url="http://api.pmg.test:5000/") self.assertEqual(200, res.status_code) self.assertEqual(7, res.json["count"]) def test_private_memeber_bill(self): """ Count the total number of private bills """ res = self.client.get("bill/pmb/", base_url="http://api.pmg.test:5000/") self.assertEqual(200, res.status_code) self.assertEqual(2, res.json["count"])
from tests import PMGTestCase from tests.fixtures import dbfixture, BillData, BillTypeData class TestBillAPI(PMGTestCase): def setUp(self): super(TestBillAPI, self).setUp() self.fx = dbfixture.data(BillTypeData, BillData) self.fx.setup() def test_total_bill(self): """ Viewing all private member bills """ res = self.client.get("bill/", base_url="http://api.pmg.test:5000/") self.assertEqual(200, res.status_code) self.assertEqual(6, res.json["count"]) def test_private_memeber_bill(self): """ Count the total number of private bills """ res = self.client.get("bill/pmb/", base_url="http://api.pmg.test:5000/") self.assertEqual(200, res.status_code) self.assertEqual(2, res.json["count"])
Use %d to format int value
package camelinaction; import org.apache.camel.jsonpath.JsonPath; import org.apache.camel.language.Bean; /** * A bean that acts as a JSon order service to handle incoming JSon orders */ public class JSonOrderService { public String handleIncomingOrder(@JsonPath("$.order.customerId") int customerId, @JsonPath("$.order.item") String item, @Bean(ref = "guid", method = "generate") int orderId) { // convert the order to a CSV and inject the generated order id return String.format("%d,%s,'%s'", orderId, customerId, item); } }
package camelinaction; import org.apache.camel.jsonpath.JsonPath; import org.apache.camel.language.Bean; /** * A bean that acts as a JSon order service to handle incoming JSon orders */ public class JSonOrderService { public String handleIncomingOrder(@JsonPath("$.order.customerId") int customerId, @JsonPath("$.order.item") String item, @Bean(ref = "guid", method = "generate") int orderId) { // convert the order to a CSV and inject the generated order id return String.format("%s,%s,'%s'", orderId, customerId, item); } }
Fix issues with database calculated rating column Actually its not nullable, but since we don't set one on creation, Hibernate trips on double. Therefore we use Double again.
package com.faforever.api.data.domain; import lombok.Setter; import org.hibernate.annotations.Generated; import org.hibernate.annotations.GenerationTime; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.MappedSuperclass; import javax.persistence.OneToOne; @MappedSuperclass @Setter public abstract class Rating { private int id; private int ranking; private Double mean; private Double deviation; private Player player; private Double rating; private int numberOfGames; @Id @Column(name = "id") public int getId() { return id; } @Column(name = "ranking") public int getRanking() { return ranking; } @Column(name = "mean") public Double getMean() { return mean; } @Column(name = "deviation") public Double getDeviation() { return deviation; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id", updatable = false, insertable = false) public Player getPlayer() { return player; } @Column(name = "rating", updatable = false, insertable = false) @Generated(GenerationTime.ALWAYS) public Double getRating() { return rating; } @Column(name = "num_games", updatable = false) public int getNumberOfGames() { return numberOfGames; } }
package com.faforever.api.data.domain; import lombok.Setter; import org.hibernate.annotations.Generated; import org.hibernate.annotations.GenerationTime; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.MappedSuperclass; import javax.persistence.OneToOne; @MappedSuperclass @Setter public abstract class Rating { private int id; private int ranking; private Double mean; private Double deviation; private Player player; private double rating; private int numberOfGames; @Id @Column(name = "id") public int getId() { return id; } @Column(name = "ranking") public int getRanking() { return ranking; } @Column(name = "mean") public Double getMean() { return mean; } @Column(name = "deviation") public Double getDeviation() { return deviation; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id", updatable = false, insertable = false) public Player getPlayer() { return player; } @Column(name = "rating", updatable = false) @Generated(GenerationTime.ALWAYS) public double getRating() { return rating; } @Column(name = "num_games", updatable = false) public int getNumberOfGames() { return numberOfGames; } }
Use db as backend for EOS file browser
<?php /** * Created by PhpStorm. * User: labkode * Date: 6/27/17 * Time: 11:16 AM */ namespace OC\CernBox\Storage\Eos; class InstanceMapper implements IInstanceMapper { /** * @var []InstanceInfo */ private $mappings = []; public function __construct() { $this->logger = \OC::$server->getLogger(); $data = \OC_DB::prepare('SELECT * FROM cernbox_eos_instances')->execute()->fetchAll(); $infos = array(); foreach($data as $d) { $mgm = $d['mgm_url']; $path = $d['root_path']; $name = $d['name']; $info = new InstanceInfo($name, $mgm, $path); $this->mappings[] = $info; } } public function getInstanceInfoByPath($rootPath) { foreach($this->mappings as $info) { if(strpos(trim($rootPath, '/'), trim($info->getInstanceRootPath(), '/')) === 0) { return $info; } } return false; } public function getInstanceInfoByName($instanceName) { foreach($this->mappings as $info) { if($info->getInstanceName() === $instanceName) { return $info; } } return false; } public function getAllMappings() { return $this->mappings; } }
<?php /** * Created by PhpStorm. * User: labkode * Date: 6/27/17 * Time: 11:16 AM */ namespace OC\CernBox\Storage\Eos; class InstanceMapper implements IInstanceMapper { /** * @var []InstanceInfo */ private $mappings; public function __construct() { $info = new InstanceInfo('Experiment', 'root://eospublic.cern.ch', '/eos/experiment'); $this->mappings = [$info]; } public function getInstanceInfoByPath($rootPath) { foreach($this->mappings as $info) { if(strpos(trim($rootPath, '/'), trim($info->getInstanceRootPath(), '/')) === 0) { return $info; } } return false; } public function getInstanceInfoByName($instanceName) { foreach($this->mappings as $info) { if($info->getInstanceName() === $instanceName) { return $info; } } return false; } public function getAllMappings() { return $this->mappings; } }
Make constructor param more specific
package com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers; import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer; import com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers.TagSegmentationScorer; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; /** * Score the segmentation of an {@link org.jsoup.nodes.Element} based upon the {@link org.jsoup.parser.Tag} it contains. */ public class SegmentationElementScorer extends Scorer<Element> { public final static String SCORE_LABEL = "element-segmentation"; Scorer<Tag> tagScorer; public SegmentationElementScorer(TagSegmentationScorer tagScorer){ super(SCORE_LABEL); this.tagScorer = tagScorer; } @Override public int score(Element input) { validateScoreInput(input); int score = tagScorer.score(input.tag()); return score; } private void validateScoreInput(Element input){ if (input == null){ throw new NullPointerException( "The input cannot be null" ); } if(input.attributes() == null){ throw new NullPointerException( "the input.attributes cannot be null" ); } } }
package com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers; import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; /** * Score the segmentation of an {@link org.jsoup.nodes.Element} based upon the {@link org.jsoup.parser.Tag} it contains. */ public class SegmentationElementScorer extends Scorer<Element> { public final static String SCORE_LABEL = "element-segmentation"; Scorer<Tag> tagScorer; public SegmentationElementScorer(Scorer<Tag> tagScorer){ super(SCORE_LABEL); this.tagScorer = tagScorer; } @Override public int score(Element input) { validateScoreInput(input); int score = tagScorer.score(input.tag()); return score; } private void validateScoreInput(Element input){ if (input == null){ throw new NullPointerException( "The input cannot be null" ); } if(input.attributes() == null){ throw new NullPointerException( "the input.attributes cannot be null" ); } } }
Use a sha1 as key.
<?php namespace Prometheus; class Sample { private $name; private $labelNames; private $labelValues; private $value; public function __construct(array $data) { $this->name = $data['name']; $this->labelNames = $data['labelNames']; $this->labelValues = $data['labelValues']; $this->value = $data['value']; } /** * @return string */ public function getName() { return $this->name; } /** * @return array */ public function getLabelNames() { return $this->labelNames; } /** * @return array */ public function getLabelValues() { return $this->labelValues; } /** * @return int|double */ public function getValue() { return $this->value; } /** * @return string */ public function getKey() { return sha1($this->getName() . serialize($this->getLabelValues())); } }
<?php namespace Prometheus; class Sample { private $name; private $labelNames; private $labelValues; private $value; public function __construct(array $data) { $this->name = $data['name']; $this->labelNames = $data['labelNames']; $this->labelValues = $data['labelValues']; $this->value = $data['value']; } /** * @return string */ public function getName() { return $this->name; } /** * @return array */ public function getLabelNames() { return $this->labelNames; } /** * @return array */ public function getLabelValues() { return $this->labelValues; } /** * @return int|double */ public function getValue() { return $this->value; } /** * @return string */ public function getKey() { return $this->getName() . serialize($this->getLabelValues()); } }
Use others to pick box props from
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import InputBase from './InputBase'; import Box, { omitBoxProps, pickBoxProps } from '../box'; import ValidationText from '../validationText'; import theme from './theme.css'; class TextArea extends PureComponent { render() { const { className, error, helpText, inverse, ...others } = this.props; const classNames = cx(theme['wrapper'], className); const boxProps = pickBoxProps(others); const inputProps = { error, inverse, ...omitBoxProps(others), }; return ( <Box className={classNames} {...boxProps}> <InputBase className={theme['text-area']} element="textarea" {...inputProps} /> <ValidationText error={error} help={helpText} inverse={inverse} /> </Box> ); } } TextArea.propTypes = { /** Sets a class name for the wrapper to give custom styles. */ className: PropTypes.string, /** The text to use as error message below the input. */ error: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), /** The text to use as help text below the input. */ helpText: PropTypes.string, /** Boolean indicating whether the input should render as inverse. */ inverse: PropTypes.bool, }; TextArea.defaultProps = { inverse: false, }; export default TextArea;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import InputBase from './InputBase'; import Box, { omitBoxProps, pickBoxProps } from '../box'; import ValidationText from '../validationText'; import theme from './theme.css'; class TextArea extends PureComponent { render() { const { className, error, helpText, inverse, ...others } = this.props; const classNames = cx(theme['wrapper'], className); const boxProps = pickBoxProps(this.props); const inputProps = { error, inverse, ...omitBoxProps(others), }; return ( <Box className={classNames} {...boxProps}> <InputBase className={theme['text-area']} element="textarea" {...inputProps} /> <ValidationText error={error} help={helpText} inverse={inverse} /> </Box> ); } } TextArea.propTypes = { /** Sets a class name for the wrapper to give custom styles. */ className: PropTypes.string, /** The text to use as error message below the input. */ error: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), /** The text to use as help text below the input. */ helpText: PropTypes.string, /** Boolean indicating whether the input should render as inverse. */ inverse: PropTypes.bool, }; TextArea.defaultProps = { inverse: false, }; export default TextArea;
Add option to fail fast on parse
package org.commcare.modern.parse; import org.commcare.core.interfaces.UserSandbox; import org.commcare.core.parse.ParseUtils; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; /** * Convenience methods, mostly for touchforms so we don't have to deal with Java IO * in Jython which is terrible * * Used by touchforms * * Created by wpride1 on 8/20/15. */ @SuppressWarnings("unused") public class ParseUtilsHelper extends ParseUtils { public static void parseXMLIntoSandbox(String restore, UserSandbox sandbox, boolean failFast) throws InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException, IOException { InputStream stream = new ByteArrayInputStream(restore.getBytes(StandardCharsets.UTF_8)); parseIntoSandbox(stream, sandbox, failFast); } public static void parseFileIntoSandbox(File restore, UserSandbox sandbox) throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException { InputStream stream = new FileInputStream(restore); parseIntoSandbox(stream, sandbox); } }
package org.commcare.modern.parse; import org.commcare.core.interfaces.UserSandbox; import org.commcare.core.parse.ParseUtils; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; /** * Convenience methods, mostly for touchforms so we don't have to deal with Java IO * in Jython which is terrible * * Used by touchforms * * Created by wpride1 on 8/20/15. */ @SuppressWarnings("unused") public class ParseUtilsHelper extends ParseUtils { public static void parseXMLIntoSandbox(String restore, UserSandbox sandbox) throws InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException, IOException { InputStream stream = new ByteArrayInputStream(restore.getBytes(StandardCharsets.UTF_8)); parseIntoSandbox(stream, sandbox); } public static void parseFileIntoSandbox(File restore, UserSandbox sandbox) throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException { InputStream stream = new FileInputStream(restore); parseIntoSandbox(stream, sandbox); } }
Replace jquery Ready() with vanilla JS We see some errors with loading the JS for some users, caused by $ being undefined. Why that happens is unknown, since jquery should be loaded before the main.js file, but we want to ultimately remove the jquery dependency anyway.
// This file gets added to the page via /app/views/shared/_head // That Rails view also adds several JavaScript globals to the page, // including the available locales and wikis, the Features enabled, // and other static (from a JavaScript perspective) data objects. // Polyfill import '@babel/polyfill'; import Rails from 'rails-ujs'; require('location-origin'); Rails.start(); // Enables rails-ujs, which adds JavaScript enhancement to some Rails views document.addEventListener('DOMContentLoaded', () => { window.I18n = require('i18n-js'); window.List = require('list.js'); // List is used for sorting tables outside of React require('./utils/course.js'); // This adds jquery features for some views outside of React // This is the main React entry point. It renders the navbar throughout the app, and // renders other components depending on the route. require('./components/app.jsx'); require('events').EventEmitter.defaultMaxListeners = 30; require('./utils/editable.js'); require('./utils/users_profile.js'); });
// This file gets added to the page via /app/views/shared/_head // That Rails view also adds several JavaScript globals to the page, // including the available locales and wikis, the Features enabled, // and other static (from a JavaScript perspective) data objects. // Polyfill import '@babel/polyfill'; import Rails from 'rails-ujs'; require('location-origin'); Rails.start(); // Enables rails-ujs, which adds JavaScript enhancement to some Rails views $(() => { window.I18n = require('i18n-js'); window.List = require('list.js'); // List is used for sorting tables outside of React require('./utils/course.js'); // This adds jquery features for some views outside of React // This is the main React entry point. It renders the navbar throughout the app, and // renders other components depending on the route. require('./components/app.jsx'); require('events').EventEmitter.defaultMaxListeners = 30; require('./utils/editable.js'); require('./utils/users_profile.js'); });
Use SingleThemeProvider - here google
package ch.difty.scipamato.publ.web.autoconfiguration; import org.apache.wicket.protocol.http.WebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import com.giffing.wicket.spring.boot.context.extensions.ApplicationInitExtension; import com.giffing.wicket.spring.boot.context.extensions.WicketApplicationInitConfiguration; import de.agilecoders.wicket.core.Bootstrap; import de.agilecoders.wicket.core.settings.SingleThemeProvider; import de.agilecoders.wicket.less.BootstrapLess; import de.agilecoders.wicket.themes.markup.html.google.GoogleTheme; @ApplicationInitExtension @ConditionalOnProperty(prefix = BootstrapProperties.PROPERTY_PREFIX, value = "enabled", matchIfMissing = true) @ConditionalOnClass(BootstrapConfig.class) @EnableConfigurationProperties({ BootstrapProperties.class }) public class BootstrapConfig implements WicketApplicationInitConfiguration { private final BootstrapProperties prop; public BootstrapConfig(BootstrapProperties prop) { this.prop = prop; } @Override public void init(WebApplication webApplication) { // TODO configurable solution to switch between bootswatch themes and google and own etc. prop.setThemeProvider(new SingleThemeProvider(new GoogleTheme())); Bootstrap.install(webApplication, prop); BootstrapLess.install(webApplication); } }
package ch.difty.scipamato.publ.web.autoconfiguration; import org.apache.wicket.protocol.http.WebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import com.giffing.wicket.spring.boot.context.extensions.ApplicationInitExtension; import com.giffing.wicket.spring.boot.context.extensions.WicketApplicationInitConfiguration; import de.agilecoders.wicket.core.Bootstrap; import de.agilecoders.wicket.core.settings.ThemeProvider; import de.agilecoders.wicket.less.BootstrapLess; import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider; @ApplicationInitExtension @ConditionalOnProperty(prefix = BootstrapProperties.PROPERTY_PREFIX, value = "enabled", matchIfMissing = true) @ConditionalOnClass(BootstrapConfig.class) @EnableConfigurationProperties({ BootstrapProperties.class }) public class BootstrapConfig implements WicketApplicationInitConfiguration { private final BootstrapProperties prop; public BootstrapConfig(BootstrapProperties prop) { this.prop = prop; } @Override public void init(WebApplication webApplication) { final ThemeProvider themeProvider = new BootswatchThemeProvider(prop.getTheme()); prop.setThemeProvider(themeProvider); Bootstrap.install(webApplication, prop); BootstrapLess.install(webApplication); } }
WORK WORK CARRY MOVE MOVE MOVE
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
Add 'clear' and 'format' to Ukrainian locale
/** * Ukrainian translation for bootstrap-datepicker * Igor Polynets */ ;(function($){ $.fn.datepicker.dates['uk'] = { days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота", "Неділя"], daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Нед"], daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"], months: ["Cічень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"], monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"], today: "Сьогодні", clear: "Очистити", format: "dd.mm.yyyy", weekStart: 1 }; }(jQuery));
/** * Ukrainian translation for bootstrap-datepicker * Igor Polynets */ ;(function($){ $.fn.datepicker.dates['uk'] = { days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота", "Неділя"], daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Нед"], daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"], months: ["Cічень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"], monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"], today: "Сьогодні", weekStart: 1 }; }(jQuery));
Remove call to open account window when loading module
from ghostlines.storage.app_storage import AppStorage from ghostlines.windows.account_details_window import AccountDetailsWindow from ghostlines.windows.sign_in_window import SignInWindow class AccountWindow(object): def __init__(self, sign_in=SignInWindow, account_details=AccountDetailsWindow): if self.is_logged_in: self.window = account_details(logout_window=sign_in) else: self.window = sign_in(success_window=account_details) @property def is_logged_in(self): token = AppStorage("pm.ghostlines.ghostlines.access_token").retrieve() # TODO: Retrieve returns NSNull if set to None. Empty string used to clear password for now. return token != '' and token is not None def open(self): self.window.open()
from ghostlines.storage.app_storage import AppStorage from ghostlines.windows.account_details_window import AccountDetailsWindow from ghostlines.windows.sign_in_window import SignInWindow class AccountWindow(object): def __init__(self, sign_in=SignInWindow, account_details=AccountDetailsWindow): if self.is_logged_in: self.window = account_details(logout_window=sign_in) else: self.window = sign_in(success_window=account_details) @property def is_logged_in(self): token = AppStorage("pm.ghostlines.ghostlines.access_token").retrieve() # TODO: Retrieve returns NSNull if set to None. Empty string used to clear password for now. return token != '' and token is not None def open(self): self.window.open() AccountWindow().open()
Replace default links and values
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'Vitaly Potyarkin' BIO = 'Unsorted ramblings, sometimes related to programming' SITENAME = 'Randomize' SITEURL = '' PATH = 'content' TIMEZONE = 'Europe/Moscow' DEFAULT_LANG = 'EN' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Blogroll LINKS = () # Social widget SOCIAL = [ ('calendar', '/archives.html'), ('tags', '/tags.html'), ('email', 'sio.wtf@gmail.com'), ('github', 'https://github.com/sio'), ] DEFAULT_PAGINATION = 6 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'Vitaly Potyarkin' BIO = 'Unsorted ramblings, sometimes related to programming' SITENAME = 'Randomize' SITEURL = '' PATH = 'content' TIMEZONE = 'Europe/Moscow' DEFAULT_LANG = 'EN' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True
Add selection option for instances of CommandHandlers
package org.jeecqrs.commands.registry; import java.util.Iterator; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.inject.Instance; import javax.inject.Inject; import org.jeecqrs.commands.CommandHandler; /** * */ public class AutoDiscoverCommandHandlerRegistry<C> extends AbstractCommandHandlerRegistry<C> { private Logger log = Logger.getLogger(AutoDiscoverCommandHandlerRegistry.class.getName()); @Inject private Instance<CommandHandler<C>> handlerInstances; @PostConstruct public void startup() { log.info("Scanning command handlers"); Iterator<CommandHandler<C>> it = select(handlerInstances); if (!it.hasNext()) log.warning("No CommandHandlers found"); while (it.hasNext()) { CommandHandler h = it.next(); log.fine("Discovered CommandHandler: "+ h); this.register(h.handledCommandType(), h); } } protected Iterator<CommandHandler<C>> select(Instance<CommandHandler<C>> instances) { return instances.iterator(); } }
package org.jeecqrs.commands.registry; import java.util.Iterator; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.inject.Instance; import javax.inject.Inject; import org.jeecqrs.commands.CommandHandler; /** * */ public class AutoDiscoverCommandHandlerRegistry<C> extends AbstractCommandHandlerRegistry<C> { private Logger log = Logger.getLogger(AutoDiscoverCommandHandlerRegistry.class.getName()); @Inject private Instance<CommandHandler> handlerInstances; @PostConstruct public void startup() { log.info("Scanning command handlers"); Iterator<CommandHandler> it = handlerInstances.iterator(); if (!it.hasNext()) { log.warning("No CommandHandlers found"); } while (it.hasNext()) { CommandHandler h = it.next(); log.fine("Discovered CommandHandler: "+ h); this.register(h.handledCommandType(), h); } } }
Refactor Space Before Bang further
'use strict'; var helpers = require('../helpers.js'); module.exports = { 'name': 'space-before-bang', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = []; ast.traverseByTypes(['important'], function (block, i, parent) { var previous = parent.content[i - 1]; if (!previous.is('space')) { if (parser.options.include) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': block.start.line, 'column': block.start.column, 'message': 'Whitespace required before !important', 'severity': parser.severity }); } } else { if (!parser.options.include) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': previous.start.line, 'column': previous.start.column, 'message': 'Whitespace not allowed before !important', 'severity': parser.severity }); } } }); return result; } };
'use strict'; var helpers = require('../helpers.js'); module.exports = { 'name': 'space-before-bang', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = []; ast.traverseByTypes(['important'], function (block, i, parent) { var previous = parent.content[i - 1]; if (!previous.is('space')) { if (parser.options.include) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': block.start.line, 'column': block.start.column, 'message': 'Whitespace required before !important', 'severity': parser.severity }); } } else { if (!parser.options.include) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': block.start.line, 'column': block.start.column - 1, 'message': 'Whitespace not allowed before !important', 'severity': parser.severity }); } } }); return result; } };
[Props] Make the source prop type optional This way if it's marked as required in `Image` we won't get warnings.
'use strict'; let React = require('react-native'); let { Image, PixelRatio, PropTypes, } = React; class ResponsiveImage extends React.Component { setNativeProps(nativeProps) { this.refs.image.setNativeProps(nativeProps); } render() { let { source } = this.props; let optimalSource = this._getClosestHighQualitySource(); if (optimalSource) { source = optimalSource; } if (!source) { throw new Error(`Couldn't find an appropriate image source`); } return <Image {...this.props} ref="image" source={source} />; } _getClosestHighQualitySource() { let { sources } = this.props; let pixelRatios = Object.keys(sources); if (!pixelRatios.length) { return null; } pixelRatios.sort((ratioA, ratioB) => parseFloat(ratioA) - parseFloat(ratioB) ); for (let ii = 0; ii < pixelRatios.length; ii++) { if (pixelRatios[ii] >= PixelRatio.get()) { return sources[pixelRatios[ii]]; } } let largestPixelRatio = pixelRatios[pixelRatios.length - 1]; return sources[largestPixelRatio]; } } ResponsiveImage.propTypes = { ...Image.propTypes, source: PropTypes.shape({ uri: PropTypes.string, }), sources: PropTypes.objectOf(Image.propTypes.source.isRequired), }; module.exports = ResponsiveImage;
'use strict'; let React = require('react-native'); let { Image, PixelRatio, PropTypes, } = React; class ResponsiveImage extends React.Component { setNativeProps(nativeProps) { this.refs.image.setNativeProps(nativeProps); } render() { let { source } = this.props; let optimalSource = this._getClosestHighQualitySource(); if (optimalSource) { source = optimalSource; } if (!source) { throw new Error(`Couldn't find an appropriate image source`); } return <Image {...this.props} ref="image" source={source} />; } _getClosestHighQualitySource() { let { sources } = this.props; let pixelRatios = Object.keys(sources); if (!pixelRatios.length) { return null; } pixelRatios.sort((ratioA, ratioB) => parseFloat(ratioA) - parseFloat(ratioB) ); for (let ii = 0; ii < pixelRatios.length; ii++) { if (pixelRatios[ii] >= PixelRatio.get()) { return sources[pixelRatios[ii]]; } } let largestPixelRatio = pixelRatios[pixelRatios.length - 1]; return sources[largestPixelRatio]; } } ResponsiveImage.propTypes = { ...Image.propTypes, sources: PropTypes.objectOf(Image.propTypes.source.isRequired), }; module.exports = ResponsiveImage;
Change size of inline images
<?php /** * * * @author Knut Kohl <github@knutkohl.de> * @copyright 2012-2013 Knut Kohl * @license GNU General Public License http://www.gnu.org/licenses/gpl.txt * @version $Id$ */ return array( // ----------------------------------------------------------------------- // INTERNAL SETTINGS, DO NOT TOUCH // ----------------------------------------------------------------------- /** * View settings */ 'View' => array( // Compile templates and reuse unless changed 'ReuseCode' => TRUE, // Replace static images by base64 encoded inline code // Only for images with max x/y of 8px 'InlineImages' => 8, // Don't compress HTML 'Verbose' => FALSE, // FALSE, 0, 10, 62, (95 is not working with UTF-8) 'JavaScriptPacker' => 62, // XML View settings 'XML' => array( 'Node' => 'node', 'Data' => 'data', ), ), );
<?php /** * * * @author Knut Kohl <github@knutkohl.de> * @copyright 2012-2013 Knut Kohl * @license GNU General Public License http://www.gnu.org/licenses/gpl.txt * @version $Id$ */ return array( // ----------------------------------------------------------------------- // INTERNAL SETTINGS, DO NOT TOUCH // ----------------------------------------------------------------------- /** * View settings */ 'View' => array( // Compile templates and reuse unless changed 'ReuseCode' => TRUE, // Replace static images by base64 encoded inline code // Only for images with max x/y of 16px 'InlineImages' => 16, // Don't compress HTML 'Verbose' => FALSE, // FALSE, 0, 10, 62, (95 is not working with UTF-8) 'JavaScriptPacker' => 62, // XML View settings 'XML' => array( 'Node' => 'node', 'Data' => 'data', ), ), );
Optimize context value per official docs
/** * @file TimestampProvider component. */ import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import axios from 'axios'; import getLogger from '../utils/logger'; const log = getLogger('TimestampContext'); export const TimestampContext = React.createContext({ timestamp: null, fetchTimestamp: () => {}, }); export default class TimestampProvider extends PureComponent { static propTypes = { children: PropTypes.node, }; state = { // eslint-disable-next-line react/no-unused-state timestamp: null, // eslint-disable-next-line react/no-unused-state fetchTimestamp: () => this.fetchTimestamp(), }; fetchTimestamp = async () => { try { const res = await axios.get('/home/timestamp'); this.setState(() => ({ timestamp: res.data.timestamp, })); } catch (error) { log.error(error); } }; render() { const { children } = this.props; return ( <TimestampContext.Provider value={this.state}> {children} </TimestampContext.Provider> ); } }
/** * @file TimestampProvider component. */ import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import axios from 'axios'; import getLogger from '../utils/logger'; const log = getLogger('TimestampContext'); export const TimestampContext = React.createContext({ timestamp: null, fetchTimestamp: () => {}, }); export default class TimestampProvider extends PureComponent { static propTypes = { children: PropTypes.node, }; state = { timestamp: null, }; fetchTimestamp = async () => { try { const res = await axios.get('/home/timestamp'); this.setState(() => ({ timestamp: res.data.timestamp, })); } catch (error) { log.error(error); } }; render() { const { children } = this.props; const { timestamp } = this.state; return ( <TimestampContext.Provider value={{ timestamp, fetchTimestamp: this.fetchTimestamp }} > {children} </TimestampContext.Provider> ); } }
Update service provider to use bindShared. Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Support; use Illuminate\Support\ServiceProvider; use Illuminate\Foundation\AliasLoader; class MessagesServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->bindShared('orchestra.messages', function () { return new Messages; }); $this->app->booting(function () { $loader = AliasLoader::getInstance(); $loader->alias('Orchestra\Messages', 'Orchestra\Support\Facades\Messages'); }); } /** * Bootstrap the application events. * * @return void */ public function boot() { $app = $this->app; $app->after(function () use ($app) { $app['orchestra.messages']->save(); }); } }
<?php namespace Orchestra\Support; use Illuminate\Support\ServiceProvider; use Illuminate\Foundation\AliasLoader; class MessagesServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app['orchestra.messages'] = $this->app->share(function () { return new Messages; }); $this->app->booting(function () { $loader = AliasLoader::getInstance(); $loader->alias('Orchestra\Messages', 'Orchestra\Support\Facades\Messages'); }); } /** * Bootstrap the application events. * * @return void */ public function boot() { $app = $this->app; $app->after(function () use ($app) { $app['orchestra.messages']->save(); }); } }
Include sender in message if echo is specified. Needs io object.
var read = require('fs').readFileSync; var client = require('khoros-client'); module.exports = function (io, server) { // Serve client js. if (server) { var clientSource = read(require.resolve('khoros-client/khoros.js'), 'utf-8'); server.on('request', function(req, res) { if (req.url == "/khoros/khoros.js") { res.writeHead(200, {"Content-Type": "text/plain"}); res.end(clientSource); } }); } // Return middleware. return function (socket, next) { socket.onevent = function (packet) { if(packet.type == 2) { var type = packet.data[0]; var data = packet.data[1]; switch(type) { case "khoros.join": console.log("New listener in room: " + data.khoros.room); socket.join(data.khoros.room); break; default: data.khoros.clientID = socket.client.id; if (data.khoros.echo) { // Send to all including sender io.in(data.khoros.room).emit(type, data); } else { // Send to all except sender socket.broadcast.to(data.khoros.room).emit(type, data); } break; } } } return next ? next() : null; } }
var read = require('fs').readFileSync; var client = require('khoros-client'); module.exports = function (server) { // Serve client js. if (server) { var clientSource = read(require.resolve('khoros-client/khoros.js'), 'utf-8'); server.on('request', function(req, res) { if (req.url == "/khoros/khoros.js") { res.writeHead(200, {"Content-Type": "text/plain"}); res.end(clientSource); } }); } // Return middleware. return function (socket, next) { socket.onevent = function (packet) { if(packet.type == 2) { var type = packet.data[0]; var data = packet.data[1]; switch(type) { case "khoros.join": console.log("New listener in room: " + data.khoros.room); socket.join(data.khoros.room); break; default: data.khoros.clientID = socket.client.id; socket.broadcast.to(data.khoros.room).emit(type, data); break; } } } return next ? next() : null; } }
Fix type of variable on PHPDoc
<?php namespace Chris\Composer\AutoregisterClassmapPlugin\Manipulator; /** * Class AutoloadManipulator * * @author Christophe Chausseray <chausseray.christophe@gmail.com> * * Manipulator of the existing autoload files. */ class AutoloadManipulator { /** * @var string */ protected $vendorDir; /** * AutoloadManipulator constructor. * * @param string $vendorDir */ public function __construct($vendorDir) { $this->vendorDir = $vendorDir; } /** * Rename "autoload_psr4.php" into "autoload_psr4_child.php" * * @return bool */ public function moveAutoloadPsr4() { return $this->moveFile('autoload_psr4.php', 'autoload_psr4_child.php'); } /** * Rename one autoload file into something else. * * @param string $oldName * @param string $newName * * @return bool */ protected function moveFile($oldName, $newName) { return rename($this->vendorDir . '/composer/' . $oldName, $this->vendorDir . '/composer/' . $newName); } }
<?php namespace Chris\Composer\AutoregisterClassmapPlugin\Manipulator; /** * Class AutoloadManipulator * * @author Christophe Chausseray <chausseray.christophe@gmail.com> * * Manipulator of the existing autoload files. */ class AutoloadManipulator { /** * @var string */ protected $vendorDir; /** * AutoloadManipulator constructor. * * @param string $vendorDir */ public function __construct($vendorDir) { $this->vendorDir = $vendorDir; } /** * Rename "autoload_psr4.php" into "autoload_psr4_child.php" * * @return bool */ public function moveAutoloadPsr4() { return $this->moveFile('autoload_psr4.php', 'autoload_psr4_child.php'); } /** * Rename one autoload file into something else. * * @param $oldName * @param $newName * * @return bool */ protected function moveFile($oldName, $newName) { return rename($this->vendorDir . '/composer/' . $oldName, $this->vendorDir . '/composer/' . $newName); } }
Fix bug that appears when a reference file model is created from scratch where the dq_def member exists, but has no rows. git-svn-id: 7ab1303e5df1b63f74144546e35d3203cc1d26c5@3127 560b4ebf-6bc0-4cc5-b8e0-b136f69d22d4
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None and len(dq_table) > 0: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
import numpy as np from . import dqflags def dynamic_mask(input_model): # # Return a mask model given a mask with dynamic DQ flags # Dynamic flags define what each plane refers to using the DQ_DEF extension dq_table = input_model.dq_def # Get the DQ array and the flag definitions if dq_table is not None: # # Make an empty mask dqmask = np.zeros(input_model.dq.shape, dtype=input_model.dq.dtype) for record in dq_table: bitplane = record['VALUE'] dqname = record['NAME'].strip() try: standard_bitvalue = dqflags.pixel[dqname] except KeyError: print 'Keyword %s does not correspond to an existing DQ mnemonic, so will be ignored' % (dqname) continue just_this_bit = np.bitwise_and(input_model.dq, bitplane) pixels = np.where(just_this_bit != 0) dqmask[pixels] = np.bitwise_or(dqmask[pixels], standard_bitvalue) else: dqmask = input_model.dq return dqmask
Apply Buble to build locale
import fs from 'fs' import path from 'path' import {rollup} from 'rollup' import uglify from 'rollup-plugin-uglify' import chalk from 'chalk' import buble from 'rollup-plugin-buble' async function build () { console.log(chalk.cyan('Building individual translations.')) const files = fs.readdirSync('./src/locale/translations') files.forEach(async function (file) { const inputOptions = { input: path.join(__dirname, '..', 'src', 'locale', 'translations', file), plugins: [ buble(), uglify() ] } const bundle = await rollup(inputOptions) const outputOptions = { file: path.join(__dirname, '..', 'dist', 'locale', 'translations', file), format: 'es' } await bundle.write(outputOptions) }) await console.log(chalk.green('Individual translations built.')) } async function buildAll () { console.log(chalk.cyan('Building translation importer.')) const bundle = await rollup({ input: path.join(__dirname, '..', 'src', 'locale', 'index.js'), plugins: [ buble(), uglify() ] }) await bundle.write({ file: path.join(__dirname, '..', 'dist', 'locale', 'index.js'), format: 'es' }) await console.log(chalk.green('All translations built.')) } build() buildAll()
import fs from 'fs' import path from 'path' import {rollup} from 'rollup' import uglify from 'rollup-plugin-uglify' import chalk from 'chalk' async function build () { console.log(chalk.cyan('Building individual translations.')) const files = fs.readdirSync('./src/locale/translations') files.forEach(async function (file) { const inputOptions = { input: path.join(__dirname, '..', 'src', 'locale', 'translations', file), plugins: [ uglify() ] } const bundle = await rollup(inputOptions) const outputOptions = { file: path.join(__dirname, '..', 'dist', 'locale', 'translations', file), format: 'es' } await bundle.write(outputOptions) }) await console.log(chalk.green('Individual translations built.')) } async function buildAll () { console.log(chalk.cyan('Building translation importer.')) const bundle = await rollup({ input: path.join(__dirname, '..', 'src', 'locale', 'index.js'), plugins: [ uglify() ] }) await bundle.write({ file: path.join(__dirname, '..', 'dist', 'locale', 'index.js'), format: 'es' }) await console.log(chalk.green('All translations built.')) } build() buildAll()
Make the buffer radio be big enough to change points visually
var AddAnalysisOptionModel = require('./add-analysis-option-model'); module.exports = function (analysisDefinitionNodeModel) { var models = []; var areaOfInfluence = _t('components.modals.add-analysis.options.sub-titles.area-of-influence'); // Buffer models.push( new AddAnalysisOptionModel({ title: _t('components.modals.add-analysis.options.buffer.title'), desc: _t('components.modals.add-analysis.options.buffer.desc'), sub_title: areaOfInfluence, node_attrs: { type: 'buffer', source_id: analysisDefinitionNodeModel.id, radio: 300 } }) ); // Trade-area models.push( new AddAnalysisOptionModel({ title: _t('components.modals.add-analysis.options.trade-area.title'), desc: _t('components.modals.add-analysis.options.trade-area.desc'), sub_title: areaOfInfluence, node_attrs: { type: 'trade-area', source_id: analysisDefinitionNodeModel.id, kind: 'drive', time: 300 } }) ); return models; };
var AddAnalysisOptionModel = require('./add-analysis-option-model'); module.exports = function (analysisDefinitionNodeModel) { var models = []; var areaOfInfluence = _t('components.modals.add-analysis.options.sub-titles.area-of-influence'); // Buffer models.push( new AddAnalysisOptionModel({ title: _t('components.modals.add-analysis.options.buffer.title'), desc: _t('components.modals.add-analysis.options.buffer.desc'), sub_title: areaOfInfluence, node_attrs: { type: 'buffer', source_id: analysisDefinitionNodeModel.id, radio: 123 } }) ); // Trade-area models.push( new AddAnalysisOptionModel({ title: _t('components.modals.add-analysis.options.trade-area.title'), desc: _t('components.modals.add-analysis.options.trade-area.desc'), sub_title: areaOfInfluence, node_attrs: { type: 'trade-area', source_id: analysisDefinitionNodeModel.id, kind: 'drive', time: 300 } }) ); return models; };
Add global level vars for other packages
from functools import wraps import platform # FIXME: had to duplicate this for package level imports. this is a bad design operating_system = platform.system() distribution, version, codename = platform.linux_distribution() def is_debian(versions=None, distro_name='Debian'): # FIXME: this is duplicated above. Figure out why operating_system = platform.system() distribution, version, codename = platform.linux_distribution() is_version = True if versions: is_version = version in versions or codename in versions return operating_system == 'Linux' \ and distribution == distro_name \ and is_version def only_debian(warn=True, error=False, versions=None): def wrapper(func): @wraps(func) def run_if_debian(*args, **kwargs): if is_debian(versions=versions): return func(*args, **kwargs) elif error: # FIXME: logitize me raise OSError('This command can only be run on Debian') elif warn: # FIXME: should log and warn if warn pass return run_if_debian return wrapper
from functools import wraps import platform def is_debian(versions=None, distro_name='Debian'): operating_system = platform.system() distribution, version, codename = platform.linux_distribution() is_version = True if versions: is_version = version in versions or codename in versions return operating_system == 'Linux' \ and distribution == distro_name \ and is_version def only_debian(warn=True, error=False, versions=None): def wrapper(func): @wraps(func) def run_if_debian(*args, **kwargs): if is_debian(versions=versions): return func(*args, **kwargs) elif error: # FIXME: logitize me raise OSError('This command can only be run on Debian') elif warn: # FIXME: should log and warn if warn pass return run_if_debian return wrapper
Add response to sensor stream API handler
var express = require('express'); var router = express.Router(); var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database('/home/pi/homeauto/backend/temp.db'); /* GET home page. */ router.get('/v1/temperature', function(req, res, next) { var filter = "WHERE sensor_fk = 1"; if(req.query.starttime && req.query.endtime) { filter += " AND time >= " + req.query.starttime + " AND time <= " + req.query.endtime; } else if(req.query.starttime) { filter += " AND time >= " + req.query.starttime; } else if(req.query.endtime) { filter += " AND time <= " + req.query.endtime; } var stmt = "SELECT * FROM sensorstream " + filter + " ORDER BY time"; console.log(stmt) db.all(stmt, function(err, rows) { res.send(rows); }); }); router.get('/v1/temperature/current', function(req, res, next) { db.all("SELECT * FROM sensorstream WHERE sensor_fk = 1 ORDER BY time DESC LIMIT 1", function(err, rows) { res.send(rows); }); }); router.get('/v1/sensorstream/:id', function(req, res, next) { var sensor_id = req.params.id; console.log("sensor id: " + id) res.send({}) }); module.exports = router;
var express = require('express'); var router = express.Router(); var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database('/home/pi/homeauto/backend/temp.db'); /* GET home page. */ router.get('/v1/temperature', function(req, res, next) { var filter = "WHERE sensor_fk = 1"; if(req.query.starttime && req.query.endtime) { filter += " AND time >= " + req.query.starttime + " AND time <= " + req.query.endtime; } else if(req.query.starttime) { filter += " AND time >= " + req.query.starttime; } else if(req.query.endtime) { filter += " AND time <= " + req.query.endtime; } var stmt = "SELECT * FROM sensorstream " + filter + " ORDER BY time"; console.log(stmt) db.all(stmt, function(err, rows) { res.send(rows); }); }); router.get('/v1/temperature/current', function(req, res, next) { db.all("SELECT * FROM sensorstream WHERE sensor_fk = 1 ORDER BY time DESC LIMIT 1", function(err, rows) { res.send(rows); }); }); router.get('/v1/sensorstream/:id', function(req, res, next) { var sensor_id = req.params.id; console.log("sensor id: " + id) }); module.exports = router;
Add sensor field to Event model in sensor.core
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.db import models VALUE_MAX_LEN = 128 class GenericEvent(models.Model): """Represents a measurement event abstracting away what exactly is measured. """ sensor = models.ForeignKey('core.GenericSensor') datetime = models.DateTimeField() value = models.CharField(max_length=VALUE_MAX_LEN) class Event(models.Model): """Base class for sensor-specific event types""" generic_event = models.OneToOneField('core.GenericEvent') sensor = models.ForeignKey('core.Sensor') datetime = models.DateTimeField() def value_to_string(self): """Event.value_to_string() -> unicode Returns a string representation of the """ raise NotImplementedError(self.__class__.value_to_string) class Meta: abstract = True
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.db import models VALUE_MAX_LEN = 128 class GenericEvent(models.Model): """Represents a measurement event abstracting away what exactly is measured. """ sensor = models.ForeignKey('core.GenericSensor') datetime = models.DateTimeField() value = models.CharField(max_length=VALUE_MAX_LEN) class Event(models.Model): """Base class for sensor-specific event types""" generic_event = models.OneToOneField('core.GenericEvent') datetime = models.DateTimeField() def value_to_string(self): """Event.value_to_string() -> unicode Returns a string representation of the """ raise NotImplementedError(self.__class__.value_to_string) class Meta: abstract = True
Fix focus jumping to comment after cleaning the customer
/** * @module timed * @submodule timed-components * @public */ import Component from 'ember-component' import service from 'ember-service/inject' import { observes } from 'ember-computed-decorators' import { later } from 'ember-runloop' const ENTER_CHAR_CODE = 13 /** * The tracking bar component * * @class TrackingBarComponent * @extends Ember.Component * @public */ export default Component.extend({ tracking: service('tracking'), /** * Key press event * * Start activity if the pressed key is enter * * @event keyPress * @param {jQuery.Event} e The keypress event * @public */ keyPress(e) { if ( e.which === ENTER_CHAR_CODE && !e.target.classList.contains('tt-input') ) { this.get('tracking.startActivity').perform() } }, /** * Set the focus to the comment field as soon as the task is selected * * The 'later' needs to be there so that the focus happens after all the * other events are done. Otherwise it'd focus the play button. * * @method _setCommentFocus * @public */ @observes('tracking.activity.task') _setCommentFocus() { later(this, () => { if (this.get('tracking.activity.task.id')) { this.$('input[name=comment]').focus() } }) } })
/** * @module timed * @submodule timed-components * @public */ import Component from 'ember-component' import service from 'ember-service/inject' import { observes } from 'ember-computed-decorators' import { later } from 'ember-runloop' const ENTER_CHAR_CODE = 13 /** * The tracking bar component * * @class TrackingBarComponent * @extends Ember.Component * @public */ export default Component.extend({ tracking: service('tracking'), /** * Key press event * * Start activity if the pressed key is enter * * @event keyPress * @param {jQuery.Event} e The keypress event * @public */ keyPress(e) { if ( e.which === ENTER_CHAR_CODE && !e.target.classList.contains('tt-input') ) { this.get('tracking.startActivity').perform() } }, /** * Set the focus to the comment field as soon as the task is selected * * The 'later' needs to be there so that the focus happens after all the * other events are done. Otherwise it'd focus the play button. * * @method _setCommentFocus * @public */ @observes('tracking.activity.task') _setCommentFocus() { if (this.get('tracking.activity.task.id')) { later(this, () => { this.$('input[name=comment]').focus() }) } } })
Remove value which is already default
from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class Excerpt(models.Model): name = models.CharField(max_length=128, verbose_name=_('name')) is_public = models.BooleanField(default=False, verbose_name=_('is public')) is_active = models.BooleanField(default=True, verbose_name=_('is active')) owner = models.ForeignKey(User, related_name='excerpts', verbose_name=_('owner')) bounding_geometry = models.OneToOneField('BoundingGeometry', verbose_name=_('bounding geometry')) @property def type_of_geometry(self): return self.bounding_geometry.type_of_geometry @property def extent(self): return self.bounding_geometry.extent def __str__(self): return self.name def _active_excerpts(): return Excerpt.objects.filter(is_active=True).filter( bounding_geometry__bboxboundinggeometry__isnull=False ) def private_user_excerpts(user): return _active_excerpts().filter(is_public=False, owner=user) def public_user_excerpts(user): return _active_excerpts().filter(is_public=True, owner=user) def other_users_public_excerpts(user): return _active_excerpts().filter(is_public=True).exclude(owner=user)
from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class Excerpt(models.Model): name = models.CharField(max_length=128, verbose_name=_('name'), blank=False) is_public = models.BooleanField(default=False, verbose_name=_('is public')) is_active = models.BooleanField(default=True, verbose_name=_('is active')) owner = models.ForeignKey(User, related_name='excerpts', verbose_name=_('owner')) bounding_geometry = models.OneToOneField('BoundingGeometry', verbose_name=_('bounding geometry')) @property def type_of_geometry(self): return self.bounding_geometry.type_of_geometry @property def extent(self): return self.bounding_geometry.extent def __str__(self): return self.name def _active_excerpts(): return Excerpt.objects.filter(is_active=True).filter( bounding_geometry__bboxboundinggeometry__isnull=False ) def private_user_excerpts(user): return _active_excerpts().filter(is_public=False, owner=user) def public_user_excerpts(user): return _active_excerpts().filter(is_public=True, owner=user) def other_users_public_excerpts(user): return _active_excerpts().filter(is_public=True).exclude(owner=user)
Reduce search response time by keeping wordlist in memory
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().split('\n') @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] for word in WORDS: if fragment in word: results.append({ 'word': word, 'category': classify(word), }) return jsonify(results) def classify(word): length = len(word) if length < 7: return 'short' elif length < 10: return 'medium' else: return 'long'
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] with open('typesetter/data/words.txt') as words: for word in words: word = word.strip('\n') if fragment in word: results.append({ 'word': word, 'category': classify(word), }) return jsonify(results) def classify(word): length = len(word) if length < 7: return 'short' elif length < 10: return 'medium' else: return 'long'
Stop console error about content security policy
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'smallprint', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, contentSecurityPolicy: { 'style-src': "'self' 'unsafe-inline'", }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'smallprint', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Change way README is imported. The custom read function is unnecessary since only one file is being accessed. Removing it reduces the amount of code.
#!/usr/bin/env python from distutils.core import setup setup( name='facebook-sdk', version='0.3.2', description='This client library is designed to support the Facebook ' 'Graph API and the official Facebook JavaScript SDK, which ' 'is the canonical way to implement Facebook authentication.', author='Facebook', maintainer='Martey Dodoo', maintainer_email='facebook-sdk@marteydodoo.com', url='https://github.com/pythonforfacebook/facebook-sdk', license='Apache', py_modules=[ 'facebook', ], long_description=open("README.rst").read(), classifiers=[ 'License :: OSI Approved :: Apache Software License', ], )
#!/usr/bin/env python from distutils.core import setup import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='facebook-sdk', version='0.3.2', description='This client library is designed to support the Facebook ' 'Graph API and the official Facebook JavaScript SDK, which ' 'is the canonical way to implement Facebook authentication.', author='Facebook', maintainer='Martey Dodoo', maintainer_email='facebook-sdk@marteydodoo.com', url='https://github.com/pythonforfacebook/facebook-sdk', license='Apache', py_modules=[ 'facebook', ], long_description=read("README.rst"), classifiers=[ 'License :: OSI Approved :: Apache Software License', ], )
Add option to pass options object to ng-simditor
module.exports = angular .module('simditor.directive', []) .directive('simditor', simditor); simditor.$inject = ['simditorOptions']; function simditor(simditorOptions) { return { restrict: 'AE', require: 'ngModel', scope: { options: '<' }, link: function(scope, element, attr, ngModel) { if (!ngModel) return; var options = scope.options || {}; if (attr.placeholder != null) { options.placeholder = attr.placeholder; } var $textarea = angular.element('<textarea></textarea>'); element.append($textarea); var config = angular.extend({ textarea: $textarea }, simditorOptions, options); var editor = new Simditor(config); ngModel.$render = function() { editor.setValue(ngModel.$viewValue || ''); }; editor.on('valuechanged', function(e) { ngModel.$setViewValue(editor.getValue()); }); } }; };
module.exports = angular .module('simditor.directive', []) .directive('simditor', simditor); simditor.$inject = ['simditorOptions']; function simditor(simditorOptions) { return { restrict: 'AE', require: 'ngModel', link: function(scope, element, attr, ngModel) { if (!ngModel) return; var $textarea = angular.element('<textarea placeholder="' + attr.placeholder + '"></textarea>'); element.append($textarea); var config = angular.extend({ textarea: $textarea }, simditorOptions); var editor = new Simditor(config); ngModel.$render = function() { editor.setValue(ngModel.$viewValue || ''); }; editor.on('valuechanged', function(e) { ngModel.$setViewValue(editor.getValue()); }); } }; };
Add new utility find function for converting id to longname for unit fields
var ObjectEditor = { Data: { Units: require('../WEdata/data/Units.json') }, Fields: { Units: require('../WEdata/fields/UnitMetaData.json') }, Find: { UnitFieldIdByLongName: function(longName) { // e.g. bountydice -> ubdi // TODO: time this function -- it may take too long for lookups for(var fieldKey in ObjectEditor.Fields.Units) { if( ObjectEditor.Fields.Units[fieldKey] && ObjectEditor.Fields.Units[fieldKey].field.toLowerCase() === longName.toLowerCase()) { return fieldKey; } } // console.error('Unable to lookup unit field by long name:', longName); return null; // Unable to find by long name }, UnitFieldLongNameById: function(id) { // e.g. ubdi -> bountydice return ObjectEditor.Fields.Units[id].field; } } } module.exports = ObjectEditor;
var ObjectEditor = { Data: { Units: require('../WEdata/data/Units.json') }, Fields: { Units: require('../WEdata/fields/UnitMetaData.json') }, Find: { UnitFieldIdByLongName: function(longName) { // e.g. bountydice -> ubdi // TODO: time this function -- it may take too long for lookups for(var fieldKey in ObjectEditor.Fields.Units) { if( ObjectEditor.Fields.Units[fieldKey] && ObjectEditor.Fields.Units[fieldKey].field.toLowerCase() === longName.toLowerCase()) { return fieldKey; } } // console.error('Unable to lookup unit field by long name:', longName); return null; // Unable to find by long name } } } module.exports = ObjectEditor;
Print out bag contents for lidar and button topics
#!/usr/bin/env python # -*- coding: utf-8 -*- """Convert a rosbag file to legacy lidar binary format. """ """LIDAR datatype format is: ( timestamp (long), flag (bool saved as int), accelerometer[3] (double), gps[3] (double), distance[LIDAR_NUM_ANGLES] (long), ) 'int' and 'long' are the same size on the raspberry pi (32 bits). """ import sys import rosbag def print_bag(bag): topics = ['/scan', '/flagbutton_pressed'] for message in bag.read_messages(topics=topics): print(message) if __name__ == '__main__': if len(sys.argv) < 2: print(('Usage: {} <rosbag> [<outfile>] \n\n' 'Print contents of rosbag file. If <outfile> is provided, \n' 'write contents of rosbag file to <outfile> in the legacy \n' 'lidar binary format.').format(__file__)) sys.exit(1) outfile = None filename = sys.argv[1] if len(sys.argv) == 3: outfile = sys.argv[2] with rosbag.Bag(filename) as bag: print_bag(bag) sys.exit()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Convert a rosbag file to legacy lidar binary format. """ """LIDAR datatype format is: ( timestamp (long), flag (bool saved as int), accelerometer[3] (double), gps[3] (double), distance[LIDAR_NUM_ANGLES] (long), ) 'int' and 'long' are the same size on the raspberry pi (32 bits). """ import sys import rosbag def decode_bag(bag): topics = ['/scan', '/flagbutton_pressed'] return [message for message in bag.read_messages(topics=topics)] if __name__ == '__main__': if len(sys.argv) < 2: print(('Usage: {} <rosbag> [<outfile>] \n\n' 'Print contents of rosbag file. If <outfile> is provided, \n' 'write contents of rosbag file to <outfile> in the legacy \n' 'lidar binary format.').format(__file__)) sys.exit(1) outfile = None filename = sys.argv[1] if len(sys.argv) == 3: outfile = sys.argv[2] with rosbag.Bag(filename) as bag: print(decode_bag(bag)) sys.exit()
tests: Allow multiple 'golden' results for agglomeration test on Linux
import sys import platform import h5py import numpy segh5 = sys.argv[1] predh5 = sys.argv[2] classifier = sys.argv[3] threshold = float(sys.argv[4]) from neuroproof import Agglomeration # open as uint32 and float respectively seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32) pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32) pred = pred.transpose((2,1,0,3)) pred = pred.copy() res = Agglomeration.agglomerate(seg, pred, classifier, threshold) # The 'golden' results depend on std::unordered, and therefore # the expected answer is different on Mac and Linux. if platform.system() == "Darwin": expected_unique = [239] else: # Depending on which linux stdlib we use, we might get different results expected_unique = [232, 233] result_unique = len(numpy.unique(res)) assert result_unique in expected_unique, \ "Wrong number of unique labels in the segmentation. Expected one of {}, but got {}"\ .format(expected_unique, len(numpy.unique(res))) print("SUCCESS")
import sys import platform import h5py import numpy segh5 = sys.argv[1] predh5 = sys.argv[2] classifier = sys.argv[3] threshold = float(sys.argv[4]) from neuroproof import Agglomeration # open as uint32 and float respectively seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32) pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32) pred = pred.transpose((2,1,0,3)) pred = pred.copy() res = Agglomeration.agglomerate(seg, pred, classifier, threshold) # The 'golden' results depend on std::unordered, and therefore # the expected answer is different on Mac and Linux. if platform.system() == "Darwin": expected_unique = 239 else: expected_unique = 233 result_unique = len(numpy.unique(res)) assert result_unique == expected_unique, \ "Expected {} unique labels (including 0) in the resulting segmentation, but got {}"\ .format(expected_unique, len(numpy.unique(res))) print("SUCCESS")
Fix a typo: error message showed the whole list of flies, instead of the one to which we tried to connect
// Enumerates USB devices, finds and identifies CrazyRadio USB dongle. package main import ( "fmt" "os" "time" "github.com/krasin/crazyradio" "github.com/krasin/crazyradio/usb" ) func fail(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) os.Exit(1) } func main() { st, err := crazyradio.Start(usb.Hub) if err != nil { fail("Unable to start station: %v\n", err) } addr, err := st.Scan() if err != nil { fail("Scan: %v\n", err) } if len(addr) == 0 { fail("No Crazyflies found\n") } flieAddr := addr[0] flie, err := st.Open(flieAddr) if err != nil { fail("Unable to connect to [%s]: %v\n", flieAddr, err) } flie.Write([]byte{60, 0, 0, 0, 0, 0, 0, 0, 128, 250, 117, 61, 64, 48, 117}) fmt.Printf("Press Ctrl+C to exit\n") for { time.Sleep(time.Second) } }
// Enumerates USB devices, finds and identifies CrazyRadio USB dongle. package main import ( "fmt" "os" "time" "github.com/krasin/crazyradio" "github.com/krasin/crazyradio/usb" ) func fail(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) os.Exit(1) } func main() { st, err := crazyradio.Start(usb.Hub) if err != nil { fail("Unable to start station: %v\n", err) } addr, err := st.Scan() if err != nil { fail("Scan: %v\n", err) } if len(addr) == 0 { fail("No Crazyflies found\n") } flie, err := st.Open(addr[0]) if err != nil { fail("Unable to connect to [%s]: %v\n", addr, err) } flie.Write([]byte{60, 0, 0, 0, 0, 0, 0, 0, 128, 250, 117, 61, 64, 48, 117}) fmt.Printf("Press Ctrl+C to exit\n") for { time.Sleep(time.Second) } }
Throw error if no config passed to errorHandler factory (instead of using example config)
/* * Error handling middleware factory * * @see module:midwest/util/format-error * @see module:midwest/util/log-error */ 'use strict'; // modules > 3rd party const _ = require('lodash'); // modules > internal const format = require('../util/format-error'); const log = require('../util/log-error'); module.exports = function (config) { if (!config) { throw new Error('`config` required for errorHandler middleware factory'); } return function errorHandler(error, req, res, next) { error = format(error, req, config); log(error, req, config.log); // limit what properties are sent to the client by overriding toJSON(). if (req.isAdmin && !req.isAdmin()) { error.toJSON = function () { return _.pick(this, config.mystify.properties); }; } res.status(error.status).locals = { error }; if (config.post) { config.post(req, res, next); } else { next(); } }; };
/* * Error handling middleware factory * * @see module:midwest/util/format-error * @see module:midwest/util/log-error */ 'use strict'; // modules > 3rd party const _ = require('lodash'); // modules > internal const format = require('../util/format-error'); const log = require('../util/log-error'); module.exports = function (config) { config = config || require('./example/config/error-handler'); return function errorHandler(error, req, res, next) { error = format(error, req, config); log(error, req, config.log); // limit what properties are sent to the client by overriding toJSON(). if (req.isAdmin && !req.isAdmin()) { error.toJSON = function () { return _.pick(this, config.mystify.properties); }; } res.status(error.status).locals = { error }; if (config.post) { config.post(req, res, next); } else { next(); } }; };
Make load balancer as fast as possible. No config is used, servers are defined in code.
package sk.httpclient.app; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import java.util.List; public class MyLoadBalancer implements ILoadBalancer { private int c = 0; @Override public void addServers(List<Server> newServers) { //super.addServers(newServers); } private final Server[] a = new Server[]{ new Server("localhost", 8887), new Server("localhost", 8888), new Server("localhost", 8889) }; @Override public Server chooseServer(Object key) { c = ++c % 3; return a[c]; } @Override public void markServerDown(Server server) { } @Override public List<Server> getServerList(boolean availableOnly) { return null; } @Override public List<Server> getReachableServers() { return null; } @Override public List<Server> getAllServers() { return null; } }
package sk.httpclient.app; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; import java.util.List; public class MyLoadBalancer extends DynamicServerListLoadBalancer { private int c = 0; @Override public void addServers(List<Server> newServers) { super.addServers(newServers); } @Override public Server chooseServer(Object key) { //c = ++c % upServerList.size(); //return upServerList.get(c); return super.chooseServer(key); } @Override public void markServerDown(Server server) { } @Override public List<Server> getServerList(boolean availableOnly) { return null; } @Override public List<Server> getReachableServers() { return null; } @Override public List<Server> getAllServers() { return null; } }
Edit docs test for local test on windows machine
import subprocess import unittest import os import subprocess import unittest import os class Doc_Test(unittest.TestCase): @property def path_to_docs(self): dirname, filename = os.path.split(os.path.abspath(__file__)) return dirname.split(os.path.sep)[:-2] + ['docs'] def test_html(self): wd = os.getcwd() os.chdir(os.path.sep.join(self.path_to_docs)) response = subprocess.run(["make", "html"]) self.assertTrue(response.returncode == 0) # response = subprocess.call(["make", "html"], shell=True) # Needed for local test on Windows # self.assertTrue(response == 0) os.chdir(wd) def test_linkcheck(self): wd = os.getcwd() os.chdir(os.path.sep.join(self.path_to_docs)) response = subprocess.run(["make", "linkcheck"]) print(response.returncode) self.assertTrue(response.returncode == 0) # response = subprocess.call(["make", "linkcheck"], shell=True) # Needed for local test on Windows # print(response) # self.assertTrue(response == 0) os.chdir(wd) if __name__ == '__main__': unittest.main()
import subprocess import unittest import os import subprocess import unittest import os class Doc_Test(unittest.TestCase): @property def path_to_docs(self): dirname, filename = os.path.split(os.path.abspath(__file__)) return dirname.split(os.path.sep)[:-2] + ['docs'] def test_html(self): wd = os.getcwd() os.chdir(os.path.sep.join(self.path_to_docs)) response = subprocess.run(["make", "html"]) self.assertTrue(response.returncode == 0) os.chdir(wd) def test_linkcheck(self): wd = os.getcwd() os.chdir(os.path.sep.join(self.path_to_docs)) response = subprocess.run(["make", "linkcheck"]) print(response.returncode) self.assertTrue(response.returncode == 0) os.chdir(wd) if __name__ == '__main__': unittest.main()