text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix key error when no tags are specified
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() def save(self, bundle, skip_errors=False): bundle = super(ExpenseResource, self).save(bundle, skip_errors) if "tags" in bundle.data: bundle.obj.reset_tags_from_string(bundle.data["tags"]) return bundle class Meta: queryset = Expense.objects.all() excludes = ["created", "updated"] # WARNING: Tastypie docs say that this is VERY INSECURE! # For development only! authorization = Authorization()
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() def save(self, bundle, skip_errors=False): bundle = super(ExpenseResource, self).save(bundle, skip_errors) bundle.obj.reset_tags_from_string(bundle.data["tags"]) return bundle class Meta: queryset = Expense.objects.all() excludes = ["created", "updated"] # WARNING: Tastypie docs say that this is VERY INSECURE! # For development only! authorization = Authorization()
Add pretty lib to inspect struct
package gmws import ( "fmt" "os" "github.com/kr/pretty" "github.com/svvu/gomws/mwsHttps" ) // MwsConfig is configuraton to create the gomws base. // AccessKey and SecretKey are optional, bette to set them in evn variables. type MwsConfig struct { SellerId string AuthToken string Region string AccessKey string SecretKey string } // MwsClient the interface for API clients. type MwsClient interface { Version() string Name() string NewClient(config MwsConfig) (MwsClient, error) GetServiceStatus() (mwsHttps.Response, error) } const ( envAccessKey = "AWS_ACCESS_KEY" envSecretKey = "AWS_SECRET_KEY" ) // Credential the credential to access the API. type Credential struct { AccessKey string SecretKey string } // GetCredential get the credential from evn variables. func GetCredential() Credential { credential := Credential{} credential.AccessKey = os.Getenv(envAccessKey) credential.SecretKey = os.Getenv(envSecretKey) return credential } // Inspect print out the value in a user friendly way. func Inspect(value interface{}) { fmt.Printf("%# v", pretty.Formatter(value)) }
package gmws import ( "os" "github.com/svvu/gomws/mwsHttps" ) // MwsConfig is configuraton to create the gomws base. // AccessKey and SecretKey are optional, bette to set them in evn variables. type MwsConfig struct { SellerId string AuthToken string Region string AccessKey string SecretKey string } // MwsClient the interface for API clients. type MwsClient interface { Version() string Name() string NewClient(config MwsConfig) (MwsClient, error) GetServiceStatus() (mwsHttps.Response, error) } const ( envAccessKey = "AWS_ACCESS_KEY" envSecretKey = "AWS_SECRET_KEY" ) // Credential the credential to access the API. type Credential struct { AccessKey string SecretKey string } // GetCredential get the credential from evn variables. func GetCredential() Credential { credential := Credential{} credential.AccessKey = os.Getenv(envAccessKey) credential.SecretKey = os.Getenv(envSecretKey) return credential }
Fix bug that prevented images from being stored.
<?php namespace Nohex\Eix\Modules\Catalog\Model; use Nohex\Eix\Services\Data\Sources\ImageStore as DataSource; use Nohex\Eix\Modules\Catalog\Model\Image; /** * Representation of an image associated with a product. */ class ProductImage extends Image { const COLLECTION = 'products'; protected function getDefaultDataSource() { $dataSource = DataSource::getInstance(static::COLLECTION); // Set alternative image sizes. $dataSource->setAlternativeImageSizes(array( 32, 96, 140 )); return $dataSource; } protected function getFactory() { return ProductImages::getInstance(); } }
<?php namespace Nohex\Eix\Modules\Catalog\Model; use Nohex\Eix\Services\Data\Sources\ImageStore as DataSource; use Nohex\Eix\Modules\Catalog\Model\Image; /** * Representation of an image associated with a product. */ class ProductImage extends Image { const COLLECTION = 'products'; protected function getDefaultDataSource() { return DataSource::getInstance(static::COLLECTION); // Set alternative image sizes. $this->dataSource->setAlternativeImageSizes(array( 32, 96, 140 )); } protected function getFactory() { return ProductImages::getInstance(); } }
Fix possible issue when MD5ing multibyte strings.
package com.vaguehope.onosendai.util; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public final class HashHelper { private HashHelper () { throw new AssertionError(); } public static BigInteger md5String (final String s) { final MessageDigest md = MD_MD5_FACTORY.get(); md.update(getBytes(s)); return new BigInteger(1, md.digest()); } private static byte[] getBytes (final String s) { try { return s.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } } /** * MessageDigest.getInstance("MD5") can take up to a second, so using this * to cache it and improve performance. */ private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() { @Override protected MessageDigest initialValue () { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); return md; } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("JVM is missing MD5.", e); } } }; }
package com.vaguehope.onosendai.util; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public final class HashHelper { private HashHelper () { throw new AssertionError(); } public static BigInteger md5String (final String s) { final MessageDigest md = MD_MD5_FACTORY.get(); md.update(getBytes(s), 0, s.length()); return new BigInteger(1, md.digest()); } private static byte[] getBytes (final String s) { try { return s.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } } /** * MessageDigest.getInstance("MD5") can take up to a second, so using this * to cache it and improve performance. */ private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() { @Override protected MessageDigest initialValue () { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); return md; } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("JVM is missing MD5.", e); } } }; }
Add a blank line in the end
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-11-30 # Python 3.4 """ 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), 使用 Python 如何生成 200 个激活码(或者优惠券)? """ import uuid def generate_key(): key_list = [] for i in range(200): uuid_key = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.uuid1())) key_list.append(str(uuid_key).replace('-', '')) return key_list if __name__ == '__main__': print(generate_key())
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-11-30 # Python 3.4 """ 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), 使用 Python 如何生成 200 个激活码(或者优惠券)? """ import uuid def generate_key(): key_list = [] for i in range(200): uuid_key = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.uuid1())) key_list.append(str(uuid_key).replace('-', '')) return key_list if __name__ == '__main__': print(generate_key())
Remove includes to be compatible with currently released chrome
import Image from '../image'; export default function bitDepth(newBitDepth = 8) { this.checkProcessable('bitDepth', { bitDepth: [8, 16] }); if (!~[8,16].indexOf(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16'); if (this.bitDepth === newBitDepth) return this.clone(); let newImage = Image.createFrom(this, {bitDepth: newBitDepth}); if (newBitDepth === 8) { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] >> 8; } } else { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] << 8 | this.data[i]; } } return newImage; }
import Image from '../image'; export default function bitDepth(newBitDepth = 8) { this.checkProcessable('bitDepth', { bitDepth: [8, 16] }); if (![8,16].includes(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16'); if (this.bitDepth === newBitDepth) return this.clone(); let newImage = Image.createFrom(this, {bitDepth: newBitDepth}); if (newBitDepth === 8) { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] >> 8; } } else { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] << 8 | this.data[i]; } } return newImage; }
Upgrade from v4 to v5
/** * @author Hamza Waqas <hamzawaqas@live.com> * @since 1/14/14 */ (function() { var _ = require('lodash'); var Main = function(apiKey) { var _services = ['name', 'search', 'thumbnail'] , Inherits = require('./inherits') , self = this; // Make some configuration; this.options = { api_url: "http://api.pipl.com/search/v5/", apiKey: apiKey }; _.forEach(_services, function(service) { module.exports[service] = require(__dirname + '/services/' + service)(Inherits, self.options); }); return module.exports; }.bind(this); module.exports = Main; }).call(this);
/** * @author Hamza Waqas <hamzawaqas@live.com> * @since 1/14/14 */ (function() { var _ = require('lodash'); var Main = function(apiKey) { var _services = ['name', 'search', 'thumbnail'] , Inherits = require('./inherits') , self = this; // Make some configuration; this.options = { api_url: "http://api.pipl.com/search/v4/", apiKey: apiKey }; _.forEach(_services, function(service) { module.exports[service] = require(__dirname + '/services/' + service)(Inherits, self.options); }); return module.exports; }.bind(this); module.exports = Main; }).call(this);
Fix the order of the returned values from `analytic_signal`.
# -*- coding: utf-8 -*- """ Cross Correlation see @https://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html """ # Author: Avraam Marimpis <avraam.marimpis@gmail.com> from .estimator import Estimator from ..analytic_signal import analytic_signal import numpy as np def crosscorr(data, fb, fs, pairs=None): """ Parameters ---------- Returns ------- """ n_channels, _ = np.shape(data) _, _, filtered = analytic_signal(data, fb, fs) r = np.zeros([n_channels, n_channels], dtype=np.float32) for i in range(n_channels): for ii in range(n_channels): r[i, ii] = np.correlate(filtered[i,], filtered[ii,], mode="valid") return r
# -*- coding: utf-8 -*- """ Cross Correlation see @https://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html """ # Author: Avraam Marimpis <avraam.marimpis@gmail.com> from .estimator import Estimator from ..analytic_signal import analytic_signal import numpy as np def crosscorr(data, fb, fs, pairs=None): """ Parameters ---------- Returns ------- """ n_channels, _ = np.shape(data) filtered, _, _ = analytic_signal(data, fb, fs) r = np.zeros([n_channels, n_channels], dtype=np.float32) for i in range(n_channels): for ii in range(n_channels): r[i, ii] = np.correlate(filtered[i, ], filtered[ii, ], mode='valid') return r
Use find instead of split
import MeCab class MeCabParser(object): def __init__(self, arg=''): self.model = MeCab.Model_create(arg) def parse(self, s): tagger = self.model.createTagger() lattice = self.model.createLattice() lattice.set_sentence(s) tagger.parse(lattice) node = lattice.bos_node() morphs = [] while node: if node.surface != '': feature = node.feature morphs.append({ 'surface': node.surface, 'pos': feature[0:feature.find(',')], 'feature': feature, }) node = node.next return morphs
import MeCab class MeCabParser(object): def __init__(self, arg=''): self.model = MeCab.Model_create(arg) def parse(self, s): tagger = self.model.createTagger() lattice = self.model.createLattice() lattice.set_sentence(s) tagger.parse(lattice) node = lattice.bos_node() morphs = [] while node: if node.surface != '': feature = node.feature morphs.append({ 'surface': node.surface, 'pos': feature.split(',')[0], 'feature': feature, }) node = node.next return morphs
Fix allocation of points array for real
/** * $$\\ToureNPlaner\\$$ */ package algorithms; import com.carrotsearch.hppc.IntArrayList; public class Points { private IntArrayList points; public Points() { points = new IntArrayList(); } public void addPoint(int lat, int lon) { points.add(lat); points.add(lon); } public void addEmptyPoints(int num) { points.resize(points.size() + num*2); } public int getPointLat(int index) { return points.get(index * 2); } public int getPointLon(int index) { return points.get(index * 2 + 1); } public void setPointLat(int index, int lat) { points.set(index * 2, lat); } public void setPointLon(int index, int lon) { points.set(index * 2 + 1, lon); } public int size() { return points.size() / 2; } }
/** * $$\\ToureNPlaner\\$$ */ package algorithms; import com.carrotsearch.hppc.IntArrayList; public class Points { private IntArrayList points; public Points() { points = new IntArrayList(); } public void addPoint(int lat, int lon) { points.add(lat); points.add(lon); } public void addEmptyPoints(int num) { points.resize(this.size() + num*2); } public int getPointLat(int index) { return points.get(index * 2); } public int getPointLon(int index) { return points.get(index * 2 + 1); } public void setPointLat(int index, int lat) { points.set(index * 2, lat); } public void setPointLon(int index, int lon) { points.set(index * 2 + 1, lon); } public int size() { return points.size() / 2; } }
Exit with code 0 if only warnings are present
const table = require('text-table') const chalk = require('chalk') class Reporter { report (results) { let output = '\n' let totalErrors = 0 let totalWarnings = 0 results.forEach((result) => { totalErrors += result.errorCount totalWarnings += result.warningCount output += chalk.underline(result.filePath) + '\n' output += table(result.messages.map((msg) => { return [ '', `${msg.line}:${msg.column}`, (msg.severity === 2) ? chalk.red(msg.ruleId) : chalk.yellow(msg.ruleId), msg.message ] })) output += '\n\n' }) if (totalErrors > 0 || totalWarnings > 0) { output += chalk.red.bold(`\u2716 errors: ${totalErrors}`) output += ' | ' output += chalk.yellow.bold(`warnings ${totalWarnings}`) console.log(output) process.exit(totalErrors > 0 ? 1 : 0) } } } module.exports = Reporter
const table = require('text-table') const chalk = require('chalk') class Reporter { report (results) { let output = '\n' let totalErrors = 0 let totalWarnings = 0 results.forEach((result) => { totalErrors += result.errorCount totalWarnings += result.warningCount output += chalk.underline(result.filePath) + '\n' output += table(result.messages.map((msg) => { return [ '', `${msg.line}:${msg.column}`, (msg.severity === 2) ? chalk.red(msg.ruleId) : chalk.yellow(msg.ruleId), msg.message ] })) output += '\n\n' }) if (totalErrors > 0 || totalWarnings > 0) { output += chalk.red.bold(`\u2716 errors: ${totalErrors}`) output += ' | ' output += chalk.yellow.bold(`warnings ${totalWarnings}`) console.log(output) process.exit(1) } } } module.exports = Reporter
Add key to module table list item
import React, { PropTypes } from 'react'; import ActionDelete from 'material-ui/svg-icons/action/delete'; import IconButton from 'material-ui/IconButton'; import { List, ListItem } from 'material-ui/List'; import { red700 } from 'material-ui/styles/colors'; const ModuleTable = ({ modules, removeModule, }) => ( <List> {modules.map(module => <ListItem key={module.ModuleCode} rightIconButton={ <IconButton onTouchTap={() => removeModule(module.ModuleCode)} touch={true} tooltip="Remove module" tooltipPosition="bottom-left" > <ActionDelete color={red700} /> </IconButton> } primaryText={module.ModuleCode} secondaryText={module.ModuleTitle} /> )} </List> ); ModuleTable.propTypes = { modules: PropTypes.array.isRequired, removeModule: PropTypes.func.isRequired, }; export default ModuleTable;
import React, { PropTypes } from 'react'; import ActionDelete from 'material-ui/svg-icons/action/delete'; import IconButton from 'material-ui/IconButton'; import { List, ListItem } from 'material-ui/List'; import { red700 } from 'material-ui/styles/colors'; const ModuleTable = ({ modules, removeModule, }) => ( <List> {modules.map(module => <ListItem rightIconButton={ <IconButton onTouchTap={() => removeModule(module.ModuleCode)} touch={true} tooltip="Remove module" tooltipPosition="bottom-left" > <ActionDelete color={red700} /> </IconButton> } primaryText={module.ModuleCode} secondaryText={module.ModuleTitle} /> )} </List> ); ModuleTable.propTypes = { modules: PropTypes.array.isRequired, removeModule: PropTypes.func.isRequired, }; export default ModuleTable;
Add uploading true or false Add uploading true or false. Use handlebar helper to show used if uploading
import Ember from 'ember'; export default Ember.View.extend({ tagName: 'input', name: 'file', attributeBindings: ['name', 'type', 'data-form-data'], type: 'file', didInsertElement: function() { var _this = this, controller = this.get('controller'); $.get(CatsUiENV.API_NAMESPACE + '/cloudinary_params', {timestamp: Date.now() / 1000}).done(function(response) { // Need to ensure that the input attribute is updated before initializing Cloudinary Ember.run(function() { _this.set('data-form-data', JSON.stringify(response)); }); _this.$().cloudinary_fileupload({ disableImageResize: false, imageMaxWidth: 1000, imageMaxHeight: 1000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|ico)$/i, maxFileSize: 5000000 // 5MB }); _this.$().bind("fileuploadstart", function(e){ controller.set('uploading', true); }); _this.$().bind("fileuploadstop", function(e){ controller.set('uploading', false); }); _this.$().bind('fileuploaddone', function (e, data) { controller.set('newCat.cloudinaryPublicId', data.result.public_id); }); }); } });
import Ember from 'ember'; export default Ember.View.extend({ tagName: 'input', name: 'file', attributeBindings: ['name', 'type', 'data-form-data'], type: 'file', didInsertElement: function() { var _this = this, controller = this.get('controller'); $.get(CatsUiENV.API_NAMESPACE + '/cloudinary_params', {timestamp: Date.now() / 1000}).done(function(response) { // Need to ensure that the input attribute is updated before initializing Cloudinary Ember.run(function() { _this.set('data-form-data', JSON.stringify(response)); }); _this.$().cloudinary_fileupload({ disableImageResize: false, imageMaxWidth: 1000, imageMaxHeight: 1000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|ico)$/i, maxFileSize: 5000000 // 5MB }); _this.$().bind('fileuploaddone', function (e, data) { controller.set('newCat.cloudinaryPublicId', data.result.public_id); }); }); } });
fix(shop): Update admin order show page Update admin order show page see #401
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Order; class OrderController extends Controller { public function index() { $orders = Order::all(); return view('admin.orders.index')->with('orders', $orders); } public function show($id) { $order = Order::findOrFail($id); $status = $order->status; $total_amount = 0; foreach ($order->orderProducts as $product) { $amount = $product->price*$product->quantity; $total_amount = $amount + $total_amount; } return view('admin.orders.show') ->with('order', $order) ->with('status', $status) ->with('total_amount', $total_amount); } public function edit(Request $request, $id) { $aa = $request->status; $order = Order::findOrFail($id); $order->update($request->all()); return redirect()->route('adminOrdersShow', ['id' => $id]); } }
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Order; class OrderController extends Controller { public function index() { $orders = Order::all(); return view('admin.orders.index')->with('orders', $orders); } public function show($id) { $order = Order::findOrFail($id); $status = $order->status; $total_amount = 0; foreach ($order->orderProducts as $product) { $amount = $product->price*$product->quantity; $total_amount = $amount + $total_amount; } return view('admin.orders.show')->with('order', $order)->with('status', $status)->with('total_amount', $total_amount); } public function edit(Request $request, $id) { $aa = $request->status; $order = Order::findOrFail($id); $order->update($request->all()); return redirect()->route('adminOrdersShow', ['id' => $id]); } }
Extend directly from replyable view
/* global define */ define([ 'jquery', 'underscore', 'backbone', 'marionette', 'dust', 'dust.helpers', 'dust.marionette', 'views/replyable-view', 'controllers/navigation/navigator', 'content/comments/comment-template' ], function ($, _, Backbone, Marionette, dust, dustHelpers, dustMarionette, ReplyableView, Navigator) { 'use strict'; var CommentView = ReplyableView.extend({ template: 'content/comments/comment-template.dust', tagName: function () { return 'li id="comment-' + this.model.get('ID') + '" class="media comment"'; }, events: { 'click .b3-reply-comment': 'renderReplyBox', // from ReplyableView 'click .b3-comment-author': 'displayAuthor' }, initialize: function () { this.post = null; this.user = null; }, serializeData: function () { return this.model.toJSON(); }, parentId: function () { return this.model.get('ID'); }, displayAuthor: function (event) { var slug = $(event.currentTarget).attr('slug'); Navigator.navigateToAuthor(slug, null, true); event.preventDefault(); } }); return CommentView; });
/* global define */ define([ 'jquery', 'underscore', 'backbone', 'marionette', 'dust', 'dust.helpers', 'dust.marionette', 'views/replyable-view', 'controllers/navigation/navigator', 'content/comments/comment-template' ], function ($, _, Backbone, Marionette, dust, dustHelpers, dustMarionette, ReplyableView, Navigator) { 'use strict'; var view = _.extend(ReplyableView, { template: 'content/comments/comment-template.dust', tagName: function () { return 'li id="comment-' + this.model.get('ID') + '" class="media comment"'; }, events: { 'click .b3-reply-comment': 'renderReplyBox', // from ReplyableView 'click .b3-comment-author': 'displayAuthor' }, initialize: function () { this.post = null; this.user = null; }, serializeData: function () { return this.model.toJSON(); }, parentId: function () { return this.model.get('ID'); }, displayAuthor: function (event) { var slug = $(event.currentTarget).attr('slug'); Navigator.navigateToAuthor(slug, null, true); event.preventDefault(); } }); var CommentView = Backbone.Marionette.ItemView.extend(view); return CommentView; });
Test functional error wrapping with ‘new’
const { OError, isOError, unwrapOError } = _private; describe('OError (white box test)', () => { it('is exported as O.Error', () => { expect(OError).toBe(O.Error); }); }); describe('isOError (white box test)', () => { it('returns true for wrapped functional errors (anything besides undefined)', () => { [null, 0, 1, '', 'foo', '0', [], {}, () => {}].forEach(value => { let error = OError(value); expect(isOError(error)).toBe(true); // Works also if created with ‘new’ error = new OError(value); expect(isOError(error)).toBe(true); }); }); it('returns false for everything else', () => { [undefined, null, {}, [], () => {}, 1, 0, Error(), new Error(), O, OError].forEach(other => { expect(isOError(other)).toBe(false); }); }); }); describe('unwrapOError (white box test)', () => { it('extracts the value of a functional error', () => { [null, 0, 1, '', 'foo', '0', [], {}, () => {}].forEach(value => { let error = OError(value); expect(unwrapOError(error)).toBe(value); // Works also if created with ‘new’ error = new OError(value); expect(unwrapOError(error)).toBe(value); }); }); });
const { OError, isOError, unwrapOError } = _private; describe('OError (white box test)', () => { it('is exported as O.Error', () => { expect(OError).toBe(O.Error); }); }); describe('isOError (white box test)', () => { it('returns true for wrapped functional errors (anything besides undefined)', () => { [null, 0, 1, '', 'foo', '0', [], {}, () => {}].forEach(value => { const error = OError(value); expect(isOError(error)).toBe(true); }); }); it('returns false for everything else', () => { [undefined, null, {}, [], () => {}, 1, 0, Error(), new Error(), O, OError].forEach(other => { expect(isOError(other)).toBe(false); }); }); }); describe('unwrapOError (white box test)', () => { it('extracts the value of a functional error', () => { [null, 0, 1, '', 'foo', '0', [], {}, () => {}].forEach(value => { const error = OError(value); expect(unwrapOError(error)).toBe(value); }); }); });
Remove UA code from example GA call.
<nav role="navigation" id="nav-main" class="nav-main js-nav-main"> <h2 class="is-hidden-visually">Menu</h2> <?php wp_nav_menu(array( 'container' => false, // remove nav container 'menu' => __( 'Hoofdmenu', 'stickyricetheme' ), // nav name 'menu_class' => 'nav-main__list', // adding custom nav class 'theme_location' => 'main-nav', // where it's located in the theme )); ?> <a href="#page-top" class="nav-main-toggle nav-main-toggle--close js-nav-main-hide">Terug naar boven</a> </nav> <footer role="contentinfo" class="contentinfo copy"> <p>&copy; Fat Pixel</p> </footer> <?php wp_footer(); ?> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-XXXXXXXXX-X', { 'anonymize_ip': true }); </script> </body> </html>
<nav role="navigation" id="nav-main" class="nav-main js-nav-main"> <h2 class="is-hidden-visually">Menu</h2> <?php wp_nav_menu(array( 'container' => false, // remove nav container 'menu' => __( 'Hoofdmenu', 'stickyricetheme' ), // nav name 'menu_class' => 'nav-main__list', // adding custom nav class 'theme_location' => 'main-nav', // where it's located in the theme )); ?> <a href="#page-top" class="nav-main-toggle nav-main-toggle--close js-nav-main-hide">Terug naar boven</a> </nav> <footer role="contentinfo" class="contentinfo copy"> <p>&copy; Fat Pixel</p> </footer> <?php wp_footer(); ?> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-141682345-9"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-XXXXXXXXX-X', { 'anonymize_ip': true }); </script> </body> </html>
Fix in link action. Remove the `_link` method and add action to `_delete`, this fix concurrency problems. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
import os from threading import Thread def _delete(path: str, src: str, link: bool): os.remove(path) if link: os.symlink(src, path) def manager_files(paths, link): # The first file is preserved to not delete all files in directories. first = True src = "" deleted_files = [] linked_files = [] errors = [] for path in paths: if os.path.isfile(path): if first: first = False src = path else: Thread(target=_delete, args=(path, src, link)).start() deleted_files.append(path) if link: linked_files.append(path) else: errors.append("Not identified by file: \"{}\"".format(path)) return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors} # Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect def manager(duplicates, create_link=False): if len(duplicates) == 0: return None processed_files = [] for files_by_hash in duplicates.values(): processed_files.append(manager_files(files_by_hash, create_link)) return processed_files def delete(duplicates): return manager(duplicates) def link(duplicates): return manager(duplicates, True)
import os from threading import Thread def _delete(path): os.remove(path) def _link(src, path): os.symlink(src, path) def manager_files(paths, link): # The first file is preserved to not delete all files in directories. first = True src = "" deleted_files = [] linked_files = [] errors = [] for path in paths: if os.path.isfile(path): if first: first = False src = path else: Thread(target=_delete, args=(path)).start() deleted_files.append(path) if link: Thread(target=_link, args=(src, path)).start() linked_files.append(path) else: errors.append("Not identified by file: \"{}\"".format(path)) return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors} # Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect def manager(duplicates, create_link=False): if len(duplicates) == 0: return None processed_files = [] for files_by_hash in duplicates.values(): processed_files.append(manager_files(files_by_hash, create_link)) return processed_files def delete(duplicates): return manager(duplicates) def link(duplicates): return manager(duplicates, True)
[Glitch] Fix not showing custom emojis in share page emoji picker Port e02a13f64e5c2c93fa73a67a4ce32a7d1df24760 to glitch-soc
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from 'flavours/glitch/store/configureStore'; import { hydrateStore } from 'flavours/glitch/actions/store'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from 'mastodon/locales'; import Compose from 'flavours/glitch/features/standalone/compose'; import initialState from 'flavours/glitch/util/initial_state'; import { fetchCustomEmojis } from 'flavours/glitch/actions/custom_emojis'; const { localeData, messages } = getLocale(); addLocaleData(localeData); const store = configureStore(); if (initialState) { store.dispatch(hydrateStore(initialState)); } store.dispatch(fetchCustomEmojis()); export default class TimelineContainer extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, }; render () { const { locale } = this.props; return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> <Compose /> </Provider> </IntlProvider> ); } }
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from 'flavours/glitch/store/configureStore'; import { hydrateStore } from 'flavours/glitch/actions/store'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from 'mastodon/locales'; import Compose from 'flavours/glitch/features/standalone/compose'; import initialState from 'flavours/glitch/util/initial_state'; const { localeData, messages } = getLocale(); addLocaleData(localeData); const store = configureStore(); if (initialState) { store.dispatch(hydrateStore(initialState)); } export default class TimelineContainer extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, }; render () { const { locale } = this.props; return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> <Compose /> </Provider> </IntlProvider> ); } }
Add a docstring for `test_rule_linenumber`
# Copyright (c) 2020 Albin Vass <albin.vass@gmail.com> # # 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 ansiblelint.rules.SudoRule import SudoRule TEST_TASKLIST = """ - debug: msg: test - command: echo test sudo: true """ def test_rule_linenumber(monkeypatch): """Check that SudoRule offense contains a line number.""" rule = SudoRule() matches = rule.matchyaml(dict(path="", type='tasklist'), TEST_TASKLIST) assert matches[0].linenumber == 5
# Copyright (c) 2020 Albin Vass <albin.vass@gmail.com> # # 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 ansiblelint.rules.SudoRule import SudoRule TEST_TASKLIST = """ - debug: msg: test - command: echo test sudo: true """ def test_rule_linenumber(monkeypatch): rule = SudoRule() matches = rule.matchyaml(dict(path="", type='tasklist'), TEST_TASKLIST) assert matches[0].linenumber == 5
Update method to get all Employee data
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Users_model extends CI_Model { public function get_users($email) { $this->db->where('Email', $email); return $this->db->get('MsEmployee')->result(); } public function get_users_by_emplid($emplid) { $this->db->where('EmployeeID', $emplid); return $this->db->get('MsEmployee')->result(); } public function get_users_session($email) { $this->db->where('Email', $email); $this->db->select('EmployeeID, Role, Email'); return $this->db->get('MsEmployee')->result()[0]; } } /* End of file Users_model.php */ /* Location: ./application/models/Users_model.php */
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Users_model extends CI_Model { public function get_users($email) { $this->db->where('Email', $email); return $this->db->get('MsEmployee')->result(); } public function get_users_by_emplid($emplid) { $this->db->where('EmployeeID', $emplid); $this->db->select('EmployeeID, FullName'); return $this->db->get('MsEmployee')->result(); } public function get_users_session($email) { $this->db->where('Email', $email); $this->db->select('EmployeeID, Role, Email'); return $this->db->get('MsEmployee')->result()[0]; } } /* End of file Users_model.php */ /* Location: ./application/models/Users_model.php */
Remove untested files from karma
// Karma configuration module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // testing frameworks to use frameworks: ['mocha', 'chai', 'sinon'], // list of files / patterns to load in the browser. order matters! files: [ // angular source 'client/lib/angular/angular.js', 'client/lib/angular-route/angular-route.js', 'client/lib/angular-mocks/angular-mocks.js', // our app code 'client/app/**/*.js', // our spec files - in order of the README 'specs/client/authControllerSpec.js', 'specs/client/routingSpec.js' ], // test results reporter to use reporters: ['nyan','unicorn'], // start these browsers. PhantomJS will load up in the background browsers: ['PhantomJS'], // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // if true, Karma exits after running the tests. singleRun: true }); };
// Karma configuration module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // testing frameworks to use frameworks: ['mocha', 'chai', 'sinon'], // list of files / patterns to load in the browser. order matters! files: [ // angular source 'client/lib/angular/angular.js', 'client/lib/angular-route/angular-route.js', 'client/lib/angular-mocks/angular-mocks.js', // our app code 'client/app/**/*.js', // our spec files - in order of the README 'specs/client/authControllerSpec.js', 'specs/client/servicesSpec.js', 'specs/client/linksControllerSpec.js', 'specs/client/shortenControllerSpec.js', 'specs/client/routingSpec.js' ], // test results reporter to use reporters: ['nyan','unicorn'], // start these browsers. PhantomJS will load up in the background browsers: ['PhantomJS'], // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // if true, Karma exits after running the tests. singleRun: true }); };
Normalize DOM from DOM or selector
export function regexEscape(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string } export function isDOM(obj) { if ("HTMLElement" in window) { return (obj && obj instanceof HTMLElement); } return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName); } export function fragmentFromString(strHTML) { return document.createRange().createContextualFragment(strHTML); } export function encodeHtml(input) { if (/[&"'<>]/i.test(input)) { return document.createElement('a').appendChild( document.createTextNode(input) ).parentNode.innerHTML; } return input; } export function hashCode(str) { let hash = 0; let i = 0; let chr; let len = str.length; for (i; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash } export function getElement(selectorOrNode) { if (isDOM(selectorOrNode)) { return selectorOrNode; } else { let element = document.querySelector(selectorOrNode); if (element) { return element; } } return null; } export default { regexEscape, isDOM, fragmentFromString, encodeHtml, hashCode, getElement };
export function regexEscape(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string } export function isDOM(obj) { if ("HTMLElement" in window) { return (obj && obj instanceof HTMLElement); } return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName); } export function fragmentFromString(strHTML) { return document.createRange().createContextualFragment(strHTML); } export function encodeHtml(input) { if (/[&"'<>]/i.test(input)) { return document.createElement('a').appendChild( document.createTextNode(input) ).parentNode.innerHTML; } return input; } export function hashCode(str) { let hash = 0; let i = 0; let chr; let len = str.length; for (i; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash } export default { regexEscape, isDOM, fragmentFromString, encodeHtml, hashCode };
Test Class Update: Change UIScope => VaadinUIScope
package org.vaadin.spring.mvp.explicit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.vaadin.spring.annotation.EnableVaadin; import org.vaadin.spring.annotation.VaadinUIScope; import org.vaadin.spring.events.EventBus; import org.vaadin.spring.mvp.FooView; @Configuration @EnableVaadin public class ExplicitConfig { @Autowired private EventBus eventBus; @Bean @VaadinUIScope public FooView fooView() { return new FooView(); } @Bean @VaadinUIScope public ExplicitPresenter fooPresenter() { return new ExplicitPresenter(fooView(), eventBus); } }
package org.vaadin.spring.mvp.explicit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.vaadin.spring.UIScope; import org.vaadin.spring.annotation.EnableVaadin; import org.vaadin.spring.events.EventBus; import org.vaadin.spring.mvp.FooView; @Configuration @EnableVaadin public class ExplicitConfig { @Autowired private EventBus eventBus; @Bean @UIScope public FooView fooView() { return new FooView(); } @Bean @UIScope public ExplicitPresenter fooPresenter() { return new ExplicitPresenter(fooView(), eventBus); } }
Fix to work on new strings database.
<?php error_reporting(E_ALL); ini_set("display_errors", 1); if(isset($_GET['param'])) { $db = new PDO('sqlite:strings.db'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->query("PRAGMA case_sensitive_like = ON"); $q = $db->prepare(" SELECT strings.str, strings.anim_id, strings.type, files.name AS filename, files.type AS filetype FROM strings,files WHERE strings.file_id = files.id AND strings.str LIKE ?"); $s = "%".$_GET['param']."%"; $q->bindValue(1, $s, PDO::PARAM_STR); $q->execute(); $result = $q->fetchAll(); print(json_encode($result)); die(); } print(json_encode(array())); ?>
<?php error_reporting(E_ALL); ini_set("display_errors", 1); if(isset($_GET['param'])) { $db = new PDO('sqlite:strings.db'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->query("PRAGMA case_sensitive_like = ON"); $q = $db->prepare(" SELECT strings.str, strings.anim_id, strings.type, files.name AS filename, files.type AS filetype FROM strings,files WHERE strings.file = files.id AND strings.str LIKE ?"); $s = "%".$_GET['param']."%"; $q->bindValue(1, $s, PDO::PARAM_STR); $q->execute(); $result = $q->fetchAll(); print(json_encode($result)); die(); } print(json_encode(array())); ?>
Fix URL of question link
"use strict"; var QAService = require("../services/QAService"); var notFound = require("../notFound"); module.exports = [{ method: "GET", path: "/{qaid}", handler: function hander(request, reply) { QAService.getQaidById(request.params.qaid, function getData(error, data) { if (error || !data || !data.questions) { return notFound(reply); } return reply({ questions: data.questions }); }); }, config: { plugins: { hal: { prepare: function prepare(rep, next) { rep.entity.questions.forEach(function addEachQaid(item) { var link; link = rep.link("hack:questions", "/" + rep.request.params.qaid + "/" + item._id); link.name = item.question; }); rep.ignore("questions"); next(); } } } } }, { method: "PUT", path: "/{qaid}", handler: function (request, reply) { reply("Create a QAID"); } }, { method: "POST", path: "/{qaid}", handler: function (request, reply) { reply("Add a question to this QAID"); } }];
"use strict"; var QAService = require("../services/QAService"); var notFound = require("../notFound"); module.exports = [{ method: "GET", path: "/{qaid}", handler: function hander(request, reply) { QAService.getQaidById(request.params.qaid, function getData(error, data) { if (error || !data || !data.questions) { return notFound(reply); } return reply({ questions: data.questions }); }); }, config: { plugins: { hal: { prepare: function prepare(rep, next) { rep.entity.questions.forEach(function addEachQaid(item) { var link; link = rep.link("hack:questions", "/" + item._id); link.name = item.question; }); rep.ignore("questions"); next(); } } } } }, { method: "PUT", path: "/{qaid}", handler: function (request, reply) { reply("Create a QAID"); } }, { method: "POST", path: "/{qaid}", handler: function (request, reply) { reply("Add a question to this QAID"); } }];
Fix path name for angular component
// Testacular configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'app/components/angular/angular.js', 'test/vendor/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ]; // list of files to exclude exclude = []; // test results reporter to use // possible values: dots || progress reporter = 'progress'; // web server port port = 8080; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari // - PhantomJS browsers = ['Chrome']; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
// Testacular configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'app/components/AngularJS/angular.js', 'test/vendor/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ]; // list of files to exclude exclude = []; // test results reporter to use // possible values: dots || progress reporter = 'progress'; // web server port port = 8080; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari // - PhantomJS browsers = ['Chrome']; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
Add peewee dependency for simpledb.
from setuptools import setup, find_packages setup( name='weaveserver', version='0.8', author='Srivatsan Iyer', author_email='supersaiyanmode.rox@gmail.com', packages=find_packages(), license='MIT', description='Library to interact with Weave Server', long_description=open('README.md').read(), install_requires=[ 'weavelib', 'eventlet!=0.22', 'bottle', 'GitPython', 'redis', 'sqlite3', 'appdirs', 'peewee', ], entry_points={ 'console_scripts': [ 'weave-launch = app:handle_launch', 'weave-main = app:handle_main' ] } )
from setuptools import setup, find_packages setup( name='weaveserver', version='0.8', author='Srivatsan Iyer', author_email='supersaiyanmode.rox@gmail.com', packages=find_packages(), license='MIT', description='Library to interact with Weave Server', long_description=open('README.md').read(), install_requires=[ 'weavelib', 'eventlet!=0.22', 'bottle', 'GitPython', 'redis', 'sqlite3' 'appdirs' ], entry_points={ 'console_scripts': [ 'weave-launch = app:handle_launch', 'weave-main = app:handle_main' ] } )
Update version of Wikidata dump to 20150126
#!/usr/bin/env python # -*- coding: utf-8 -*- import wikidata # The data (= ID) of the Wikidata dump dump_id = '20150126' # The files to download download_urls = [ "https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-terms.nt.gz" % dump_id, "https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-properties.nt.gz" % dump_id, "https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-simple-statements.nt.gz" % dump_id ] # Download and process the files for url in download_urls: filename = wikidata.download(url) filename = wikidata.english_please(filename) if 'properties' in filename: wikidata.simple_properties(filename)
#!/usr/bin/env python # -*- coding: utf-8 -*- import wikidata # The data (= ID) of the Wikidata dump dump_id = '20150105' # The files to download download_urls = [ "https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-terms.nt.gz" % dump_id, "https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-properties.nt.gz" % dump_id, "https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-simple-statements.nt.gz" % dump_id ] # Download and process the files for url in download_urls: filename = wikidata.download(url) filename = wikidata.english_please(filename) if 'properties' in filename: wikidata.simple_properties(filename)
Fix not loggin on empty routes
<?php /** * Part of the Tracker package. * * NOTICE OF LICENSE * * Licensed under the 3-clause BSD License. * * This source file is subject to the 3-clause BSD License that is * bundled with this package in the LICENSE file. It is also available at * the following URL: http://www.opensource.org/licenses/BSD-3-Clause * * @package Tracker * @version 1.0.0 * @author Antonio Carlos Ribeiro @ PragmaRX * @license BSD License (3-clause) * @copyright (c) 2013, PragmaRX * @link http://pragmarx.com */ namespace PragmaRX\Tracker\Data\Repositories; use PragmaRX\Tracker\Support\Config; class Route extends Repository { public function __construct($model, Config $config) { parent::__construct($model); $this->config = $config; } public function isTrackable($route) { $forbidden = $this->config->get('do_not_track_routes'); return ! $forbidden || ! $route->currentRouteName() || ! in_array_wildcard($route->currentRouteName(), $forbidden); } }
<?php /** * Part of the Tracker package. * * NOTICE OF LICENSE * * Licensed under the 3-clause BSD License. * * This source file is subject to the 3-clause BSD License that is * bundled with this package in the LICENSE file. It is also available at * the following URL: http://www.opensource.org/licenses/BSD-3-Clause * * @package Tracker * @version 1.0.0 * @author Antonio Carlos Ribeiro @ PragmaRX * @license BSD License (3-clause) * @copyright (c) 2013, PragmaRX * @link http://pragmarx.com */ namespace PragmaRX\Tracker\Data\Repositories; use PragmaRX\Tracker\Support\Config; class Route extends Repository { public function __construct($model, Config $config) { parent::__construct($model); $this->config = $config; } public function isTrackable($route) { $forbidden = $this->config->get('do_not_track_routes'); return $route->currentRouteName() && ! in_array_wildcard($route->currentRouteName(), $forbidden); } }
Return 0 if a shortname equals to "cu.l" "cu.l" can't be converted to double
package ca.etsmtl.applets.etsmobile.util; import java.util.Comparator; import ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCourse; /** * Created by Steven on 2016-01-14. */ public class CourseComparator implements Comparator<MoodleCourse> { @Override public int compare(MoodleCourse course1, MoodleCourse course2) { String shortname1 = course1.getShortname().substring(3,5) + "." + course1.getShortname().substring(5,6); String shortname2 = course2.getShortname().substring(3,5) + "." + course2.getShortname().substring(5,6); if (shortname1.equals("cu.l") || shortname2.equals("cu.l")) return 0; if (Double.valueOf(shortname1) > Double.valueOf(shortname2)) { return 1; } if (Double.valueOf(shortname1) < Double.valueOf(shortname2)) { return -1; } return 0; } }
package ca.etsmtl.applets.etsmobile.util; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.Comparator; import ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCourse; import ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCourses; import ca.etsmtl.applets.etsmobile.model.Seances; /** * Created by Steven on 2016-01-14. */ public class CourseComparator implements Comparator<MoodleCourse> { @Override public int compare(MoodleCourse course1, MoodleCourse course2) { String shortname1 = course1.getShortname().substring(3,5) + "." + course1.getShortname().substring(5,6); String shortname2 = course2.getShortname().substring(3,5) + "." + course2.getShortname().substring(5,6); if (Double.valueOf(shortname1) > Double.valueOf(shortname2)) { return 1; } if (Double.valueOf(shortname1) < Double.valueOf(shortname2)) { return -1; } return 0; } }
Remove @Component for optional encoder Instantiation is optional as to avoid introducing a hard dependency on spring-security.
package org.jasig.cas.authentication.handler; import javax.validation.constraints.NotNull; /** * Pass the encode/decode responsibility to a delegated Spring Security * password encoder. * * @author Joe McCall * @since 4.3 */ public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder { @NotNull private org.springframework.security.crypto.password.PasswordEncoder delegate; public void setDelegate(final org.springframework.security.crypto.password.PasswordEncoder delegate) { this.delegate = delegate; } @Override public String encode(final String password) { return delegate.encode(password); } @Override public boolean matches(final CharSequence rawPassword, final String encodedPassword) { return delegate.matches(rawPassword, encodedPassword); } }
package org.jasig.cas.authentication.handler; import org.springframework.stereotype.Component; import javax.validation.constraints.NotNull; /** * Pass the encode/decode responsibility to a delegated Spring Security * password encoder. * * @author Joe McCall * @since 4.3 */ @Component("springSecurityDelegatingPasswordEncoder") public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder { @NotNull private org.springframework.security.crypto.password.PasswordEncoder delegate; public void setDelegate(final org.springframework.security.crypto.password.PasswordEncoder delegate) { this.delegate = delegate; } @Override public String encode(final String password) { return delegate.encode(password); } @Override public boolean matches(final CharSequence rawPassword, final String encodedPassword) { return delegate.matches(rawPassword, encodedPassword); } }
Change the library export name.
const fs = require('fs'); const merge = require('webpack-merge'); const path = require('path'); const webpack = require('webpack'); const common = { entry: './src/index.js', output: { library: 'Wargamer', libraryTarget: 'umd', path: path.resolve(__dirname, 'dist'), umdNamedDefine: true, }, module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/, }, { test: /\.js$/, use: 'eslint-loader', exclude: /node_modules/, }, ], }, plugins: [ new webpack.BannerPlugin(fs.readFileSync('./LICENSE', 'utf8').trim()), ], devtool: 'source-map', }; const dev = { output: { filename: 'wargamer.js', }, }; const prod = { output: { filename: 'wargamer.min.js', }, plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: true }), ], }; module.exports = (env) => { const { target } = env; switch (target) { case 'prod': case 'production': return merge(common, prod); default: return merge(common, dev); } };
const fs = require('fs'); const merge = require('webpack-merge'); const path = require('path'); const webpack = require('webpack'); const common = { entry: './src/index.js', output: { library: 'wargamer', libraryTarget: 'umd', path: path.resolve(__dirname, 'dist'), umdNamedDefine: true, }, module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/, }, { test: /\.js$/, use: 'eslint-loader', exclude: /node_modules/, }, ], }, plugins: [ new webpack.BannerPlugin(fs.readFileSync('./LICENSE', 'utf8').trim()), ], devtool: 'source-map', }; const dev = { output: { filename: 'wargamer.js', }, }; const prod = { output: { filename: 'wargamer.min.js', }, plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: true }), ], }; module.exports = (env) => { const { target } = env; switch (target) { case 'prod': case 'production': return merge(common, prod); default: return merge(common, dev); } };
Change controller service to controller server in config.
package core.ipc; import core.languageHandler.Language; public enum IPCServiceName { CONTROLLER_SERVER(0, "controller_server"), PYTHON(1, Language.PYTHON.toString()), CSHARP(2, Language.CSHARP.toString()), SCALA(3, Language.SCALA.toString()), ; private final int index; private final String name; /** * @param index */ private IPCServiceName(final int index, final String name) { this.index = index; this.name = name; } protected int value() { return index; } protected static IPCServiceName identifyService(String name) { for (IPCServiceName service : IPCServiceName.values()) { if (name.equals(service.name)) { return service; } } return null; } @Override public String toString() { return name; } }
package core.ipc; import core.languageHandler.Language; public enum IPCServiceName { CONTROLLER_SERVER(0, "controller_service"), PYTHON(1, Language.PYTHON.toString()), CSHARP(2, Language.CSHARP.toString()), SCALA(3, Language.SCALA.toString()), ; private final int index; private final String name; /** * @param index */ private IPCServiceName(final int index, final String name) { this.index = index; this.name = name; } protected int value() { return index; } protected static IPCServiceName identifyService(String name) { for (IPCServiceName service : IPCServiceName.values()) { if (name.equals(service.name)) { return service; } } return null; } @Override public String toString() { return name; } }
Use topk in the click model
from math import exp class ClickModel(object): ''' Simple Position-biased Model: P(C_r=1) = P(A_r=1|E_r=1)P(E_r=1), where C_r is click on the r-th document, A_r is being attracted by the r-th document, and E_r is examination of the r-th document. In this simple model, the examination probability is defined as P(E_r=1) = exp(- r / sigma). Therefore, P(A_r=1|E_r=1) = P(C_r=1) / P(E_r=1). ''' @classmethod def estimate(cls, ctrs, sigma=10.0, topk=10): result = {} for ctr in ctrs: if ctr.rank <= topk: eprob = cls._eprob(ctr.rank, sigma) aprob = min([1.0, ctr.ctr / eprob]) result[(ctr.query_id, ctr.question_id)] = aprob return result @classmethod def _eprob(cls, rank, sigma): return exp(- float(rank) / sigma)
from math import exp class ClickModel(object): ''' Simple Position-biased Model: P(C_r=1) = P(A_r=1|E_r=1)P(E_r=1), where C_r is click on the r-th document, A_r is being attracted by the r-th document, and E_r is examination of the r-th document. In this simple model, the examination probability is defined as P(E_r=1) = exp(- r / sigma). Therefore, P(A_r=1|E_r=1) = P(C_r=1) / P(E_r=1). ''' @classmethod def estimate(cls, ctrs, sigma=10.0, topk=10): result = {} for ctr in ctrs: eprob = cls._eprob(ctr.rank, sigma) aprob = min([1.0, ctr.ctr / eprob]) result[(ctr.query_id, ctr.question_id)] = aprob return result @classmethod def _eprob(cls, rank, sigma): return exp(- float(rank) / sigma)
Migrate ScrollView fake type to ReactNative.NativeComponent Reviewed By: yungsters Differential Revision: D7985122 fbshipit-source-id: b78fc6ad84485e8aa42657c2b21d70c9f3a271d6
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ const ReactNative = require('ReactNative'); // This class is purely a facsimile of ScrollView so that we can // properly type it with Flow before migrating ScrollView off of // createReactClass. If there are things missing here that are in // ScrollView, that is unintentional. class InternalScrollViewType<Props> extends ReactNative.NativeComponent<Props> { scrollTo( y?: number | {x?: number, y?: number, animated?: boolean}, x?: number, animated?: boolean, ) {} flashScrollIndicators() {} scrollToEnd(options?: {animated?: boolean}) {} scrollWithoutAnimationTo(y: number = 0, x: number = 0) {} getScrollResponder(): any {} getScrollableNode(): any {} getInnerViewNode(): any {} scrollResponderScrollNativeHandleToKeyboard( nodeHandle: any, additionalOffset?: number, preventNegativeScrollOffset?: boolean, ) {} scrollResponderScrollTo( x?: number | {x?: number, y?: number, animated?: boolean}, y?: number, animated?: boolean, ) {} } module.exports = InternalScrollViewType;
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ const React = require('React'); // This class is purely a facsimile of ScrollView so that we can // properly type it with Flow before migrating ScrollView off of // createReactClass. If there are things missing here that are in // ScrollView, that is unintentional. class InternalScrollViewType<Props> extends React.Component<Props> { scrollTo( y?: number | {x?: number, y?: number, animated?: boolean}, x?: number, animated?: boolean, ) {} flashScrollIndicators() {} scrollToEnd(options?: {animated?: boolean}) {} scrollWithoutAnimationTo(y: number = 0, x: number = 0) {} setNativeProps(props: Object) {} getScrollResponder(): any {} getScrollableNode(): any {} getInnerViewNode(): any {} scrollResponderScrollNativeHandleToKeyboard( nodeHandle: any, additionalOffset?: number, preventNegativeScrollOffset?: boolean, ) {} scrollResponderScrollTo( x?: number | {x?: number, y?: number, animated?: boolean}, y?: number, animated?: boolean, ) {} } module.exports = InternalScrollViewType;
Change upload path for images
from django.contrib.gis.db import models import os from phonenumber_field.modelfields import PhoneNumberField class Image(models.Model): """ The Image model holds an image and related data. The Created and Modified time fields are created automatically by Django when the object is created or modified, and can not be altered. This model uses Django's built-ins for holding the image location and data in the database, as well as for keeping created and modified timestamps. """ image = models.ImageField(upload_to='/') caption = models.TextField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Vendor(models.Model): """ The Vendor model holds the information for a vendor, including the geographic location as a pair of latitudinal/logitudinal coordinates, a street address, and an optional text description of their location (in case the address/coordinates are of, say, a dock instead of a shop). """ pass
from django.contrib.gis.db import models import os from phonenumber_field.modelfields import PhoneNumberField class Image(models.Model): """ The Image model holds an image and related data. The Created and Modified time fields are created automatically by Django when the object is created or modified, and can not be altered. This model uses Django's built-ins for holding the image location and data in the database, as well as for keeping created and modified timestamps. """ image = models.ImageField(upload_to='%Y/%m/%d') caption = models.TextField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Vendor(models.Model): """ The Vendor model holds the information for a vendor, including the geographic location as a pair of latitudinal/logitudinal coordinates, a street address, and an optional text description of their location (in case the address/coordinates are of, say, a dock instead of a shop). """ pass
Swap the order for my most favorite languages
var express = require('express'); var router = express.Router(); // GET home page router.get('/', function(req, res) { res.render('index', { meta: { title: 'Rollie Ma - Polyglot Developer from Vancouver, BC', description: 'Hi, I\'m Rollie Ma. A Linux lover and LEGO bricks enthusiast. ' + 'A polyglot developer obsessed with Golang, JavaScript, Python and PHP. ' + 'A receptive learner captivated by mobile development, NoSQL and data mining. ' + 'An amateur explorer interested in information aggregation and artificial intelligence fields.', url: 'http://rolli3.net', image: 'http://rolli3.net/images/logos/logo-120x120.png' } }); }); // GET about|projects|resume pages router.get('*', function(req, res) { res.redirect(req.url.replace(/^\/?/, '/#')); }); module.exports = router;
var express = require('express'); var router = express.Router(); // GET home page router.get('/', function(req, res) { res.render('index', { meta: { title: 'Rollie Ma - Polyglot Developer from Vancouver, BC', description: 'Hi, I\'m Rollie Ma. A Linux lover and LEGO bricks enthusiast. ' + 'A polyglot developer obsessed with PHP, Golang, Python and JavaScript. ' + 'A receptive learner captivated by mobile development, NoSQL and data mining. ' + 'An amateur explorer interested in information aggregation and artificial intelligence fields.', url: 'http://rolli3.net', image: 'http://rolli3.net/images/logos/logo-120x120.png' } }); }); // GET about|projects|resume pages router.get('*', function(req, res) { res.redirect(req.url.replace(/^\/?/, '/#')); }); module.exports = router;
[validation] Use exceptions to get the error message.
package edu.kit.iti.formal.pse.worthwhile.validation; import org.antlr.runtime.EarlyExitException; import org.eclipse.xtext.nodemodel.SyntaxErrorMessage; import org.eclipse.xtext.parser.antlr.SyntaxErrorMessageProvider; /** * This class provides the correct syntax error messages. * * @author matthias * */ public class WorthwhileSyntaxErrorMessageProvider extends SyntaxErrorMessageProvider { /** * Error code for "No newline at end of file". */ public static final String NO_NEWLINE_AT_EOF = "NoNewlineAtEOF"; /** * Error code for "No return type specified for function". */ public static final String NO_FUNCTION_RETURN_TYPE = "NoFunctionReturnType"; /** * Returns a syntax error messages for the context. * * @param context * the context from which you want the error message * * @return the syntax error message */ @Override public final SyntaxErrorMessage getSyntaxErrorMessage(final IParserErrorContext context) { if (context.getRecognitionException() instanceof EarlyExitException) { if (context.getCurrentNode().getRootNode().getTotalEndLine() == context.getCurrentNode() .getEndLine()) { return new SyntaxErrorMessage("Newline is missing", NO_NEWLINE_AT_EOF); } else { return new SyntaxErrorMessage("Delete this token.", "deleteToken"); } } return super.getSyntaxErrorMessage(context); } }
package edu.kit.iti.formal.pse.worthwhile.validation; import org.eclipse.xtext.nodemodel.SyntaxErrorMessage; import org.eclipse.xtext.parser.antlr.SyntaxErrorMessageProvider; /** * This class provides the correct syntax error messages. * * @author matthias * */ public class WorthwhileSyntaxErrorMessageProvider extends SyntaxErrorMessageProvider { /** * Error code for "No newline at end of file". */ public static final String NO_NEWLINE_AT_EOF = "NoNewlineAtEOF"; /** * Error code for "No return type specified for function" */ public static final String NO_FUNCTION_RETURN_TYPE = "NoFunctionReturnType"; /** * Returns improved syntax error messages. TODO find a better way to get improved messages * * @param context * the context from which you want the error message * * @return the syntax error message */ @Override public final SyntaxErrorMessage getSyntaxErrorMessage(final IParserErrorContext context) { System.out.println(context.getDefaultMessage()); if (context.getDefaultMessage().contains("loop did not match anything at input '<EOF>'")) { return new SyntaxErrorMessage("Newline is missing", NO_NEWLINE_AT_EOF); } else if (context.getDefaultMessage().contains("loop did not match anything") || context.getDefaultMessage().contains("missing EOF")) { return new SyntaxErrorMessage("Delete this token.", "deleteToken"); } return super.getSyntaxErrorMessage(context); } }
Sort movies list by released year
import React from 'react'; import PropTypes from 'prop-types'; import { browserHistory } from 'react-router'; import { ListGroup, ListGroupItem, Alert } from 'react-bootstrap'; import { Meteor } from 'meteor/meteor'; import Documents from '../../api/documents/documents'; import container from '../../modules/container'; const handleNav = _id => browserHistory.push(`/documents/${_id}`); const DocumentsList = ({ documents }) => ( documents.length > 0 ? <ListGroup className="DocumentsList"> {documents.map(({ _id, title, released, rating }) => ( <ListGroupItem key={ _id } onClick={ () => handleNav(_id) }> { title } { released } [{ rating }] </ListGroupItem> ))} </ListGroup> : <Alert bsStyle="warning">No documents yet.</Alert> ); DocumentsList.propTypes = { documents: PropTypes.array, }; export default container((props, onData) => { const subscription = Meteor.subscribe('documents.list'); if (subscription.ready()) { const documents = Documents.find({},{sort:{released:-1}}).fetch(); onData(null, { documents }); } }, DocumentsList);
import React from 'react'; import PropTypes from 'prop-types'; import { browserHistory } from 'react-router'; import { ListGroup, ListGroupItem, Alert } from 'react-bootstrap'; import { Meteor } from 'meteor/meteor'; import Documents from '../../api/documents/documents'; import container from '../../modules/container'; const handleNav = _id => browserHistory.push(`/documents/${_id}`); const DocumentsList = ({ documents }) => ( documents.length > 0 ? <ListGroup className="DocumentsList"> {documents.map(({ _id, title, released, rating }) => ( <ListGroupItem key={ _id } onClick={ () => handleNav(_id) }> { title } { released } [{ rating }] </ListGroupItem> ))} </ListGroup> : <Alert bsStyle="warning">No documents yet.</Alert> ); DocumentsList.propTypes = { documents: PropTypes.array, }; export default container((props, onData) => { const subscription = Meteor.subscribe('documents.list'); if (subscription.ready()) { const documents = Documents.find().fetch(); onData(null, { documents }); } }, DocumentsList);
Add an ID to join component
const Join = () => { return ( <div id="join" className="component"> <h1>Bli med i linjeforeningen!</h1> <p>Alle informatikere er med i linjeforeningen. Gå videre til <a href="https://online.ntnu.no/">hovedsiden</a> for å lage din brukerkonto på Online sine systemer.</p> <p>Har du lyst til å gjøre studietiden til informatikere enda bedre? Som komitemedlem i Online blir du del av en familie du aldri vil glemme. Vi tilbyr utfordrende og spennende verv i et meget sosialt miljø med stor takhøyde.</p> <p>Les mer om de ulike komiteene, linjeforeningen og mye mer på <a href="https://online.ntnu.no/#!about" target="_blank">nettsidene våre</a>.</p> </div> ); }; export default Join;
const Join = () => { return ( <div className="component"> <h1>Bli med i linjeforeningen!</h1> <p>Alle informatikere er med i linjeforeningen. Gå videre til <a href="https://online.ntnu.no/">hovedsiden</a> for å lage din brukerkonto på Online sine systemer.</p> <p>Har du lyst til å gjøre studietiden til informatikere enda bedre? Som komitemedlem i Online blir du del av en familie du aldri vil glemme. Vi tilbyr utfordrende og spennende verv i et meget sosialt miljø med stor takhøyde.</p> <p>Les mer om de ulike komiteene, linjeforeningen og mye mer på <a href="https://online.ntnu.no/#!about" target="_blank">nettsidene våre</a>.</p> </div> ); }; export default Join;
Change for fixing session ID fixation problem.
package gov.nih.nci.nbia.beans.basket; import gov.nih.nci.nbia.zip.ZipManager; import com.icesoft.faces.async.render.SessionRenderer; /** * This listens to zip progress and tell ICEfaces to push a change * to the UI as progress increases. * * <p>This object is a result of switching to ICEfaces which * broke the old ajax progress bar. */ public class ZipManagerProgressManager implements ZipManager.ZipManagerListener { public ZipManagerProgressManager(/*BasketBean basketBean*/) { //this.basketBean = basketBean; } public void progressUpdate() { // Increase the finished percent, and render the page SessionRenderer.render(ALL); } public void completed() { //let ui set this //basketBean.setDownloading(false); System.out.println("completed zipping!!!"); SessionRenderer.render(ALL); } private static final String ALL = "all"; }
package gov.nih.nci.nbia.beans.basket; import gov.nih.nci.nbia.zip.ZipManager; import com.icesoft.faces.async.render.SessionRenderer; /** * This listens to zip progress and tell ICEfaces to push a change * to the UI as progress increases. * * <p>This object is a result of switching to ICEfaces which * broke the old ajax progress bar. */ public class ZipManagerProgressManager implements ZipManager.ZipManagerListener { public ZipManagerProgressManager(/*BasketBean basketBean*/) { //this.basketBean = basketBean; } public void progressUpdate() { // Increase the finished percent, and render the page SessionRenderer.render(ALL); } public void completed() { //let ui set this //basketBean.setDownloading(false); System.out.println("completed zipping!!!"); SessionRenderer.render(ALL); } private static final String ALL = "all"; }
Change d to v, add verbose alias
#!/usr/bin/env node const yargs = require('yargs'); // ./modules const rocketLaunch = require('./modules/rocketLaunch'); const info = require('./modules/info'); const settings = require('./modules/settings'); const argv = yargs // eslint-disable-line .usage('Usage: space <command> [options]') .demandCommand(1) .command('about', 'Info about the CLI', info.about) .command('next', 'Get next rocket launch', function (yargs) { return yargs .option('v', { alias: ['verbose', 'details'], describe: 'Details about the next launch' }).option('tz', { alias: 'timezone', describe: 'Define time zone for time info e.g. America/New_York, Europe/Paris, Asia/Shanghai' }).option('lt', { alias: 'limit', describe: 'Define amount of upcoming events to show' }); }, rocketLaunch.nextLaunch ) .command('settings', 'Set default settings', function (yargs) { return yargs.option('tz', { alias: 'timezone', describe: 'Define default time zone for time info e.g. America/New_York, Europe/Paris, Asia/Shanghai' }); }, settings.update ) .help('h') .alias('h', 'help') .argv;
#!/usr/bin/env node const yargs = require('yargs'); // ./modules const rocketLaunch = require('./modules/rocketLaunch'); const info = require('./modules/info'); const settings = require('./modules/settings'); const argv = yargs // eslint-disable-line .usage('Usage: space <command> [options]') .demandCommand(1) .command('about', 'Info about the CLI', info.about) .command('next', 'Get next rocket launch', function (yargs) { return yargs.option('d', { alias: 'details', describe: 'Details about the next launch' }).option('tz', { alias: 'timezone', describe: 'Define time zone for time info e.g. America/New_York, Europe/Paris, Asia/Shanghai' }).option('lt', { alias: 'limit', describe: 'Define amount of upcoming events to show' }); }, rocketLaunch.nextLaunch ) .command('settings', 'Set default settings', function (yargs) { return yargs.option('tz', { alias: 'timezone', describe: 'Define default time zone for time info e.g. America/New_York, Europe/Paris, Asia/Shanghai' }); }, settings.update ) .help('h') .alias('h', 'help') .argv;
Make pytest-runner and sphinx optionlly required.
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io import sys import setuptools with io.open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() needs_pytest = {'pytest', 'test'}.intersection(sys.argv) pytest_runner = ['pytest_runner'] if needs_pytest else [] needs_sphinx = {'release', 'build_sphinx', 'upload_docs'}.intersection(sys.argv) sphinx = ['sphinx'] if needs_sphinx else [] setup_params = dict( name='jaraco.functools', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="jaraco.functools", long_description=long_description, url="https://bitbucket.org/jaraco/jaraco.functools", packages=setuptools.find_packages(), namespace_packages=['jaraco'], setup_requires=[ 'hgtools', ] + pytest_runner + sphinx, tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io import setuptools with io.open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() setup_params = dict( name='jaraco.functools', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="jaraco.functools", long_description=long_description, url="https://bitbucket.org/jaraco/jaraco.functools", packages=setuptools.find_packages(), namespace_packages=['jaraco'], setup_requires=[ 'hgtools', 'pytest-runner', 'sphinx', ], tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
Remove hard code of date while testing
import ATV from 'atvjs'; import template from './template.hbs'; let Page = ATV.Page.create({ name: 'list-games', template: template, ready(options, resolve, reject) { ATV.Navigation.showLoading("Loading Games…"); let heheGames = 'http://hehestreams.xyz/api/v1/nba/games'; ATV .Ajax .get(heheGames, {headers : ATV.Settings.get("header")}) .then((xhr) => { let response = xhr.response; resolve({ data: response }); }, (xhr) => { let response = xhr.response; reject({ status: xhr.status, message: response.message }); }); }, events: { select: 'onSelect' }, onSelect(e) { let element = e.target; let uuid = element.getAttribute('data-uuid'); let title = element.getAttribute('data-title'); if (uuid) { ATV.Navigation.navigate('select-stream', {uuid : uuid, title: title}); } } }); export default Page;
import ATV from 'atvjs'; import template from './template.hbs'; let Page = ATV.Page.create({ name: 'list-games', template: template, ready(options, resolve, reject) { ATV.Navigation.showLoading("Loading Games…"); let heheGames = 'http://hehestreams.xyz/api/v1/nba/games?date=2016-11-05'; ATV .Ajax .get(heheGames, {headers : ATV.Settings.get("header")}) .then((xhr) => { let response = xhr.response; resolve({ data: response }); }, (xhr) => { let response = xhr.response; reject({ status: xhr.status, message: response.message }); }); }, events: { select: 'onSelect' }, onSelect(e) { let element = e.target; let uuid = element.getAttribute('data-uuid'); let title = element.getAttribute('data-title'); if (uuid) { ATV.Navigation.navigate('select-stream', {uuid : uuid, title: title}); } } }); export default Page;
Fix creation of BOM when create Variant
# -*- coding: utf-8 -*- from odoo import models, api class ProductTemplate(models.Model): _inherit = 'product.template' @api.multi def create_get_variant(self, value_ids, custom_values=None): """Add bill of matrials to the configured variant.""" if custom_values is None: custom_values = {} variant = super(ProductTemplate, self).create_get_variant( value_ids, custom_values=custom_values ) attr_products = variant.attribute_value_ids.mapped('product_id') line_vals = [ (0, 0, {'product_id': product.id}) for product in attr_products ] values = { 'product_tmpl_id': self.id, 'product_id': variant.id, 'bom_line_ids': line_vals } self.env['mrp.bom'].create(values) return variant
# -*- coding: utf-8 -*- from odoo import models, api class ProductTemplate(models.Model): _inherit = 'product.template' @api.multi def create_variant(self, value_ids, custom_values=None): """Add bill of matrials to the configured variant.""" if custom_values is None: custom_values = {} variant = super(ProductTemplate, self).create_variant( value_ids, custom_values=custom_values ) attr_products = variant.attribute_value_ids.mapped('product_id') line_vals = [ (0, 0, {'product_id': product.id}) for product in attr_products ] values = { 'product_tmpl_id': self.id, 'product_id': variant.id, 'bom_line_ids': line_vals } self.env['mrp.bom'].create(values) return variant
Return the result of defineProperty
const FIRST_ROW = 0; const FIRST_COL = 0; const CHAR_CODE_OFFSET = 65; const LABEL_OFFSET = 1; const calculateLabel = function calculateLabel(row, col) { const rowLabel = String.fromCharCode(CHAR_CODE_OFFSET + row); const colLabel = col + LABEL_OFFSET; return colLabel + rowLabel; }; const constAttr = function constAttr(obj, attr, value) { return Reflect.defineProperty(obj, attr, { value, writable: false, enumerable: true }); }; // Tile factory // // Takes 0-indexed row and col values const createTile = function createTile(row = FIRST_ROW, col = FIRST_COL) { const label = calculateLabel(row, col); const tile = {}; constAttr(tile, 'row', row); constAttr(tile, 'col', col); constAttr(tile, 'label', label); return tile; }; export default createTile;
const FIRST_ROW = 0; const FIRST_COL = 0; const CHAR_CODE_OFFSET = 65; const LABEL_OFFSET = 1; const calculateLabel = function calculateLabel(row, col) { const rowLabel = String.fromCharCode(CHAR_CODE_OFFSET + row); const colLabel = col + LABEL_OFFSET; return colLabel + rowLabel; }; const constAttr = function constAttr(obj, attr, value) { Reflect.defineProperty(obj, attr, { value, writable: false, enumerable: true }); }; // Tile factory // // Takes 0-indexed row and col values const createTile = function createTile(row = FIRST_ROW, col = FIRST_COL) { const label = calculateLabel(row, col); const tile = {}; constAttr(tile, 'row', row); constAttr(tile, 'col', col); constAttr(tile, 'label', label); return tile; }; export default createTile;
Read in README.md as long description
# Copyright 2019 The resource-policy-evaluation-library 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. from __future__ import print_function from setuptools import setup setup( name="rpe-lib", description="A resource policy evaluation library", long_description=open('README.md').read(), author="Joe Ceresini", url="https://github.com/forseti-security/resource-policy-evaluation-library", use_scm_version=True, setup_requires=['setuptools_scm'], install_requires=[ 'google-api-python-client', 'google-api-python-client-helpers', 'tenacity', ], packages=[ 'rpe', 'rpe.engines', 'rpe.resources', ], package_data={}, license="Apache 2.0", keywords="gcp policy enforcement", )
# Copyright 2019 The resource-policy-evaluation-library 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. from __future__ import print_function from setuptools import setup setup( name="rpe-lib", description="A resource policy evaluation library", author="Joe Ceresini", url="https://github.com/forseti-security/resource-policy-evaluation-library", use_scm_version=True, setup_requires=['setuptools_scm'], install_requires=[ 'google-api-python-client', 'google-api-python-client-helpers', 'tenacity', ], packages=[ 'rpe', 'rpe.engines', 'rpe.resources', ], package_data={}, license="Apache 2.0", keywords="gcp policy enforcement", )
Use dash to be compliant with XXX-devel pattern.
from __future__ import print_function import subprocess def get_version_from_git(): cmd = ["git", "describe", "--tags", "--long", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, since, gsha = version.split("-") status = "" except ValueError: vers, status, since, gsha = version.split("-") return vers, status, since, gsha vers, status, since, gsha = get_version_from_git() if status == "": print("No X.X.X-devel[rc] tag.") else: print(vers + "-" + status + "-"+ gsha[1:])
from __future__ import print_function import subprocess def get_version_from_git(): cmd = ["git", "describe", "--tags", "--long", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, since, gsha = version.split("-") status = "" except ValueError: vers, status, since, gsha = version.split("-") return vers, status, since, gsha vers, status, since, gsha = get_version_from_git() if status == "": print("No X.X.X-devel[rc] tag.") else: print(vers + "." + status + "."+ gsha[1:])
Move the privacy config portlet to the Configuration section
package it.smc.liferay.privacy.web.application.list; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import com.liferay.application.list.BasePanelApp; import com.liferay.application.list.PanelApp; import com.liferay.application.list.constants.PanelCategoryKeys; import com.liferay.portal.kernel.model.Portlet; import it.smc.liferay.privacy.web.util.PrivacyPortletKeys; @Component( immediate = true, property = { "panel.app.order:Integer=300", "panel.category.key=" + PanelCategoryKeys.SITE_ADMINISTRATION_CONFIGURATION }, service = PanelApp.class ) public class PrivacyPanelApp extends BasePanelApp { @Override public String getPortletId() { return PrivacyPortletKeys.PRIVACY_ADMIN; } @Override @Reference( target = "(javax.portlet.name=" + PrivacyPortletKeys.PRIVACY_ADMIN + ")", unbind = "-" ) public void setPortlet(Portlet portlet) { super.setPortlet(portlet); } }
package it.smc.liferay.privacy.web.application.list; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import com.liferay.application.list.BasePanelApp; import com.liferay.application.list.PanelApp; import com.liferay.application.list.constants.PanelCategoryKeys; import com.liferay.portal.kernel.model.Portlet; import it.smc.liferay.privacy.web.util.PrivacyPortletKeys; @Component( immediate = true, property = { "panel.app.order:Integer=300", "panel.category.key=" + PanelCategoryKeys.SITE_ADMINISTRATION_CONTENT }, service = PanelApp.class ) public class PrivacyPanelApp extends BasePanelApp { @Override public String getPortletId() { return PrivacyPortletKeys.PRIVACY_ADMIN; } @Override @Reference( target = "(javax.portlet.name=" + PrivacyPortletKeys.PRIVACY_ADMIN + ")", unbind = "-" ) public void setPortlet(Portlet portlet) { super.setPortlet(portlet); } }
Correct type comment for table columns
"""Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % self.id, self.title
"""Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : db.Column Autogenerated primary key title : db.Column body : db.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % self.id, self.title
Fix URL patterns for ManufacturerPart and SupplierPart
""" URL lookup for Company app """ from django.conf.urls import url, include from . import views company_detail_urls = [ url(r'^thumb-download/', views.CompanyImageDownloadFromURL.as_view(), name='company-image-download'), # Any other URL url(r'^.*$', views.CompanyDetail.as_view(), name='company-detail'), ] company_urls = [ url(r'^(?P<pk>\d+)/', include(company_detail_urls)), url(r'suppliers/', views.CompanyIndex.as_view(), name='supplier-index'), url(r'manufacturers/', views.CompanyIndex.as_view(), name='manufacturer-index'), url(r'customers/', views.CompanyIndex.as_view(), name='customer-index'), # Redirect any other patterns to the 'company' index which displays all companies url(r'^.*$', views.CompanyIndex.as_view(), name='company-index'), ] manufacturer_part_urls = [ url(r'^(?P<pk>\d+)/', views.ManufacturerPartDetail.as_view(template_name='company/manufacturer_part.html'), name='manufacturer-part-detail'), ] supplier_part_urls = [ url(r'^(?P<pk>\d+)/', views.SupplierPartDetail.as_view(template_name='company/supplier_part.html'), name='supplier-part-detail'), ]
""" URL lookup for Company app """ from django.conf.urls import url, include from . import views company_detail_urls = [ url(r'^thumb-download/', views.CompanyImageDownloadFromURL.as_view(), name='company-image-download'), # Any other URL url(r'^.*$', views.CompanyDetail.as_view(), name='company-detail'), ] company_urls = [ url(r'^(?P<pk>\d+)/', include(company_detail_urls)), url(r'suppliers/', views.CompanyIndex.as_view(), name='supplier-index'), url(r'manufacturers/', views.CompanyIndex.as_view(), name='manufacturer-index'), url(r'customers/', views.CompanyIndex.as_view(), name='customer-index'), # Redirect any other patterns to the 'company' index which displays all companies url(r'^.*$', views.CompanyIndex.as_view(), name='company-index'), ] manufacturer_part_urls = [ url(r'^(?P<pk>\d+)/', include([ url('^.*$', views.ManufacturerPartDetail.as_view(template_name='company/manufacturer_part.html'), name='manufacturer-part-detail'), ])), ] supplier_part_urls = [ url('^.*$', views.SupplierPartDetail.as_view(template_name='company/supplier_part.html'), name='supplier-part-detail'), ]
Copy gtml file to dist directory
module.exports = { all: { files: [ { expand: true, src: ['config.json'], dest: 'dist' }, { expand: true, src: ['javascript.json'], dest: 'dist' }, { expand: true, cwd: 'src/config/', src: ['**'], dest: 'dist/config/' }, { expand: true, cwd: 'src/images/', src: ['**'], dest: 'dist/images/', }, { expand: true, cwd: 'src/flash/', src: ['**'], dest: 'dist/flash/' }, { expand: true, cwd: 'src/templates/', src: ['**'], dest: 'dist/templates/' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: 'dist/css/images' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: 'dist/css/' }, { expand: true, cwd: 'src/javascript/', src: ['**'], dest: 'dist/dev/src/javascript/' }, { expand: true, cwd: 'src/javascript/gtm/', src: ['experimental.js'], dest: 'dist/js/gtm/' } ] } };
module.exports = { all: { files: [ { expand: true, src: ['config.json'], dest: 'dist' }, { expand: true, src: ['javascript.json'], dest: 'dist' }, { expand: true, cwd: 'src/config/', src: ['**'], dest: 'dist/config/' }, { expand: true, cwd: 'src/images/', src: ['**'], dest: 'dist/images/', }, { expand: true, cwd: 'src/flash/', src: ['**'], dest: 'dist/flash/' }, { expand: true, cwd: 'src/templates/', src: ['**'], dest: 'dist/templates/' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: 'dist/css/images' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: 'dist/css/' }, { expand: true, cwd: 'src/javascript/', src: ['**'], dest: 'dist/dev/src/javascript/' } ] } };
Fix phapp update commant to build regardless from environment mode, as documented since 0.6.0-beta2.
<?php namespace drunomics\Phapp\Commands; use drunomics\Phapp\PhappCommandBase; use drunomics\Phapp\ServiceUtil\BuildCommandsTrait; /** * Updates the app. */ class UpdateCommands extends PhappCommandBase { use BuildCommandsTrait; /** * Updates the app. * * @option bool $build Build before running an update. * * @command update */ public function update(array $options = ['build' => TRUE]) { $collection = $this->collectionBuilder(); $collection->setProgressIndicator(NULL); if ($options['build']) { $collection->addCode(function() { $this->io()->title('Building...'); }); $collection->addTask( $this->getBuildCommands()->build(['clean' => FALSE]) ); $collection->addCode(function() { $this->io()->title('Updating...'); }); } $collection->addTask( $this->invokeManifestCommand('update') ); return $collection; } }
<?php namespace drunomics\Phapp\Commands; use drunomics\Phapp\PhappCommandBase; use drunomics\Phapp\ServiceUtil\BuildCommandsTrait; /** * Updates the app. */ class UpdateCommands extends PhappCommandBase { use BuildCommandsTrait; /** * Updates the app. * * @option bool $build Build before running an update. * * @command update */ public function update(array $options = ['build' => TRUE]) { $collection = $this->collectionBuilder(); $collection->setProgressIndicator(NULL); if (getenv('PHAPP_ENV_MODE') == 'development' && $options['build']) { $collection->addCode(function() { $this->io()->title('Building...'); }); $collection->addTask( $this->getBuildCommands()->build(['clean' => FALSE]) ); $collection->addCode(function() { $this->io()->title('Updating...'); }); } $collection->addTask( $this->invokeManifestCommand('update') ); return $collection; } }
Remove Mutation mock, which breaks in node 6.11.1
const Relay = jest.genMockFromModule('react-relay'); class MockStore { reset() { this.successResponse = undefined; } succeedWith(response) { this.reset(); this.successResponse = response; } failWith(response) { this.reset(); this.failureResponse = response; } update(callbacks) { if (this.successResponse) { callbacks.onSuccess(this.successResponse); } else if (this.failureResponse) { callbacks.onFailure(this.failureResponse); } this.reset(); } commitUpdate(mutation, callbacks) { return this.update(callbacks); } applyUpdate(mutation, callbacks) { return this.update(callbacks); } } module.exports = { QL: Relay.QL, Mutation: Relay.Mutation, Route: Relay.Route, RootContainer: () => null, createContainer: (component) => component, Store: new MockStore(), };
const Relay = jest.genMockFromModule('react-relay'); class Mutation extends Relay.Mutation { _resolveProps(props) { this.props = props; } } class MockStore { reset() { this.successResponse = undefined; } succeedWith(response) { this.reset(); this.successResponse = response; } failWith(response) { this.reset(); this.failureResponse = response; } update(callbacks) { if (this.successResponse) { callbacks.onSuccess(this.successResponse); } else if (this.failureResponse) { callbacks.onFailure(this.failureResponse); } this.reset(); } commitUpdate(mutation, callbacks) { return this.update(callbacks); } applyUpdate(mutation, callbacks) { return this.update(callbacks); } } module.exports = { QL: Relay.QL, Mutation, Route: Relay.Route, RootContainer: () => null, createContainer: (component) => component, Store: new MockStore(), };
Revert "I don't know what changed" This reverts commit d58deaaa289b4d641fc2d845ab063daad31d34e4.
<?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>
Handle sleeping in main loop
import time import subprocess from local_settings import * import redis redis_instance = redis.StrictRedis() def iterate_all_destinations(): times = [] for dest in DESTINATIONS: # TODO: different parameters for Linux p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE) p.wait() (output, _) = p.communicate() if p.returncode != 0: continue output = output.split("\n") for line in output: if "bytes from" in line: line = line.split(" ") for item in line: if item.startswith("time="): item = item.split("=") times.append(float(item[1])) message = None if len(times) == 0: message = "no_pings" else: message = min(times) redis_instance.publish("home:broadcast:ping", message) if __name__ == '__main__': while True: iterate_all_destinations() time.sleep(1)
import time import subprocess from local_settings import * import redis redis_instance = redis.StrictRedis() def iterate_all_destinations(): times = [] for dest in DESTINATIONS: # TODO: different parameters for Linux p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE) p.wait() (output, _) = p.communicate() if p.returncode != 0: continue output = output.split("\n") for line in output: if "bytes from" in line: line = line.split(" ") for item in line: if item.startswith("time="): item = item.split("=") times.append(float(item[1])) message = None if len(times) == 0: message = "no_pings" else: message = min(times) redis_instance.publish("home:broadcast:ping", message) time.sleep(1) if __name__ == '__main__': while True: iterate_all_destinations()
Change div to p when creating new logs
/** * public/src/js/logger.js - delish * * Licensed under MIT license. * Copyright (C) 2017 Karim Alibhai. */ const util = require('util') , debounce = require('debounce') let currentLog = document.querySelector('.lead') , nextLog = document.querySelector('.lead.next') /** * Updates the current log status. * @param {String} message the string with formatting * @param {...Object} values any values to plug in */ export default debounce(function () { let text = util.format.apply(util, arguments) // transition to the new log nextLog.innerText = text currentLog.classList.add('hide') nextLog.classList.remove('next') // after the CSS transition completes, swap // the log elements out setTimeout(() => { let parent = currentLog.parentElement parent.removeChild(currentLog) currentLog = nextLog nextLog = document.createElement('p') nextLog.classList.add('lead') nextLog.classList.add('next') parent.appendChild(nextLog) }, 700) }, 700)
/** * public/src/js/logger.js - delish * * Licensed under MIT license. * Copyright (C) 2017 Karim Alibhai. */ const util = require('util') , debounce = require('debounce') let currentLog = document.querySelector('.lead') , nextLog = document.querySelector('.lead.next') /** * Updates the current log status. * @param {String} message the string with formatting * @param {...Object} values any values to plug in */ export default debounce(function () { let text = util.format.apply(util, arguments) // transition to the new log nextLog.innerText = text currentLog.classList.add('hide') nextLog.classList.remove('next') // after the CSS transition completes, swap // the log elements out setTimeout(() => { let parent = currentLog.parentElement parent.removeChild(currentLog) currentLog = nextLog nextLog = document.createElement('div') nextLog.classList.add('lead') nextLog.classList.add('next') parent.appendChild(nextLog) }, 700) }, 700)
Fix error with undeclared variable Looks like a simple missprint for me
exports.init = init; function init(genericAWSClient) { return createSimpleQueueServiceClient; function createSimpleQueueServiceClient(accessKeyId, secretAccessKey, options) { options = options || {}; var client = genericAWSClient({ host: options.host || "sqs.us-east-1.amazonaws.com", path: options.path || "/", accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, secure: options.secure, agent: options.agent, token: options.token }); return { client: client, call: call }; function call(action, query, callback) { query["Action"] = action query["Version"] = options.version || '2011-10-01' query["SignatureMethod"] = "HmacSHA256" query["SignatureVersion"] = "2" return client.call(action, query, callback); } } }
exports.init = init; function init(genericAWSClient) { return createSimpleQueueServiceClient; function createSimpleQueueServiceClient(accessKeyId, secretAccessKey, options) { options = options || {}; var client = genericAWSClient({ host: options.host || "sqs.us-east-1.amazonaws.com", path: options.path || "/", accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, secure: options.secure, agent: options.agent, token: options.token }); return { client: aws, call: call }; function call(action, query, callback) { query["Action"] = action query["Version"] = options.version || '2011-10-01' query["SignatureMethod"] = "HmacSHA256" query["SignatureVersion"] = "2" return client.call(action, query, callback); } } }
Update the docblock of the example
"""`Factory` providers - building a complex object graph with deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
"""`Factory` providers deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
Add .html extension to generated URLs
<?php namespace FrozenSilex; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RequestContext; /** * URL Generator which intercepts calls and passes the generated * URLs to the Freezer * * @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com> */ class FreezingUrlGenerator implements UrlGeneratorInterface { protected $generator; protected $freezer; protected $context; function __construct(UrlGeneratorInterface $generator, Freezer $freezer) { $this->generator = $generator; $this->freezer = $freezer; } /** {@inheritDoc} */ function generate($name, $parameters = array(), $absolute = false) { $url = $this->generator->generate($name, $parameters, $absolute); if (!$absolute) { $this->freezer->freezeRoute($name, $parameters); } if (substr($url, -1, 1) === '/') { $url .= "index.html"; } else { $url .= ".html"; } return $url; } function setContext(RequestContext $context) { $this->generator->setContext($context); } function getContext() { return $this->generator->getContext(); } }
<?php namespace FrozenSilex; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RequestContext; /** * URL Generator which intercepts calls and passes the generated * URLs to the Freezer * * @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com> */ class FreezingUrlGenerator implements UrlGeneratorInterface { protected $generator; protected $freezer; protected $context; function __construct(UrlGeneratorInterface $generator, Freezer $freezer) { $this->generator = $generator; $this->freezer = $freezer; } /** {@inheritDoc} */ function generate($name, $parameters = array(), $absolute = false) { $url = $this->generator->generate($name, $parameters, $absolute); if (!$absolute) { $this->freezer->freezeRoute($name, $parameters); } return $url; } function setContext(RequestContext $context) { $this->generator->setContext($context); } function getContext() { return $this->generator->getContext(); } }
Fix issue with smoothscroll pattern
""" Smooth scroll pattern """ from .pattern import Pattern import time import math # fast linear sin approx def fastApprox(val): return 1.0 - math.fabs( math.fmod(val, 2.0) - 1.0) def constrain_int(value): return int(min(255, max(value, 0))) class ScrollSmooth(Pattern): def __init__(self): super(Pattern, self).__init__() @classmethod def get_id(self): return 7 @classmethod def update(self, strip, state): # logging.info("Smooth") for x in range(len(strip)): c1 = [c * (x / float(state.length + 1) + float(time.time()) * 1000.0 / float(state.delay)) for c in state.color1] # c2 is out of phase by 1 c2 = [c * (x / float(state.length + 1) + 1 + float(time.time()) * 1000.0 / float(state.delay)) for c in state.color2] c3 = tuple(constrain_int(a + b) for a, b in zip(c1, c2)) strip[x] = c3
""" Smooth scroll pattern """ from .pattern import Pattern import time import math # fast linear sin approx def fastApprox(val): return 1.0 - math.fabs( math.fmod(val, 2.0) - 1.0) def constrain_int(value): return int(min(255, max(value, 0))) class ScrollSmooth(Pattern): def __init__(self): super(Pattern, self).__init__() @classmethod def get_id(self): return 7 @classmethod def update(self, strip, state): # logging.info("Smooth") for x in range(len(strip)): c1 = [c * (x / float(state.length + 1) + float(time.time()) * 1000.0 / float(state.delay)) for c in state.color1] # c2 is out of phase by 1 c2 = [c * (x / float(state.length + 1) + 1 + float(time.time()) * 1000.0 / float(state.delay)) for c in state.color2] c3 = [constrain_int(a + b) for a, b in zip(c1, c2)] strip[x] = c3
Fix issue when server changed and connection failed
import { DB_CONNECT_REQUEST, DB_CONNECT_SUCCESS, DB_CONNECT_FAILURE, } from '../actions/connections'; import { SAVE_SERVER_SUCCESS } from '../actions/servers'; const initialState = { didInvalidate: true, }; export default function (state = initialState, action) { switch (action.type) { case SAVE_SERVER_SUCCESS: { if (state.server && action.server.id === state.server.id) { return { ...state, didInvalidate: true }; } return state; } case DB_CONNECT_REQUEST: { const { server, database } = action; return { isConnecting: true, isConnected: false, didInvalidate: false, server, database, }; } case DB_CONNECT_SUCCESS: { return { ...state, isConnecting: false, isConnected: true, error: null }; } case DB_CONNECT_FAILURE: { return { ...state, isConnecting: false, error: action.error, }; } default : return state; } }
import { DB_CONNECT_REQUEST, DB_CONNECT_SUCCESS, DB_CONNECT_FAILURE, } from '../actions/connections'; import { UPDATE_SERVER_SUCCESS } from '../actions/servers'; const initialState = { didInvalidate: true, }; export default function (state = initialState, action) { switch (action.type) { case UPDATE_SERVER_SUCCESS: { const id = parseInt(action.id, 10); if (state.server && id === state.server.id) { return { ...state, didInvalidate: true }; } return state; } case DB_CONNECT_REQUEST: { const { server, database } = action; return { isConnecting: true, isConnected: false, didInvalidate: false, server, database, }; } case DB_CONNECT_SUCCESS: { return { ...state, isConnecting: false, isConnected: true, error: null }; } case DB_CONNECT_FAILURE: { return { ...state, isConnecting: false, error: action.error, }; } default : return state; } }
Test changing file path for nosetests
import unittest import src import resources.Constants as const class TestAssignments(unittest.TestCase): string_file = '' int_file = '' @classmethod def setUpClass(cls): cls.string_file = src.main("./resources/BasicStringAssignment.txt") cls.int_file = src.main("./resources/BasicIntegerAssignment.txt") def testString(self): test_string = '"test123ID"' exp_result = [("test123ID", const.STRING)] result = src.lexer(test_string) self.assertEqual(result, exp_result) def testVariableAssignmentString(self): exp_result = [('string', const.ID), ('=', const.STMT), ("words", const.STRING)] result = src.lexer(self.string_file) self.assertEqual(result, exp_result) def testDoubleQuoteString(self): test_string = '""""' exp_result = [('""', const.STRING)] result = src.lexer(test_string) self.assertEqual(result, exp_result)
import unittest import src import resources.Constants as const class TestAssignments(unittest.TestCase): string_file = '' int_file = '' @classmethod def setUpClass(cls): cls.string_file = src.main("../resources/BasicStringAssignment.txt") cls.int_file = src.main("../resources/BasicIntegerAssignment.txt") def testString(self): test_string = '"test123ID"' exp_result = [("test123ID", const.STRING)] result = src.lexer(test_string) self.assertEqual(result, exp_result) def testVariableAssignmentString(self): exp_result = [('string', const.ID), ('=', const.STMT), ("words", const.STRING)] result = src.lexer(self.string_file) self.assertEqual(result, exp_result) def testDoubleQuoteString(self): test_string = '""""' exp_result = [('""', const.STRING)] result = src.lexer(test_string) self.assertEqual(result, exp_result)
Remove code no longer required
package org.realityforge.arez.gwt.examples; import elemental2.dom.DomGlobal; import org.realityforge.arez.Arez; import org.realityforge.arez.extras.WhyRun; final class ExampleUtil { private ExampleUtil() { } static void jsonLogSpyEvents() { Arez.context().getSpy().addSpyEventHandler( new JsonLogSpyEventProcessor() ); } static void whyRun() { DomGlobal.console.log( new WhyRun( Arez.context() ).whyRun() ); } static void logAllErrors() { Arez.context().addObserverErrorHandler( ( observer, error, throwable ) -> { DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer ); if ( null != throwable ) { DomGlobal.console.log( throwable ); } } ); } }
package org.realityforge.arez.gwt.examples; import elemental2.dom.DomGlobal; import org.realityforge.arez.Arez; import org.realityforge.arez.browser.extras.spy.ConsoleSpyEventProcessor; import org.realityforge.arez.extras.WhyRun; final class ExampleUtil { private ExampleUtil() { } static void spyEvents() { Arez.context().getSpy().addSpyEventHandler( new ConsoleSpyEventProcessor() ); } static void jsonLogSpyEvents() { Arez.context().getSpy().addSpyEventHandler( new JsonLogSpyEventProcessor() ); } static void whyRun() { DomGlobal.console.log( new WhyRun( Arez.context() ).whyRun() ); } static void logAllErrors() { Arez.context().addObserverErrorHandler( ( observer, error, throwable ) -> { DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer ); if ( null != throwable ) { DomGlobal.console.log( throwable ); } } ); } }
Rewrite the script in a package fasshion.
# coding=utf-8 from urllib2 import urlopen, Request import json import re class XmlyDownloader(object): def __init__(self): self.headers = {'User-Agent': 'Safari/537.36'} def getIDs(self, url): resp = urlopen(Request(url, headers=self.headers)) return re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') def download_file(self, ID): url = 'http://www.ximalaya.com/tracks/{}.json'.format(ID) resp = urlopen(Request(url, headers=self.headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urlopen(data['play_path_64']).read()) def download_album(self, album_url): for ID in self.getIDs(album_url): self.download_file(ID) if __name__ == '__main__': album_url = 'http://www.ximalaya.com/7712455/album/4474664' xmly = XmlyDownloader() xmly.download_album(album_url)
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read())
Add get route for /
// Dependencies var express = require('express'); var methodOverride = require('method-override'); var bodyParser = require('body-parser'); var exphbs = require("express-handlebars"); // Sets up the Express App var app = express(); var PORT = process.env.PORT || 8080; // Models to sync var db = require("./models"); app.use(bodyParser.urlencoded({ extended: false })); app.use(methodOverride("_method")); app.engine("handlebars", exphbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); // Serve files in 'public' directory app.use(express.static('public')); // Load routes app.get('/', function(req, res) { res.render('index'); }); app.use(require('./controllers/guest_controller')); app.use(require('./controllers/manager_controller')); app.use(require('./controllers/restaurant_controller')); app.use(require('./controllers/room_controller')); app.use(require('./controllers/table_controller')); // Sync models then start the server to begin listening db.sequelize.sync().then(function() { app.listen(PORT, function() { console.log("App listening on PORT " + PORT); }); });
// Dependencies var express = require('express'); var methodOverride = require('method-override'); var bodyParser = require('body-parser'); var exphbs = require("express-handlebars"); // Sets up the Express App var app = express(); var PORT = process.env.PORT || 8080; // Models to sync var db = require("./models"); app.use(bodyParser.urlencoded({ extended: false })); app.use(methodOverride("_method")); app.engine("handlebars", exphbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); // Serve files in 'public' directory app.use(express.static('public')); // Load routes app.use(require('./controllers/guest_controller')); app.use(require('./controllers/manager_controller')); app.use(require('./controllers/restaurant_controller')); app.use(require('./controllers/room_controller')); app.use(require('./controllers/table_controller')); // Sync models then start the server to begin listening db.sequelize.sync().then(function() { app.listen(PORT, function() { console.log("App listening on PORT " + PORT); }); });
Fix add Ember Try config for 1.12.X
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-1.12.X', dependencies: { 'ember': '1.12.1' } }, { name: 'ember-1.13.X', dependencies: { 'ember': '1.13.10' } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } } ] };
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-1.13.X', dependencies: { 'ember': '1.13.10' } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } } ] };
Update - Starting Date First Semester
package utils; public class SemesterInfo { public static final int NO_OF_WEEKS_FIRST_SEMESTER = 16; public static final int CHRISTMAS_HOLIDAY = 12; public static final int CHRISTMAS_HOLIDAY_LENGTH = 2; public static final int NO_OF_WEEKS_SECOND_SEMESTER = 15; public static final int EASTER_HOLIDAY = 7; public static final int EASTER_HOLIDAY_LENGTH = 1; public static final String STARTING_DATE_FIRST_SEMESTER = "2017-10-02"; public static final String STARTING_DATE_SECOND_SEMESTER = "2017-02-27"; public static int getNoOfWeeks(int semester) { return (semester == 1 ? NO_OF_WEEKS_FIRST_SEMESTER : NO_OF_WEEKS_SECOND_SEMESTER); } public static int getHolidayStartingWeek(int semester) { return (semester == 1 ? CHRISTMAS_HOLIDAY : EASTER_HOLIDAY); } public static int getHolidayLength(int semester) { return (semester == 1 ? CHRISTMAS_HOLIDAY_LENGTH : EASTER_HOLIDAY_LENGTH); } public static String getStartingDate(int semester) { return (semester == 1 ? STARTING_DATE_FIRST_SEMESTER : STARTING_DATE_SECOND_SEMESTER); } }
package utils; public class SemesterInfo { public static final int NO_OF_WEEKS_FIRST_SEMESTER = 16; public static final int CHRISTMAS_HOLIDAY = 12; public static final int CHRISTMAS_HOLIDAY_LENGTH = 2; public static final int NO_OF_WEEKS_SECOND_SEMESTER = 15; public static final int EASTER_HOLIDAY = 7; public static final int EASTER_HOLIDAY_LENGTH = 1; public static final String STARTING_DATE_FIRST_SEMESTER = "2016-10-03"; public static final String STARTING_DATE_SECOND_SEMESTER = "2017-02-27"; public static int getNoOfWeeks(int semester) { return (semester == 1 ? NO_OF_WEEKS_FIRST_SEMESTER : NO_OF_WEEKS_SECOND_SEMESTER); } public static int getHolidayStartingWeek(int semester) { return (semester == 1 ? CHRISTMAS_HOLIDAY : EASTER_HOLIDAY); } public static int getHolidayLength(int semester) { return (semester == 1 ? CHRISTMAS_HOLIDAY_LENGTH : EASTER_HOLIDAY_LENGTH); } public static String getStartingDate(int semester) { return (semester == 1 ? STARTING_DATE_FIRST_SEMESTER : STARTING_DATE_SECOND_SEMESTER); } }
Use es6 promises instead of Q
const JSONPUtil = { /** * Request JSONP data * * @todo: write test to verify this util is working properly * * @param {string} url * @returns {Promise} promise */ request(url) { return new Promise(function (resolve, reject) { var callback = `jsonp_${Date.now().toString(16)}`; var script = document.createElement("script"); // Add jsonp callback window[callback] = function handleJSONPResponce(data) { if (data != null) { return resolve(data); } reject(new Error("Empty response")); }; // Add clean up method script.cleanUp = function () { if (this.parentNode) { this.parentNode.removeChild(script); } }; // Add handler script.onerror = function handleScriptError(error) { script.cleanUp(); reject(error); }; script.onload = function handleScriptLoad() { script.cleanUp(); }; // Load data script.src = `${url}${ /[?&]/.test(url) ? "&" : "?" }jsonp=${callback}`; document.head.appendChild(script); }); } }; export default JSONPUtil;
import Q from "q"; const JSONPUtil = { /** * Request JSONP data * * @todo: write test to verify this util is working properly * * @param {string} url * @returns {Q.promise} promise */ request(url) { var deferred = Q.defer(); var callback = `jsonp_${Date.now().toString(16)}`; var script = document.createElement("script"); // Add jsonp callback window[callback] = function handleJSONPResponce(data) { if (data != null) { return deferred.resolve(data); } deferred.reject(new Error("Empty response")); }; // Add clean up method script.cleanUp = function () { if (this.parentNode) { this.parentNode.removeChild(script); } }; // Add handler script.onerror = function handleScriptError(error) { script.cleanUp(); deferred.reject(error); }; script.onload = function handleScriptLoad() { script.cleanUp(); }; // Load data script.src = `${url}${ /[?&]/.test(url) ? "&" : "?" }jsonp=${callback}`; document.head.appendChild(script); return deferred.promise; } }; export default JSONPUtil;
Remove Latin so Chrome stops trying to translate
@extends('admin.layouts.master') @section('main_content') {{-- @TODO: likely a better way to split this out in Blade! --}} @include('admin.layouts.partials.subnav-settings') <div class="container"> <div class="row"> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h1 class="page-header">Settings</h1> <p>Click below to create a new scholarship or edit the current one, or select another option from the sidebar.</p> {!! link_to_route('admin.scholarship.create', 'Create new scholarship »', null, ['class' => 'btn btn-default', 'role'=> 'button']) !!} {!! link_to_route('admin.scholarship.edit', 'Edit current scholarship »', $scholarship_id, ['class' => 'btn btn-default', 'role'=> 'button']) !!} </div> </div> </div> @stop
@extends('admin.layouts.master') @section('main_content') {{-- @TODO: likely a better way to split this out in Blade! --}} @include('admin.layouts.partials.subnav-settings') <div class="container"> <div class="row"> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h1 class="page-header">Settings</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem quam, voluptate, vero odio hic eum minima excepturi, accusantium delectus quasi veniam saepe quod vitae qui repudiandae quae aperiam rerum soluta.</p> {!! link_to_route('admin.scholarship.create', 'Create new scholarship »', null, ['class' => 'btn btn-default', 'role'=> 'button']) !!} {!! link_to_route('admin.scholarship.edit', 'Edit current scholarship »', $scholarship_id, ['class' => 'btn btn-default', 'role'=> 'button']) !!} </div> </div> </div> @stop
Remove pointless @method annotations from MockInterface
<?php /** * Mockery * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://github.com/padraic/mockery/blob/master/LICENSE * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to padraic@php.net so we can send you a copy immediately. * * @category Mockery * @package Mockery * @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com) * @license http://github.com/padraic/mockery/blob/master/LICENSE New BSD License */ namespace Mockery; interface ExpectationInterface { /** * @return int */ public function getOrderNumber(); /** * @return MockInterface */ public function getMock(); /** * @param array $args * @return self */ public function andReturn(...$args); /** * @return self */ public function andReturns(); }
<?php /** * Mockery * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://github.com/padraic/mockery/blob/master/LICENSE * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to padraic@php.net so we can send you a copy immediately. * * @category Mockery * @package Mockery * @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com) * @license http://github.com/padraic/mockery/blob/master/LICENSE New BSD License */ namespace Mockery; /** * @method Expectation once() * @method Expectation zeroOrMoreTimes() * @method Expectation twice() * @method Expectation times(int $limit) * @method Expectation never() * @method Expectation atLeast() * @method Expectation atMost() * @method Expectation between() * @method Expectation because(string $message) */ interface ExpectationInterface { /** * @return int */ public function getOrderNumber(); /** * @return MockInterface */ public function getMock(); /** * @param array $args * @return self */ public function andReturn(...$args); /** * @return self */ public function andReturns(); }
Fix position of todos app
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { observer } from 'mobx-react'; import injectSheet from 'react-jss'; import Webview from 'react-electron-web-view'; import * as environment from '../../../environment'; const styles = theme => ({ root: { background: theme.colorBackground, height: '100%', width: 300, position: 'absolute', top: 0, right: -300, }, webview: { height: '100%', }, }); @injectSheet(styles) @observer class TodosWebview extends Component { static propTypes = { classes: PropTypes.object.isRequired, authToken: PropTypes.string.isRequired, }; render() { const { authToken, classes } = this.props; return ( <div className={classes.root}> <Webview className={classes.webview} src={`${environment.TODOS_FRONTEND}?authToken=${authToken}`} /> </div> ); } } export default TodosWebview;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { observer } from 'mobx-react'; import injectSheet from 'react-jss'; import Webview from 'react-electron-web-view'; import * as environment from '../../../environment'; const styles = theme => ({ root: { background: theme.colorBackground, height: '100%', width: 300, position: 'absolute', top: 0, right: 0, }, webview: { height: '100%', }, }); @injectSheet(styles) @observer class TodosWebview extends Component { static propTypes = { classes: PropTypes.object.isRequired, authToken: PropTypes.string.isRequired, }; render() { const { authToken, classes } = this.props; return ( <div className={classes.root}> <Webview className={classes.webview} src={`${environment.TODOS_FRONTEND}?authToken=${authToken}`} /> </div> ); } } export default TodosWebview;
Change to how we rectify the "IPv6 bug".
<?php /** * Class to interact with a cisco router. */ class CiscoRouter extends Router { use CiscoTrait; /* {@inheritDoc} */ function getPrefixList($name, $type = 'ipv4') { $type = ($type == 'ipv4' ? 'ip' : 'ipv6'); $data = $this->exec('show ' . $type . ' prefix-list ' . $name); $entries = array(); foreach (explode("\n", $data) as $line) { if (preg_match('#seq ([0-9]+) (.*)$#', trim($line), $m)) { $entries[$m[1]] = strtolower(trim($m[2])); } } return $entries; } function postConnect() { // Check for potential IPv6 bug. $data = $this->exec('show ipv6'); if (stristr($data, 'Invalid input detected')) { if ($this->isDebug()) { echo '! IPv6 Bug detected.', "\n"; } $this->exec('routing-context vrf global'); } } }
<?php /** * Class to interact with a cisco router. */ class CiscoRouter extends Router { use CiscoTrait; /* {@inheritDoc} */ function getPrefixList($name, $type = 'ipv4') { $type = ($type == 'ipv4' ? 'ip' : 'ipv6'); $data = $this->exec('show ' . $type . ' prefix-list ' . $name); $entries = array(); foreach (explode("\n", $data) as $line) { if (preg_match('#seq ([0-9]+) (.*)$#', trim($line), $m)) { $entries[$m[1]] = strtolower(trim($m[2])); } } return $entries; } function postConnect() { // Check for IPv6 bug. $data = $this->exec('show ipv6'); if (stristr($data, 'Invalid input detected')) { if ($this->isDebug()) { echo '! IPv6 Bug detected.', "\n"; } $oldSocket = $this->socket; $this->socket = null; $this->createNewSocket(); $this->connect(); $oldSocket->disconnect(); } } }
Implement range of possible values with clamping if values are outside range
#/usr/bin/env python # -*- coding: utf-8 -*- import click import requests import requests_cache # Cache the API calls and expire after 12 hours requests_cache.install_cache(expire_after=43200) url = 'http://ben-major.co.uk/labs/top40/api/singles/' @click.command() @click.option('--count', type=click.IntRange(1, 40, clamp=True), default=10, help='Number of songs to show. Maximum is 40') def get_charts(count): """Prints the top COUNT songs in the UK Top 40 chart.""" response = requests.get(url).json() data = response['entries'][:count] for index, element in enumerate(data, start=1): click.echo( '{}. {} - {}'.format( index, element['title'], element['artist'].encode('utf-8', 'replace'))) if __name__ == '__main__': get_charts()
#/usr/bin/env python # -*- coding: utf-8 -*- import click import requests import requests_cache # Cache the API calls and expire after 12 hours requests_cache.install_cache(expire_after=43200) url = 'http://ben-major.co.uk/labs/top40/api/singles/' @click.command() @click.option('--count', default=10, help='Number of songs to show. Maximum is 40') def get_charts(count): """Prints the top COUNT songs in the UK Top 40 chart.""" response = requests.get(url).json() data = response['entries'][:count] for index, element in enumerate(data, start=1): click.echo( '{}. {} - {}'.format( index, element['title'], element['artist'].encode('utf-8', 'replace'))) if __name__ == '__main__': get_charts()
Divide changelog and readme when uploading
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import re from setuptools import setup, find_packages with open('json2parquet/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.rst') as readme_file: readme = readme_file.read() with open('CHANGELOG.rst') as changelog_file: changelog = changelog_file.read() setup( name='json2parquet', version=version, description='A simple Parquet converter for JSON/python data', long_description=readme + '\n\n' + changelog, author='Andrew Gross', author_email='andrew.w.gross@gmail.com', url='https://github.com/andrewgross/json2parquet', install_requires=[ 'pyarrow==0.6.0' ], packages=[n for n in find_packages() if not n.startswith('tests')], include_package_data=True, )
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import re from setuptools import setup, find_packages with open('json2parquet/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.rst') as readme_file: readme = readme_file.read() with open('CHANGELOG.rst') as changelog_file: changelog = changelog_file.read() setup( name='json2parquet', version=version, description='A simple Parquet converter for JSON/python data', long_description=readme + changelog, author='Andrew Gross', author_email='andrew.w.gross@gmail.com', url='https://github.com/andrewgross/json2parquet', install_requires=[ 'pyarrow==0.6.0' ], packages=[n for n in find_packages() if not n.startswith('tests')], include_package_data=True, )
Configure Celery correctly in smoketest
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): app = Celery('cla_backend') app.config_from_object('django.conf:settings') app.connection().connect() conn.connect() conn.release()
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.config_from_object('django.conf:settings') conn.connect() conn.release()
Apply extension's enhancer to saga-counter example
/*eslint-disable no-unused-vars*/ import "babel-polyfill" import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware, compose } from 'redux' import createSagaMiddleware from 'redux-saga' // import sagaMonitor from './sagaMonitor' import Counter from './components/Counter' import reducer from './reducers' import rootSaga from './sagas' const sagaMiddleware = createSagaMiddleware(/* {sagaMonitor} */) const store = createStore( reducer, compose( applyMiddleware(sagaMiddleware), window.devToolsExtension && window.devToolsExtension() ) ) sagaMiddleware.run(rootSaga) const action = type => store.dispatch({type}) function render() { ReactDOM.render( <Counter value={store.getState()} onIncrement={() => action('INCREMENT')} onDecrement={() => action('DECREMENT')} onIncrementIfOdd={() => action('INCREMENT_IF_ODD')} onIncrementAsync={() => action('INCREMENT_ASYNC')} />, document.getElementById('root') ) } render() store.subscribe(render)
/*eslint-disable no-unused-vars*/ import "babel-polyfill" import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import createSagaMiddleware from 'redux-saga' // import sagaMonitor from './sagaMonitor' import Counter from './components/Counter' import reducer from './reducers' import rootSaga from './sagas' const sagaMiddleware = createSagaMiddleware(/* {sagaMonitor} */) const store = createStore( reducer, applyMiddleware(sagaMiddleware) ) sagaMiddleware.run(rootSaga) const action = type => store.dispatch({type}) function render() { ReactDOM.render( <Counter value={store.getState()} onIncrement={() => action('INCREMENT')} onDecrement={() => action('DECREMENT')} onIncrementIfOdd={() => action('INCREMENT_IF_ODD')} onIncrementAsync={() => action('INCREMENT_ASYNC')} />, document.getElementById('root') ) } render() store.subscribe(render)
Fix path handling for db-password
'use strict'; const fs = require('fs'); const path = require('path'); const escape = require('pg-escape'); const hasDBAvailable = Boolean(process.env.DB); if (!hasDBAvailable) { module.exports = {}; return; } const pgPass = fs.readFileSync(path.join(__dirname, 'db-password'), {encoding: 'utf8'}); const pgConfig = { host: 'localhost', user: process.env.PGUSER || 'hmbserver', password: process.env.PGPASSWORD || pgPass, database: process.env.PGDATABASE || 'hmb' }; const Pool = require('pg').Pool; const pgPool = new Pool(pgConfig); pgPool.on('error', (err, client) => { logger.error('Idle psql client error', { errorMsg: err.message, errorStack: err.stack, client }); }); function insertUser(username, email, passwordHash) { return pgPool.query('insert into users values($1, $2, \'\', $3)', [ escape.string(username), escape.string(email), passwordHash ]); } module.exports = { hasDBAvailable, pgPool, insertUser };
'use strict'; const fs = require('fs'); const escape = require('pg-escape'); const hasDBAvailable = Boolean(process.env.DB); if (!hasDBAvailable) { module.exports = {}; return; } const pgConfig = { host: 'localhost', user: process.env.PGUSER || 'hmbserver', password: process.env.PGPASSWORD || fs.readFileSync('db-password', {encoding: 'utf8'}), database: process.env.PGDATABASE || 'hmb' }; const Pool = require('pg').Pool; const pgPool = new Pool(pgConfig); pgPool.on('error', (err, client) => { logger.error('Idle psql client error', { errorMsg: err.message, errorStack: err.stack, client }); }); function insertUser(username, email, passwordHash) { return pgPool.query('insert into users values($1, $2, \'\', $3)', [ escape.string(username), escape.string(email), passwordHash ]); } module.exports = { hasDBAvailable, pgPool, insertUser };
Fix data type of shipment point id for /api/v5/integration-modules/{code}/edit
<?php /** * PHP version 7.3 * * @category ShipmentPoint * @package RetailCrm\Api\Model\Entity\Integration\Delivery */ namespace RetailCrm\Api\Model\Entity\Integration\Delivery; use RetailCrm\Api\Component\Serializer\Annotation as JMS; /** * Class ShipmentPoint * * @category ShipmentPoint * @package RetailCrm\Api\Model\Entity\Integration\Delivery */ class ShipmentPoint { /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("code") */ public $code; /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("shipmentPointId") */ public $shipmentPointId; /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("shipmentPointLabel") */ public $shipmentPointLabel; }
<?php /** * PHP version 7.3 * * @category ShipmentPoint * @package RetailCrm\Api\Model\Entity\Integration\Delivery */ namespace RetailCrm\Api\Model\Entity\Integration\Delivery; use RetailCrm\Api\Component\Serializer\Annotation as JMS; /** * Class ShipmentPoint * * @category ShipmentPoint * @package RetailCrm\Api\Model\Entity\Integration\Delivery */ class ShipmentPoint { /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("code") */ public $code; /** * @var int * * @JMS\Type("int") * @JMS\SerializedName("shipmentPointId") */ public $shipmentPointId; /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("shipmentPointLabel") */ public $shipmentPointLabel; }
Replace .call with a normal method call (faster) It's faster to call methods directly instead of using `.call` and assigning a scope yourself
var EngineIO = require("engine.io") var EventEmitter = require("events").EventEmitter var EngineStream = require("./eiostream") module.exports = EngineServer function EngineServer(onConnection) { var engine = new EventEmitter var servers = [] engine.attach = attach engine.close = close if (onConnection) { engine.on("connection", onConnection) } function attach(httpServer, options) { options = options || {} if (typeof options === "string") { options = { path: options } } var server = EngineIO.attach(httpServer, options) servers.push(server) server.on("error", engine.emit.bind(engine, "error")); server.on("connection", function (socket) { engine.emit("connection", EngineStream(socket)) }) } function close() { servers.forEach(invoke("close")) } return engine } function invoke(method) { return function (obj) { return (obj[method])() } }
var EngineIO = require("engine.io") var EventEmitter = require("events").EventEmitter var EngineStream = require("./eiostream") module.exports = EngineServer function EngineServer(onConnection) { var engine = new EventEmitter var servers = [] engine.attach = attach engine.close = close if (onConnection) { engine.on("connection", onConnection) } function attach(httpServer, options) { options = options || {} if (typeof options === "string") { options = { path: options } } var server = EngineIO.attach(httpServer, options) servers.push(server) server.on("error", engine.emit.bind(engine, "error")); server.on("connection", function (socket) { engine.emit("connection", EngineStream(socket)) }) } function close() { servers.forEach(invoke("close")) } return engine } function invoke(method) { return function (obj) { return obj[method].call(obj) } }
Fix typo in use statement
<?php namespace Drubo\Robo\Task\Filesystem; use Drubo\Robo\Task\Filesystem\Clean\Directories as CleanDirectories; use Drubo\Robo\Task\Filesystem\Prepare\Directories as PrepareDicrectories; use Drubo\Robo\Task\Filesystem\Prepare\Files; trait loadTasks { /** * Clean filesystem directories. * * @return \Drubo\Robo\Task\Filesystem\Clean\Directories */ protected function taskFilesystemCleanDirectories() { return $this->task(CleanDirectories::class); } /** * Prepare filesystem directories. * * @return \Drubo\Robo\Task\Filesystem\Prepare\Directories */ protected function taskFilesystemPrepareDirectories() { return $this->task(PrepareDicrectories::class); } /** * Prepare filesystem files. * * @return \Drubo\Robo\Task\Filesystem\Prepare\Files */ protected function taskFilesystemPrepareFiles() { return $this->task(Files::class); } }
<?php namespace Drubo\Robo\Task\Filesystem; use Drubo\Robo\Task\Filesystem\Clean\Directories as CleanDicrectories; use Drubo\Robo\Task\Filesystem\Prepare\Directories as PrepareDicrectories; use Drubo\Robo\Task\Filesystem\Prepare\Files; trait loadTasks { /** * Clean filesystem directories. * * @return \Drubo\Robo\Task\Filesystem\Clean\Directories */ protected function taskFilesystemCleanDirectories() { return $this->task(CleanDicrectories::class); } /** * Prepare filesystem directories. * * @return \Drubo\Robo\Task\Filesystem\Prepare\Directories */ protected function taskFilesystemPrepareDirectories() { return $this->task(PrepareDicrectories::class); } /** * Prepare filesystem files. * * @return \Drubo\Robo\Task\Filesystem\Prepare\Files */ protected function taskFilesystemPrepareFiles() { return $this->task(Files::class); } }
:art: Create untested (so far) task spy
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const Scheduler = require("../../lib/scheduler"); const fsWatcher = require("../../lib/fs-watcher"); const MockInspector = require("../mock/file-tree-inspector"); const Ticker = require("../mock/ticker"); let scheduler = null; let ticker = null; let fakeFS = null; let taskSpy = function(find) { let task = {}; task.pwd = ""; task.events = []; task.find = () => new Promise(function(resolve, reject) { resolve(find()); }); task.move = files => new Promise(function(resolve, reject) { task.events.push(["move", files]); }); task.run = wd => new Promise(function(resolve, reject) { task.events.push(["run", wd]); }); return task; }; describe("in a mocked environment", () => { beforeEach(() => { let mockObj = MockInspector(); ticker = Ticker(); fakeFS = mockObj.fs; scheduler = Scheduler( {"watcher": fsWatcher({"tick": ticker.tick, "inspector": mockObj.inspector})}); }); it("does nothing when given nothing", done => { scheduler({}).then(() => { done(); }, error => { expect(error).toBe("not an error"); done(); }); }); });
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const Scheduler = require("../../lib/scheduler"); const fsWatcher = require("../../lib/fs-watcher"); const MockInspector = require("../mock/file-tree-inspector"); const Ticker = require("../mock/ticker"); let scheduler = null; let ticker = null; let fakeFS = null; describe("in a mocked environment", () => { beforeEach(() => { let mockObj = MockInspector(); ticker = Ticker(); fakeFS = mockObj.fs; scheduler = Scheduler( {"watcher": fsWatcher({"tick": ticker.tick, "inspector": mockObj.inspector})}); }); it("does nothing when given nothing", done => { scheduler({}).then(() => { done(); }, error => { expect(error).toBe("not an error"); done(); }); }); });
Reorder routes, put i18n route first
<?php namespace Umpirsky\I18nRoutingBundle\Routing\Strategy; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; use Umpirsky\I18nRoutingBundle\Routing\Generator\LocaleRequirementGeneratorInterface; class PrefixExceptDefaultStrategy extends AbstractStrategy { private $routeNameSuffix; public function __construct(LocaleRequirementGeneratorInterface $localeRequirementGenerator, string $defaultLocale, string $routeNameSuffix) { $this->routeNameSuffix = $routeNameSuffix; parent::__construct($localeRequirementGenerator, $defaultLocale); } public function generate(string $name, Route $route): RouteCollection { $collection = new RouteCollection(); if (false !== $route->getOption('i18n')) { $i18nRoute = clone $route; $i18nRoute->setPath('/{_locale}'.$route->getPath()); $i18nRoute->setRequirement('_locale', $this->localeRequirementGenerator->generate()); $collection->add($name.$this->routeNameSuffix, $i18nRoute); } $collection->add($name, $route); return $collection; } }
<?php namespace Umpirsky\I18nRoutingBundle\Routing\Strategy; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; use Umpirsky\I18nRoutingBundle\Routing\Generator\LocaleRequirementGeneratorInterface; class PrefixExceptDefaultStrategy extends AbstractStrategy { private $routeNameSuffix; public function __construct(LocaleRequirementGeneratorInterface $localeRequirementGenerator, string $defaultLocale, string $routeNameSuffix) { $this->routeNameSuffix = $routeNameSuffix; parent::__construct($localeRequirementGenerator, $defaultLocale); } public function generate(string $name, Route $route): RouteCollection { $collection = new RouteCollection(); $collection->add($name, $route); if (false === $route->getOption('i18n')) { return $collection; } $i18nRoute = clone $route; $i18nRoute->setPath('/{_locale}'.$route->getPath()); $i18nRoute->setRequirement('_locale', $this->localeRequirementGenerator->generate()); $collection->add($name.$this->routeNameSuffix, $i18nRoute); return $collection; } }
Remove old views and replace with new PasswordResetConfirmView
from django.conf.urls import patterns, url from cellcounter.accounts import views urlpatterns = patterns('', url('^new/$', views.RegistrationView.as_view(), name='register'), url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'), url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'), url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'), url('^password/reset/$', views.PasswordResetView.as_view(), name='password-reset'), url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$', views.PasswordResetConfirmView.as_view(), name='password-reset-confirm'), url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'), )
from django.conf.urls import patterns, url from cellcounter.accounts import views urlpatterns = patterns('', url('^new/$', views.RegistrationView.as_view(), name='register'), url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'), url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'), url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'), url('^password/reset/$', views.PasswordResetView.as_view(), name='password-reset'), url('^password/reset/done/$', views.password_reset_done, name='password-reset-done'), url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$', 'django.contrib.auth.views.password_reset_confirm', { 'template_name': 'accounts/reset_confirm.html', 'post_reset_redirect': 'password-reset-done', }, name='password-reset-confirm'), url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'), )
Add --tasklist (no dash) and better description
package forager.ui; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import forager.server.Overlord; @Parameters(separators = "=", commandDescription = "Starts a forager master server") public class Server implements CommandLauncher { public static final int DEFAULT_PORT = 53380; public static final String DEFAULT_TASKLIST = "./tasklist"; @Parameter(names = { "-p", "--port" }, description = "Server port") private int port = DEFAULT_PORT; @Parameter(names = { "-t", "--task-list", "--tasklist" }, description = "Path to the task list (created if it doesn't exist)") private String taskList = DEFAULT_TASKLIST; @Override public void launch() throws Exception { Overlord server = new Overlord(port, taskList); server.start(); } }
package forager.ui; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import forager.server.Overlord; @Parameters(separators = "=", commandDescription = "Starts a forager master server") public class Server implements CommandLauncher { public static final int DEFAULT_PORT = 53380; public static final String DEFAULT_TASKLIST = "./tasklist"; @Parameter(names = { "-p", "--port" }, description = "Server port") private int port = DEFAULT_PORT; @Parameter(names = { "-t", "--task-list" }, description = "Task list location") private String taskList = DEFAULT_TASKLIST; @Override public void launch() throws Exception { Overlord server = new Overlord(port, taskList); server.start(); } }
Fix searchForm JS in headerbar
/** * @class Denkmal_Component_HeaderBar * @extends Denkmal_Component_Abstract */ var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({ /** @type String */ _class: 'Denkmal_Component_HeaderBar', /** @type Denkmal_Form_SearchContent|Null */ _searchForm: null, events: { 'click .showSearch': 'showSearch' }, childrenEvents: { 'CM_FormField_Text focus': function() { this._expandSearch(true); }, 'CM_FormField_Text blur': function() { this._expandSearch(false); } }, showSearch: function() { if (!this._hasSearchForm()) { return; } this._expandSearch(true); console.log(this); console.log(this._getSearchForm()); this._getSearchForm().setFocus(); }, /** * @return Denkmal_Form_SearchContent */ _getSearchForm: function() { if (null === this._searchForm) { this._searchForm = this.findChild('Denkmal_Form_SearchContent'); } return this._searchForm; }, /** * @returns {Boolean} */ _hasSearchForm: function() { return (null !== this._getSearchForm()); }, /** * @param {Boolean} state */ _expandSearch: function(state) { this.$('.bar').toggleClass('search-expand', state); } });
/** * @class Denkmal_Component_HeaderBar * @extends Denkmal_Component_Abstract */ var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({ /** @type String */ _class: 'Denkmal_Component_HeaderBar', events: { 'click .showSearch': 'showSearch' }, childrenEvents: { 'CM_FormField_Text focus': function() { this._expandSearch(true); }, 'CM_FormField_Text blur': function() { this._expandSearch(false); } }, showSearch: function() { if (!this._hasSearchForm()) { return; } this._expandSearch(true); this._getSearchForm().setFocus(); }, /** * @return FB_Form_SearchContent */ _getSearchForm: function() { if (null === this._searchForm) { this._searchForm = this.findChild('FB_Form_SearchContent'); } return this._searchForm; }, /** * @returns {Boolean} */ _hasSearchForm: function() { return (null !== this._getSearchForm()); }, /** * @param {Boolean} state */ _expandSearch: function(state) { this.$('.bar').toggleClass('search-expand', state); } });
Update comments about Bulk Send Job List
<?php /** * HelloSign PHP SDK (https://github.com/hellosign/hellosign-php-sdk/) */ /** * The MIT License (MIT) * * Copyright (C) 2014 hellosign.com * * 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. */ namespace HelloSign; /** * Represents a paged list of HelloSign BulkSendJobs */ class BulkSendJobList extends AbstractResourceList { /** * @var string * @ignore */ protected $list_type = 'bulk_send_jobs'; /** * @var string * @ignore */ protected $resource_class = 'BulkSendJob'; }
<?php /** * HelloSign PHP SDK (https://github.com/hellosign/hellosign-php-sdk/) */ /** * The MIT License (MIT) * * Copyright (C) 2014 hellosign.com * * 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. */ namespace HelloSign; /** * Represents a paged list of HelloSign API Apps */ class BulkSendJobList extends AbstractResourceList { /** * @var string * @ignore */ protected $list_type = 'bulk_send_jobs'; /** * @var string * @ignore */ protected $resource_class = 'BulkSendJob'; }
Add comments lost by converting to JS
'use babel'; /* eslint-disable no-multi-str, prefer-const, func-names */ let linkPaths; const regex = new RegExp('((?:\\w:)?/?(?:[-\\w.]+/)*[-\\w.]+):(\\d+)(?::(\\d+))?', 'g'); // ((?:\w:)?/? # Prefix of the path either '/' or 'C:/' (optional) // (?:[-\w.]+/)*[-\w.]+) # The path of the file some/file/path.ext // :(\d+) # Line number prefixed with a colon // (?::(\d+))? # Column number prefixed with a colon (optional) const template = '<a class="-linked-path" data-path="$1" data-line="$2" data-column="$3">$&</a>'; export default linkPaths = lines => lines.replace(regex, template); linkPaths.listen = parentView => parentView.on('click', '.-linked-path', function () { const el = this; let { path, line, column } = el.dataset; line = Number(line) - 1; // column number is optional column = column ? Number(column) - 1 : 0; atom.workspace.open(path, { initialLine: line, initialColumn: column, }); });
'use babel'; /* eslint-disable no-multi-str, prefer-const, func-names */ let linkPaths; const regex = new RegExp('\ ((?:\\w:)?/?\ (?:[-\\w.]+/)*[-\\w.]+)\ :(\\d+)\ (?::(\\d+))?\ ', 'g'); const template = '<a class="-linked-path" data-path="$1" data-line="$2" data-column="$3">$&</a>'; export default linkPaths = lines => lines.replace(regex, template); linkPaths.listen = parentView => parentView.on('click', '.-linked-path', function () { const el = this; let { path, line, column } = el.dataset; line = Number(line) - 1; // column number is optional column = column ? Number(column) - 1 : 0; atom.workspace.open(path, { initialLine: line, initialColumn: column, }); });
Modify utli.go writeStringColumn to overwrite existing columns
package dsbldr import ( "fmt" ) // BasicOAuthHeader spits out a basic OAuth Header based on access token func BasicOAuthHeader(consumerKey, nonce, signature, signatureMethod, timestamp, token string) string { return fmt.Sprintf(`OAuth oauth_consumer_key="%s", oauth_nonce="%s", oauth_signature="%s", oauth_signature_method="%s", oauth_timestamp="%s", oauth_token="%s`, consumerKey, nonce, signature, signatureMethod, timestamp, token) } func writeStringColumn(data *[][]string, columnName string, values []string) { var colIndex int for i := range (*data)[0] { // Find first empty column or column with same header to overwrite if (*data)[0][i] == "" || (*data)[0][i] == columnName { colIndex = i (*data)[0][i] = columnName break } } // Add all the values as well (remember that Builder.data is pre-allocated) for i := 1; i < len(*data); i++ { (*data)[i][colIndex] = values[i-1] } }
package dsbldr import ( "fmt" ) // BasicOAuthHeader spits out a basic OAuth Header based on access token func BasicOAuthHeader(consumerKey, nonce, signature, signatureMethod, timestamp, token string) string { return fmt.Sprintf(`OAuth oauth_consumer_key="%s", oauth_nonce="%s", oauth_signature="%s", oauth_signature_method="%s", oauth_timestamp="%s", oauth_token="%s`, consumerKey, nonce, signature, signatureMethod, timestamp, token) } func writeStringColumn(data *[][]string, columnName string, values []string) { var colIndex int for i := range (*data)[0] { // Find first empty column if (*data)[0][i] == "" { colIndex = i (*data)[0][i] = columnName break } } // Add all the values as well (remember that Builder.data is pre-allocated) for i := 1; i < len(*data); i++ { (*data)[i][colIndex] = values[i-1] } }
Add missing find_spec for import hook, to avoid issues when trying to set colormap
class MatplotlibBackendSetter(object): """ Import hook to make sure the proper Qt backend is set when importing Matplotlib. """ enabled = True def find_module(self, mod_name, pth): if self.enabled and 'matplotlib' in mod_name: self.enabled = False set_mpl_backend() def find_spec(self, name, import_path, target_module=None): pass def set_mpl_backend(): from matplotlib import rcParams, rcdefaults # standardize mpl setup rcdefaults() from glue.external.qt import is_pyqt5 if is_pyqt5(): rcParams['backend'] = 'Qt5Agg' else: rcParams['backend'] = 'Qt4Agg' # The following is a workaround for the fact that Matplotlib checks the # rcParams at import time, not at run-time. I have opened an issue with # Matplotlib here: https://github.com/matplotlib/matplotlib/issues/5513 from matplotlib import get_backend from matplotlib import backends backends.backend = get_backend()
class MatplotlibBackendSetter(object): """ Import hook to make sure the proper Qt backend is set when importing Matplotlib. """ enabled = True def find_module(self, mod_name, pth): if self.enabled and 'matplotlib' in mod_name: self.enabled = False set_mpl_backend() return def set_mpl_backend(): from matplotlib import rcParams, rcdefaults # standardize mpl setup rcdefaults() from glue.external.qt import is_pyqt5 if is_pyqt5(): rcParams['backend'] = 'Qt5Agg' else: rcParams['backend'] = 'Qt4Agg' # The following is a workaround for the fact that Matplotlib checks the # rcParams at import time, not at run-time. I have opened an issue with # Matplotlib here: https://github.com/matplotlib/matplotlib/issues/5513 from matplotlib import get_backend from matplotlib import backends backends.backend = get_backend()
Improve performance of Skeleton func
//go:generate go run maketables.go > tables.go package confusables import ( "bytes" "golang.org/x/text/unicode/norm" ) // TODO: document casefolding approaches // (suggest to force casefold strings; explain how to catch paypal - pAypal) // TODO: DOC you might want to store the Skeleton and check against it later // TODO: implement xidmodifications.txt restricted characters func mapConfusableRunes(ss string) string { var buffer bytes.Buffer for _, r := range ss { replacement, replacementExists := confusablesMap[r] if replacementExists { buffer.WriteString(replacement) } else { buffer.WriteRune(r) } } return buffer.String() } // Skeleton converts a string to it's "skeleton" form // as descibed in http://www.unicode.org/reports/tr39/#Confusable_Detection // 1. Converting X to NFD format // 2. Successively mapping each source character in X to the target string // according to the specified data table // 3. Reapplying NFD func Skeleton(s string) string { return norm.NFD.String( mapConfusableRunes( norm.NFD.String(s))) } func Confusable(x, y string) bool { return Skeleton(x) == Skeleton(y) }
//go:generate go run maketables.go > tables.go package confusables import ( "unicode/utf8" "golang.org/x/text/unicode/norm" ) // TODO: document casefolding approaches // (suggest to force casefold strings; explain how to catch paypal - pAypal) // TODO: DOC you might want to store the Skeleton and check against it later // TODO: implement xidmodifications.txt restricted characters // Skeleton converts a string to it's "skeleton" form // as descibed in http://www.unicode.org/reports/tr39/#Confusable_Detection func Skeleton(s string) string { // 1. Converting X to NFD format s = norm.NFD.String(s) // 2. Successively mapping each source character in X to the target string // according to the specified data table for i, w := 0, 0; i < len(s); i += w { char, width := utf8.DecodeRuneInString(s[i:]) replacement, exists := confusablesMap[char] if exists { s = s[:i] + replacement + s[i+width:] w = len(replacement) } else { w = width } } // 3. Reapplying NFD s = norm.NFD.String(s) return s } func Confusable(x, y string) bool { return Skeleton(x) == Skeleton(y) }
Fix new form confirm code @atfornes please note that this code is common for the + buttons of project and community Fixes #249
'use strict'; angular.module('Teem') .factory('NewForm', [ '$location', '$window', '$rootScope', function($location, $window, $rootScope) { var scope, objectName, scopeFn = { isNew () { return $location.search().form === 'new'; }, cancelNew () { scope[objectName].delete(); $location.search('form', undefined); $window.history.back(); }, confirmNew () { $location.search('form', undefined); // TODO fix with community invite if (objectName === 'project') { scope.invite.selected.forEach(function(i){ scope.project.addContributor(i); }); } $rootScope.$broadcast('teem.' + objectName + '.join'); } }; function initialize(s, o) { scope = s; objectName = o; Object.assign(scope, scopeFn); } return { initialize }; }]);
'use strict'; angular.module('Teem') .factory('NewForm', [ '$location', '$window', '$rootScope', function($location, $window, $rootScope) { var scope, objectName, scopeFn = { isNew () { return $location.search().form === 'new'; }, cancelNew () { scope[objectName].delete(); $location.search('form', undefined); $window.history.back(); }, confirmNew () { $location.search('form', undefined); scope.invite.selected.forEach(function(i){ scope.project.addContributor(i); }); $rootScope.$broadcast('teem.project.join'); } }; function initialize(s, o) { scope = s; objectName = o; Object.assign(scope, scopeFn); } return { initialize }; }]);
Use let in the detect test suite
'use strict'; let bluebird = require('bluebird'); let fs = bluebird.promisifyAll(require('fs')); let hljs = require('../../build'); let path = require('path'); let utility = require('../utility'); function testAutoDetection(language) { let languagePath = utility.buildPath('detect', language); it(`should have test for ${language}`, function() { return fs.statAsync(languagePath) .then(path => path.isDirectory().should.be.true); }); it(`should be detected as ${language}`, function() { return fs.readdirAsync(languagePath) .map(function(example) { let filename = path.join(languagePath, example); return fs.readFileAsync(filename, 'utf-8'); }) .each(function(content) { let expected = language, actual = hljs.highlightAuto(content).language; actual.should.equal(expected); }); }); } describe('hljs.highlightAuto()', function() { let languages = hljs.listLanguages(); languages.forEach(testAutoDetection); });
'use strict'; var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testAutoDetection(language) { var languagePath = utility.buildPath('detect', language); it(`should have test for ${language}`, function() { return fs.statAsync(languagePath) .then(path => path.isDirectory().should.be.true); }); it(`should be detected as ${language}`, function() { return fs.readdirAsync(languagePath) .map(function(example) { var filename = path.join(languagePath, example); return fs.readFileAsync(filename, 'utf-8'); }) .each(function(content) { var expected = language, actual = hljs.highlightAuto(content).language; actual.should.equal(expected); }); }); } describe('hljs.highlightAuto()', function() { var languages = hljs.listLanguages(); languages.forEach(testAutoDetection); });
Remove path attribute from PostMapping
package nl.ekholabs.nlp.controller; import java.io.IOException; import nl.ekholabs.nlp.model.TextResponse; import nl.ekholabs.nlp.service.SpeechToTextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; @RestController public class SpeechToTextController { private final SpeechToTextService speechToTextService; @Autowired public SpeechToTextController(final SpeechToTextService speechToTextService) { this.speechToTextService = speechToTextService; } @PostMapping(produces = APPLICATION_JSON_UTF8_VALUE, consumes = MULTIPART_FORM_DATA_VALUE) public TextResponse process(final @RequestParam(value = "input") MultipartFile fileToProcess) throws IOException { final String outputText = speechToTextService.processSpeech(fileToProcess.getBytes()); return new TextResponse(outputText); } }
package nl.ekholabs.nlp.controller; import java.io.IOException; import nl.ekholabs.nlp.model.TextResponse; import nl.ekholabs.nlp.service.SpeechToTextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; @RestController public class SpeechToTextController { private final SpeechToTextService speechToTextService; @Autowired public SpeechToTextController(final SpeechToTextService speechToTextService) { this.speechToTextService = speechToTextService; } @PostMapping(path = "/", produces = APPLICATION_JSON_UTF8_VALUE, consumes = MULTIPART_FORM_DATA_VALUE) public TextResponse process(final @RequestParam(value = "input") MultipartFile fileToProcess) throws IOException { final String outputText = speechToTextService.processSpeech(fileToProcess.getBytes()); return new TextResponse(outputText); } }
Reorder the flag checks so version can be shown
#!/usr/bin/env node var oust = require('../index'); var pkg = require('../package.json'); var fs = require('fs'); var argv = require('minimist')(process.argv.slice(2)); var printHelp = function() { console.log([ 'oust', pkg.description, '', 'Usage:', ' $ oust <filename> <type>' ].join('\n')); }; if(argv.v || argv.version) { console.log(pkg.version); return; } if(argv.h || argv.help || argv._.length === 0) { printHelp(); return; } var file = argv._[0]; var type = argv._[1]; fs.readFile(file, function(err, data) { if(err) { console.error('Error opening file:', err.message); process.exit(1); } var res = oust(data, type); console.log(res.join('\n')); });
#!/usr/bin/env node var oust = require('../index'); var pkg = require('../package.json'); var fs = require('fs'); var argv = require('minimist')(process.argv.slice(2)); var printHelp = function() { console.log([ 'oust', pkg.description, '', 'Usage:', ' $ oust <filename> <type>' ].join('\n')); }; if(argv.h || argv.help || argv._.length === 0) { printHelp(); return; } if(argv.v || argv.version) { console.log(pkg.version); return; } var file = argv._[0]; var type = argv._[1]; fs.readFile(file, function(err, data) { if(err) { console.error('Error opening file:', err.message); process.exit(1); } var res = oust(data, type); console.log(res.join('\n')); });
Add validation rule for status_code
"use strict"; const valid_uri = require("valid-url").isUri; const mongoose = require("mongoose"); mongoose.Promise = global.Promise; const Schema = mongoose.Schema; module.exports = mongoose.model("Shortlink", new Schema({ path: { type: String, required: true, minlength: 1, index: true, unique: true }, url: { type: String, required: true, validate: { validator: (v) => { return (valid_uri(v) !== undefined); }, message: "{VALUE} is not a valid URI" } }, created: { type: Date, default: Date.now }, updated: { type: Date, default: Date.now }, status_code: { type: Number, validate: { validator: (v) => { return (!isNaN(parseFloat(v)) && isFinite(v)); }, message: "{VALUE} must be a valid http status code (i.e. a number)" }, default: 301 } }));
"use strict"; const valid_uri = require("valid-url").isUri; const mongoose = require("mongoose"); mongoose.Promise = global.Promise; const Schema = mongoose.Schema; module.exports = mongoose.model("Shortlink", new Schema({ path: { type: String, required: true, minlength: 1, index: true, unique: true }, url: { type: String, required: true, validate: { validator: (v) => { return (valid_uri(v) !== undefined); }, message: "{VALUE} is not a valid URI" } }, created: { type: Date, default: Date.now }, updated: { type: Date, default: Date.now }, status_code: { type: Number, default: 301 } }));
Remove not used extConfig setting this gets changed few lines below and defined class doesn't even exist.
<?php class Kwc_Advanced_IntegratorTemplate_Component extends Kwc_Abstract { public static function getSettings($param = null) { $ret = parent::getSettings($param); $ret['componentName'] = trlKwfStatic('Integrator Template'); $ret['dataClass'] = 'Kwc_Advanced_IntegratorTemplate_Data'; $ret['ownModel'] = 'Kwf_Component_FieldModel'; $ret['generators']['embed'] = array( 'class' => 'Kwf_Component_Generator_Page_Static', 'component' => 'Kwc_Advanced_IntegratorTemplate_Embed_Component', 'name' => '', 'filename' => 'embed' ); $ret['extConfig'] = 'Kwf_Component_Abstract_ExtConfig_Form'; $ret['flags']['noIndex'] = true; $ret['editComponents'] = array('embed'); return $ret; } }
<?php class Kwc_Advanced_IntegratorTemplate_Component extends Kwc_Abstract { public static function getSettings($param = null) { $ret = parent::getSettings($param); $ret['componentName'] = trlKwfStatic('Integrator Template'); $ret['dataClass'] = 'Kwc_Advanced_IntegratorTemplate_Data'; $ret['ownModel'] = 'Kwf_Component_FieldModel'; $ret['extConfig'] = 'Kwc_Advanced_IntegratorTemplate_ExtConfig'; $ret['generators']['embed'] = array( 'class' => 'Kwf_Component_Generator_Page_Static', 'component' => 'Kwc_Advanced_IntegratorTemplate_Embed_Component', 'name' => '', 'filename' => 'embed' ); $ret['extConfig'] = 'Kwf_Component_Abstract_ExtConfig_Form'; $ret['flags']['noIndex'] = true; $ret['editComponents'] = array('embed'); return $ret; } }
Increase quality of (default) figure image.
<?php snippet_detect('html_head', array( 'criticalcss' => false, 'prev_next' => false, 'prerender' => false )); ?> <?php snippet('banner'); ?> <main role="main" class="Contain Copy"> <h1><?php echo $page->title()->smartypants()->widont(); ?></h1> <?php echo figure($page->images()->first(), array( 'crop' => true, 'cropratio' => '1/2', 'quality' => 78, 'caption' => 'This is an image defined in the template, from the figure plugin.', 'alt' => 'Alt text defined in template' )); ?> <?php echo $page->intro()->kirbytext(); ?> <?php echo $page->text()->kirbytext(); ?> <?php snippet('share_page'); ?> </main> <?php snippet_detect('footer'); ?>
<?php snippet_detect('html_head', array( 'criticalcss' => false, 'prev_next' => false, 'prerender' => false )); ?> <?php snippet('banner'); ?> <main role="main" class="Contain Copy"> <h1><?php echo $page->title()->smartypants()->widont(); ?></h1> <?php echo figure($page->images()->first(), array( 'crop' => true, 'cropratio' => '1/2', 'quality' => 40, 'caption' => 'This is an image defined in the template, from the figure plugin.', 'alt' => 'Alt text defined in template' )); ?> <?php echo $page->intro()->kirbytext(); ?> <?php echo $page->text()->kirbytext(); ?> <?php snippet('share_page'); ?> </main> <?php snippet_detect('footer'); ?>
Remove todo, 1.8 can use 40 symbols scoreboard score names.
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_8__1_9_r1__1_9_r2; import java.io.IOException; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleScoreboardScore; import protocolsupport.protocol.packet.middleimpl.PacketData; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class ScoreboardScore extends MiddleScoreboardScore<RecyclableCollection<PacketData>> { @Override public RecyclableCollection<PacketData> toData(ProtocolVersion version) throws IOException { PacketData serializer = PacketData.create(ClientBoundPacket.PLAY_SCOREBOARD_SCORE_ID, version); serializer.writeString(name); serializer.writeByte(mode); serializer.writeString(objectiveName); if (mode != 1) { serializer.writeVarInt(value); } return RecyclableSingletonList.create(serializer); } }
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_8__1_9_r1__1_9_r2; import java.io.IOException; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleScoreboardScore; import protocolsupport.protocol.packet.middleimpl.PacketData; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class ScoreboardScore extends MiddleScoreboardScore<RecyclableCollection<PacketData>> { @Override public RecyclableCollection<PacketData> toData(ProtocolVersion version) throws IOException { PacketData serializer = PacketData.create(ClientBoundPacket.PLAY_SCOREBOARD_SCORE_ID, version); serializer.writeString(name); //TODO: check if 1.8 could use 40 symbol name serializer.writeByte(mode); serializer.writeString(objectiveName); if (mode != 1) { serializer.writeVarInt(value); } return RecyclableSingletonList.create(serializer); } }