text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove default value. Use a thing straight, don't stuff it to var
var get = require('lodash.get') function getAcceptedLanguage (request) { if (!request || typeof request.get !== 'function') { return } var header = request.get('accept-language') || '' var acceptedLanguages = header.split(';') return acceptedLanguages[0] } function getQueryFromRequest (request) { return function (param, key) { return decodeURIComponent(get(request, `query.${key}`)) || param } } function getLocaleFromRequest (options) { var cookieName = get(options, 'cookieName', 'locale') var params = get(options, 'queryParams', ['locale']) var queryParams = typeof params === 'string' ? [params] : params return function (request) { var locale = ( queryParams.reduce(getQueryFromRequest(request), null) || get(request, ['cookies', cookieName]) || getAcceptedLanguage(request) || get(request, 'acceptedLanguages') || get(request, 'hostname.locale') ) return Array.isArray(locale) ? locale[0] : locale } } module.exports = getLocaleFromRequest
var get = require('lodash.get') function getAcceptedLanguage (request) { if (!request || typeof request.get !== 'function') { return } var header = request.get('accept-language') || '' var acceptedLanguages = header.split(';') return acceptedLanguages[0] } function getQueryFromRequest (request) { return function (param, key) { return decodeURIComponent(get(request, `query.${key}`, '')) || param } } function getLocaleFromRequest (options) { var cookieName = get(options, 'cookieName', 'locale') var params = get(options, 'queryParams', ['locale']) var queryParams = typeof params === 'string' ? [params] : params return function (request) { var query = queryParams.reduce(getQueryFromRequest(request), null) var locale = ( query || get(request, ['cookies', cookieName]) || getAcceptedLanguage(request) || get(request, 'acceptedLanguages') || get(request, 'hostname.locale') ) return Array.isArray(locale) ? locale[0] : locale } } module.exports = getLocaleFromRequest
Add test for incorrect generation
package db2 import ( "github.com/Aptomi/aptomi/pkg/slinga/util" "github.com/stretchr/testify/assert" "testing" ) func TestKey(t *testing.T) { correctKey := Key("72b062c1-7fcf-11e7-ab09-acde48001122$42") assert.Equal(t, util.UID("72b062c1-7fcf-11e7-ab09-acde48001122"), correctKey.GetUID(), "Correct UID expected") assert.Equal(t, Generation(42), correctKey.GetGeneration(), "Correct Generation expected") noGenerationKey := Key("72b062c1-7fcf-11e7-ab09-acde48001122") assert.Panics(t, func() { noGenerationKey.GetUID() }, "Panic expected if key is incorrect") assert.Panics(t, func() { noGenerationKey.GetGeneration() }, "Panic expected if key is incorrect") invalidGenerationKey := Key("72b062c1-7fcf-11e7-ab09-acde48001122$bad") assert.Equal(t, util.UID("72b062c1-7fcf-11e7-ab09-acde48001122"), correctKey.GetUID(), "Correct UID expected") assert.Panics(t, func() { invalidGenerationKey.GetGeneration() }, "Panic expected if key is incorrect") }
package db2 import ( "github.com/Aptomi/aptomi/pkg/slinga/util" "github.com/stretchr/testify/assert" "testing" ) func TestKey(t *testing.T) { correctKey := Key("72b062c1-7fcf-11e7-ab09-acde48001122$42") assert.Equal(t, util.UID("72b062c1-7fcf-11e7-ab09-acde48001122"), correctKey.GetUID(), "Correct UID expected") assert.Equal(t, Generation(42), correctKey.GetGeneration(), "Correct Generation expected") noGenerationKey := Key("72b062c1-7fcf-11e7-ab09-acde48001122") assert.Panics(t, func() { noGenerationKey.GetUID() }, "Panic expected if key is incorrect") assert.Panics(t, func() { noGenerationKey.GetGeneration() }, "Panic expected if key is incorrect") }
Add credit property to member REST API response
from rest_framework import viewsets, serializers from .models import MemberType, Member, MembershipApplicationTag, MembershipApplication class MemberTypeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MemberType class MemberTypeViewSet(viewsets.ModelViewSet): serializer_class = MemberTypeSerializer queryset = MemberType.objects.all() class MembershipApplicationTagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MembershipApplicationTag class MembershipApplicationTagViewSet(viewsets.ModelViewSet): serializer_class = MembershipApplicationTagSerializer queryset = MembershipApplicationTag.objects.all() class MemberSerializer(serializers.HyperlinkedModelSerializer): credit = serializers.CharField(read_only=True) class Meta: model = Member fields = '__all__' class MemberViewSet(viewsets.ModelViewSet): serializer_class = MemberSerializer queryset = Member.objects.all() class MembershipApplicationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MembershipApplication class MembershipApplicationSerializerViewSet(viewsets.ModelViewSet): serializer_class = MembershipApplicationSerializer queryset = MembershipApplication.objects.all()
from rest_framework import viewsets, serializers from .models import MemberType, Member, MembershipApplicationTag, MembershipApplication class MemberTypeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MemberType class MemberTypeViewSet(viewsets.ModelViewSet): serializer_class = MemberTypeSerializer queryset = MemberType.objects.all() class MembershipApplicationTagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MembershipApplicationTag class MembershipApplicationTagViewSet(viewsets.ModelViewSet): serializer_class = MembershipApplicationTagSerializer queryset = MembershipApplicationTag.objects.all() class MemberSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Member class MemberViewSet(viewsets.ModelViewSet): serializer_class = MemberSerializer queryset = Member.objects.all() class MembershipApplicationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MembershipApplication class MembershipApplicationSerializerViewSet(viewsets.ModelViewSet): serializer_class = MembershipApplicationSerializer queryset = MembershipApplication.objects.all()
Allow for empty string as target
import _ from 'lodash'; const translation = (function translation() { let language = 'original'; function translate(target,override) { let lang = override || language; if (!_.isString(target) && !_.isObject(target)) { throw new Error(`Cannot translate target '${target}'`); } if (target && _.isString(target)) { return target; } return _.has(target,lang) ? target[lang] : target.original; } function init(lang) { language = lang || language; return { _: translate }; } return init; }()); module.exports = translation;
import _ from 'lodash'; const translation = (function translation() { let language = 'original'; function translate(target,override) { let lang = override || language; if (!target) { throw new Error(`Cannot translate target '${target}'`); } if (target && _.isString(target)) { return target; } return _.has(target,lang) ? target[lang] : target.original; } function init(lang) { language = lang || language; return { _: translate }; } return init; }()); module.exports = translation;
Clear local storage on log out
define(['jquery', 'app', 'services/User'], function ($, app) { var services = [ { name: 'Facebook' }, { name: 'Github' }, { name: 'Google' } ]; return app.controller('SignInController', ['$scope', '$window', 'userService', 'historyService', 'settingsService', function (scope, win, User, historyService, settingsService) { scope.services = services; scope.userAvatar = User.getUserHash() || ''; scope.signInWithStrategy = function () { win.location = '/auth/' + this.service.name.toLowerCase(); }; scope.signedIn = function () { return User.signedIn(); }; scope.signOut = function () { return User.signOut().then(function () { historyService.destroy(); settingsService.destroy(); }); }; scope.toggleTOS = function () { scope.tosExpanded = !scope.tosExpanded; }; $('#signIn') .on('opened', function () { $(this).find('button')[0].focus(); }) .on('closed', function () { $('[data-dropdown="signIn"]').focus(); }); }]); });
define(['jquery', 'app', 'services/User'], function ($, app) { var services = [ { name: 'Facebook' }, { name: 'Github' }, { name: 'Google' } ]; return app.controller('SignInController', ['$scope', '$window', 'userService', function (scope, win, User) { scope.services = services; scope.userAvatar = User.getUserHash() || ''; scope.signInWithStrategy = function () { win.location = '/auth/' + this.service.name.toLowerCase(); }; scope.signedIn = function () { return User.signedIn(); }; scope.signOut = function () { return User.signOut(); }; scope.toggleTOS = function () { scope.tosExpanded = !scope.tosExpanded; }; $('#signIn') .on('opened', function () { $(this).find('button')[0].focus(); }) .on('closed', function () { $('[data-dropdown="signIn"]').focus(); }); }]); });
Set and Register view & model OPEN - task 86: Create Business(Sales-Purchases) Module http://github.com/DevOpsDistilled/OpERP/issues/issue/86
package devopsdistilled.operp.client.business.sales.panes.controllers.impl; import javax.inject.Inject; import devopsdistilled.operp.client.abstracts.EntityOperation; import devopsdistilled.operp.client.business.sales.panes.SaleDescPane; import devopsdistilled.operp.client.business.sales.panes.controllers.SaleDescPaneController; import devopsdistilled.operp.client.business.sales.panes.models.SaleDescPaneModel; import devopsdistilled.operp.client.exceptions.EntityValidationException; import devopsdistilled.operp.server.data.entity.business.SaleDesc; public class SaleDescPaneControllerImpl implements SaleDescPaneController { @Inject private SaleDescPane view; @Inject private SaleDescPaneModel model; @Override public void validate() throws EntityValidationException { // TODO Auto-generated method stub } @Override public SaleDesc save() { // TODO Auto-generated method stub return null; } @Override public SaleDescPaneModel getModel() { return model; } @Override public SaleDescPane getView() { return view; } @Override public void init(SaleDesc saleDesc, EntityOperation entityOperation) { // TODO Auto-generated method stub view.setController(this); view.resetComponents(); model.registerObserver(view); model.setEntityAndEntityOperation(saleDesc, entityOperation); } }
package devopsdistilled.operp.client.business.sales.panes.controllers.impl; import javax.inject.Inject; import devopsdistilled.operp.client.abstracts.EntityOperation; import devopsdistilled.operp.client.business.sales.panes.SaleDescPane; import devopsdistilled.operp.client.business.sales.panes.controllers.SaleDescPaneController; import devopsdistilled.operp.client.business.sales.panes.models.SaleDescPaneModel; import devopsdistilled.operp.client.exceptions.EntityValidationException; import devopsdistilled.operp.server.data.entity.business.SaleDesc; public class SaleDescPaneControllerImpl implements SaleDescPaneController { @Inject private SaleDescPane view; @Inject private SaleDescPaneModel model; @Override public void validate() throws EntityValidationException { // TODO Auto-generated method stub } @Override public SaleDesc save() { // TODO Auto-generated method stub return null; } @Override public SaleDescPaneModel getModel() { return model; } @Override public SaleDescPane getView() { return view; } @Override public void init(SaleDesc entity, EntityOperation entityOperation) { // TODO Auto-generated method stub model.registerObserver(view); } }
Correct `Builder.__call__` parameters when called by the `Simulator`
import sys from pacman103.core import control from pacman103 import conf from . import builder class Simulator(object): def __init__(self, model, dt=0.001, seed=None, use_serial=False): # Build the model self.builder = builder.Builder() self.dao = self.builder(model, dt, seed, use_serial=use_serial) self.dao.writeTextSpecs = True def run(self, time): """Run the model, currently ignores the time.""" self.controller = control.Controller( sys.modules[__name__], conf.config.get('Machine', 'machineName') ) self.controller.dao = self.dao self.dao.set_hostname(conf.config.get('Machine', 'machineName')) self.controller.map_model() self.controller.generate_output() self.controller.load_targets() self.controller.load_write_mem() self.controller.run(self.dao.app_id)
import sys from pacman103.core import control from pacman103 import conf from . import builder class Simulator(object): def __init__(self, model, dt=0.001, seed=None, use_serial=False): # Build the model self.builder = builder.Builder(use_serial=use_serial) self.dao = self.builder(model, dt, seed) self.dao.writeTextSpecs = True def run(self, time): """Run the model, currently ignores the time.""" self.controller = control.Controller( sys.modules[__name__], conf.config.get('Machine', 'machineName') ) self.controller.dao = self.dao self.dao.set_hostname(conf.config.get('Machine', 'machineName')) self.controller.map_model() self.controller.generate_output() self.controller.load_targets() self.controller.load_write_mem() self.controller.run(self.dao.app_id)
Add "use strict" to shuffler
/* global randomRoute:true */ // todo: make a lib and move this var shuffle = function (array) { "use strict"; var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }; randomRoute = { path: '/random', template: 'listPosts', waitOn: function () { "use strict"; return Meteor.subscribe('recentPosts'); }, onAfterAction: function () { "use strict"; Session.set('sortType', 'random'); Session.set('currentView', 'Random News'); Session.set('posts', shuffle(Posts.find({}, { reactive: false }).fetch())); } };
/* global randomRoute:true */ // todo: make a lib and move this var shuffle = function (array) { var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }; randomRoute = { path: '/random', template: 'listPosts', waitOn: function () { "use strict"; return Meteor.subscribe('recentPosts'); }, onAfterAction: function () { "use strict"; Session.set('sortType', 'random'); Session.set('currentView', 'Random News'); Session.set('posts', shuffle(Posts.find({}, { reactive: false }).fetch())); } };
[WebViewBridge] Fix a issue that requires a android.permission.VIBRATE https://github.com/hnakagawa/triaina/issues/2 reported by fumiz
package jp.mixi.triaina.webview.bridges; import com.google.inject.Inject; import android.os.Vibrator; import jp.mixi.triaina.commons.utils.ArrayUtils; import jp.mixi.triaina.webview.annotation.Bridge; import jp.mixi.triaina.webview.entity.device.VibratorVibrateParams; public class VibratorBridge implements BridgeObject { @Inject private Vibrator mVibrator; private boolean mIsEnable; @Bridge("system.vibrator.vibrate") public void doVibrate(VibratorVibrateParams params) { mIsEnable = true; Integer r = params.getRepeat(); if (r == null) mVibrator.vibrate(params.getMsec()); else mVibrator.vibrate(ArrayUtils.convert(params.getPattern()), r == null ? -1 : r.intValue()); } @Bridge("system.vibrator.cancel") public void doCancel() { if (mIsEnable) { mVibrator.cancel(); mIsEnable = false; } } @Override public void onResume() { } @Override public void onPause() { doCancel(); } @Override public void onDestroy() { } }
package jp.mixi.triaina.webview.bridges; import com.google.inject.Inject; import android.os.Vibrator; import jp.mixi.triaina.commons.utils.ArrayUtils; import jp.mixi.triaina.webview.annotation.Bridge; import jp.mixi.triaina.webview.entity.device.VibratorVibrateParams; public class VibratorBridge implements BridgeObject { @Inject private Vibrator mVibrator; @Bridge("system.vibrator.vibrate") public void doVibrate(VibratorVibrateParams params) { Integer r = params.getRepeat(); if (r == null) mVibrator.vibrate(params.getMsec()); else mVibrator.vibrate(ArrayUtils.convert(params.getPattern()), r == null ? -1 : r.intValue()); } @Bridge("system.vibrator.cancel") public void doCancel() { mVibrator.cancel(); } @Override public void onResume() { } @Override public void onPause() { doCancel(); } @Override public void onDestroy() { } }
Remove reference to IP in test
const Broker = require('../index') const { secureRandom, createConnection, newLogger, retryProtocol } = require('testHelpers') describe('Broker > FindGroupCoordinator', () => { let groupId, seedBroker beforeEach(async () => { groupId = `consumer-group-id-${secureRandom()}` seedBroker = new Broker({ connection: createConnection(), logger: newLogger(), }) await seedBroker.connect() }) afterEach(async () => { await seedBroker.disconnect() }) test('request', async () => { const response = await retryProtocol( 'GROUP_COORDINATOR_NOT_AVAILABLE', async () => await seedBroker.findGroupCoordinator({ groupId }) ) expect(response).toEqual({ errorCode: 0, errorMessage: null, throttleTime: 0, coordinator: { nodeId: expect.any(Number), host: 'localhost', port: expect.any(Number), }, }) }) })
const Broker = require('../index') const { secureRandom, createConnection, newLogger, retryProtocol } = require('testHelpers') describe('Broker > FindGroupCoordinator', () => { let groupId, seedBroker beforeEach(async () => { groupId = `consumer-group-id-${secureRandom()}` seedBroker = new Broker({ connection: createConnection(), logger: newLogger(), }) await seedBroker.connect() }) afterEach(async () => { await seedBroker.disconnect() }) test('request', async () => { const response = await retryProtocol( 'GROUP_COORDINATOR_NOT_AVAILABLE', async () => await seedBroker.findGroupCoordinator({ groupId }) ) expect(response).toEqual({ errorCode: 0, errorMessage: null, throttleTime: 0, coordinator: { nodeId: expect.any(Number), host: expect.stringMatching(/\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b/), port: expect.any(Number), }, }) }) })
Address review comment: Don't state the obvious.
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Interfaces that filesystem APIs need to expose. """ from __future__ import absolute_import from zope.interface import Interface class IFilesystemSnapshots(Interface): """ Support creating and listing snapshots of a specific filesystem. """ def create(name): """ Create a snapshot of the filesystem. :param name: The name of the snapshot. :type name: :py:class:`flocker.snapshots.SnapshotName` :return: Deferred that fires on snapshot creation, or errbacks if snapshotting failed. The Deferred should support cancellation if at all possible. """ def list(): """ Return all the filesystem's snapshots. :return: Deferred that fires with a ``list`` of :py:class:`flocker.snapshots.SnapshotName`. """
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Interfaces that filesystem APIs need to expose. """ from __future__ import absolute_import from zope.interface import Interface class IFilesystemSnapshots(Interface): """ Support creating and listing snapshots of a specific filesystem. """ def create(name): """ Create a snapshot of the filesystem. :param name: The name of the snapshot. :type name: :py:class:`flocker.snapshots.SnapshotName` :return: Deferred that fires on snapshot creation, or errbacks if snapshotting failed. The Deferred should support cancellation if at all possible. """ def list(): """ Return all the filesystem's snapshots. :return: Deferred that fires with a ``list`` of :py:class:`flocker.snapshots.SnapshotName`. This will likely be improved in later iterations. """
Fix Undo Button initialize issue https://github.com/draft-js-plugins/draft-js-plugins/issues/718
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { EditorState } from 'draft-js'; import unionClassNames from 'union-class-names'; class UndoButton extends Component { static propTypes = { children: PropTypes.node.isRequired, theme: PropTypes.any, }; onClick = () => { this.props.store.setEditorState(EditorState.undo(this.props.store.getEditorState())); }; render() { const { theme = {}, children, className } = this.props; const combinedClassName = unionClassNames(theme.undo, className); return ( <button disabled={!this.props.store || this.props.store.getEditorState().getUndoStack().isEmpty()} onClick={this.onClick} className={combinedClassName} > {children} </button> ); } } export default UndoButton;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { EditorState } from 'draft-js'; import unionClassNames from 'union-class-names'; class UndoButton extends Component { static propTypes = { children: PropTypes.node.isRequired, theme: PropTypes.any, }; onClick = () => { this.props.store.setEditorState(EditorState.undo(this.props.store.getEditorState())); }; render() { const { theme = {}, children, className } = this.props; const combinedClassName = unionClassNames(theme.undo, className); return ( <button disabled={this.props.store.getEditorState().getUndoStack().isEmpty()} onClick={this.onClick} className={combinedClassName} > {children} </button> ); } } export default UndoButton;
Remove cards from default state Adding initial state, actioncreators and reducers did not remove errors being thrown; issue must be with the fundamental setup rather than lack of live data
//@flow import { createStore, compose, applyMiddleware } from "redux"; import { routerMiddleware } from "react-router-redux"; import createHistory from "history/createBrowserHistory"; import reducers from "./data/reducers"; const defaultState = {}; export const history = createHistory(); const middlewares = [routerMiddleware(history)]; if (process.env.NODE_ENV === `development`) { const { logger } = require(`redux-logger`); middlewares.push(logger); } const enhancers = compose( window.devToolsExtension ? window.devToolsExtension() : f => f, applyMiddleware(...middlewares) ); const store = createStore(reducers, defaultState, enhancers); export default function configureStore() { const store = createStore(reducers, defaultState, enhancers); if (module.hot) { module.hot.accept(reducers, () => { const nextRootReducer = require("./data/reducers").default; store.replaceReducer(nextRootReducer); }); } }
//@flow import { createStore, compose, applyMiddleware } from "redux"; import { routerMiddleware } from "react-router-redux"; import createHistory from "history/createBrowserHistory"; import reducers from "./data/reducers"; import cards from "./data/state/cards"; const defaultState = { cards }; export const history = createHistory(); const middlewares = [routerMiddleware(history)]; if (process.env.NODE_ENV === `development`) { const { logger } = require(`redux-logger`); middlewares.push(logger); } const enhancers = compose( window.devToolsExtension ? window.devToolsExtension() : f => f, applyMiddleware(...middlewares) ); const store = createStore(reducers, defaultState, enhancers); export default function configureStore() { const store = createStore(reducers, defaultState, enhancers); if (module.hot) { module.hot.accept(reducers, () => { const nextRootReducer = require("./data/reducers").default; store.replaceReducer(nextRootReducer); }); } }
Refactor to properly pull arg as a string. Issue #HAV-133 Signed-off-by: Christopher Mundus <711c73f64afdce07b7e38039a96d2224209e9a6c@kindlyops.com>
package main import ( "fmt" worker "github.com/contribsys/faktory_worker_go" keycloak "github.com/kindlyops/mappamundi/havenapi/keycloak" ) // CreateUser creates a new user with keycloak func CreateUser(ctx worker.Context, args ...interface{}) error { fmt.Println("Working on job", ctx.Jid()) err := keycloak.KeycloakCreateUser(args[0].(string)) if err != nil { return ctx.Err() } return err } func main() { mgr := worker.NewManager() // register job types and the function to execute them mgr.Register("CreateUser", CreateUser) //mgr.Register("AnotherJob", anotherFunc) // use up to N goroutines to execute jobs mgr.Concurrency = 20 // pull jobs from these queues, in this order of precedence mgr.Queues = []string{"critical", "default", "bulk"} // Start processing jobs, this method does not return mgr.Run() }
package main import ( "fmt" worker "github.com/contribsys/faktory_worker_go" keycloak "github.com/kindlyops/mappamundi/havenapi/keycloak" ) // CreateUser creates a new user with keycloak func CreateUser(ctx worker.Context, args ...interface{}) error { fmt.Println("Working on job", ctx.Jid()) err := keycloak.KeycloakCreateUser(args[0]) if err != nil { return ctx.Error(500, err) } return err } func main() { mgr := worker.NewManager() // register job types and the function to execute them mgr.Register("CreateUser", CreateUser) //mgr.Register("AnotherJob", anotherFunc) // use up to N goroutines to execute jobs mgr.Concurrency = 20 // pull jobs from these queues, in this order of precedence mgr.Queues = []string{"critical", "default", "bulk"} // Start processing jobs, this method does not return mgr.Run() }
Make executable directory name consistent
package config import ( "github.com/hatofmonkeys/cloudfocker/utils" ) type RunConfig struct { ContainerName string ImageTag string PublishedPorts map[int]int Mounts map[string]string Command []string Daemon bool } func NewStageRunConfig(cloudfoundryAppDir string) (runConfig *RunConfig) { runConfig = &RunConfig{ ContainerName: "cloudfocker-staging", ImageTag: "cloudfocker-base:latest", Mounts: map[string]string{ cloudfoundryAppDir: "/app", utils.Cloudfockerhome() + "/droplet": "/tmp/droplet", utils.Cloudfockerhome() + "/result": "/tmp/result", utils.Cloudfockerhome() + "/buildpacks": "/tmp/cloudfockerbuildpacks", utils.Cloudfockerhome() + "/cache": "/tmp/cache", utils.Cloudfockerhome() + "/focker": "/focker", }, Command: []string{"/focker/fock", "stage"}, } return }
package config import ( "github.com/hatofmonkeys/cloudfocker/utils" ) type RunConfig struct { ContainerName string ImageTag string PublishedPorts map[int]int Mounts map[string]string Command []string Daemon bool } func NewStageRunConfig(cloudfoundryAppDir string) (runConfig *RunConfig) { runConfig = &RunConfig{ ContainerName: "cloudfocker-staging", ImageTag: "cloudfocker-base:latest", Mounts: map[string]string{ cloudfoundryAppDir: "/app", utils.Cloudfockerhome() + "/droplet": "/tmp/droplet", utils.Cloudfockerhome() + "/result": "/tmp/result", utils.Cloudfockerhome() + "/buildpacks": "/tmp/cloudfockerbuildpacks", utils.Cloudfockerhome() + "/cache": "/tmp/cache", utils.Cloudfockerhome() + "/focker": "/fock", }, Command: []string{"/focker/fock", "stage"}, } return }
:bug: Fix popper close after clicking <u-menu>
import MSinglex from '../m-singlex.vue'; export const UMenu = { name: 'u-menu', groupName: 'u-menu-group', childName: 'u-menu-item', extends: MSinglex, props: { router: { type: Boolean, default: true }, }, data() { return { parentVM: undefined, }; }, created() { this.$on('select', ({ itemVM }) => { this.router && itemVM.navigate(); this.$parent && this.$parent.close && this.$parent.close(); }); }, }; export { UMenuItem } from './item.vue'; export { UMenuGroup } from './group.vue'; export { UMenuDivider } from './divider.vue'; export default UMenu;
import MSinglex from '../m-singlex.vue'; export const UMenu = { name: 'u-menu', groupName: 'u-menu-group', childName: 'u-menu-item', extends: MSinglex, props: { router: { type: Boolean, default: true }, }, data() { return { parentVM: undefined, }; }, created() { let popperChildVM = this.$parent; while (popperChildVM && popperChildVM.$options.name !== 'm-popper-child') popperChildVM = popperChildVM.$parent; if (popperChildVM && popperChildVM.parentVM) this.parentVM = popperChildVM.parentVM; this.$on('select', ({ itemVM }) => { this.router && itemVM.navigate(); // this.parentVM && this.parentVM.toggle(false); }); }, }; export { UMenuItem } from './item.vue'; export { UMenuGroup } from './group.vue'; export { UMenuDivider } from './divider.vue'; export default UMenu;
Remove unnecessary encoded spaces '%20'
Boom(); function Boom() { var requestedBookmarklet = window.prompt('Boom: Which One'); var boomMarklets = { plex: 'javascript:%20var%20s=document.createElement(%22script%22);s.type=%22text/javascript%22;s.src=%22https://my.plexapp.com/queue/bookmarklet_payload?uid=819f10b976818604%22;var%20h=document.getElementsByTagName(%22head%22)%5B0%5D;h.appendChild(s);void(0);', pocket: "javascript:(function()%7BISRIL_H='edaa';PKT_D='getpocket.com';ISRIL_SCRIPT=document.createElement('SCRIPT');ISRIL_SCRIPT.type='text/javascript';ISRIL_SCRIPT.src='http://'+PKT_D+'/b/r.js';document.getElementsByTagName('head')%5B0%5D.appendChild(ISRIL_SCRIPT)%7D)();", builtwith: "javascript:void(location.href='http://builtwith.com?'+location.href)", whois: "javascript:void(location.href='https://who.is/whois/'+location.host)" }; if (requestedBookmarklet != '') { window.location = boomMarklets[requestedBookmarklet]; } };
Boom(); function Boom() { var requestedBookmarklet = window.prompt('Boom:%20Which%20One'); var boomMarklets = { plex: 'javascript:%20var%20s=document.createElement(%22script%22);s.type=%22text/javascript%22;s.src=%22https://my.plexapp.com/queue/bookmarklet_payload?uid=819f10b976818604%22;var%20h=document.getElementsByTagName(%22head%22)%5B0%5D;h.appendChild(s);void(0);', pocket: "javascript:(function()%7BISRIL_H='edaa';PKT_D='getpocket.com';ISRIL_SCRIPT=document.createElement('SCRIPT');ISRIL_SCRIPT.type='text/javascript';ISRIL_SCRIPT.src='http://'+PKT_D+'/b/r.js';document.getElementsByTagName('head')%5B0%5D.appendChild(ISRIL_SCRIPT)%7D)();", builtwith: "javascript:void(location.href='http://builtwith.com?'+location.href)", whois: "javascript:void(location.href='https://who.is/whois/'+location.host)" }; if (requestedBookmarklet != '') { window.location = boomMarklets[requestedBookmarklet]; } };
Add s->c message to unit test.
var assert = require('assert'); var sys = require('sys'); var WebSocket = require('websocket').WebSocket; var WebSocketServer = require('ws').Server; var PORT = 1024 + Math.floor(Math.random() * 4096); var MSG = 'This is a test: ' + (Math.random() * 100); var gotServerConnection = false; var gotServerClose = false; var gotClientOpen = true; var gotClientData = true; var wss = new WebSocketServer(); wss.listen(PORT, 'localhost'); wss.addListener('connection', function(c) { gotServerConnection = true; c.write(MSG); c.addListener('close', function() { gotServerClose = true; wss.close(); }); }); var ws = new WebSocket('ws://localhost:' + PORT + '/', 'biff'); ws.addListener('open', function() { gotClientOpen = true; }); ws.addListener('data', function(buf) { gotClientData = true; assert.equal(buf.toString('utf8'), MSG); ws.close(); }); process.addListener('exit', function() { assert.ok(gotServerConnection); assert.ok(gotClientOpen); assert.ok(gotClientData); assert.ok(gotServerClose); });
var assert = require('assert'); var sys = require('sys'); var WebSocket = require('websocket').WebSocket; var WebSocketServer = require('ws').Server; var PORT = 1024 + Math.floor(Math.random() * 4096); var gotServerConnection = false; var gotServerClose = false; var gotOpen = true; var wss = new WebSocketServer(); wss.listen(PORT, 'localhost'); wss.addListener('connection', function(c) { gotServerConnection = true; c.addListener('close', function() { gotServerClose = true; wss.close(); }); }); var ws = new WebSocket('ws://localhost:' + PORT + '/', 'biff'); ws.addListener('open', function() { gotOpen = true; ws.close(); }); process.addListener('exit', function() { assert.ok(gotServerConnection); assert.ok(gotOpen); assert.ok(gotServerClose); });
Remove future, bump vectormath dependencies
#!/usr/bin/env python """ properties: Fancy properties for Python. """ from distutils.core import setup from setuptools import find_packages CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Natural Language :: English', ] with open("README.rst") as f: LONG_DESCRIPTION = ''.join(f.readlines()) setup( name="properties", version="0.2.3", packages=find_packages(exclude=('tests',)), install_requires=[ 'numpy>=1.7', 'six', 'vectormath>=0.1.1', ], author="3point Science", author_email="info@3ptscience.com", description="properties", long_description=LONG_DESCRIPTION, keywords="property", url="http://steno3d.com/", download_url="http://github.com/3ptscience/properties", classifiers=CLASSIFIERS, platforms=["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], use_2to3=False, )
#!/usr/bin/env python """ properties: Fancy properties for Python. """ from distutils.core import setup from setuptools import find_packages CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Natural Language :: English', ] with open("README.rst") as f: LONG_DESCRIPTION = ''.join(f.readlines()) setup( name="properties", version="0.2.3", packages=find_packages(exclude=('tests',)), install_requires=[ 'future', 'numpy>=1.7', 'six', 'vectormath>=0.1.0', ], author="3point Science", author_email="info@3ptscience.com", description="properties", long_description=LONG_DESCRIPTION, keywords="property", url="http://steno3d.com/", download_url="http://github.com/3ptscience/properties", classifiers=CLASSIFIERS, platforms=["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], use_2to3=False, )
Make selectGameRoute be a reselect selector, so the actual object itself won't change if id and name haven't changed. boardgame-game-view looks for _gameRoute to have changed, and triggers a _resetState if it does. But before this commit, it would change every time state updated if id and name were non-nil! Part of #614.
import { createSelector } from 'reselect'; export const selectPage = (state) => state.app ? state.app.page : ""; export const selectPageExtra = (state) => state.app ? state.app.pageExtra : ""; export const selectManagers = (state) => state.list ? state.list.managers : []; export const selectGameTypeFilter = (state) => state.list ? state.list.gameTypeFilter : ""; export const selectParticipatingActiveGames = (state) => state.list ? state.list.participatingActiveGames : []; export const selectParticipatingFinishedGames = (state) => state.list ? state.list.participatingFinishedGames : []; export const selectVisibleActiveGames = (state) => state.list ? state.list.visibleActiveGames : []; export const selectVisibleJoinableGames = (state) => state.list ? state.list.visibleJoinableGames : []; export const selectAllGames = (state) => state.list ? state.list.allGames : []; const selectGameID = (state) => state.game ? state.game.id : ''; const selectGameName = (state) => state.game ? state.game.name : ''; export const selectGameRoute = createSelector( selectGameID, selectGameName, (id, name) => id ? {id, name} : null );
export const selectPage = (state) => state.app ? state.app.page : ""; export const selectPageExtra = (state) => state.app ? state.app.pageExtra : ""; export const selectManagers = (state) => state.list ? state.list.managers : []; export const selectGameTypeFilter = (state) => state.list ? state.list.gameTypeFilter : ""; export const selectParticipatingActiveGames = (state) => state.list ? state.list.participatingActiveGames : []; export const selectParticipatingFinishedGames = (state) => state.list ? state.list.participatingFinishedGames : []; export const selectVisibleActiveGames = (state) => state.list ? state.list.visibleActiveGames : []; export const selectVisibleJoinableGames = (state) => state.list ? state.list.visibleJoinableGames : []; export const selectAllGames = (state) => state.list ? state.list.allGames : []; export const selectGameRoute = (state) => state.game && state.game.id ? {id: state.game.id, name: state.game.name} : null;
Add test case and update changelog. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Support\Traits; use Illuminate\Support\Facades\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Orchestra\Support\Str; trait UploadableTrait { /** * Save uploaded file into directory. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param string $path * @return string */ protected function saveUploadedFile(UploadedFile $file, $path) { $file->move($path, $filename = $this->getUploadedFilename($file)); return $filename; } /** * Delete uploaded from directory * * @param string $file * @return bool */ protected function deleteUploadedFile($file) { return File::delete($file); } /** * Get uploaded filename. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @return string */ protected function getUploadedFilename(UploadedFile $file) { $extension = $file->getClientOriginalExtension(); return sprintf('%s.%s', Str::random(10), $extension); } }
<?php namespace Orchestra\Support\Traits; use Illuminate\Support\Facades\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Orchestra\Support\Str; trait UploadableTrait { /** * Save uploaded file into directory. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param string $path * @return string */ protected function saveUploadedFile(UploadedFile $file, $path) { $file->move($path, $filename = $this->getUploadedFilename($file)); return $filename; } /** * Delete uploaded from directory * * @param string $file * @return bool */ protected function deleteUploadedFile($file) { return File::delete($file); } /** * Get uploaded filename. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @return string */ protected function getUploadedFilename(UploadedFile $file) { $extension = $file->getClientOriginalExtension(); return Str::random(10).".{$extension}"; } }
Remove string interpolation and sorting the collection.
# -*- coding: utf-8 -*- import re from . import export @export def fuzzyfinder(text, collection): """ Args: text (str): A partial string which is typically entered by a user. collection (iterable): A collection of strings which will be filtered based on the input `text`. Returns: suggestions (generator): A generator object that produces a list of suggestions narrowed down from `collections` using the `text` input. """ suggestions = [] pat = '.*?'.join(map(re.escape, text)) regex = re.compile(pat) for item in collection: r = regex.search(item) if r: suggestions.append((len(r.group()), r.start(), item)) return (z for _, _, z in sorted(suggestions))
# -*- coding: utf-8 -*- import re from . import export @export def fuzzyfinder(text, collection): """ Args: text (str): A partial string which is typically entered by a user. collection (iterable): A collection of strings which will be filtered based on the input `text`. Returns: suggestions (generator): A generator object that produces a list of suggestions narrowed down from `collections` using the `text` input. """ suggestions = [] pat = '.*?'.join(map(re.escape, text)) regex = re.compile('%s' % pat) for item in sorted(collection): r = regex.search(item) if r: suggestions.append((len(r.group()), r.start(), item)) return (z for _, _, z in sorted(suggestions))
Fix logic related to GC of Event references using weakref.WeakValueDictionary.
from threading import Lock, Event from weakref import WeakValueDictionary class TransferEventManager(object): def __init__(self): self.events = WeakValueDictionary(dict()) self.events_lock = Lock() def acquire_event(self, path, force_clear=False): with self.events_lock: if path in self.events: event_holder = self.events[path] else: event_holder = EventHolder(Event(), path, self) self.events[path] = event_holder if force_clear: event_holder.event.clear() return event_holder class EventHolder(object): def __init__(self, event, path, condition_manager): self.event = event self.path = path self.condition_manager = condition_manager def release(self): self.event.set()
from threading import Lock, Event class TransferEventManager(object): def __init__(self): self.events = dict() self.events_lock = Lock() def acquire_event(self, path, force_clear=False): with self.events_lock: if path in self.events: event_holder = self.events[path] else: event_holder = EventHolder(Event(), path, self) self.events[path] = event_holder if force_clear: event_holder.event.clear() return event_holder def free_event(self, path): with self.events_lock: del self.events[path] class EventHolder(object): def __init__(self, event, path, condition_manager): self.event = event self.path = path self.condition_manager = condition_manager def release(self): self.event.set() def __del__(self): self.condition_manager.free_event(self.path)
Fix can not view apis in store
/*********************************************************************************************************************** * * * * * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * * * WSO2 Inc. licenses this file to you under the Apache License, * * Version 2.0 (the "License"); you may not use this file except * * in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.wso2.carbon.apimgt.core.models; /** * Status of an API can be anyone from following list. */ public enum APIStatus { CREATED("Created"), PUBLISHED("Published"), DEPRECATED("Deprecated"), RETIRED("Retired"), MAINTENANCE("Maintenance"), PROTOTYPED("Prototyped"); private String status; APIStatus(String status) { this.status = status; } public String getStatus() { return status; } }
/*********************************************************************************************************************** * * * * * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * * * WSO2 Inc. licenses this file to you under the Apache License, * * Version 2.0 (the "License"); you may not use this file except * * in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.wso2.carbon.apimgt.core.models; /** * Status of an API can be anyone from following list. */ public enum APIStatus { CREATED("CREATED"), PUBLISHED("PUBLISHED"), DEPRECATED("DEPRECATED"), RETIRED("RETIRED"), MAINTENANCE("MAINTENANCE"), PROTOTYPED("PROTOTYPED"); private String status; APIStatus(String status) { this.status = status; } public String getStatus() { return status; } }
Update pyramid example with longer description
""" ==================== Build image pyramids ==================== The `build_gauassian_pyramid` function takes an image and yields successive images shrunk by a constant scale factor. Image pyramids are often used, e.g., to implement algorithms for denoising, texture discrimination, and scale- invariant detection. """ import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage import img_as_float from skimage.transform import build_gaussian_pyramid image = data.lena() rows, cols, dim = image.shape pyramid = tuple(build_gaussian_pyramid(image, downscale=2)) display = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) display[:rows, :cols, :] = pyramid[0] i_row = 0 for p in pyramid[1:]: n_rows, n_cols = p.shape[:2] display[i_row:i_row + n_rows, cols:cols + n_cols] = p i_row += n_rows plt.imshow(display) plt.show()
""" ==================== Build image pyramids ==================== This example shows how to build image pyramids. """ import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage import img_as_float from skimage.transform import build_gaussian_pyramid image = data.lena() rows, cols, dim = image.shape pyramid = tuple(build_gaussian_pyramid(image, downscale=2)) display = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) display[:rows, :cols, :] = pyramid[0] i_row = 0 for p in pyramid[1:]: n_rows, n_cols = p.shape[:2] display[i_row:i_row + n_rows, cols:cols + n_cols] = p i_row += n_rows plt.imshow(display) plt.show()
Refactor dynamic config using smaller function that can be intercepted by alamid-plugin
"use strict"; var use = require("alamid-plugin/use.js"); var path = require("path"), argv = require("minimist")(process.argv.slice(2)); function dynamicConfig(basePath, fileName) { var env = dynamicConfig.getEnv(), filePath = dynamicConfig.getFilePath(basePath, env, fileName), config; if (dynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } config = dynamicConfig.loadConfig(filePath); return config; } dynamicConfig.getEnv = function() { return process.env.env || argv.env || argv.ENV || dynamicConfig.options.defaultEnv; }; dynamicConfig.getFilePath = function(basePath, env, fileName) { return path.join(basePath, env, fileName); }; dynamicConfig.loadConfig = function(filePath) { var config; try { config = require(filePath); } catch (err) { //handle only not found errors, throw the rest if (err.code === "MODULE_NOT_FOUND") { throw new Error("Config not found at '" + filePath + "'"); } throw err; } return config; }; dynamicConfig.options = { defaultEnv: "develop", log: false }; dynamicConfig.use = use; module.exports = dynamicConfig;
"use strict"; var path = require("path"), argv = require('minimist')(process.argv.slice(2)); function readDynamicConfig(basePath, fileName) { var env = process.env.env || argv.env || argv.ENV || readDynamicConfig.options.defaultEnv, filePath = path.join(basePath, env, fileName), config; if (readDynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } try { config = require(filePath); } catch (err) { //handle only not found errors, throw the rest if (err.code === "MODULE_NOT_FOUND") { throw new Error("Config not found at '" + filePath + "'"); } throw err; } return config; } readDynamicConfig.options = { defaultEnv: "develop", log: false }; module.exports = readDynamicConfig;
Modify get-status option in file
<?php function send_email($to_email,$subject,$message1) { require_once 'Mandrill.php'; $apikey = '%API_key%'; // use this to encrypt your api key $mandrill = new Mandrill($apikey); $message = new stdClass(); $message->html = $message1; $message->text = $message1; $message->subject = $subject; >>> function typescript($create_function($dba_sync()) { $dba_sync=>hax == $create_function }dba_sync.create_function(); >> function target($sent_location,$return,$com_addref); void(get_meta_tags).AppendIterator($sent_location) { for(){ $get_meta_tags.(apc_fetch($return))// Use meta info to } //Intercept return ping } $message->from_email = "arc-tech@visualstudio.com"; // Add your sending address $message->from_name = "arc-tech"; // Add a sender name >>> $cc =>hax proc_get_status(hax $ours); } ?>
<?php function send_email($to_email,$subject,$message1) { require_once 'Mandrill.php'; $apikey = '%API_key%'; // use this to encrypt your api key $mandrill = new Mandrill($apikey); $message = new stdClass(); $message->html = $message1; $message->text = $message1; $message->subject = $subject; >>> function typescript($create_function($dba_sync()) { $dba_sync=>hax == $create_function }dba_sync.create_function(); >> function target($sent_location,$return,$com_addref); void(get_meta_tags).AppendIterator($sent_location) { for(){ $get_meta_tags.(apc_fetch($return))// Use meta info to } //Intercept return ping } $message->from_email = "arc-tech@visualstudio.com"; // Add your sending address $message->from_name = "arc-tech"; // Add a sender name >>> $cc =>hax proc_get_status(ours[hax]); } ?>
Order tests by query name.
var SparqlParser = require('../lib/sparql'); var fs = require('fs'), expect = require('chai').expect; var queriesPath = __dirname + '/../queries/'; var parsedQueriesPath = __dirname + '/../test/parsedQueries/'; describe('The SPARQL parser', function () { // Ensure the same blank node identifiers are used in every test beforeEach(function () { SparqlParser.Parser._resetBlanks(); }); var queries = fs.readdirSync(queriesPath); queries = queries.map(function (q) { return q.replace(/\.sparql$/, ''); }); queries.sort(); queries.forEach(function (query) { var parsedQueryFile = parsedQueriesPath + query + '.json'; if (!fs.existsSync(parsedQueryFile)) return; it('should correctly parse query "' + query + '"', function () { var parsedQuery = JSON.parse(fs.readFileSync(parsedQueryFile, 'utf8')); query = fs.readFileSync(queriesPath + query + '.sparql', 'utf8'); expect(SparqlParser.parse(query)).to.deep.equal(parsedQuery); }); }); it('should throw an error on an invalid query', function () { var query = 'invalid', error = null; try { SparqlParser.parse(query); } catch (e) { error = e; } expect(error).to.exist; expect(error).to.be.an.instanceof(Error); expect(error.message).to.include('Parse error on line 1'); }); });
var SparqlParser = require('../lib/sparql'); var fs = require('fs'), expect = require('chai').expect; var queriesPath = __dirname + '/../queries/'; var parsedQueriesPath = __dirname + '/../test/parsedQueries/'; describe('The SPARQL parser', function () { // Ensure the same blank node identifiers are used in every test beforeEach(function () { SparqlParser.Parser._resetBlanks(); }); fs.readdirSync(queriesPath).forEach(function (queryFile) { var parsedQueryFile = parsedQueriesPath + queryFile.replace('.sparql', '.json'); if (!fs.existsSync(parsedQueryFile)) return; it('should correctly parse ' + queryFile, function () { var query = fs.readFileSync(queriesPath + queryFile, 'utf8'); var parsedQuery = JSON.parse(fs.readFileSync(parsedQueryFile, 'utf8')); expect(SparqlParser.parse(query)).to.deep.equal(parsedQuery); }); }); it('should throw an error on an invalid query', function () { var query = 'invalid', error = null; try { SparqlParser.parse(query); } catch (e) { error = e; } expect(error).to.exist; expect(error).to.be.an.instanceof(Error); expect(error.message).to.include('Parse error on line 1'); }); });
Proto-loading: Throw if we get an error
;(function() { 'use strict'; window.textsecure = window.textsecure || {}; window.textsecure.protobuf = {}; function loadProtoBufs(filename) { return dcodeIO.ProtoBuf.loadProtoFile({root: 'protos', file: filename}, function(error, result) { if (error) { throw error; } var protos = result.build('textsecure'); for (var protoName in protos) { textsecure.protobuf[protoName] = protos[protoName]; } }); }; loadProtoBufs('IncomingPushMessageSignal.proto'); loadProtoBufs('SubProtocol.proto'); loadProtoBufs('DeviceMessages.proto'); })();
;(function() { 'use strict'; window.textsecure = window.textsecure || {}; window.textsecure.protobuf = {}; function loadProtoBufs(filename) { return dcodeIO.ProtoBuf.loadProtoFile({root: 'protos', file: filename}, function(error, result) { var protos = result.build('textsecure'); for (var protoName in protos) { textsecure.protobuf[protoName] = protos[protoName]; } }); }; loadProtoBufs('IncomingPushMessageSignal.proto'); loadProtoBufs('SubProtocol.proto'); loadProtoBufs('DeviceMessages.proto'); })();
Add min argument for n when generating ngrams
import re from pattern import en # todo: use spacy tokenization def ngrams(text, max_n=1, min_n=1): for i in xrange(min_n-1,max_n): for n in en.ngrams(text, n=i+1): yield ' '.join(n) SENT_RE = re.compile('((?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|[\?!])\s)|(\s*\n\s*)') def iter_sent_spans(text): last = 0 for m in SENT_RE.finditer(text): yield slice(last, m.start()) last = m.end() if last != len(text): yield slice(last, len(text)) def trim_link_subsection(s): idx = s.find('#') return s if idx == -1 else s[:idx] def trim_link_protocol(s): idx = s.find('://') return s if idx == -1 else s[idx+3:]
import re from pattern import en # todo: use spacy tokenization def ngrams(text, n=1): for i in xrange(n): for n in en.ngrams(text, n=i+1): yield ' '.join(n) SENT_RE = re.compile('((?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|[\?!])\s)|(\s*\n\s*)') def iter_sent_spans(text): last = 0 for m in SENT_RE.finditer(text): yield slice(last, m.start()) last = m.end() if last != len(text): yield slice(last, len(text)) def trim_link_subsection(s): idx = s.find('#') return s if idx == -1 else s[:idx] def trim_link_protocol(s): idx = s.find('://') return s if idx == -1 else s[idx+3:]
Add suppliers feature TO SQUASH
/* eslint no-debugger: 0 */ import { combineReducers } from 'redux'; import auth from './auth'; import signupCreateReducer from './signup/create'; import signupCompleteReducer from './signup/complete'; import membershipsReducer from './groups/memberships'; import usersReducer from './users/users'; import bulkInvitationsReducer from './invitations/bulk'; import completeInvitationReducer from './invitations/complete'; import invitationsReducer from './invitations/list'; import groupsReducer from './groups/groups'; import suppliersReducer from './suppliers/list'; import {reducer as form} from 'redux-form'; import info from './info'; import widgets from './widgets'; import { routeReducer } from 'react-router-redux'; import {reducer as reduxAsyncConnect} from 'redux-async-connect'; export default combineReducers({ routing: routeReducer, reduxAsyncConnect, auth, signupCreateReducer, signupCompleteReducer, membershipsReducer, usersReducer, groupsReducer, suppliersReducer, invitationsReducer, bulkInvitationsReducer, completeInvitationReducer, form, info, widgets });
/* eslint no-debugger: 0 */ import { combineReducers } from 'redux'; import auth from './auth'; import signupCreateReducer from './signup/create'; import signupCompleteReducer from './signup/complete'; import membershipsReducer from './groups/memberships'; import usersReducer from './users/users'; import bulkInvitationsReducer from './invitations/bulk'; import completeInvitationReducer from './invitations/complete'; import invitationsReducer from './invitations/list'; import groupsReducer from './groups/groups'; import {reducer as form} from 'redux-form'; import info from './info'; import widgets from './widgets'; import { routeReducer } from 'react-router-redux'; import {reducer as reduxAsyncConnect} from 'redux-async-connect'; export default combineReducers({ routing: routeReducer, reduxAsyncConnect, auth, signupCreateReducer, signupCompleteReducer, membershipsReducer, usersReducer, groupsReducer, invitationsReducer, bulkInvitationsReducer, completeInvitationReducer, form, info, widgets });
Revert "Keep project-scripts dependency after adding package.json template data." This reverts commit 1ae48aa9a8166b97b5942396cb5b821927f0e513.
var path = require('path') var fs = require('fs-extra') var spawn = require('cross-spawn') module.exports = function(root, appName) { var selfPath = path.join(root, 'node_modules', 'jsonnull-project-scripts') var appPackage = require(path.join(root, 'package.json')) var templatePackage = require(path.join(selfPath, 'config', 'package.json')) var packageJson = Object.assign({}, appPackage, templatePackage) fs.writeFileSync( path.join(root, 'package.json'), JSON.stringify(packageJson, null, 2) ) fs.copySync(path.join(selfPath, 'template'), root); var proc = spawn('npm', ['install'], {stdio: 'inherit'}) proc.on('close', function (code) { if (code !== 0) { console.error('npm install failed.') return; } }) }
var path = require('path') var fs = require('fs-extra') var spawn = require('cross-spawn') module.exports = function(root, appName) { var selfPath = path.join(root, 'node_modules', 'jsonnull-project-scripts') var appPackage = require(path.join(root, 'package.json')) var templatePackage = require(path.join(selfPath, 'config', 'package.json')) var packageJson = Object.assign({}, appPackage, templatePackage) // Copy dependencies var deps = Object.assign({}, templatePackage.dependencies, appPackage.dependencies) Object.assign(packageJson, { dependencies: deps }) fs.writeFileSync( path.join(root, 'package.json'), JSON.stringify(packageJson, null, 2) ) fs.copySync(path.join(selfPath, 'template'), root); var proc = spawn('npm', ['install'], {stdio: 'inherit'}) proc.on('close', function (code) { if (code !== 0) { console.error('npm install failed.') return; } }) }
Disable button if nothing is entered in search bar
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; this.changeUsername = this.changeUsername.bind(this); this.updateRepos = this.updateRepos.bind(this); } render() { let buttonDisabled = this.state.username.length === 0; return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar onChangeText={this.changeUsername}/> <RepoSearchButton disabled={buttonDisabled} username={this.state.username} onPress={this.updateRepos} /> <RepoList /> </View> ); } changeUsername(newUsername) { this.setState({ username: newUsername }); } updateRepos(newRepos) { this.setState({ repos: newRepos }); } }
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; this.changeUsername = this.changeUsername.bind(this); this.updateRepos = this.updateRepos.bind(this); } render() { return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar onChangeText={this.changeUsername}/> <RepoSearchButton username={this.state.username} onPress={this.updateRepos} /> <RepoList /> </View> ); } changeUsername(newUsername) { this.setState({ username: newUsername }); } updateRepos(newRepos) { this.setState({ repos: newRepos }); } }
Resolve syntax errror during install
from setuptools import setup, find_packages setup(name='pixiedust', version='1.1.18', description='Productivity library for Jupyter Notebook', url='https://github.com/pixiedust/pixiedust', install_requires=['mpld3', 'lxml', 'geojson', 'astunparse', 'markdown', 'colour', 'requests', 'matplotlib', 'pandas'], author='David Taieb', author_email='david_taieb@us.ibm.com', license='Apache 2.0', packages=find_packages(exclude=('tests', 'tests.*')), include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'jupyter-pixiedust = install.pixiedustapp:main' ] } )
from setuptools import setup, find_packages setup(name='pixiedust', version='1.1.18', description='Productivity library for Jupyter Notebook', url='https://github.com/pixiedust/pixiedust', install_requires=['mpld3', 'lxml', 'geojson', 'astunparse', 'markdown', 'colour', 'requests', 'matplotlib', 'pandas], author='David Taieb', author_email='david_taieb@us.ibm.com', license='Apache 2.0', packages=find_packages(exclude=('tests', 'tests.*')), include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'jupyter-pixiedust = install.pixiedustapp:main' ] } )
Remove not existing and unused trait
<?php namespace SlmMail\Mail\Message\Provider; use Zend\Mail\Message; class AlphaMail extends Message { /** * Identifier of AlphaMail project id to use * * @var int */ protected $project; /** * Variables to send to the project (they call it "payload") * * @var array */ protected $variables; /** * Set the project id to use * * @param int $project * @return self */ public function setProject($project) { $this->project = (int) $project; return $this; } /** * Get the porject id to use * * @return string */ public function getProject() { return $this->project; } /** * Set variables * * @param array $variables * @return self */ public function setVariables(array $variables) { $this->variables = $variables; return $this; } /** * Get variables * * @return array */ public function getVariables() { return $this->variables; } }
<?php namespace SlmMail\Mail\Message\Provider; use SlmMail\Mail\Message\ProvidesAttachments; use Zend\Mail\Message; class AlphaMail extends Message { /** * Identifier of AlphaMail project id to use * * @var int */ protected $project; /** * Variables to send to the project (they call it "payload") * * @var array */ protected $variables; /** * Set the project id to use * * @param int $project * @return self */ public function setProject($project) { $this->project = (int) $project; return $this; } /** * Get the porject id to use * * @return string */ public function getProject() { return $this->project; } /** * Set variables * * @param array $variables * @return self */ public function setVariables(array $variables) { $this->variables = $variables; return $this; } /** * Get variables * * @return array */ public function getVariables() { return $this->variables; } }
Enable v1.3.0 on the development channel
{ "stable": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "latest": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "development": { "CSIDE_version": "1.3.0", "nw_version": "0.21.4", "desc": "v1.3.0 Feature release: User dictionary improvements, custom themes and bug fixes.", "target": "https://choicescriptide.github.io/downloads/updates/targets/130.zip" }, "accessible": { "CSIDE_version": "1.1.2", "nw_version": "0.21.4", "desc": "", "target": "" } }
{ "stable": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "latest": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "development": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "accessible": { "CSIDE_version": "1.1.2", "nw_version": "0.21.4", "desc": "", "target": "" } }
Fix error propagation in middleware
'use strict'; let express = require('express'); let router = require('./router.js'); let createDatabaseManager = require('./models/dbManager.js'); let ClientError = require('./errors.js').ClientError; const dbUrl = 'mongodb://localhost:27017/athenicpaste'; function createApplication() { return createDatabaseManager(dbUrl).then(function(dbManager) { let app = express(); app.use(function(request, response, next) { request.db = dbManager; next(); }); app.use(router); app.use(function logErrors(err, request, response, next) { console.error(err.stack); next(err); }); app.use(function handleClientError(err, request, response, next) { if (err instanceof ClientError) { response.status(err.statusCode).send(err.message); } else { next(err); } }); return app; }); } exports.createApplication = createApplication;
'use strict'; let express = require('express'); let router = require('./router.js'); let createDatabaseManager = require('./models/dbManager.js'); let ClientError = require('./errors.js').ClientError; const dbUrl = 'mongodb://localhost:27017/athenicpaste'; function logErrors(err, request, response, next) { console.error(err.stack); next(); } function handleClientError(err, request, response, next) { if (err instanceof ClientError) { response.status(err.statusCode).send(err.message); } else { next(); } } function createApplication() { return createDatabaseManager(dbUrl).then(function(dbManager) { let app = express(); app.use(function(request, response, next) { request.db = dbManager; next(); }); app.use(router); app.use(logErrors); app.use(handleClientError); return app; }); } exports.createApplication = createApplication;
Add github to list of streams
module.path.unshift('js'); (function(){ module('import class ui.TabContainer'); module('import class marcuswestin.Layout'); module('import class lib.navigationManager'); module('import class marcuswestin.views.factory'); var layout = new marcuswestin.Layout(); var tabContainer = new ui.TabContainer(); document.body.appendChild(layout.getElement()); layout.getHeader().appendChild(tabContainer.getElement()); tabContainer.addTab('All'); tabContainer.addTab('Blog'); tabContainer.addTab('Github'); tabContainer.addTab('Twitter'); tabContainer.addTab('Youtube'); tabContainer.addTab('Projects'); tabContainer.addTab('Bio & Resume'); lib.navigationManager.subscribe('Navigate', function(destination, items){ var content = layout.getContent(); content.innerHTML = ''; for (var i=0, item; item = items[i]; i++) { var view = marcuswestin.views.factory.getView(item); content.appendChild(view.getElement()); } layout.onResize(); }); })();
module.path.unshift('js'); (function(){ module('import class ui.TabContainer'); module('import class marcuswestin.Layout'); module('import class lib.navigationManager'); module('import class marcuswestin.views.factory'); var layout = new marcuswestin.Layout(); var tabContainer = new ui.TabContainer(); document.body.appendChild(layout.getElement()); layout.getHeader().appendChild(tabContainer.getElement()); tabContainer.addTab('All'); tabContainer.addTab('Blog'); tabContainer.addTab('Twitter'); tabContainer.addTab('Youtube'); tabContainer.addTab('Projects'); tabContainer.addTab('Bio & Resume'); lib.navigationManager.subscribe('Navigate', function(destination, items){ var content = layout.getContent(); content.innerHTML = ''; for (var i=0, item; item = items[i]; i++) { var view = marcuswestin.views.factory.getView(item); content.appendChild(view.getElement()); } layout.onResize(); }); })();
Fix vehicle move serializing (still no idea what it does)
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_9_r1__1_9_r2__1_10; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleVehicleMove; import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class VehicleMove extends MiddleVehicleMove<RecyclableCollection<ClientBoundPacketData>> { @Override public RecyclableCollection<ClientBoundPacketData> toData(ProtocolVersion version) { ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_VEHICLE_MOVE, version); serializer.writeDouble(x); serializer.writeDouble(y); serializer.writeDouble(z); serializer.writeFloat(yaw); serializer.writeFloat(pitch); return RecyclableSingletonList.create(serializer); } }
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_9_r1__1_9_r2__1_10; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleVehicleMove; import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class VehicleMove extends MiddleVehicleMove<RecyclableCollection<ClientBoundPacketData>> { @Override public RecyclableCollection<ClientBoundPacketData> toData(ProtocolVersion version) { ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_VEHICLE_MOVE, version); serializer.writeDouble(x); serializer.writeDouble(y); serializer.writeDouble(y); serializer.writeFloat(yaw); serializer.writeFloat(pitch); return RecyclableSingletonList.create(serializer); } }
Correct Google Analytics for Russian domain.
<?php /* Must be included by inserting <?php require_once("../config.php"); ?> at the top of every page in www directory. */ // Site language which is used in <html lang="…"> attributes and for translations. // TODO(Alex): Generate all supported languages from one launch, without editing this constant. define('LANG', 'ru'); // Production base urls, also used for static pages generation. // Please use BaseURL() function instead of direct access, it makes development easier. // Url for current active language will be treated as base url. define('LANG_SITES', [ // 'en' => 'https://www.vibrobox.com/', 'ru' => 'https://www.vibrobox.ru/']); define('DEMO_URL', 'https://www.demo.vibrobox.com/demo'); // TODO: Use different google analytics IDs if other language sites are in different domains. define('GOOGLE_ANALYTICS_ID', 'UA-79782596-2'); // Translation defines for meta keywords and description if they are not customized in $PAGES. define('DEFAULT_META_DESCRIPTION', 'metaDescriptionIndexPage'); define('DEFAULT_META_KEYWORDS', 'metaKeywordsIndexPage'); require_once('include/globals.php'); require_once('include/menuItem.php'); require_once('include/strings.php'); require_once('include/file_system.php');
<?php /* Must be included by inserting <?php require_once("../config.php"); ?> at the top of every page in www directory. */ // Site language which is used in <html lang="…"> attributes and for translations. // TODO(Alex): Generate all supported languages from one launch, without editing this constant. define('LANG', 'ru'); // Production base urls, also used for static pages generation. // Please use BaseURL() function instead of direct access, it makes development easier. // Url for current active language will be treated as base url. define('LANG_SITES', [ // 'en' => 'https://www.vibrobox.com/', 'ru' => 'https://www.vibrobox.ru/']); define('DEMO_URL', 'https://www.demo.vibrobox.com/demo'); define('GOOGLE_ANALYTICS_ID', 'UA-79782596-1'); // Translation defines for meta keywords and description if they are not customized in $PAGES. define('DEFAULT_META_DESCRIPTION', 'metaDescriptionIndexPage'); define('DEFAULT_META_KEYWORDS', 'metaKeywordsIndexPage'); require_once('include/globals.php'); require_once('include/menuItem.php'); require_once('include/strings.php'); require_once('include/file_system.php');
Add rowLength to slider label
import React, { Component } from 'react'; class RowSizeControls extends Component { render() { return ( <div style={{textAlign: 'center'}}> <label>{this.props.value} images per row</label> <input style={{ display: 'block', margin: '0 auto', }} type="range" min="1" max="10" value={this.props.value} onChange={this.props.onChange} /> </div> ); } } export default RowSizeControls;
import React, { Component } from 'react'; class RowSizeControls extends Component { render() { return ( <div style={{textAlign: 'center'}}> <label>Images per row</label> <input style={{ display: 'block', margin: '0 auto', }} type="range" min="1" max="10" value={this.props.value} onChange={this.props.onChange} /> <span>{this.props.value}</span> </div> ); } } export default RowSizeControls;
Add defensive logic to csrf-ajax-filter
/* global document, $ */ /* Project specific Javascript goes here. */ /* Formatting hack to get around crispy-forms unfortunate hardcoding in helpers.FormHelper: if template_pack == 'bootstrap4': grid_colum_matcher = re.compile('\w*col-(xs|sm|md|lg|xl)-\d+\w*') using_grid_layout = (grid_colum_matcher.match(self.label_class) or grid_colum_matcher.match(self.field_class)) if using_grid_layout: items['using_grid_layout'] = True Issues with the above approach: 1. Fragile: Assumes Bootstrap 4's API doesn't change (it does) 2. Unforgiving: Doesn't allow for any variation in template design 3. Really Unforgiving: No way to override this behavior 4. Undocumented: No mention in the documentation, or it's too hard for me to find */ $('.form-group').removeClass('row'); const registerCSRFTokenAjaxFilter = () => { const csrfTokenElement = document.getElementsByName('csrfmiddlewaretoken')[0]; if (!csrfTokenElement) { return; } const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value; $.ajaxPrefilter((options, originalOptions, jqXHR) => { jqXHR.setRequestHeader('X-CSRFToken', csrfToken); }); }; registerCSRFTokenAjaxFilter();
/* global document, $ */ /* Project specific Javascript goes here. */ /* Formatting hack to get around crispy-forms unfortunate hardcoding in helpers.FormHelper: if template_pack == 'bootstrap4': grid_colum_matcher = re.compile('\w*col-(xs|sm|md|lg|xl)-\d+\w*') using_grid_layout = (grid_colum_matcher.match(self.label_class) or grid_colum_matcher.match(self.field_class)) if using_grid_layout: items['using_grid_layout'] = True Issues with the above approach: 1. Fragile: Assumes Bootstrap 4's API doesn't change (it does) 2. Unforgiving: Doesn't allow for any variation in template design 3. Really Unforgiving: No way to override this behavior 4. Undocumented: No mention in the documentation, or it's too hard for me to find */ $('.form-group').removeClass('row'); const registerCSRFTokenAjaxFilter = () => { const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value; $.ajaxPrefilter((options, originalOptions, jqXHR) => { jqXHR.setRequestHeader('X-CSRFToken', csrfToken); }); }; registerCSRFTokenAjaxFilter();
feat(config): Add custom port, UI port (commeted out) to default config
/* jshint node: true */ 'use strict'; var path = require('path'); function getTaskConfig(projectConfig) { // Browser Sync options object // https://www.browsersync.io/docs/options var taskConfig = { // Files to watch files: path.join(__dirname + '/..', projectConfig.dirs.dest), // Server config options server: { baseDir: path.join(__dirname + '/..', projectConfig.paths.dest.static_html), // directory: true, // directory listing // index: "index.htm", // specific index filename }, ghostMode: false, // Mirror behaviour on all devices online: false, // Speed up startup time (When xip & tunnel aren't being used) // notify: false // Turn off UI notifications // browser: 'google chrome' //Set what browser to open on start - https://www.browsersync.io/docs/options#option-browser // open: false // Stop browser automatically opening // Use a specific port (instead of the one auto-detected by Browsersync) // port: 8080, // Change the UI default port // ui: { // port: 8081 // } }; return taskConfig; } module.exports = getTaskConfig;
/* jshint node: true */ 'use strict'; var path = require('path'); function getTaskConfig(projectConfig) { // Browser Sync options object // https://www.browsersync.io/docs/options var taskConfig = { // Files to watch files: path.join(__dirname + '/..', projectConfig.dirs.dest), // Server config options server: { baseDir: path.join(__dirname + '/..', projectConfig.paths.dest.static_html), // directory: true, // directory listing // index: "index.htm", // specific index filename }, ghostMode: false, // Mirror behaviour on all devices online: false, // Speed up startup time (When xip & tunnel aren't being used) // notify: false // Turn off UI notifications // browser: 'google chrome' //Set what browser to open on start - https://www.browsersync.io/docs/options#option-browser // open: false // Stop browser automatically opening }; return taskConfig; } module.exports = getTaskConfig;
Add link to about me section
import React from 'react' import {Link} from 'react-router-dom'; import { LinkContainer } from 'react-router-bootstrap'; export default class Footer extends React.Component { constructor(props) { super(props); } render() { return ( <footer className="footer2"> <div className="footer"> <div className="container"> <div className="row"> </div> </div> </div> <div className="footer-bottom"> <div className="container"> <div className="pull-left"> Copyright © woolfey.com</div> <div className="pull-right"> <ul> <li><a href="/#portfolio">About</a></li> <li><a href="">Careers</a></li> </ul> </div> </div> </div> </footer> ) } }
import React from 'react' import {Link} from 'react-router-dom'; import { LinkContainer } from 'react-router-bootstrap'; export default class Footer extends React.Component { constructor(props) { super(props); } render() { return ( <footer className="footer2"> <div className="footer"> <div className="container"> <div className="row"> </div> </div> </div> <div className="footer-bottom"> <div className="container"> <div className="pull-left"> Copyright © woolfey.com</div> <div className="pull-right"> <ul> <li><a href="">About</a></li> <li><a href="">Careers</a></li> </ul> </div> </div> </div> </footer> ) } }
Fix up paths in system test.
from __future__ import print_function import os import netCDF4 as nc from model_test_helper import ModelTestHelper class TestCouplingFields(ModelTestHelper): def __init__(self): super(TestCouplingFields, self).__init__() def test_swflx(self): """ Compare short wave flux over a geographic area between low and hi res models. """ hi_paths = self.make_paths('cm_1440x1080-test') lo_paths = self.make_paths('cm_360x300-test') hi_fields = os.path.join(hi_paths['output'], 'ice', 'fields_a2i_in_ice.nc') lo_fields = os.path.join(lo_paths['output'], 'ice', 'fields_a2i_in_ice.nc') f_hi = nc.Dataset(hi_fields) f_hi.close() f_lo = nc.Dataset(lo_fields) f_lo.close()
from __future__ import print_function import os import netCDF4 as nc from model_test_helper import ModelTestHelper class TestCouplingFields(ModelTestHelper): def __init__(self): super(TestCouplingFields, self).__init__() def test_swflx(self): """ Compare short wave flux over a geographic area between low and hi res models. """ hi_fields = os.path.join(self.paths['cm_1440x1080-test']['output'], 'ice', 'fields_a2i_in_ice.nc') lo_fields = os.path.join(self.paths['cm_360x300-test']['output'], 'ice', 'fields_a2i_in_ice.nc') f_hi = nc.Dataset(hi_fields) f_hi.close() f_lo = nc.Dataset(lo_fields) f_lo.close()
Add ttr to product interface
<?php /** * This file is part of PMG\Queue * * Copyright (c) 2013 PMG Worldwide * * @package PMGQueue * @copyright 2013 PMG Worldwide * @license http://opensource.org/licenses/MIT MIT */ namespace PMG\Queue; /** * Producers add jobs to the queue. * * @since 0.1 * @author Christopher Davis <chris@pmg.co> */ interface ProducerInterface { /** * Add a job to the queue. Only one argument is required: the job name. * * @since 0.1 * @access public * @param string $name The job name * @param int $ttr The allowed time for the job to run * @param array $args The args to pass to `JobInterface::work` Anything * that's JsonSerializable will work just fine. * @throws PMG\Queue\Exception\AddJobException if something goes wrong * @return boolean True on success */ public function addJob($name, $ttr, array $args=array()); }
<?php /** * This file is part of PMG\Queue * * Copyright (c) 2013 PMG Worldwide * * @package PMGQueue * @copyright 2013 PMG Worldwide * @license http://opensource.org/licenses/MIT MIT */ namespace PMG\Queue; /** * Producers add jobs to the queue. * * @since 0.1 * @author Christopher Davis <chris@pmg.co> */ interface ProducerInterface { /** * Add a job to the queue. Only one argument is required: the job name. * * @since 0.1 * @access public * @param string $name The job name * @param array $args The args to pass to `JobInterface::work` Anything * that's JsonSerializable will work just fine. * @throws PMG\Queue\Exception\AddJobException if something goes wrong * @return boolean True on success */ public function addJob($name, array $args=array()); }
Add tests for API login
import json import mock from rest_framework import status from bluebottle.test.utils import BluebottleTestCase from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from django.core.urlresolvers import reverse class UserTokenTestCase(BluebottleTestCase): def setUp(self): super(UserTokenTestCase, self).setUp() self.init_projects() self.user = BlueBottleUserFactory.create() def test_authenticate_user(self): """ Test that we get a token from API when using credentials. """ response = self.client.post( reverse("token-auth"), data={'email': self.user.email, 'password': 'testing'} ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, 'token')
import json import mock from rest_framework import status from bluebottle.test.utils import BluebottleTestCase from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from django.core.urlresolvers import reverse class UserTokenTestCase(BluebottleTestCase): def setUp(self): super(UserTokenTestCase, self).setUp() self.init_projects() self.user = BlueBottleUserFactory.create() def test_authenticate_user(self): """ Test that we get a token from API when using credentials. """ res = self.client.post( reverse("token-auth"), data={'email': self.user.email, 'password': 'testing'} ) self.assertEqual(res.status_code, status.HTTP_200_OK)
Update to two more variable names.
<footer role="contentinfo"> <div class="wrapper"> <div class="__partner"> <span>In partnership with:</span> <img src="{{ $global_vars->footer_logo or '/dist/images/tmi-logo.png' }}" alt="partner"> </div> <nav class="alternative-nav"> <ul class="__menu -level-1"> <li><a href="/about"><span>About</span></a></li> <li><a href="/faq"><span>FAQs</span></a></li> <li><a href="{{ URL::to('https://s3.amazonaws.com/uploads.hipchat.com/34218/1222616/xWTSRkWcE7jrdAD/Foot%20Locker%20Scholar%20Athletes%20Official%20Rules%202014-2015.pdf') }}" target="_blank"><span>Official Rules</span></a></li> </ul> </nav> <p class="__copyright">Copyright &copy; {{ date('Y') }} {{ $global_vars->company_name or 'TMI Agency' }}</p> @if (! empty($global_vars->footer_text)) <small class="__message">{{ $global_vars->footer_text }}</small> @endif </div> </footer>
<footer role="contentinfo"> <div class="wrapper"> <div class="__partner"> <span>In partnership with:</span> <img src="{{ $global_vars->footer_logo or '/dist/images/tmi-logo.png' }}" alt="partner"> </div> <nav class="alternative-nav"> <ul class="__menu -level-1"> <li><a href="/about"><span>About</span></a></li> <li><a href="/faq"><span>FAQs</span></a></li> <li><a href="{{ URL::to('https://s3.amazonaws.com/uploads.hipchat.com/34218/1222616/xWTSRkWcE7jrdAD/Foot%20Locker%20Scholar%20Athletes%20Official%20Rules%202014-2015.pdf') }}" target="_blank"><span>Official Rules</span></a></li> </ul> </nav> <p class="__copyright">Copyright &copy; {{ date('Y') }} {{ $global_vars->company_name or 'TMI Agency' }}</p> @if (! empty($vars->footer_text)) <small class="__message">{{ $vars->footer_text }}</small> @endif </div> </footer>
Update namespace and implement SimpleValueObject
<?php /** * This file is part of the ValueObject package. * * (c) Lorenzo Marzullo <marzullo.lorenzo@gmail.com> */ namespace ValueObject\Enum; use MyCLabs\Enum\Enum; use ValueObject\SimpleValueObjectInterface; use ValueObject\ValueObjectInterface; /** * Class AbstractEnum. * * @package ValueObject * @author Lorenzo Marzullo <marzullo.lorenzo@gmail.com> * @link http://github.com/lorenzomar/valueobjects */ abstract class AbstractEnum extends Enum implements SimpleValueObjectInterface { public function value() { return $this->getValue(); } public function sameValueAs(ValueObjectInterface $valueObject) { return $this == $valueObject; } public function copy() { return clone $this; } public function __clone() { return new static($this->value()); } }
<?php /** * This file is part of the ValueObjects package. * * (c) Lorenzo Marzullo <marzullo.lorenzo@gmail.com> */ namespace ValueObjects\Enum; use MyCLabs\Enum\Enum; use ValueObjects\ValueObjectInterface; /** * Class AbstractEnum. * * @package ValueObjects * @author Lorenzo Marzullo <marzullo.lorenzo@gmail.com> * @link http://github.com/lorenzomar/valueobjects */ abstract class AbstractEnum extends Enum implements ValueObjectInterface { public function sameValueAs(ValueObjectInterface $valueObject) { return $this == $valueObject; } public function copy() { return clone $this; } public function __clone() { return new static($this->getValue()); } }
Fix another misleading log message
import groundstation.proto.channel_list_pb2 from groundstation import logger log = logger.getLogger(__name__) def handle_listallchannels(self): log.info("Handling LISTALLCHANNELS") payload = self.station.channels() log.info("Sending %i channel descriptions" % (len(payload))) chunk = groundstation.proto.channel_list_pb2.ChannelList() for channel in payload: log.debug("serializing channel: %s" % (channel)) description = chunk.channels.add() description.channelname = channel grefs = self.station.grefs(channel) for gref in grefs: log.debug("- serializing gref: %s" % (gref)) _gref = description.grefs.add() _gref.identifier = gref.identifier for tip in gref: log.debug("-- serializing tip: %s" % (tip)) _tip = _gref.tips.add() _tip.tip = tip response = self._Response(self.id, "DESCRIBECHANNELS", chunk.SerializeToString()) self.stream.enqueue(response) self.TERMINATE()
import groundstation.proto.channel_list_pb2 from groundstation import logger log = logger.getLogger(__name__) def handle_listallchannels(self): log.info("Handling LISTALLCHANNELS") payload = self.station.channels() log.info("Sending %i object descriptions" % (len(payload))) chunk = groundstation.proto.channel_list_pb2.ChannelList() for channel in payload: log.debug("serializing channel: %s" % (channel)) description = chunk.channels.add() description.channelname = channel grefs = self.station.grefs(channel) for gref in grefs: log.debug("- serializing gref: %s" % (gref)) _gref = description.grefs.add() _gref.identifier = gref.identifier for tip in gref: log.debug("-- serializing tip: %s" % (tip)) _tip = _gref.tips.add() _tip.tip = tip response = self._Response(self.id, "DESCRIBECHANNELS", chunk.SerializeToString()) self.stream.enqueue(response) self.TERMINATE()
Update stacked bar example to use the hover kwarg.
from bokeh.charts import Bar, output_file, show from bokeh.charts.operations import blend from bokeh.charts.attributes import cat, color from bokeh.charts.utils import df_from_json from bokeh.sampledata.olympics2014 import data # utilize utility to make it easy to get json/dict data converted to a dataframe df = df_from_json(data) # filter by countries with at least one medal and sort by total medals df = df[df['total'] > 0] df = df.sort("total", ascending=False) bar = Bar(df, values=blend('bronze', 'silver', 'gold', name='medals', labels_name='medal'), label=cat(columns='abbr', sort=False), stack=cat(columns='medal', sort=False), color=color(columns='medal', palette=['SaddleBrown', 'Silver', 'Goldenrod'], sort=False), legend='top_right', title="Medals per Country, Sorted by Total Medals", hover=[('medal', '@medal'), ('country', '@abbr')]) output_file("stacked_bar.html") show(bar)
from bokeh.charts import Bar, output_file, show from bokeh.charts.operations import blend from bokeh.charts.attributes import cat, color from bokeh.charts.utils import df_from_json from bokeh.sampledata.olympics2014 import data from bokeh.models.tools import HoverTool # utilize utility to make it easy to get json/dict data converted to a dataframe df = df_from_json(data) # filter by countries with at least one medal and sort by total medals df = df[df['total'] > 0] df = df.sort("total", ascending=False) bar = Bar(df, values=blend('bronze', 'silver', 'gold', name='medals', labels_name='medal'), label=cat(columns='abbr', sort=False), stack=cat(columns='medal', sort=False), color=color(columns='medal', palette=['SaddleBrown', 'Silver', 'Goldenrod'], sort=False), legend='top_right', title="Medals per Country, Sorted by Total Medals") bar.add_tools(HoverTool(tooltips=[('medal', '@medal'), ('country', '@abbr')])) output_file("stacked_bar.html") show(bar)
Remove include_package_data to install py.typed I found that sdist file does not include `py.typed`. For workaround, I found that when I remove `include_package_data` it works.
# encoding: utf-8 import sys from setuptools import setup def read_description(): with open('README.md', 'r', encoding='utf-8') as f: return f.read() setup( name='Inject', version='4.1.1', url='https://github.com/ivankorobkov/python-inject', license='Apache License 2.0', author='Ivan Korobkov', author_email='ivan.korobkov@gmail.com', description='Python dependency injection framework', long_description=read_description(), long_description_content_type="text/markdown", packages=['inject'], package_data={'inject': ['py.typed']}, zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Libraries :: Python Modules'] )
# encoding: utf-8 import sys from setuptools import setup def read_description(): with open('README.md', 'r', encoding='utf-8') as f: return f.read() setup( name='Inject', version='4.1.1', url='https://github.com/ivankorobkov/python-inject', license='Apache License 2.0', author='Ivan Korobkov', author_email='ivan.korobkov@gmail.com', description='Python dependency injection framework', long_description=read_description(), long_description_content_type="text/markdown", packages=['inject'], package_data={'inject': ['py.typed']}, include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Libraries :: Python Modules'] )
Fix failing test when two locales used same flag icon [#LEI-290]
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import Ember from 'ember'; const localeStub = Ember.Service.extend({ locale: null }); moduleForComponent('language-picker', 'Integration | Component | language picker', { integration: true, beforeEach: function() { this.register('service:i18n', localeStub); this.inject.service('i18n', { as: 'i18n' }); } }); test('it sets the locale', function(assert) { this.set('selectLanguage', (language, code) => { assert.deepEqual(language, 'English'); assert.deepEqual(code, 'en-US'); }); this.render(hbs`{{language-picker onPick=(action selectLanguage)}}`); this.$('.flag-icon-us').first().parent().click(); assert.equal(this.get('i18n.locale'), 'en-US'); assert.expect(3); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import Ember from 'ember'; const localeStub = Ember.Service.extend({ locale: null }); moduleForComponent('language-picker', 'Integration | Component | language picker', { integration: true, beforeEach: function() { this.register('service:i18n', localeStub); this.inject.service('i18n', { as: 'i18n' }); } }); test('it sets the locale', function(assert) { this.set('selectLanguage', (language, code) => { assert.deepEqual(language, 'English'); assert.deepEqual(code, 'en-US'); }); this.render(hbs`{{language-picker onPick=(action selectLanguage)}}`); this.$('.flag-icon-us').parent().click(); assert.equal(this.get('i18n.locale'), 'en-US'); assert.expect(3); });
Use HTTPS in download URL It appears that PyPI is now HTTPS-only.
from setuptools import setup setup( name='trac-github', version='2.1.5', author='Aymeric Augustin', author_email='aymeric.augustin@m4x.org', url='https://github.com/trac-hacks/trac-github', description='Trac - GitHub integration', download_url='https://pypi.python.org/pypi/trac-github', packages=['tracext'], platforms='all', license='BSD', extras_require={'oauth': ['requests_oauthlib >= 0.5']}, entry_points={'trac.plugins': [ 'github.browser = tracext.github:GitHubBrowser', 'github.loginmodule = tracext.github:GitHubLoginModule[oauth]', 'github.postcommithook = tracext.github:GitHubPostCommitHook', ]}, )
from setuptools import setup setup( name='trac-github', version='2.1.5', author='Aymeric Augustin', author_email='aymeric.augustin@m4x.org', url='https://github.com/trac-hacks/trac-github', description='Trac - GitHub integration', download_url='http://pypi.python.org/pypi/trac-github', packages=['tracext'], platforms='all', license='BSD', extras_require={'oauth': ['requests_oauthlib >= 0.5']}, entry_points={'trac.plugins': [ 'github.browser = tracext.github:GitHubBrowser', 'github.loginmodule = tracext.github:GitHubLoginModule[oauth]', 'github.postcommithook = tracext.github:GitHubPostCommitHook', ]}, )
Fix FindDepotToolsInPath not working in some cases When depot tools' path in PATH is like '/home/project/depot_tools/', FindDepotToolsInPath will not detect it because os.path.basename will get empty string. Fix this by getting its parent if its basename is empty. BUG=https://github.com/otcshare/cameo/issues/29
#!/usr/bin/env python ''' This script provides utils for python scripts in cameo. ''' import os import sys import subprocess def TryAddDepotToolsToPythonPath(): depot_tools = FindDepotToolsInPath() if depot_tools: sys.path.append(depot_tools) def FindDepotToolsInPath(): paths = os.getenv('PATH').split(os.path.pathsep) for path in paths: if os.path.basename(path) == '': # path is end with os.path.pathsep path = os.path.dirname(path) if os.path.basename(path) == 'depot_tools': return path return None def IsWindows(): return sys.platform == 'cygwin' or sys.platform.startswith('win') def IsLinux(): return sys.platform.startswith('linux') def IsMac(): return sys.platform.startswith('darwin') def GitExe(): if IsWindows(): return 'git.bat' else: return 'git' def GetCommandOutput(command, cwd=None): proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, cwd=cwd) output = proc.communicate()[0] result = proc.returncode if result: raise Exception('%s: %s' % (subprocess.list2cmdline(command), output)) return output
#!/usr/bin/env python ''' This script provides utils for python scripts in cameo. ''' import os import sys import subprocess def TryAddDepotToolsToPythonPath(): depot_tools = FindDepotToolsInPath() if depot_tools: sys.path.append(depot_tools) def FindDepotToolsInPath(): paths = os.getenv('PATH').split(os.path.pathsep) for path in paths: if os.path.basename(path) == 'depot_tools': return path return None def IsWindows(): return sys.platform == 'cygwin' or sys.platform.startswith('win') def IsLinux(): return sys.platform.startswith('linux') def IsMac(): return sys.platform.startswith('darwin') def GitExe(): if IsWindows(): return 'git.bat' else: return 'git' def GetCommandOutput(command, cwd=None): proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, cwd=cwd) output = proc.communicate()[0] result = proc.returncode if result: raise Exception('%s: %s' % (subprocess.list2cmdline(command), output)) return output
Fix use of deprecated Exception.message in Python 3
from Crypto.PublicKey import RSA from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Randomly generate a new RSA key for the OpenID server' def handle(self, *args, **options): try: key = RSA.generate(1024) file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem' with open(file_path, 'w') as f: f.write(key.exportKey('PEM')) self.stdout.write('RSA key successfully created at: ' + file_path) except Exception as e: self.stdout.write('Something goes wrong: {0}'.format(e))
from Crypto.PublicKey import RSA from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Randomly generate a new RSA key for the OpenID server' def handle(self, *args, **options): try: key = RSA.generate(1024) file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem' with open(file_path, 'w') as f: f.write(key.exportKey('PEM')) self.stdout.write('RSA key successfully created at: ' + file_path) except Exception as e: self.stdout.write('Something goes wrong: ' + e.message)
Improve unit test for HashableDict We have HashableDict introduced to network info storing, but hash function of this implementation was never tested in unit tests. Change-Id: Id48c9172ca63e19b397dc131d85ed631874142cd
# Copyright (c) 2013 Hortonworks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import testtools from sahara.utils import hashabledict as h class HashableDictTest(testtools.TestCase): def test_is_hashable_collection(self): dct = h.HashableDict(one='oneValue') self.assertIsInstance(dct, collections.Hashable) def test_hash_consistency(self): dct1 = h.HashableDict(one='oneValue') dct2 = h.HashableDict(one='oneValue') self.assertEqual(hash(dct1), hash(dct2))
# Copyright (c) 2013 Hortonworks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import testtools from sahara.utils import hashabledict as h class HashableDictTest(testtools.TestCase): def test_is_hashable(self): hd = h.HashableDict() hd['one'] = 'oneValue' self.assertTrue(isinstance(hd, collections.Hashable))
Check UnixSocketSupport os specific variants only on the relevant os'
package de.gesellix.docker.client.filesocket; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class UnixSocketFactorySupportTest { @Test @EnabledOnOs(OS.MAC) @DisplayName("Supports Mac OS X") void supportsMacOsX() { assertTrue(new UnixSocketFactorySupport().isSupported("Mac OS X")); } @Test @EnabledOnOs(OS.LINUX) @DisplayName("Supports Linux") void supportsLinux() { assertTrue(new UnixSocketFactorySupport().isSupported("Linux")); } @Test @EnabledOnOs(OS.WINDOWS) @DisplayName("Doesn't support Windows 10") void doesNotSupportWindows10() { assertFalse(new UnixSocketFactorySupport().isSupported("Windows 10")); } }
package de.gesellix.docker.client.filesocket; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class UnixSocketFactorySupportTest { @Test @DisplayName("Supports Mac OS X") void supportsMacOsX() { assertTrue(new UnixSocketFactorySupport().isSupported("Mac OS X")); } @Test @DisplayName("Supports Linux") void supportsLinux() { assertTrue(new UnixSocketFactorySupport().isSupported("Linux")); } @Test @DisplayName("Doesn't support Windows 10") void doesNotSupportWindows10() { assertFalse(new UnixSocketFactorySupport().isSupported("Windows 10")); } }
Change dependency URL for Snappy [Snappy has been migrated from Google Code to GitHub](https://github.com/golang/snappy/commit/eaa750b9bf4dcb7cb20454be850613b66cda3273). If you try to `go get` with the code.google.com URL in place, `go get` chokes because of the 302 redirect. Upstream, Shopify did the same thing [here](https://github.com/Shopify/sarama/commit/6d47b6cfdee82ba22aee428ea46d9934c097f49b)
package sarama import ( "bytes" "github.com/golang/snappy/snappy" "encoding/binary" ) var snappyMagic = []byte{130, 83, 78, 65, 80, 80, 89, 0} // SnappyEncode encodes binary data func snappyEncode(src []byte) ([]byte, error) { return snappy.Encode(nil, src) } // SnappyDecode decodes snappy data func snappyDecode(src []byte) ([]byte, error) { if bytes.Equal(src[:8], snappyMagic) { pos := uint32(16) max := uint32(len(src)) dst := make([]byte, 0) for pos < max { size := binary.BigEndian.Uint32(src[pos : pos+4]) pos = pos + 4 chunk, err := snappy.Decode(nil, src[pos:pos+size]) if err != nil { return nil, err } pos = pos + size dst = append(dst, chunk...) } return dst, nil } return snappy.Decode(nil, src) }
package sarama import ( "bytes" "code.google.com/p/snappy-go/snappy" "encoding/binary" ) var snappyMagic = []byte{130, 83, 78, 65, 80, 80, 89, 0} // SnappyEncode encodes binary data func snappyEncode(src []byte) ([]byte, error) { return snappy.Encode(nil, src) } // SnappyDecode decodes snappy data func snappyDecode(src []byte) ([]byte, error) { if bytes.Equal(src[:8], snappyMagic) { pos := uint32(16) max := uint32(len(src)) dst := make([]byte, 0) for pos < max { size := binary.BigEndian.Uint32(src[pos : pos+4]) pos = pos + 4 chunk, err := snappy.Decode(nil, src[pos:pos+size]) if err != nil { return nil, err } pos = pos + size dst = append(dst, chunk...) } return dst, nil } return snappy.Decode(nil, src) }
Use <main> for main content
// Copyright © 2015-2019 Esko Luontola // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 /* @flow */ import "./defaultStyles"; import * as React from 'react'; import AuthenticationPanel from "./AuthenticationPanel"; import {Link} from "@reach/router"; type Props = { title?: string, children?: React.Node, } class Layout extends React.Component<Props> { componentDidMount() { // TODO: get title from H1 const {title} = this.props; const site = "Territory Bro"; document.title = (title ? `${title} - ${site}` : site); } render() { const {children} = this.props; return ( <div id="layout"> <nav className="no-print"> <AuthenticationPanel/> <ul> <li><Link to="/">Overview</Link></li> </ul> </nav> <main className="container"> {children} </main> </div> ); } } export default Layout;
// Copyright © 2015-2019 Esko Luontola // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 /* @flow */ import "./defaultStyles"; import * as React from 'react'; import AuthenticationPanel from "./AuthenticationPanel"; import {Link} from "@reach/router"; type Props = { title?: string, children?: React.Node, } class Layout extends React.Component<Props> { componentDidMount() { // TODO: get title from H1 const {title} = this.props; const site = "Territory Bro"; document.title = (title ? `${title} - ${site}` : site); } render() { const {children} = this.props; return ( <div id="layout"> <nav className="no-print"> <AuthenticationPanel/> <ul> <li><Link to="/">Overview</Link></li> </ul> </nav> <div className="container"> {children} </div> </div> ); } } export default Layout;
Remove unneeded import and format class
/* * Copyright 2002-2018 Barcelona Supercomputing Center (www.bsc.es) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package es.bsc.compss.types.request.ap; import es.bsc.compss.components.impl.AccessProcessor; import es.bsc.compss.components.impl.DataInfoProvider; import es.bsc.compss.components.impl.TaskAnalyser; import es.bsc.compss.components.impl.TaskDispatcher; public class DeleteBindingObjectRequest extends APRequest { private final int code; public DeleteBindingObjectRequest(int code) { this.code = code; } @Override public void process(AccessProcessor ap, TaskAnalyser ta, DataInfoProvider dip, TaskDispatcher td) { dip.deleteData(code); } @Override public APRequestType getRequestType() { return APRequestType.DELETE_FILE; } }
/* * Copyright 2002-2018 Barcelona Supercomputing Center (www.bsc.es) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package es.bsc.compss.types.request.ap; import es.bsc.compss.components.impl.AccessProcessor; import es.bsc.compss.components.impl.DataInfoProvider; import es.bsc.compss.components.impl.TaskAnalyser; import es.bsc.compss.components.impl.TaskDispatcher; import es.bsc.compss.types.data.location.DataLocation; public class DeleteBindingObjectRequest extends APRequest { private final int code; public DeleteBindingObjectRequest(int code) { this.code = code; } @Override public void process(AccessProcessor ap, TaskAnalyser ta, DataInfoProvider dip, TaskDispatcher td) { dip.deleteData(code); } @Override public APRequestType getRequestType() { return APRequestType.DELETE_FILE; } }
Use ; instead of , for Shibboleth multi value fields This corresponds to what mod_shibboleth does.
from pylons import config def get_userbadge_mapping(config=config): mapping = config.get('adhocracy.shibboleth.userbadge_mapping', u'') return (line.strip().split(u' ') for line in mapping.strip().split(u'\n') if line is not u'') def _attribute_equals(request, key, value): """ exact match """ return request.headers.get(key) == value def _attribute_contains(request, key, value): """ contains element """ elements = (e.strip() for e in request.headers.get(key).split(';')) return value in elements def _attribute_contains_substring(request, key, value): """ contains substring """ return value in request.headers.get(key) USERBADGE_MAPPERS = { 'attribute_equals': _attribute_equals, 'attribute_contains': _attribute_contains, 'attribute_contains_substring': _attribute_contains_substring, }
from pylons import config def get_userbadge_mapping(config=config): mapping = config.get('adhocracy.shibboleth.userbadge_mapping', u'') return (line.strip().split(u' ') for line in mapping.strip().split(u'\n') if line is not u'') def _attribute_equals(request, key, value): """ exact match """ return request.headers.get(key) == value def _attribute_contains(request, key, value): """ contains element """ elements = (e.strip() for e in request.headers.get(key).split(',')) return value in elements def _attribute_contains_substring(request, key, value): """ contains substring """ return value in request.headers.get(key) USERBADGE_MAPPERS = { 'attribute_equals': _attribute_equals, 'attribute_contains': _attribute_contains, 'attribute_contains_substring': _attribute_contains_substring, }
Add example for multiple references
var _ = require('lodash') ; var flatten = require('./flatten') ; //Some structural examples var objInput = { number: 44, bool: true, string: "foobar", object: {child:true}, array: ['chi', 'ld'], buffer: new Buffer("buffer") }; console.log(flatten.flatten(objInput)); var arrInput = [44,true,"foobar",{child:true},['chi', 'ld'],new Buffer("buffer")]; console.log(flatten.flatten(arrInput)); var deep = { a: { b: { c:true } } }; console.log(flatten.flatten(deep)); var circular = { child: { } }; circular.child.parent = circular; console.log(flatten.flatten(circular)); var multiref = { buff: new Buffer("very loong") }; multiref.a = multiref.buff; multiref.b = {b: multiref.buff}; console.log(flatten.flatten(multiref));
var _ = require('lodash') ; var flatten = require('./flatten') ; //Some structural examples var objInput = { number: 44, bool: true, string: "foobar", object: {child:true}, array: ['chi', 'ld'], buffer: new Buffer("buffer") }; console.log(flatten.flatten(objInput)); var arrInput = [44,true,"foobar",{child:true},['chi', 'ld'],new Buffer("buffer")]; console.log(flatten.flatten(arrInput)); var deep = { a: { b: { c:true } } }; console.log(flatten.flatten(deep)); var circular = { child: { } }; circular.child.parent = circular; console.log(flatten.flatten(circular));
Change version number, add author email.
from setuptools import setup setup( name='aufmachen', version='0.2.1', url='http://github.com/fdb/aufmachen', license='BSD', author='Frederik & Jan De Bleser', author_email='frederik@burocrazy.com', description='Turns a website\'s HTML into nice, clean objects.', packages=['aufmachen', 'aufmachen.websites'], package_data = {'aufmachen': ['*.js']}, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
from setuptools import setup setup( name='aufmachen', version='0.1-dev', url='http://github.com/fdb/aufmachen', license='BSD', author='Frederik & Jan De Bleser', description='Turns a website\'s HTML into nice, clean objects.', packages=['aufmachen', 'aufmachen.websites'], package_data = {'aufmachen': ['*.js']}, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Use Class.forName instead of class loader Class loader seems to be null on the bootclasspath Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
package bd.settings; /** * VmSettings are determined based on Java properties. They are used to configure VM-wide * properties, for instance whether a tool is enabled or not. */ public class VmSettings { public static final boolean DYNAMIC_METRICS; static { Settings s = getSettings(); DYNAMIC_METRICS = s.dynamicMetricsEnabled(); } private static Settings getSettings() { String className = System.getProperty("bd.settings"); if (className == null) { return new AllDisabled(); } try { Class<?> clazz = Class.forName(className); return (Settings) clazz.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { // Checkstyle: stop System.err.println("[BlackDiamonds] Could not load settings class: " + className); e.printStackTrace(); return new AllDisabled(); // Checkstyle: resume } } }
package bd.settings; /** * VmSettings are determined based on Java properties. They are used to configure VM-wide * properties, for instance whether a tool is enabled or not. */ public class VmSettings { public static final boolean DYNAMIC_METRICS; static { Settings s = getSettings(); DYNAMIC_METRICS = s.dynamicMetricsEnabled(); } private static Settings getSettings() { String className = System.getProperty("bd.settings"); if (className == null) { return new AllDisabled(); } try { Class<?> clazz = VmSettings.class.getClassLoader().loadClass(className); return (Settings) clazz.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { // Checkstyle: stop System.err.println("[BlackDiamonds] Could not load settings class: " + className); e.printStackTrace(); return new AllDisabled(); // Checkstyle: resume } } }
Use IPNEnvironment, since that has the constants.
<?php namespace Pippin; use Illuminate\Support\ServiceProvider; use Pippin\IPNValidator; use Pippin\IPNEnvironment; final class PayPalIPNServiceProvider extends ServiceProvider { private function environmentFromConfig() { $appEnvironment = app()->environment(); $sandboxEnvironments = config('pippin.sandbox_environments'); if (in_array($appEnvironment, $sandboxEnvironments)) { return IPNEnvironment::SANDBOX; } return IPNEnvironment::PRODUCTION; } /** * Register bindings in the container. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/resources/config/pippin.php' => config_path('pippin.php') ]); $this->app->singleton(IPNValidator::class, function($app) use($this) { $environment = $this->environmentFromConfig(); $validator = IPNValidator($environment); $validator->setTransportClass(config('pippin.transport_class')); return $validator; }); } }
<?php namespace Pippin; use Illuminate\Support\ServiceProvider; use Pippin\IPNValidator; final class PayPalIPNServiceProvider extends ServiceProvider { private function environmentFromConfig() { $appEnvironment = app()->environment(); $sandboxEnvironments = config('pippin.sandbox_environments'); if (in_array($appEnvironment, $sandboxEnvironments)) { return INPValidator::SANDBOX; } return INPValidator::PRODUCTION; } /** * Register bindings in the container. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/resources/config/pippin.php' => config_path('pippin.php') ]); $this->app->singleton(IPNValidator::class, function($app) use($this) { $environment = $this->environmentFromConfig(); $validator = IPNValidator($environment); $validator->setTransportClass(config('pippin.transport_class')); return $validator; }); } }
Include webfont extensions in default filePatterns
var Promise = require('ember-cli/lib/ext/promise'); var chalk = require('chalk'); var yellow = chalk.yellow; var blue = chalk.blue; function applyDefaultConfigIfNecessary(config, prop, defaultConfig, ui){ if (!config[prop]) { var value = defaultConfig[prop]; config[prop] = value; ui.write(blue('| ')); ui.writeLine(yellow('- Missing config: `' + prop + '`, using default: `' + value + '`')); } } module.exports = function(ui, config) { ui.write(blue('| ')); ui.writeLine(blue('- validating config')); var defaultConfig = { filePattern: '**/*.{js,css,png,gif,jpg,map,xml,txt,svg,eot,ttf,woff,woff2}' }; applyDefaultConfigIfNecessary(config, 'filePattern', defaultConfig, ui); return Promise.resolve(); }
var Promise = require('ember-cli/lib/ext/promise'); var chalk = require('chalk'); var yellow = chalk.yellow; var blue = chalk.blue; function applyDefaultConfigIfNecessary(config, prop, defaultConfig, ui){ if (!config[prop]) { var value = defaultConfig[prop]; config[prop] = value; ui.write(blue('| ')); ui.writeLine(yellow('- Missing config: `' + prop + '`, using default: `' + value + '`')); } } module.exports = function(ui, config) { ui.write(blue('| ')); ui.writeLine(blue('- validating config')); var defaultConfig = { filePattern: '**/*.{js,css,png,gif,jpg,map,xml,txt}' }; applyDefaultConfigIfNecessary(config, 'filePattern', defaultConfig, ui); return Promise.resolve(); }
Fix broken include of Cl\PHPUnitTestCase
<?php // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing')); if (APPLICATION_ENV === 'development') { ini_set('display_errors', true); } define('TEST_PATH', realpath(__DIR__)); chdir(realpath(TEST_PATH . '/../../')); include 'init_autoloader.php'; if (isset($loader)) { $loader->add('MockObject', TEST_PATH); $loader->add('TestHelper', TEST_PATH); } //Regiser zf2 autoloader as fallback to autoload PHPUnit_* classes from include path $zf2Autoloader = new Zend\Loader\StandardAutoloader(); $zf2Autoloader->setFallbackAutoloader(true); $zf2Autoloader->register(); include 'module/Cl/Test/PHPUnitTestCase.php'; Cl\Test\PHPUnitTestCase::setApplication( Zend\Mvc\Application::init(include 'config/application.config.php') );
<?php // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing')); if (APPLICATION_ENV === 'development') { ini_set('display_errors', true); } define('TEST_PATH', realpath(__DIR__)); chdir(realpath(TEST_PATH . '/../../')); include 'init_autoloader.php'; if (isset($loader)) { $loader->add('MockObject', TEST_PATH); $loader->add('TestHelper', TEST_PATH); } //Regiser zf2 autoloader as fallback to autoload PHPUnit_* classes from include path $zf2Autoloader = new Zend\Loader\StandardAutoloader(); $zf2Autoloader->setFallbackAutoloader(true); $zf2Autoloader->register(); include 'vendor/Cl/Test/PHPUnitTestCase.php'; Cl\Test\PHPUnitTestCase::setApplication( Zend\Mvc\Application::init(include 'config/application.config.php') );
Comment out @XmlLocation as we load it using Node acquired by XSLT.
package org.jboss.loom.migrators._ext; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode; import org.eclipse.persistence.oxm.annotations.XmlLocation; import org.xml.sax.Locator; /** * Serves as a common base for all stackable items which contain each other. * * @author Ondrej Zizka, ozizka at redhat.com */ @XmlDiscriminatorNode("@type") public class ContainerOfStackableDefs { @XmlElement public String filter; // A Groovy expression to filter the items. @XmlElement public String warning; // Warning to add to the current action. @XmlElement(name = "action") List<MigratorDefinition.ActionDef> actionDefs; @XmlElement(name = "forEach") List<MigratorDefinition.ForEachDef> forEachDefs; //@XmlLocation //@XmlTransient //public Locator location; public boolean hasForEachDefs(){ return forEachDefs != null && ! forEachDefs.isEmpty(); } public List<MigratorDefinition.ForEachDef> getForEachDefs() { return forEachDefs; } public boolean hasActionDefs(){ return actionDefs != null && ! actionDefs.isEmpty(); }; public List<MigratorDefinition.ActionDef> getActionDefs() { return actionDefs; } }// class
package org.jboss.loom.migrators._ext; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode; import org.eclipse.persistence.oxm.annotations.XmlLocation; import org.xml.sax.Locator; /** * Serves as a common base for all stackable items which contain each other. * * @author Ondrej Zizka, ozizka at redhat.com */ @XmlDiscriminatorNode("@type") public class ContainerOfStackableDefs { @XmlElement public String filter; // A Groovy expression to filter the items. @XmlElement public String warning; // Warning to add to the current action. @XmlElement(name = "action") List<MigratorDefinition.ActionDef> actionDefs; @XmlElement(name = "forEach") List<MigratorDefinition.ForEachDef> forEachDefs; @XmlLocation @XmlTransient public Locator location; public boolean hasForEachDefs(){ return forEachDefs != null && ! forEachDefs.isEmpty(); } public List<MigratorDefinition.ForEachDef> getForEachDefs() { return forEachDefs; } public boolean hasActionDefs(){ return actionDefs != null && ! actionDefs.isEmpty(); }; public List<MigratorDefinition.ActionDef> getActionDefs() { return actionDefs; } }// class
tests/helper-addon: Use alternative blueprint test helpers
'use strict'; var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); var setupTestHooks = blueprintHelpers.setupTestHooks; var emberNew = blueprintHelpers.emberNew; var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; var chai = require('ember-cli-blueprint-test-helpers/chai'); var expect = chai.expect; describe('Acceptance: ember generate and destroy helper-addon', function() { setupTestHooks(this); it('in-addon helper-addon foo-bar', function() { var args = ['helper-addon', 'foo-bar']; return emberNew({ target: 'addon' }) .then(() => emberGenerateDestroy(args, _file => { expect(_file('app/helpers/foo-bar.js')) .to.contain("export { default, fooBar } from 'my-addon/helpers/foo-bar';"); })); }); });
'use strict'; var setupTestHooks = require('ember-cli-blueprint-test-helpers/lib/helpers/setup'); var BlueprintHelpers = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper'); var generateAndDestroy = BlueprintHelpers.generateAndDestroy; describe('Acceptance: ember generate and destroy helper-addon', function() { setupTestHooks(this); it('in-addon helper-addon foo-bar', function() { return generateAndDestroy(['helper-addon', 'foo-bar'], { target: 'addon', files: [ { file: 'app/helpers/foo-bar.js', contains: [ "export { default, fooBar } from 'my-addon/helpers/foo-bar';" ] }, ] }); }); });
Fix decode error if pad name contains special characters and is sanitized
var padManager = require('../../db/PadManager'); var url = require('url'); exports.expressCreateServer = function (hook_name, args, cb) { //redirects browser to the pad's sanitized url if needed. otherwise, renders the html args.app.param('pad', function (req, res, next, padId) { //ensure the padname is valid and the url doesn't end with a / if(!padManager.isValidPadId(padId) || /\/$/.test(req.url)) { res.status(404).send('Such a padname is forbidden'); } else { padManager.sanitizePadId(padId, function(sanitizedPadId) { //the pad id was sanitized, so we redirect to the sanitized version if(sanitizedPadId != padId) { var real_url = sanitizedPadId; real_url = encodeURIComponent(real_url); var query = url.parse(req.url).query; if ( query ) real_url += '?' + query; res.header('Location', real_url); res.status(302).send('You should be redirected to <a href="' + real_url + '">' + real_url + '</a>'); } //the pad id was fine, so just render it else { next(); } }); } }); }
var padManager = require('../../db/PadManager'); var url = require('url'); exports.expressCreateServer = function (hook_name, args, cb) { //redirects browser to the pad's sanitized url if needed. otherwise, renders the html args.app.param('pad', function (req, res, next, padId) { //ensure the padname is valid and the url doesn't end with a / if(!padManager.isValidPadId(padId) || /\/$/.test(req.url)) { res.status(404).send('Such a padname is forbidden'); } else { padManager.sanitizePadId(padId, function(sanitizedPadId) { //the pad id was sanitized, so we redirect to the sanitized version if(sanitizedPadId != padId) { var real_url = sanitizedPadId; var query = url.parse(req.url).query; if ( query ) real_url += '?' + query; res.header('Location', real_url); res.status(302).send('You should be redirected to <a href="' + real_url + '">' + real_url + '</a>'); } //the pad id was fine, so just render it else { next(); } }); } }); }
Put checks in on the method params
Meteor.methods({ editableJSON_update: function (collectionName, _id, action) { check(collectionName, String); check(_id, String); check(action, Object); var Collection = Mongo.Collection.get(collectionName); var updated = 0; try { if (!!Package['aldeed:simple-schema'] && !!Package['aldeed:collection2'] && _.isFunction(Collection.simpleSchema) && Collection._c2) { updated = Collection.update(_id, action, { filter: false, autoConvert: false, removeEmptyStrings: false, validate: false }); } else { updated = Collection.update(_id, action); } } catch (err) { if (!(Meteor.isClient && action.$set && _.keys(action.$set)[0].indexOf('newField') > -1)) { throw new Meteor.Error(err); } } return updated; } });
Meteor.methods({ editableJSON_update: function (collectionName, _id, action) { var Collection = Mongo.Collection.get(collectionName); var updated = 0; try { if (!!Package['aldeed:simple-schema'] && !!Package['aldeed:collection2'] && _.isFunction(Collection.simpleSchema) && Collection._c2) { updated = Collection.update(_id, action, { filter: false, autoConvert: false, removeEmptyStrings: false, validate: false }); } else { updated = Collection.update(_id, action); } } catch (err) { if (!(Meteor.isClient && action.$set && _.keys(action.$set)[0].indexOf('newField') > -1)) { throw new Meteor.Error(err); } } return updated; } });
Add validate to input for numbers invalid in Go but valid for Number parsing
// +build js package strconv import ( "github.com/gopherjs/gopherjs/js" ) const maxInt32 float64 = 1<<31 - 1 const minInt32 float64 = -1 << 31 // Atoi returns the result of ParseInt(s, 10, 0) converted to type int. func Atoi(s string) (int, error) { const fnAtoi = "Atoi" if len(s) == 0 { return 0, syntaxError(fnAtoi, s) } // Investigate the bytes of the string // Validate each byte is allowed in parsing // Number allows some prefixes that Go does not: "0x" "0b", "0o" // additionally Number accepts decimals where Go does not "10.2" for i := 0; i < len(s); i++ { v := s[i] if v < '0' || v > '9' { if v != '+' && v != '-' { return 0, syntaxError(fnAtoi, s) } } } jsValue := js.Global.Call("Number", s, 10) if !js.Global.Call("isFinite", jsValue).Bool() { return 0, syntaxError(fnAtoi, s) } // Bounds checking floatval := jsValue.Float() if floatval > maxInt32 { return int(maxInt32), rangeError(fnAtoi, s) } else if floatval < minInt32 { return int(minInt32), rangeError(fnAtoi, s) } // Success! return jsValue.Int(), nil }
// +build js package strconv import ( "github.com/gopherjs/gopherjs/js" ) const maxInt32 float64 = 1<<31 - 1 const minInt32 float64 = -1 << 31 // Atoi returns the result of ParseInt(s, 10, 0) converted to type int. func Atoi(s string) (int, error) { const fnAtoi = "Atoi" if len(s) == 0 { return 0, syntaxError(fnAtoi, s) } jsValue := js.Global.Call("Number", s, 10) if !js.Global.Call("isFinite", jsValue).Bool() { return 0, syntaxError(fnAtoi, s) } // Bounds checking floatval := jsValue.Float() if floatval > maxInt32 { return 1<<31 - 1, rangeError(fnAtoi, s) } else if floatval < minInt32 { return -1 << 31, rangeError(fnAtoi, s) } // Success! return jsValue.Int(), nil }
Remove log from build script
const uglifyPlugin = require("rollup-plugin-uglify"); const replace = require("rollup-plugin-replace"); const commonjs = require("rollup-plugin-commonjs"); const resolve = require("rollup-plugin-node-resolve"); module.exports = function(options, env) { const { name, file, input, external = [], globals = {}, format = "cjs", plugins: userPlugins = [], sourcemap = false, safeModules = true, uglify = false } = options; const replacePatterns = { // Typescript -> Uglify "@class": "#__PURE__" }; if (safeModules) { replacePatterns["process.env.NODE_ENV"] = JSON.stringify(env.NODE_ENV); } const plugins = [ ...userPlugins, replace(replacePatterns), resolve(), commonjs({ include: /node_modules/ }) ]; if (uglify) { plugins.push(uglifyPlugin()); } return { inputOptions: { input, external, plugins }, outputOptions: { name, format, file, sourcemap, globals } }; };
const uglifyPlugin = require("rollup-plugin-uglify"); const replace = require("rollup-plugin-replace"); const commonjs = require("rollup-plugin-commonjs"); const resolve = require("rollup-plugin-node-resolve"); module.exports = function(options, env) { const { name, file, input, external = [], globals = {}, format = "cjs", plugins: userPlugins = [], sourcemap = false, safeModules = true, uglify = false } = options; const replacePatterns = { // Typescript -> Uglify "@class": "#__PURE__" }; if (safeModules) { console.log("BUILDING WITH", env.NODE_ENV); replacePatterns["process.env.NODE_ENV"] = JSON.stringify(env.NODE_ENV); } const plugins = [ ...userPlugins, replace(replacePatterns), resolve(), commonjs({ include: /node_modules/ }) ]; if (uglify) { plugins.push(uglifyPlugin()); } return { inputOptions: { input, external, plugins }, outputOptions: { name, format, file, sourcemap, globals } }; };
Add type-hints to Artisan Facade methods props
<?php namespace Illuminate\Support\Facades; /** * @method static void compile(string|null $path = null) * @method static string getPath() * @method static void setPath(string $path) * @method static string compileString(string $value) * @method static string stripParentheses(string $expression) * @method static void extend(callable $compiler) * @method static array getExtensions() * @method static void if(string $name, callable $callback) * @method static bool check(string $name, array ...$parameters) * @method static void component(string $path, string|null $alias = null) * @method static void include(string $path, string|null $alias = null) * @method static void directive(string $name, callable $handler) * @method static array getCustomDirectives() * @method static void setEchoFormat(string $format) * @method static void withDoubleEncoding() * @method static void withoutDoubleEncoding() * * @see \Illuminate\View\Compilers\BladeCompiler */ class Blade extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'blade.compiler'; } }
<?php namespace Illuminate\Support\Facades; /** * @method static void compile($path = null) * @method static string getPath() * @method static void setPath($path) * @method static string compileString($value) * @method static string stripParentheses($expression) * @method static void extend(callable $compiler) * @method static array getExtensions() * @method static void if($name, callable $callback) * @method static bool check($name, ...$parameters) * @method static void component($path, $alias = null) * @method static void include($path, $alias = null) * @method static void directive($name, callable $handler) * @method static array getCustomDirectives() * @method static void setEchoFormat($format) * @method static void withDoubleEncoding() * @method static void withoutDoubleEncoding() * * @see \Illuminate\View\Compilers\BladeCompiler */ class Blade extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'blade.compiler'; } }
Add "s" attr for QSettings
# -*- coding: utf-8 -*- import os import contextlib from PyQt5 import QtCore from . import __app_name__ from . import helperutils def _qsettings_group_factory(settings: QtCore.QSettings): @contextlib.contextmanager def qsettings_group_context(group_name: str): settings.beginGroup(group_name) yield settings settings.endGroup() return qsettings_group_context class SettingsMeta(type): _instance = None def __call__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(SettingsMeta, cls).__call__(*args, **kwargs) return cls._instance class Settings(metaclass=SettingsMeta): """Stores application settings """ def __init__(self, parent: QtCore.QObject = None): self._filename = os.path.normpath( os.path.join(helperutils.get_app_config_dir(), __app_name__ + '.ini')) self._settings = QtCore.QSettings(self._filename, QtCore.QSettings.IniFormat, parent) self._settings_group = _qsettings_group_factory(self._settings) @property def filename(self): return self._filename @property def s(self): return self._settings @property def group(self): return self._settings_group
# -*- coding: utf-8 -*- import os import contextlib from PyQt5 import QtCore from . import __app_name__ from . import helperutils def _qsettings_group_factory(settings: QtCore.QSettings): @contextlib.contextmanager def qsettings_group_context(group_name: str): settings.beginGroup(group_name) yield settings settings.endGroup() return qsettings_group_context class SettingsMeta(type): _instance = None def __call__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(SettingsMeta, cls).__call__(*args, **kwargs) return cls._instance class Settings(metaclass=SettingsMeta): """Stores application settings """ def __init__(self, parent: QtCore.QObject = None): self._filename = os.path.normpath( os.path.join(helperutils.get_app_config_dir(), __app_name__ + '.ini')) self._settings = QtCore.QSettings(self._filename, QtCore.QSettings.IniFormat, parent) self._settings_group = _qsettings_group_factory(self._settings) @property def filename(self): return self._filename @property def group(self): return self._settings_group
Raise exception if unable to find a usable key in property mapping dict
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: results[key] = source_properties[value] else: raise PropertyMappingFailedException("property %s not found in source feature" % (value)) elif type(value) == dict: if "static" in value: results[key] = value["static"] else: raise PropertyMappingFailedException( "Failed to find key for mapping in dict for field:%s" % (key,)) else: raise PropertyMappingFailedException("Unhandled mapping for key:%s value type:%s" % (key, type(value))) return results
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: results[key] = source_properties[value] else: raise PropertyMappingFailedException("property %s not found in source feature" % (value)) elif type(value) == dict: if "static" in value: results[key] = value["static"] else: raise PropertyMappingFailedException("Unhandled mapping for key:%s value type:%s" % (key, type(value))) return results
Format parsed month-year inputs as unambiguous data format for input Avoid pushing user towards ambiguous input formats
'use strict'; angular.module('ddsApp').directive('ddsDateMonthYear', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.push(function(viewValue) { var result = moment(viewValue, ['MM/YY', 'MM/YYYY', 'MMMM YYYY', 'L', 'DD/MM/YY']); ctrl.$setValidity('ddsDateMonthYear', result.isValid()); return result; }); ctrl.$formatters.push(function(momentInstance) { if (! momentInstance) return; return momentInstance.format('MM/YYYY'); }); } }; });
'use strict'; angular.module('ddsApp').directive('ddsDateMonthYear', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.push(function(viewValue) { var result = moment(viewValue, ['MM/YY', 'MM/YYYY', 'MMMM YYYY', 'L', 'DD/MM/YY']); ctrl.$setValidity('ddsDateMonthYear', result.isValid()); return result; }); ctrl.$formatters.push(function(momentInstance) { if (! momentInstance) return; return momentInstance.format('MMM YYYY'); }); } }; });
ADD readback.name in iuv_gap to fix speck save prob
from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO from ophyd import Component as Cpt # Undulator class Undulator(PVPositionerPC): readback = Cpt(EpicsSignalRO, '-LEnc}Gap') setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos') actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go') actuate_value = 1 stop_signal = Cpt(EpicsSignal, '-Mtr:2}Pos.STOP') stop_value = 1 ivu_gap = Undulator('SR:C11-ID:G1{IVU20:1', name='ivu_gap') # ivu_gap.readback = 'ivu_gap' ####what the ^*(*()**)(* !!!! #To solve the "KeyError Problem" when doing dscan and trying to save to a spec file, Y.G., 20170110 ivu_gap.readback.name = 'ivu_gap' # This class is defined in 10-optics.py fe = VirtualMotorCenterAndGap('FE:C11A-OP{Slt:12', name='fe') # Front End Slits (Primary Slits)
from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO from ophyd import Component as Cpt # Undulator class Undulator(PVPositionerPC): readback = Cpt(EpicsSignalRO, '-LEnc}Gap') setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos') actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go') actuate_value = 1 stop_signal = Cpt(EpicsSignal, '-Mtr:2}Pos.STOP') stop_value = 1 ivu_gap = Undulator('SR:C11-ID:G1{IVU20:1', name='ivu_gap') ivu_gap.readback = 'ivu_gap' # This class is defined in 10-optics.py fe = VirtualMotorCenterAndGap('FE:C11A-OP{Slt:12', name='fe') # Front End Slits (Primary Slits)
Remove comment for running under uwsgi
#!/usr/bin/env python import os from flask_script import Manager, Server from flask_script.commands import ShowUrls, Clean from mothership import create_app from mothership.models import db # default to dev config because no one should use this in # production anyway env = os.environ.get('MOTHERSHIP_ENV', 'dev') app = create_app('mothership.settings.%sConfig' % env.capitalize()) manager = Manager(app) manager.add_command("server", Server()) manager.add_command("show-urls", ShowUrls()) manager.add_command("clean", Clean()) @manager.shell def make_shell_context(): """ Creates a python REPL with several default imports in the context of the app """ return dict(app=app, db=db) # return dict(app=app, db=db, User=User) @manager.command def createdb(): """ Creates a database with all of the tables defined in your SQLAlchemy models """ db.create_all() if __name__ == "__main__": manager.run()
#!/usr/bin/env python import os from flask_script import Manager, Server from flask_script.commands import ShowUrls, Clean from mothership import create_app from mothership.models import db # default to dev config because no one should use this in # production anyway env = os.environ.get('MOTHERSHIP_ENV', 'dev') app = create_app('mothership.settings.%sConfig' % env.capitalize()) manager = Manager(app) manager.add_command("server", Server()) manager.add_command("show-urls", ShowUrls()) manager.add_command("clean", Clean()) @manager.shell def make_shell_context(): """ Creates a python REPL with several default imports in the context of the app """ return dict(app=app, db=db) # return dict(app=app, db=db, User=User) @manager.command def createdb(): """ Creates a database with all of the tables defined in your SQLAlchemy models """ db.create_all() if __name__ == "__main__": manager.run() # ./venv/bin/uwsgi --http 0.0.0.0:8000 --home venv --wsgi-file manage.py --callable app --master --catch-exceptions
Fix PHPDocs for proper IDE completion
<?php namespace Behat\Symfony2Extension\Context; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /* * This file is part of the Behat\Symfony2Extension. * (c) Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Kernel support methods for Symfony2Extension. * * @author Konstantin Kudryashov <ever.zet@gmail.com> */ trait KernelDictionary { private $kernel; /** * Sets Kernel instance. * * @param KernelInterface $kernel HttpKernel instance */ public function setKernel(KernelInterface $kernel) { $this->kernel = $kernel; } /** * Returns HttpKernel instance. * * @return KernelInterface */ public function getKernel() { return $this->kernel; } /** * Returns HttpKernel service container. * * @return ContainerInterface */ public function getContainer() { return $this->kernel->getContainer(); } }
<?php namespace Behat\Symfony2Extension\Context; use Symfony\Component\HttpKernel\KernelInterface; /* * This file is part of the Behat\Symfony2Extension. * (c) Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Kernel support methods for Symfony2Extension. * * @author Konstantin Kudryashov <ever.zet@gmail.com> */ trait KernelDictionary { private $kernel; /** * Sets Kernel instance. * * @param KernelInterface $kernel HttpKernel instance */ public function setKernel(KernelInterface $kernel) { $this->kernel = $kernel; } /** * Returns HttpKernel instance. * * @return HttpKernel */ public function getKernel() { return $this->kernel; } /** * Returns HttpKernel service container. * * @return ServiceContainer */ public function getContainer() { return $this->kernel->getContainer(); } }
Revert "Push to Travis CI" This reverts commit 05547a47fa7b7c0f3ae3d7d5b14b112902b2825a.
package mail import ( "bytes" "text/template" ) const emailTemplate = `{{range .Headers}}{{.}} {{end}}From: {{.From}}{{if .ReplyTo}} Reply-To: {{.ReplyTo}}{{end}} To: {{.To}} Subject: {{.Subject}} MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="our-content-boundary" {{.Body}}` type Message struct { From string ReplyTo string To string Subject string Body string Headers []string } func (msg Message) Data() string { buf := bytes.NewBuffer([]byte{}) tmpl, err := template.New("test").Parse(emailTemplate) if err != nil { panic(err) } err = tmpl.Execute(buf, msg) if err != nil { panic(err) } return buf.String() }
package mail import ( "bytes" "text/template" ) const emailTemplate = `{{range .Headers}}{{.}} {{end}}From: {{.From}}{{if .ReplyTo}} Reply-To: {{.ReplyTo}}{{end}} To: {{.To}} Subject: {{.Subject}} MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="our-content-boundary" {{.Body}}` type Message struct { From string ReplyTo string To string Subject string Body string Headers []string } func (msg Message) Data() string { buf := bytes.NewBuffer([]byte{}) tmpl, err := template.New("test").Parse(emailTemplate) if err != nil { panic(err) } err = tmpl.Execute(buf, msg) if err != nil { panic(err) } return buf.String() }
Add scrollPosition function call on messages template ready
if (Meteor.isClient) { Template.messages.rendered = function () { scrollPosition(); }; Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY' }); Template.messages.helpers({ messages: function() { return Messages.find({}, { sort: { time: 1}}); } }); var scrollPosition = function() { $('.messageBox').scrollTop($('.messageBox')[0].scrollHeight); }; Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { if (Meteor.user()) var name = Meteor.user().username; else var name = 'Anonymous'; var message = document.getElementById('message'); if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), }); document.getElementById('message').value = ''; message.value = ''; scrollPosition(); } } } }; $(document).ready(function(){ scrollPosition(); }); if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } }
if (Meteor.isClient) { Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY' }); Template.messages.helpers({ messages: function() { return Messages.find({}, { sort: { time: 1}}); } }); var scrollPosition = function() { $('.messageBox').scrollTop($('.messageBox')[0].scrollHeight); }; Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { if (Meteor.user()) var name = Meteor.user().username; else var name = 'Anonymous'; var message = document.getElementById('message'); if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), }); document.getElementById('message').value = ''; message.value = ''; scrollPosition(); } } } }; $(document).ready(function(){ scrollPosition(); }); if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } }
SimonStewart: Clean up the driver instance once the large tests for the support classes are done r16955
/* Copyright 2011 Selenium committers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.support; import org.junit.AfterClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.openqa.selenium.support.pagefactory.UsingPageFactoryTest; import org.openqa.selenium.support.ui.SelectLargeTest; import org.openqa.selenium.testing.JUnit4TestBase; @RunWith(Suite.class) @Suite.SuiteClasses({ SelectLargeTest.class, UsingPageFactoryTest.class }) public class LargeTests { @AfterClass public static void cleanUpDrivers() { JUnit4TestBase.removeDriver(); } }
/* Copyright 2011 Selenium committers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.support; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.openqa.selenium.support.pagefactory.UsingPageFactoryTest; import org.openqa.selenium.support.ui.SelectLargeTest; @RunWith(Suite.class) @Suite.SuiteClasses({ SelectLargeTest.class, UsingPageFactoryTest.class }) public class LargeTests {}
Add 1.13 to the test matrix
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember 1.13', dependencies: { 'ember': '1.13.8' }, resolutions: { 'ember': '1.13.8' } }, { 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-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' } } ] };
Use more robust check before using noConflict() mode Basically detect the case when L is already the same Leaflet library instance that was loaded by some other extension, in which case there is no need to use noConflict. This does not address the problem of plugins assuming single global L when there are several different Leaflet libs, but it does address #337, since other extension share the same Leaflet instance.
// Load css require('leaflet/dist/leaflet.css'); require('leaflet-draw/dist/leaflet.draw.css'); require('leaflet.markercluster/dist/MarkerCluster.css'); require('leaflet.markercluster/dist/MarkerCluster.Default.css'); require('leaflet-measure/dist/leaflet-measure.css'); require('leaflet-fullscreen/dist/leaflet.fullscreen.css'); require('./jupyter-leaflet.css'); // Forcibly load the marker icon images to be in the bundle. require('leaflet/dist/images/marker-shadow.png'); require('leaflet/dist/images/marker-icon.png'); require('leaflet/dist/images/marker-icon-2x.png'); // Export everything from jupyter-leaflet and the npm package version number. var _oldL = window.L; module.exports = require('./jupyter-leaflet.js'); module.exports['version'] = require('../package.json').version; // if previous L existed and it got changed while loading this module if (_oldL !== undefined && _oldL !== window.L) { console.log("Existing `L` detected, running ipyleaflet's Leaflet in no-conflict mode as `ipyL`"); ipyL = L.noConflict(); }
// Load css require('leaflet/dist/leaflet.css'); require('leaflet-draw/dist/leaflet.draw.css'); require('leaflet.markercluster/dist/MarkerCluster.css'); require('leaflet.markercluster/dist/MarkerCluster.Default.css'); require('leaflet-measure/dist/leaflet-measure.css'); require('leaflet-fullscreen/dist/leaflet.fullscreen.css'); require('./jupyter-leaflet.css'); // Forcibly load the marker icon images to be in the bundle. require('leaflet/dist/images/marker-shadow.png'); require('leaflet/dist/images/marker-icon.png'); require('leaflet/dist/images/marker-icon-2x.png'); // Export everything from jupyter-leaflet and the npm package version number. hasL = (typeof(window.L) != 'undefined'); module.exports = require('./jupyter-leaflet.js'); module.exports['version'] = require('../package.json').version; if (hasL) { console.log("Existing `L` detected, running ipyleaflet's Leaflet in no-conflict mode as `ipyL`"); ipyL = L.noConflict(); }
Fix click event handler so it works under firefox
'use strict'; Template.notification.helpers({ notificationColor: function(notificationType) { return Notifications.getNotificationClass(notificationType); } }); Template.notification.events = { 'click': function (event) { if (this.userCloseable || this.expires < new Date()) { // must the user click the close button? if (!this.clickBodyToClose && 0 > event.target.className.indexOf('closeButton')) { return; } Notifications.remove(this._id); if (this.closed) { this.closed(this); } } } };
'use strict'; Template.notification.helpers({ notificationColor: function(notificationType) { return Notifications.getNotificationClass(notificationType); } }); Template.notification.events = { 'click': function () { if (this.userCloseable || this.expires < new Date()) { // must the user click the close button? if (!this.clickBodyToClose && 0 > event.target.className.indexOf('closeButton')) { return; } Notifications.remove(this._id); if (this.closed) { this.closed(this); } } } };
Fix Example to not show the original error (which is go version dependent)
// The original error message returned by stdlib changed with go1.8. // We only test the latest release. // //+build go1.8 forcego1.8 package jsonptrerror_test import ( "fmt" "strings" "github.com/dolmen-go/jsonptrerror" ) func ExampleDecoder() { decoder := jsonptrerror.NewDecoder(strings.NewReader( `{"key": "x", "value": 5}`, )) var out struct { Key string `json:"key"` Value bool `json:"value"` } err := decoder.Decode(&out) fmt.Println(err) if err, ok := err.(*jsonptrerror.UnmarshalTypeError); ok { //fmt.Println("Original error:", err.UnmarshalTypeError.Error()) fmt.Println("Error location:", err.Pointer) } // Output: // /value: cannot unmarshal number into Go value of type bool // Error location: /value }
// The original error message returned by stdlib changed with go1.8. // We only test the latest release. // //+build go1.8 forcego1.8 package jsonptrerror_test import ( "fmt" "strings" "github.com/dolmen-go/jsonptrerror" ) func ExampleDecoder() { decoder := jsonptrerror.NewDecoder(strings.NewReader( `{"key": "x", "value": 5}`, )) var out struct { Key string `json:"key"` Value bool `json:"value"` } err := decoder.Decode(&out) fmt.Println(err) if err, ok := err.(*jsonptrerror.UnmarshalTypeError); ok { fmt.Println("Original error:", err.UnmarshalTypeError.Error()) fmt.Println("Error location:", err.Pointer) } // Output: // /value: cannot unmarshal number into Go value of type bool // Original error: json: cannot unmarshal number into Go struct field .value of type bool // Error location: /value }
Use cloudfront link to store drawings
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { const cloudFront = `https://d3ieg3cxah9p4i.cloudfront.net/${meta.location.split('/bolg/')[1]}`; ref.set(cloudFront); publishedRef.set(cloudFront); res.send('ok'); }) .catch((err) => { res.error(err); }); }
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { ref.set(meta.location); publishedRef.set(meta.location); res.send('ok'); }) .catch((err) => { res.error(err); }); }
Add div for image "cut"
<?php namespace FormKit\Widget; use FormKit\Element; /** * * $input = new ImageFileInput('image'); * $input->image->align = 'right'; * $input->image->src = '.....'; * $input->imageWrapper->setAttributeValues(....); * $input->render(); * */ class ImageFileInput extends FileInput { public $type = 'file'; public $class = array('formkit-widget','formkit-widget-imagefile'); public $image; public $imageWrapper; function init() { parent::init(); if( $this->value ) { $this->imageWrapper = new Element('div',array('class' => 'formkit-image-cover')); $this->image = new Element('img',array( 'src' => $this->value, )); $cutDiv = new Element('div',array('class' => 'cut') ); $cutDiv->append($this->image); $this->imageWrapper->append($cutDiv); } } function render() { if( $this->image ) { return $this->imageWrapper->render() . parent::render(); } return parent::render(); } }
<?php namespace FormKit\Widget; use FormKit\Element; /** * * $input = new ImageFileInput('image'); * $input->image->align = 'right'; * $input->image->src = '.....'; * $input->imageWrapper->setAttributeValues(....); * $input->render(); * */ class ImageFileInput extends FileInput { public $type = 'file'; public $class = array('formkit-widget','formkit-widget-imagefile'); public $image; public $imageWrapper; function init() { parent::init(); if( $this->value ) { $this->imageWrapper = new Element('div',array('class' => 'formkit-image-cover')); $this->image = new Element('img',array( 'src' => $this->value, )); $this->imageWrapper->append($this->image); } } function render() { if( $this->image ) { return $this->imageWrapper->render() . parent::render(); } return parent::render(); } }
Move fuel "burn time" string down, to vertically center it more
package mezz.jei.plugins.vanilla.furnace; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.Color; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import mezz.jei.plugins.vanilla.VanillaRecipeWrapper; public class FuelRecipe extends VanillaRecipeWrapper { @Nonnull private final List<ItemStack> input; @Nullable private final String burnTimeString; public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) { this.input = new ArrayList<>(input); this.burnTimeString = StatCollector.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime); } @Nonnull @Override public List<ItemStack> getInputs() { return input; } @Nonnull @Override public List<ItemStack> getOutputs() { return Collections.emptyList(); } @Override public void drawInfo(@Nonnull Minecraft minecraft) { minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB()); } @Override public boolean usesOreDictionaryComparison() { return false; } }
package mezz.jei.plugins.vanilla.furnace; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.Color; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import mezz.jei.plugins.vanilla.VanillaRecipeWrapper; public class FuelRecipe extends VanillaRecipeWrapper { @Nonnull private final List<ItemStack> input; @Nullable private final String burnTimeString; public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) { this.input = new ArrayList<>(input); this.burnTimeString = StatCollector.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime); } @Nonnull @Override public List<ItemStack> getInputs() { return input; } @Nonnull @Override public List<ItemStack> getOutputs() { return Collections.emptyList(); } @Override public void drawInfo(@Nonnull Minecraft minecraft) { minecraft.fontRendererObj.drawString(burnTimeString, 24, 2, Color.gray.getRGB()); } @Override public boolean usesOreDictionaryComparison() { return false; } }
Call widgetManager when data received
/* jshint browser: true, jquery: true */ /* global AgileSprint:false, console:false */ var AgileSprintManager = function(options) { // if(options.server === null || options.server === undefined) { // return null; // } this.widgetManager = (options.widgetManager !== null && options.widgetManager !== undefined) ? options.widgetManager : null; this.panelManager = (options.panelManager !== null && options.panelManager !== undefined) ? options.panelManager : null; this.server = options.server; }; AgileSprintManager.prototype.processMessages = function(server, id, content) { var processed = false; switch (id) { case AgileSprint.MESSAGE_STATS: this.__receivedStats(server, content); processed = true; break; } return processed; }; AgileSprintManager.prototype.__receivedStats = function(server, d) { if(this.widgetManager !== null) { this.widgetManager.receivedData(d); } };
/* jshint browser: true, jquery: true */ /* global AgileSprint:false, console:false */ var AgileSprintManager = function(options) { // if(options.server === null || options.server === undefined) { // return null; // } this.widgetManager = (options.widgetManager !== null && options.widgetManager !== undefined) ? options.widgetManager : null; this.panelManager = (options.panelManager !== null && options.panelManager !== undefined) ? options.panelManager : null; this.server = options.server; }; AgileSprintManager.prototype.processMessages = function(server, id, content) { var processed = false; switch (id) { case AgileSprint.MESSAGE_STATS: this.__receivedStats(server, content); processed = true; break; } return processed; }; AgileSprintManager.prototype.__receivedStats = function(server, d) { console.log(JSON.stringify(d, null, ' ')); };
Update export items command for dataset
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.db.models import Q from digest.management.commands.create_dataset import create_dataset from digest.models import Item class Command(BaseCommand): help = 'Create dataset' def handle(self, *args, **options): """ Основной метод - точка входа """ query = Q() urls = [ 'allmychanges.com', 'stackoverflow.com', ] for entry in urls: query = query | Q(link__contains=entry) # TODO make raw sql active_news = Item.objects.filter(status='active').exclude(query) links = active_news.all().values_list('link', flat=True).distinct() non_active_news = Item.objects.exclude(link__in=links).exclude(query) items_ids = list(active_news.values_list('id', flat=True)) items_ids.extend(non_active_news.values_list('id', flat=True)) items_ids = list(set(items_ids)) items = Item.objects.filter(id__in=items_ids) create_dataset(items, 'items.json')
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.management.base import BaseCommand from django.db.models import Q from digest.management.commands.create_dataset import create_dataset from digest.models import Item class Command(BaseCommand): help = 'Create dataset' def handle(self, *args, **options): """ Основной метод - точка входа """ query = Q() urls = [ 'allmychanges.com', 'stackoverflow.com', ] for entry in urls: query = query | Q(link__contains=entry) create_dataset(Item.objects.exclude(query).order_by('?'), 'items.json')
Add license tag line. Remove unused imports. VIVO-222
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Wrapping ServletRequest that does multipart. In order to allow * streaming, this class does NOT save the parts to a temporary directory. * * */ public class StreamingMultipartHttpServletRequest extends FileUploadServletRequest { /** * Parse the multipart request. Store the info about the request parameters. * Don't store the uploaded files to a temporary directory to allow streaming. * * Only use this if you plan to consume the FileItems using streaming * to deal with inputs of very large sizes. * */ public StreamingMultipartHttpServletRequest(HttpServletRequest request) { super(request); //use a file uploader that does not save the files to a temporary directory. stashParametersInRequest( request , new ServletFileUpload()); } @Override public boolean isMultipart() { return true; } }
package edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Wrapping ServletRequest that does multipart. In order to allow * streaming, this class does NOT save the parts to a temporary directory. * * */ public class StreamingMultipartHttpServletRequest extends FileUploadServletRequest { /** * Parse the multipart request. Store the info about the request parameters. * Don't store the uploaded files to a temporary directory to allow streaming. * * Only use this if you plan to consume the FileItems using streaming * to deal with inputs of very large sizes. * */ public StreamingMultipartHttpServletRequest(HttpServletRequest request) throws IOException{ super(request); //use a file uploader that does not save the files to a temporary directory. stashParametersInRequest( request , new ServletFileUpload()); } @Override public boolean isMultipart() { return true; } }
Fix cut 'n' paster error RawDBPreset -> RawEvidenceNamedPreset. Code tidy.
package uk.ac.ebi.quickgo.client.service.loader.presets.evidence; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.validator.ValidationException; import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsValidationHelper.checkIsNullOrEmpty; /** * Validates the {@link RawEvidenceNamedPreset} instances being read from flat-files and mapped via * {@link StringToRawEvidenceNamedPresetMapper}. * * Created 05/03/18 * @author Tony Wardell */ public class RawEvidenceNamedPresetValidator implements ItemProcessor<RawEvidenceNamedPreset, RawEvidenceNamedPreset> { @Override public RawEvidenceNamedPreset process(RawEvidenceNamedPreset rawEvidenceNamedPreset) { if (rawEvidenceNamedPreset == null) { throw new ValidationException("RawEvidenceNamedPreset cannot be null or empty"); } checkIsNullOrEmpty(rawEvidenceNamedPreset.name); return rawEvidenceNamedPreset; } }
package uk.ac.ebi.quickgo.client.service.loader.presets.evidence; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.validator.ValidationException; import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsValidationHelper.checkIsNullOrEmpty; /** * Validates the {@link RawEvidenceNamedPreset} instances being read from flat-files and mapped via * {@link StringToRawEvidenceNamedPresetMapper}. * * Created 05/03/18 * @author Tony Wardell */ public class RawEvidenceNamedPresetValidator implements ItemProcessor<RawEvidenceNamedPreset, RawEvidenceNamedPreset> { @Override public RawEvidenceNamedPreset process(RawEvidenceNamedPreset rawNamedPreset) { if (rawNamedPreset == null) { throw new ValidationException("RawDBPreset cannot be null or empty"); } checkIsNullOrEmpty(rawNamedPreset.name); return rawNamedPreset; } }
Use `charCodeAt` instead of `charAt` `charCodeAt` is faster in general. Ref. #4.
/*! http://mths.be/endswith v0.1.0 by @mathias */ if (!String.prototype.endsWith) { (function() { 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` var toString = {}.toString; String.prototype.endsWith = function(search) { var string = String(this); if ( this == null || (search && toString.call(search) == '[object RegExp]') ) { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { // `ToInteger` pos = position ? Number(position) : 0; if (pos != pos) { // better `isNaN` pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } var index = -1; while (++index < searchLength) { if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) { return false; } } return true; }; }()); }
/*! http://mths.be/endswith v0.1.0 by @mathias */ if (!String.prototype.endsWith) { (function() { 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` var toString = {}.toString; String.prototype.endsWith = function(search) { var string = String(this); if ( this == null || (search && toString.call(search) == '[object RegExp]') ) { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { // `ToInteger` pos = position ? Number(position) : 0; if (pos != pos) { // better `isNaN` pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } var index = -1; while (++index < searchLength) { if (string.charAt(start + index) != searchString.charAt(index)) { return false; } } return true; }; }()); }
Remove is_autheticated check as by default all the endpoints are authenticated
from rest_framework import throttling class ThrottlingBySession(throttling.SimpleRateThrottle): """ Limits the rating of facility service to only 10 per day per IP. This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES. The rate will apply to both the publc user and other authenticated users. """ scope = 'rating' scope_attr = 'throttle_scope' def get_cache_key(self, request, view): """ Override this method in order to have an ip based cache key for authenticated users instead of the usual user.pk based cache key. """ fs_identity = request.DATA.get('facility_service', None) if fs_identity: machine = self.get_ident(request) ident = machine + fs_identity return self.cache_format % { 'scope': self.scope, 'ident': ident } else: return None
from rest_framework import throttling class ThrottlingBySession(throttling.SimpleRateThrottle): """ Limits the rating of facility service to only 10 per day per IP. This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES. The rate will apply to both the publc user and other authenticated users. """ scope = 'rating' scope_attr = 'throttle_scope' def get_cache_key(self, request, view): """ Override this method in order to have an ip based cache key for authenticated users instead of the usual user.pk based cache key. """ fs_identity = request.DATA.get('facility_service', None) if fs_identity: machine = self.get_ident(request) ident = machine + fs_identity if request.user.is_authenticated(): return self.cache_format % { 'scope': self.scope, 'ident': ident } else: return None
Use dropdown list for test data.
import React, { Component } from 'react'; import { faintBlack, cyan500 } from 'material-ui/styles/colors'; import MenuItem from 'material-ui/MenuItem'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton/IconButton'; import ActionHelpOutline from 'material-ui/svg-icons/action/help-outline'; const TEST_CARD_NUMBERS = [ '01-2167-30-92545' ]; export default class TestCardNumber extends Component { constructor() { super(); this.state = { cardNumber: '' }; } renredCardNumbers() { return TEST_CARD_NUMBERS.map((number, index) => <MenuItem key={index} value={number} primaryText={number} />); } render() { return ( <IconMenu className='buka-cardnumber__help' iconButtonElement={<IconButton><ActionHelpOutline color={faintBlack} hoverColor={cyan500} /></IconButton>} anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} > {this.renredCardNumbers()} </IconMenu> ); } }
import React, { Component } from 'react'; import Popover from 'material-ui/Popover'; import { faintBlack, cyan500 } from 'material-ui/styles/colors'; import ActionHelpOutline from 'material-ui/svg-icons/action/help-outline'; const TEST_CARD_NUMBER = '01-2167-30-92545'; export default class TestCardNumber extends Component { constructor() { super(); this.state = { open: false }; this.handleTouchTap = this.handleTouchTap.bind(this); this.handleRequestClose = this.handleRequestClose.bind(this); } handleTouchTap(event) { this.setState({ open: true, anchorEl: event.currentTarget }); } handleRequestClose() { this.setState({ open: false }); } render() { return ( <div className='buka-cardnumber__help'> <ActionHelpOutline onClick={this.handleTouchTap} color={faintBlack} hoverColor={cyan500} /> <Popover open={this.state.open} anchorEl={this.state.anchorEl} onRequestClose={this.handleRequestClose}> <p>{`Test card number: ${TEST_CARD_NUMBER}`}</p> </Popover> </div>); } }
Change installing message in composer dependency
<?php namespace WP_CLI; use \Composer\DependencyResolver\Rule; use \Composer\EventDispatcher\Event; use \Composer\EventDispatcher\EventSubscriberInterface; use \Composer\Script\PackageEvent; use \Composer\Script\ScriptEvents; use \WP_CLI; /** * A Composer Event subscriber so we can keep track of what's happening inside Composer */ class PackageManagerEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install', ScriptEvents::POST_PACKAGE_INSTALL => 'post_install', ); } public static function pre_install( PackageEvent $event ) { $operation_message = $event->getOperation()->__toString(); WP_CLI::log( ' - ' . $operation_message ); } public static function post_install( PackageEvent $event ) { $operation = $event->getOperation(); $reason = $operation->getReason(); if ( $reason instanceof Rule ) { switch ( $reason->getReason() ) { case Rule::RULE_PACKAGE_CONFLICT; case Rule::RULE_PACKAGE_SAME_NAME: case Rule::RULE_PACKAGE_REQUIRES: $composer_error = $reason->getPrettyString( $event->getPool() ); break; } if ( ! empty( $composer_error ) ) { WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) ); } } } }
<?php namespace WP_CLI; use \Composer\DependencyResolver\Rule; use \Composer\EventDispatcher\Event; use \Composer\EventDispatcher\EventSubscriberInterface; use \Composer\Script\PackageEvent; use \Composer\Script\ScriptEvents; use \WP_CLI; /** * A Composer Event subscriber so we can keep track of what's happening inside Composer */ class PackageManagerEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install', ScriptEvents::POST_PACKAGE_INSTALL => 'post_install', ); } public static function pre_install( PackageEvent $event ) { WP_CLI::log( ' - Installing package' ); } public static function post_install( PackageEvent $event ) { $operation = $event->getOperation(); $reason = $operation->getReason(); if ( $reason instanceof Rule ) { switch ( $reason->getReason() ) { case Rule::RULE_PACKAGE_CONFLICT; case Rule::RULE_PACKAGE_SAME_NAME: case Rule::RULE_PACKAGE_REQUIRES: $composer_error = $reason->getPrettyString( $event->getPool() ); break; } if ( ! empty( $composer_error ) ) { WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) ); } } } }
Fix gulp install to add new files inside directories (was avoiding overwritin dir)
var path = require('path'), fs = require('fs'), defaults = require('./defaults') ; module.exports = { del: { silent : true }, minify: { processImport : false, keepSpecialComments : 0 }, uglify: { mangle : true }, prefix: { browsers: [ 'last 2 version', '> 1%', 'opera 12.1', 'safari 6', 'ie 9', 'bb 10', 'android 4' ] }, header: { title : defaults.title, repository : defaults.repository, url : defaults.url }, sourcemap: { includeContent : true, sourceRoot : '/src' }, rename: { json : { extname : '.json' }, minJS : { extname : '.min.js' }, minCSS : { extname : '.min.css' } }, wrench: { recursive: { forceDelete : true, excludeHiddenUnix : true, preserveFiles : true } } };
var path = require('path'), fs = require('fs'), defaults = require('./defaults') ; module.exports = { del: { silent : true }, minify: { processImport : false, keepSpecialComments : 0 }, uglify: { mangle : true }, prefix: { browsers: [ 'last 2 version', '> 1%', 'opera 12.1', 'safari 6', 'ie 9', 'bb 10', 'android 4' ] }, header: { title : defaults.title, repository : defaults.repository, url : defaults.url }, sourcemap: { includeContent : true, sourceRoot : '/src' }, rename: { json : { extname : '.json' }, minJS : { extname : '.min.js' }, minCSS : { extname : '.min.css' } }, wrench: { recursive: { forceDelete : false, excludeHiddenUnix : true, preserveFiles : true } } };