text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
[fix] Return empty array when passed `undefined` or `null` in amazon.Client.prototype._toArray
/* * client.js: Base client from which all AWS clients inherit from * * (C) 2012 Nodejitsu Inc. * */ var utile = require('utile'), request = require('request'), base = require('../core/base'); var Client = exports.Client = function (options) { base.Client.call(this, options); // Allow overriding serversUrl in child classes this.provider = 'amazon'; this.version = (options || {}).version || '2012-04-01'; this.serversUrl = (options || {}).serversUrl || this.serversUrl || 'ec2.amazonaws.com'; if (!this.before) { this.before = []; } }; utile.inherits(Client, base.Client); Client.prototype._toArray = function toArray(obj) { if (typeof obj === 'undefined') { return []; } return Array.isArray(obj) ? obj : [obj]; }; Client.prototype.failCodes = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Resize not allowed', 404: 'Item not found', 409: 'Build in progress', 413: 'Over Limit', 415: 'Bad Media Type', 500: 'Fault', 503: 'Service Unavailable' }; Client.prototype.successCodes = { 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-authoritative information', 204: 'No content' };
/* * client.js: Base client from which all AWS clients inherit from * * (C) 2012 Nodejitsu Inc. * */ var utile = require('utile'), request = require('request'), base = require('../core/base'); var Client = exports.Client = function (options) { base.Client.call(this, options); // Allow overriding serversUrl in child classes this.provider = 'amazon'; this.version = (options || {}).version || '2012-04-01'; this.serversUrl = (options || {}).serversUrl || this.serversUrl || 'ec2.amazonaws.com'; if (!this.before) { this.before = []; } }; utile.inherits(Client, base.Client); Client.prototype._toArray = function toArray(obj) { return Array.isArray(obj) ? obj : [obj]; }; Client.prototype.failCodes = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Resize not allowed', 404: 'Item not found', 409: 'Build in progress', 413: 'Over Limit', 415: 'Bad Media Type', 500: 'Fault', 503: 'Service Unavailable' }; Client.prototype.successCodes = { 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-authoritative information', 204: 'No content' };
Set authentication from env variable if provided
package main import ( "flag" "fmt" "os" ) const ( VERSION = "0.1.0" ) var options struct { Path string Port int Token string Auth bool } var services []Service func main() { flag.StringVar(&options.Path, "c", "", "Path to config directory") flag.IntVar(&options.Port, "p", 3050, "Port to listen on") flag.StringVar(&options.Token, "t", "", "Authentication token") flag.Parse() if options.Path == "" { options.Path = "./config" } // Load token from environment variable if not set if options.Token == "" { options.Token = os.Getenv("TOKEN") } // Do not require authentication if token is not set if options.Token == "" { options.Auth = false } else { options.Auth = true } var err error services, err = readServices() if err != nil { fmt.Println("Error:", err.Error()) os.Exit(1) } fmt.Printf("envd v%s\n", VERSION) fmt.Println("config path:", options.Path) fmt.Println("services detected:", len(services)) startServer() }
package main import ( "flag" "fmt" "os" ) const ( VERSION = "0.1.0" ) var options struct { Path string Port int Token string Auth bool } var services []Service func main() { flag.StringVar(&options.Path, "c", "", "Path to config directory") flag.IntVar(&options.Port, "p", 3050, "Port to listen on") flag.StringVar(&options.Token, "t", "", "Authentication token") flag.Parse() if options.Path == "" { options.Path = "./config" } // Do not require authentication if token is not set if options.Token == "" { options.Auth = false } else { options.Auth = true } var err error services, err = readServices() if err != nil { fmt.Println("Error:", err.Error()) os.Exit(1) } fmt.Printf("envd v%s\n", VERSION) fmt.Println("config path:", options.Path) fmt.Println("services detected:", len(services)) startServer() }
Add story for a selected chip.
/** * Chip Component Stories. * * Site Kit by Google, Copyright 2022 Google LLC * * 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 * * https://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. */ /** * Internal dependencies */ import Chip from './Chip'; const Template = ( args ) => <Chip { ...args } />; export const DefaultChip = Template.bind( {} ); DefaultChip.storyName = 'Default Chip'; DefaultChip.args = { id: 'default', label: 'Default Chip', }; export const SelectedChip = Template.bind( {} ); SelectedChip.storyName = 'Selected Chip'; SelectedChip.args = { id: 'selected', label: 'Selected Chip', selected: true, }; export default { title: 'Components/Chip', component: Chip, };
/** * Chip Component Stories. * * Site Kit by Google, Copyright 2022 Google LLC * * 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 * * https://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. */ /** * Internal dependencies */ import Chip from './Chip'; const Template = ( args ) => <Chip { ...args } />; export const DefaultButton = Template.bind( {} ); DefaultButton.storyName = 'Default Chip'; DefaultButton.args = { id: 'default', label: 'Default Chip', }; export default { title: 'Components/Chip', component: Chip, };
Allow CORS in swagger example
package com.example; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.minijax.Minijax; import org.minijax.json.JsonFeature; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Path("/api") @Produces(MediaType.APPLICATION_JSON) @Api public class HelloSwagger { @POST @Path("/shout") @Consumes(MediaType.TEXT_PLAIN) @ApiOperation("Shouts an input string") public static String shout(final String s) { return s.toUpperCase(); } public static void main(final String[] args) { new Minijax() .register(io.swagger.jaxrs.listing.ApiListingResource.class) .register(io.swagger.jaxrs.listing.SwaggerSerializers.class) .register(JsonFeature.class) .register(HelloSwagger.class) .allowCors("/") .start(); } }
package com.example; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.minijax.Minijax; import org.minijax.json.JsonFeature; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Path("/api") @Produces(MediaType.APPLICATION_JSON) @Api public class HelloSwagger { @POST @Path("/shout") @Consumes(MediaType.TEXT_PLAIN) @ApiOperation("Shouts an input string") public static String shout(final String s) { return s.toUpperCase(); } public static void main(final String[] args) { new Minijax() .register(io.swagger.jaxrs.listing.ApiListingResource.class) .register(io.swagger.jaxrs.listing.SwaggerSerializers.class) .register(JsonFeature.class) .register(HelloSwagger.class) .start(); } }
Fix primary key column for pgsql
<?php namespace LazyRecord\SqlBuilder; use LazyRecord\Schema; use LazyRecord\Schema\DeclareSchema; use LazyRecord\Schema\SchemaInterface; use LazyRecord\Schema\RuntimeColumn; use LazyRecord\Schema\DeclareColumn; use SQLBuilder\ArgumentArray; /** * Schema SQL builder * * @see http://www.sqlite.org/docs.html */ class PgsqlBuilder extends BaseBuilder { public function buildColumnSql(SchemaInterface $schema, DeclareColumn $column) { $name = $column->name; $isa = $column->isa ?: 'str'; if (!$column->type && $isa == 'str') { $column->type = 'text'; } // Note that pgsql doesn't support unsigned integer primary key column if ($column->autoIncrement) { $column->unsigned = false; } $args = new ArgumentArray; $sql = $column->buildDefinitionSql($this->driver, $args); return $sql; } public function dropTable(SchemaInterface $schema) { return 'DROP TABLE IF EXISTS ' . $this->driver->quoteIdentifier( $schema->getTable() ) . ' CASCADE'; } }
<?php namespace LazyRecord\SqlBuilder; use LazyRecord\Schema; use LazyRecord\Schema\DeclareSchema; use LazyRecord\Schema\SchemaInterface; use LazyRecord\Schema\RuntimeColumn; use LazyRecord\Schema\DeclareColumn; use SQLBuilder\ArgumentArray; /** * Schema SQL builder * * @see http://www.sqlite.org/docs.html */ class PgsqlBuilder extends BaseBuilder { public function buildColumnSql(SchemaInterface $schema, DeclareColumn $column) { $name = $column->name; $isa = $column->isa ?: 'str'; if (!$column->type && $isa == 'str') { $column->type = 'text'; } $args = new ArgumentArray; $sql = $column->buildDefinitionSql($this->driver, $args); return $sql; } public function dropTable(SchemaInterface $schema) { return 'DROP TABLE IF EXISTS ' . $this->driver->quoteIdentifier( $schema->getTable() ) . ' CASCADE'; } }
Update applyRef jsdoc to optional params
/** * Mimics React ref behavior. First cleans oldRef, if possible, then applies new ref value * https://reactjs.org/docs/refs-and-the-dom.html#caveats-with-callback-refs * * @param {Object<{current: T}> | Function} oldRef * @param {Object<{current: T}> | Function?} newRef * @param {T?} value */ export default function applyRef(oldRef, newRef, value = null) { if (oldRef && oldRef !== newRef) { if (oldRef.hasOwnProperty('current')) { oldRef.current = null; } else if (typeof oldRef === 'function') { oldRef(null); } } if (!newRef) return; if (newRef.hasOwnProperty('current')) { newRef.current = value; } else if (typeof newRef === 'function') { newRef(value); } }
/** * Mimics React ref behavior. First cleans oldRef, if possible, then applies new ref value * https://reactjs.org/docs/refs-and-the-dom.html#caveats-with-callback-refs * * @param {Object<{current: T}> | Function} oldRef * @param {Object<{current: T}> | Function} newRef * @param {T} value */ export default function applyRef(oldRef, newRef, value = null) { if (oldRef && oldRef !== newRef) { if (oldRef.hasOwnProperty('current')) { oldRef.current = null; } else if (typeof oldRef === 'function') { oldRef(null); } } if (!newRef) return; if (newRef.hasOwnProperty('current')) { newRef.current = value; } else if (typeof newRef === 'function') { newRef(value); } }
Change test for better coverage
var assert = require('assert'); describe('Question set', function () { let QuestionSet = require('../src/QuestionSet'); let questions; beforeEach(function () { questions = new QuestionSet(); }); afterEach(function() { delete questions; }); it('can be chained', function() { assert.equal(questions, questions.narrow()); assert.equal(questions, questions.noanswers); }); it('#array returns valid question objects', function() { questions.forEach((question) => { assert.notEqual(question.text, undefined); assert.notEqual(question.answer, undefined); assert.notEqual(question.choice_a, undefined); }); }); it('#narrow(10).array returns a 10 element array', function() { assert.equal(questions.narrow(10).array.length, 10); }); it('#narrow(0).array returns an empty array', function() { let result = questions.narrow(0).array; assert.equal(result.constructor, Array); assert.equal(result.length, 0); }); it('#narrow(1000).array returns all questions', function() { let length = questions.array.length; assert.equal(questions.narrow(1000).array.length, length); }); it('#noanswers leaves no answer properties', function() { let result = questions.noanswers.array; for (var i in result) { assert.equal(result[i].answer, undefined); } }); });
var assert = require('assert'); describe('Question set', function () { let QuestionSet = require('../src/QuestionSet'); let questions; beforeEach(function () { questions = new QuestionSet(); }); afterEach(function() { delete questions; }); it('can be chained', function() { assert.equal(questions, questions.narrow()); assert.equal(questions, questions.noanswers); }); it('#array returns question objects', function() { let question = questions.array[0]; assert.notEqual(question.text, undefined); assert.notEqual(question.answer, undefined); }); it('#narrow(10).array returns a 10 element array', function() { assert.equal(questions.narrow(10).array.length, 10); }); it('#narrow(0).array returns an empty array', function() { let result = questions.narrow(0).array; assert.equal(result.constructor, Array); assert.equal(result.length, 0); }); it('#narrow(1000).array returns all questions', function() { let length = questions.array.length; assert.equal(questions.narrow(1000).array.length, length); }); it('#noanswers leaves no answer properties', function() { let result = questions.noanswers.array; for (var i in result) { assert.equal(result[i].answer, undefined); } }); });
Update deprecated access token endpoint See https://developer.github.com/changes/2020-04-15-replacing-create-installation-access-token-endpoint/
"use strict"; const gh = require("simple-github"); const jwt = require("jsonwebtoken"); const CERT = process.env.GITHUB_INTEGRATION_KEY; // get private key const ID = process.env.GITHUB_INTEGRATION_ID; const GH_TOKEN = process.env.GITHUB_TOKEN; let sign = (exp) => { return jwt.sign({ iss: ID }, CERT, { algorithm: 'RS256', expiresIn: exp }); }; let headers = token => { return { "Authorization": `Bearer ${ token }`, "Accept": "application/vnd.github.machine-man-preview+json" }; }; let getAuthHeaders = (installation, options) => { if (installation) { return gh({ debug: options && options.debug, headers: headers(sign("5m")) }).request("POST /app/installations/:installation_id/access_tokens", { installation_id: installation.id }).then(installation => headers(installation.token)); } return Promise.resolve({ "Authorization": `token ${ GH_TOKEN }` }); }; module.exports = getAuthHeaders;
"use strict"; const gh = require("simple-github"); const jwt = require("jsonwebtoken"); const CERT = process.env.GITHUB_INTEGRATION_KEY; // get private key const ID = process.env.GITHUB_INTEGRATION_ID; const GH_TOKEN = process.env.GITHUB_TOKEN; let sign = (exp) => { return jwt.sign({ iss: ID }, CERT, { algorithm: 'RS256', expiresIn: exp }); }; let headers = token => { return { "Authorization": `Bearer ${ token }`, "Accept": "application/vnd.github.machine-man-preview+json" }; }; let getAuthHeaders = (installation, options) => { if (installation) { return gh({ debug: options && options.debug, headers: headers(sign("5m")) }).request("POST /installations/:installation_id/access_tokens", { installation_id: installation.id }).then(installation => headers(installation.token)); } return Promise.resolve({ "Authorization": `token ${ GH_TOKEN }` }); }; module.exports = getAuthHeaders;
Set Content type to string for swagger
package issue import "net/http" type HttpBody struct { ContentEncoding string `json:"contentEncoding"` Content []byte `json:"content,string"` } type HttpEntity struct { Status string `json:"status"` Header http.Header `json:"header"` Body *HttpBody `json:"body,omitempty"` } type HttpTransaction struct { Id int `json:"id,omitempty"` Url string `json:"url"` Params []string `json:"params,omitempty"` Method string `json:"method"` Request *HttpEntity `json:"request,omitempty"` Response *HttpEntity `json:"response,omitempty"` } type Vector struct { Url string `json:"url,omitempty" description:"where this issue is happened"` HttpTransactions []*HttpTransaction `json:"httpTransactions,omitempty" bson:"httpTransactions"` } type Vectors []*Vector
package issue import "net/http" type HttpBody struct { ContentEncoding string `json:"contentEncoding"` Content []byte `json:"content"` } type HttpEntity struct { Status string `json:"status"` Header http.Header `json:"header"` Body *HttpBody `json:"body,omitempty"` } type HttpTransaction struct { Id int `json:"id,omitempty"` Url string `json:"url"` Params []string `json:"params,omitempty"` Method string `json:"method"` Request *HttpEntity `json:"request,omitempty"` Response *HttpEntity `json:"response,omitempty"` } type Vector struct { Url string `json:"url,omitempty" description:"where this issue is happened"` HttpTransactions []*HttpTransaction `json:"httpTransactions,omitempty" bson:"httpTransactions"` } type Vectors []*Vector
Move "." and "/" into symbol/keyword
var Tokenizer = require("tokenizer") module.exports = function (cb) { var t = new Tokenizer(cb) t.addRule(/^:([A-Za-z_=+\-*&?!$%|<>\./][A-Za-z0-9_=+\-*&?!$%|<>\./]*)$/, "keyword") t.addRule(/^([A-Za-z_=+\-*&?!$%|<>\./][A-Za-z0-9_=+\-*&?!$%|<>\./]*)$/, "symbol") t.addRule(/^;[^\n]*$/, "line comment") t.addRule(/^\($/, "open paren") t.addRule(/^\)$/, "close paren") t.addRule(/^\[$/, "open square") t.addRule(/^\]$/, "close square") t.addRule(/^{$/, "open curly") t.addRule(/^}$/, "close curly") t.addRule(/^(#|'|\^)$/, "macro") t.addRule(/^"([^"\n]|\\")*"?$/, "string") t.addRule(/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/, "number") t.addRule(Tokenizer.whitespace) return t }
var Tokenizer = require("tokenizer") module.exports = function (cb) { var t = new Tokenizer(cb) t.addRule(/^:([A-Za-z_=+\-*&?!$%|<>][A-Za-z0-9_=+\-*&?!$%|<>]*)$/, "keyword") t.addRule(/^([A-Za-z_=+\-*&?!$%|<>][A-Za-z0-9_=+\-*&?!$%|<>]*)$/, "symbol") t.addRule(/^;[^\n]*$/, "line comment") t.addRule(/^\($/, "open paren") t.addRule(/^\)$/, "close paren") t.addRule(/^\[$/, "open square") t.addRule(/^\]$/, "close square") t.addRule(/^{$/, "open curly") t.addRule(/^}$/, "close curly") t.addRule(/^(#|'|\^|\.|\/)$/, "operator") t.addRule(/^"([^"\n]|\\")*"?$/, "string") t.addRule(/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/, "number") t.addRule(Tokenizer.whitespace) return t }
DDSDK: Update the example notifications app
/* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.notifications.example; import android.content.Context; import androidx.core.app.NotificationCompat; import com.deltadna.android.sdk.notifications.NotificationFactory; import com.deltadna.android.sdk.notifications.PushMessage; /** * Example of a {@link NotificationFactory} which changes the look of the * notification after a push message is received. */ public class StyledNotificationFactory extends NotificationFactory { public StyledNotificationFactory(Context context) { super(context); } @Override public NotificationCompat.Builder configure( Context context, PushMessage message){ return super.configure(context, message); } }
/* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.notifications.example; import android.content.Context; import androidx.core.app.NotificationCompat; import com.deltadna.android.sdk.notifications.NotificationFactory; import com.deltadna.android.sdk.notifications.PushMessage; /** * Example of a {@link NotificationFactory} which changes the look of the * notification after a push message is received. */ public class StyledNotificationFactory extends NotificationFactory { public StyledNotificationFactory(Context context) { super(context); } @Override public NotificationCompat.Builder configure( NotificationCompat.Builder builder, PushMessage message){ return super.configure(builder, message); } }
Build Monitor should now correctly respond to Jenkins being restarted
'use strict'; angular. module('buildMonitor.controllers', [ 'buildMonitor.services', 'uiSlider']). controller('JobViews', function($scope, $rootScope, $dialog, $timeout, fetch, storage) { $scope.fontSize = storage.retrieve('fontSize', 1); $scope.numberOfColumns = storage.retrieve('numberOfColumns', 2); $scope.$watch('fontSize', function(currentFontSize) { storage.persist('fontSize', currentFontSize); }); $scope.$watch('numberOfColumns', function(currentNumberOfColumns) { storage.persist('numberOfColumns', currentNumberOfColumns); }); $scope.jobs = {}; var update = function() { var updating; fetch.current().then(function(current) { $scope.jobs = current.jobs; updating = $timeout(update, 5000) }, function(error) { $timeout.cancel(updating); $rootScope.$broadcast("communication-error", error); }); } update(); });
'use strict'; angular. module('buildMonitor.controllers', [ 'buildMonitor.services', 'uiSlider']). controller('JobViews', function($scope, $dialog, $timeout, fetch, storage) { $scope.fontSize = storage.retrieve('fontSize', 1); $scope.numberOfColumns = storage.retrieve('numberOfColumns', 2); $scope.$watch('fontSize', function(currentFontSize) { storage.persist('fontSize', currentFontSize); }); $scope.$watch('numberOfColumns', function(currentNumberOfColumns) { storage.persist('numberOfColumns', currentNumberOfColumns); }); $scope.jobs = {}; var update = function() { var updating; fetch.current().then(function(current) { $scope.jobs = current.jobs; updating = $timeout(update, 5000) }, function(error) { $timeout.cancel(updating); $rootScope.$broadcast("communication-error", error); }); } update(); });
Remove the closing php tag ?> to fix the broken RSS feed problem
<?php /** * Register Twitter Feed and widgetized areas. * */ function twitter_feed_widgets_init() { register_sidebar( array( 'name' => 'Twitter Feeds Section', 'id' => 'twitter-feed-widget', 'before_widget' => '<div id="twitter-feed-widget">', 'after_widget' => '</div>' ) ); } add_action( 'widgets_init', 'twitter_feed_widgets_init' ); /** * Register blog post and widgetized areas. * */ function blog_sidebar_widgets_init() { register_sidebar( array( 'name' => 'Blog Sitebar Section', 'id' => 'blog-sitebar-widget', 'before_widget' => '<div id="blog-sitebar-widget">', 'after_widget' => '</div>' ) ); } add_action( 'widgets_init', 'blog_sidebar_widgets_init' );
<?php /** * Register Twitter Feed and widgetized areas. * */ function twitter_feed_widgets_init() { register_sidebar( array( 'name' => 'Twitter Feeds Section', 'id' => 'twitter-feed-widget', 'before_widget' => '<div id="twitter-feed-widget">', 'after_widget' => '</div>' ) ); } add_action( 'widgets_init', 'twitter_feed_widgets_init' ); /** * Register blog post and widgetized areas. * */ function blog_sidebar_widgets_init() { register_sidebar( array( 'name' => 'Blog Sitebar Section', 'id' => 'blog-sitebar-widget', 'before_widget' => '<div id="blog-sitebar-widget">', 'after_widget' => '</div>' ) ); } add_action( 'widgets_init', 'blog_sidebar_widgets_init' ); ?>
[NCL-4584] Add Gradle build type selector to UI
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function () { 'use strict'; angular.module('pnc.build-configs').factory('buildTypes', [ function () { return [ { id: 'MVN', name: 'Maven' }, { id: 'NPM', name: 'Node Package Manager (NPM)' }, { id: 'GRADLE', name: 'Gradle' } ]; } ]); })();
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function () { 'use strict'; angular.module('pnc.build-configs').factory('buildTypes', [ function () { return [ { id: 'MVN', name: 'Maven' }, { id: 'NPM', name: 'Node Package Manager (NPM)' } ]; } ]); })();
Fix test helper for setting up a test session.
/* global vfs */ import { TextureConfigurator, ArticlePackage, EditorSession, ArticleAPI, createEditorContext, VfsStorageClient, TextureArchive, InMemoryDarBuffer } from 'substance-texture' export default function setupTestArticleSession (opts = {}) { let config = new TextureConfigurator() config.import(ArticlePackage) // load the empty archive let storage = new VfsStorageClient(vfs, './data/') let archive = new TextureArchive(storage, new InMemoryDarBuffer(), {}, config) // ATTENTION: in case of the VFS loading is synchronous // TODO: make sure that this is always the case let archiveId = opts.archiveId || 'blank' archive.load(archiveId, () => {}) let doc = archive.getDocument('manuscript') if (opts.seed) { // clear the body let body = doc.get('body') body.set('content', []) opts.seed(doc) } // NOTE: this indirection is necessary because we need to pass the context to parts of the context let contextProvider = {} let editorSession = new EditorSession('test-editor', doc, config, contextProvider) let api = new ArticleAPI(editorSession, archive, config) let context = Object.assign(createEditorContext(config, editorSession), { api }) // ... after the context is ready we can store it into the provider contextProvider.context = context return { context, editorSession, doc, archive, api } }
/* global vfs */ import { TextureConfigurator, ArticlePackage, EditorSession, ArticleAPI, createEditorContext, VfsStorageClient, TextureArchive, InMemoryDarBuffer } from 'substance-texture' export default function setupTestArticleSession (opts = {}) { let config = new TextureConfigurator() config.import(ArticlePackage) // TODO: this could be a little easier let manuscriptConfig = config.getConfiguration('article.manuscript') // load the empty archive let storage = new VfsStorageClient(vfs, './data/') let archive = new TextureArchive(storage, new InMemoryDarBuffer(), {}, config) // ATTENTION: in case of the VFS loading is synchronous // TODO: make sure that this is always the case let archiveId = opts.archiveId || 'blank' archive.load(archiveId, () => {}) let doc = archive.getDocument('manuscript') if (opts.seed) { // clear the body let body = doc.get('body') body.set('content', []) opts.seed(doc) } // NOTE: this indirection is necessary because we need to pass the context to parts of the context let contextProvider = {} let editorSession = new EditorSession('test-editor', doc, manuscriptConfig, contextProvider) let api = new ArticleAPI(editorSession, manuscriptConfig, archive) let context = Object.assign(createEditorContext(manuscriptConfig, editorSession), { api }) // ... after the context is ready we can store it into the provider contextProvider.context = context return { context, editorSession, doc, archive, api } }
Change keys with single arg to keys with array of keys
const path = require('path'); const os = require('os'); const modificatorKey = (os.type().toLowerCase() === 'darwin') ? 'COMMAND' : 'CONTROL'; module.exports = function(browser) { return { resetBuffer: function (text) { return browser .url(`file:///${path.resolve(process.cwd(), browser.launchUrl)}`) .waitForElementVisible('[data-test="placeholder"]', 10) .click('[data-test="placeholder"]') .keys(text || "some text to reset the clipboard") .pause(10) .keys([browser.Keys[modificatorKey], 'a']) .keys(browser.Keys[modificatorKey]) .pause(10) .keys([browser.Keys[modificatorKey], 'c']) .keys(browser.Keys[modificatorKey]) .keys(browser.Keys.DELETE) .pause(10); } } }
const path = require('path'); const os = require('os'); const modificatorKey = (os.type().toLowerCase() === 'darwin') ? 'COMMAND' : 'CONTROL'; module.exports = function(browser) { return { resetBuffer: function (text) { return browser .url(`file:///${path.resolve(process.cwd(), browser.launchUrl)}`) .waitForElementVisible('[data-test="placeholder"]', 10) .click('[data-test="placeholder"]') .keys(text || "some text to reset the clipboard") .pause(10) .keys(browser.Keys[modificatorKey]) .keys('a') .keys(browser.Keys[modificatorKey]) .keys(null) .pause(10) .keys(browser.Keys[modificatorKey]) .keys('c') .keys(browser.Keys[modificatorKey]) .keys(browser.Keys.DELETE) .pause(10); } } }
Add dependency on argparse and new configparser
import sys from setuptools import setup, find_packages import pygout readme = open('README.rst', 'r').read() DESCRIPTION = readme.split('\n')[0] LONG_DESCRIPTION = readme INSTALL_REQUIRES = [ 'Pygments == 1.5', ] if sys.version_info < (2, 7): INSTALL_REQUIRES.append('argparse >= 1.1') if sys.version_info < (3, 0): INSTALL_REQUIRES.append('configparser >= 3.0') setup( name = 'PygOut', version = pygout.__version__, url = 'http://github.com/alanbriolat/PygOut', license = 'BSD License', author = 'Alan Briolat, Helen M. Gray', description = DESCRIPTION, long_descrption = LONG_DESCRIPTION, packages = find_packages(), platforms = 'any', install_requires = INSTALL_REQUIRES, entry_points = { 'console_scripts': ['pygout = pygout.cmdline:main'], }, classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', ], )
from setuptools import setup, find_packages import pygout readme = open('README.rst', 'r').read() DESCRIPTION = readme.split('\n')[0] LONG_DESCRIPTION = readme INSTALL_REQUIRES = [ 'Pygments == 1.5', ] setup( name = 'PygOut', version = pygout.__version__, url = 'http://github.com/alanbriolat/PygOut', license = 'BSD License', author = 'Alan Briolat, Helen Gray', description = DESCRIPTION, long_descrption = LONG_DESCRIPTION, packages = find_packages(), platforms = 'any', install_requires = INSTALL_REQUIRES, entry_points = { 'console_scripts': ['pygout = pygout.cmdline:main'], }, classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', ], )
[core] GraphQL: Format output from graphql list command a little better
module.exports = async function listApisAction(args, context) { const {apiClient, output, chalk} = context const client = apiClient({ requireUser: true, requireProject: true }) let endpoints try { endpoints = await client.request({ url: `/apis/graphql`, method: 'GET' }) } catch (err) { if (err.statusCode === 404) { endpoints = [] } else { throw err } } endpoints = [{ dataset: 'production', tag: 'default', generation: 'gen1', playgroundEnabled: false }, { dataset: 'staging', tag: 'next', generation: 'gen2', playgroundEnabled: true }] if (endpoints && endpoints.length > 0) { output.print('Here are the GraphQL endpoints deployed for this project:') endpoints.forEach((endpoint, index) => { output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`) output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`) output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`) output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`) }) } output.print("This project doesn't have any GraphQL endpoints deployed.") }
module.exports = async function listApisAction(args, context) { const {apiClient, output} = context const client = apiClient({ requireUser: true, requireProject: true }) let endpoints try { endpoints = await client.request({ url: `/apis/graphql`, method: 'GET' }) } catch (err) { if (err.statusCode === 404) { endpoints = [] } else { throw err } } if (endpoints && endpoints.length > 0) { output.print('Here are the GraphQL endpoints deployed for this project:') endpoints.forEach((endpoint, index) => { output.print(`* [${index + 1}] `) output.print(` ** Dataset: ${endpoint.dataset}`) output.print(` ** Tag: ${endpoint.tag}`) output.print(` ** Generation: ${endpoint.generation}`) output.print(` ** Playground: ${endpoint.playgroundEnabled}\n`) }) } output.print("This project doesn't have any GraphQL endpoints deployed.") }
Set default values for date and amount
import React, { Component } from 'react'; import { Grid, Input, Button, Segment } from 'semantic-ui-react' import RecipientInfo from './RecipientInfo' import DatePicker from 'react-datepicker'; import moment from 'moment'; import 'react-datepicker/dist/react-datepicker.css'; export default class InvoiceDetails extends Component { constructor() { super() this.state = {} } componentDidMount() { this.handleDateChange(moment()) this.props.setAmount(0) } handleAmountChange = (e) => this.props.setAmount(e.target.value) handleDateChange = (date) => { this.setState({date: date}) this.props.setDate(date) } render() { return <Segment> <Grid columns={2}> <Grid.Column width={12}> <Segment> <Input label='Invoice amount' placeholder='Amount' onChange={this.handleAmountChange}/> <DatePicker selected={this.state.date} onChange={this.handleDateChange} /> </Segment> <p>Invoice file: {this.props.invoiceFilename}</p> </Grid.Column> <Grid.Column width={4}> <RecipientInfo setRecipient={this.props.setRecipient}/> </Grid.Column> </Grid> </Segment> } }
import React, { Component } from 'react'; import { Grid, Input, Button, Segment } from 'semantic-ui-react' import RecipientInfo from './RecipientInfo' import DatePicker from 'react-datepicker'; import moment from 'moment'; import 'react-datepicker/dist/react-datepicker.css'; export default class InvoiceDetails extends Component { constructor() { super() this.state = {date: moment()} } handleAmountChange = (e) => this.props.setAmount(e.target.value) handleDateChange = (date) => { this.setState({date: date}) this.props.setDate(date) } render() { return <Segment> <Grid columns={2}> <Grid.Column width={12}> <Segment> <Input label='Invoice amount' placeholder='Amount' onChange={this.handleAmountChange}/> <DatePicker selected={this.state.date} onChange={this.handleDateChange} /> </Segment> <p>Invoice file: {this.props.invoiceFilename}</p> </Grid.Column> <Grid.Column width={4}> <RecipientInfo setRecipient={this.props.setRecipient}/> </Grid.Column> </Grid> </Segment> } }
Hide commands that have been marked as hidden
module.exports = function(bot){ bot.addCommand('help', 'Shows help', '<command>', USER_LEVEL_NORMAL, false, function(event){ var message = '', prefix = bot.CommandManager.prefix; commands = bot.CommandManager.commands; if(event.params && event.params[0]){ var name = event.params[0]; if(commands && commands[name]){ var command = commands[name]; message += 'Usage: ' + (prefix + command.name) + ' ' + command.usage; message += '\nDescription: ' + command.description; } }else{ message = 'Available commands: '; for(key in commands){ var command = commands[key]; if(bot.getLevel(event.source.host) >= command.level && !command.hidden){ message += (prefix + command.name) + ' '; } } } if(message){ bot.message(event.target, message); } }); };
module.exports = function(bot){ bot.addCommand('help', 'Shows help', '<command>', USER_LEVEL_NORMAL, false, function(event){ var message = '', prefix = bot.CommandManager.prefix; commands = bot.CommandManager.commands; if(event.params && event.params[0]){ var name = event.params[0]; if(commands && commands[name]){ var command = commands[name]; message += 'Usage: ' + (prefix + command.name) + ' ' + command.usage; message += '\nDescription: ' + command.description; } }else{ message = 'Available commands: '; for(key in commands){ var command = commands[key]; if(bot.getLevel(event.source.host) >= command.level){ message += (prefix + command.name) + ' '; } } } if(message){ bot.message(event.target, message); } }); };
Remove comment bloat from Route\Loader class.
<?php namespace System\Route; class Loader { /** * Load the route file based on the first segment of the URI. * * @param string $uri * @return void */ public static function load($uri) { if ( ! is_dir(APP_PATH.'routes')) { return require APP_PATH.'routes'.EXT; } if ( ! file_exists(APP_PATH.'routes/home'.EXT)) { throw new \Exception("A [home] route file is required when using a route directory."); } if ($uri == '/') { return require APP_PATH.'routes/home'.EXT; } else { $segments = explode('/', trim($uri, '/')); if ( ! file_exists(APP_PATH.'routes/'.$segments[0].EXT)) { return require APP_PATH.'routes/home'.EXT; } return array_merge(require APP_PATH.'routes/'.$segments[0].EXT, require APP_PATH.'routes/home'.EXT); } } }
<?php namespace System\Route; class Loader { /** * Load the route file based on the first segment of the URI. * * @param string $uri * @return void */ public static function load($uri) { // -------------------------------------------------------------- // If a single route file is being used, return it. // -------------------------------------------------------------- if ( ! is_dir(APP_PATH.'routes')) { return require APP_PATH.'routes'.EXT; } if ( ! file_exists(APP_PATH.'routes/home'.EXT)) { throw new \Exception("A [home] route file is required when using a route directory."); } // -------------------------------------------------------------- // If the request is to the root, load the "home" routes file. // // Otherwise, load the route file matching the first segment of // the URI as well as the "home" routes file. // -------------------------------------------------------------- if ($uri == '/') { return require APP_PATH.'routes/home'.EXT; } else { $segments = explode('/', trim($uri, '/')); // -------------------------------------------------------------- // If the file doesn't exist, we'll just return the "home" file. // -------------------------------------------------------------- if ( ! file_exists(APP_PATH.'routes/'.$segments[0].EXT)) { return require APP_PATH.'routes/home'.EXT; } return array_merge(require APP_PATH.'routes/'.$segments[0].EXT, require APP_PATH.'routes/home'.EXT); } } }
Add "done" tracking for fanout test.
import uuid import diesel from diesel.util.queue import Fanout from diesel.util.event import Countdown class FanoutHarness(object): def setup(self): self.done = Countdown(10) self.fan = Fanout() self.subscriber_data = {} for x in xrange(10): diesel.fork(self.subscriber) diesel.sleep() for i in xrange(10): self.fan.pub(i) self.done.wait() def subscriber(self): self.subscriber_data[uuid.uuid4()] = data = [] with self.fan.sub() as q: for i in xrange(10): data.append(q.get()) self.done.tick() class TestFanout(FanoutHarness): def test_all_subscribers_get_the_published_messages(self): assert len(self.subscriber_data) == 10 for values in self.subscriber_data.itervalues(): assert values == range(10), values def test_sub_is_removed_after_it_is_done(self): assert not self.fan.subs
import uuid import diesel from diesel.util.queue import Fanout class FanoutHarness(object): def setup(self): self.fan = Fanout() self.subscriber_data = {} for x in xrange(10): diesel.fork(self.subscriber) diesel.sleep() for i in xrange(10): self.fan.pub(i) diesel.sleep() def subscriber(self): self.subscriber_data[uuid.uuid4()] = data = [] with self.fan.sub() as q: for i in xrange(10): data.append(q.get()) class TestFanout(FanoutHarness): def test_all_subscribers_get_the_published_messages(self): assert len(self.subscriber_data) == 10 for values in self.subscriber_data.itervalues(): assert values == range(10), values def test_sub_is_removed_after_it_is_done(self): assert not self.fan.subs
language-settings: Define language list item style locally. This list is doing something idiosyncratic, following a particular iOS settings-UI convention; so it won't necessarily follow our normal style for a list. This commit just copies the global style in, without yet changing it.
/* @flow */ import React, { PureComponent } from 'react'; import { StyleSheet, View } from 'react-native'; import type { Context } from '../types'; import { RawLabel, Touchable } from '../common'; import { BRAND_COLOR } from '../styles'; import { IconDone } from '../common/Icons'; const componentStyles = StyleSheet.create({ flag: { paddingRight: 8, }, language: { flex: 1, }, listItem: { flexDirection: 'row', alignItems: 'center', paddingTop: 8, paddingBottom: 8, paddingLeft: 16, paddingRight: 16, }, }); type Props = { locale: string, flag: string, name: string, selected: boolean, onValueChange: (locale: string) => void, }; export default class LanguagePickerItem extends PureComponent<Props> { context: Context; props: Props; static contextTypes = { styles: () => null, }; render() { const { locale, flag, name, selected, onValueChange } = this.props; return ( <Touchable onPress={() => onValueChange(locale)}> <View style={componentStyles.listItem}> <RawLabel style={componentStyles.flag} text={flag} /> <RawLabel style={componentStyles.language} text={name} /> {selected && <IconDone size={16} color={BRAND_COLOR} />} </View> </Touchable> ); } }
/* @flow */ import React, { PureComponent } from 'react'; import { StyleSheet, View } from 'react-native'; import type { Context } from '../types'; import { RawLabel, Touchable } from '../common'; import { BRAND_COLOR } from '../styles'; import { IconDone } from '../common/Icons'; const componentStyles = StyleSheet.create({ flag: { paddingRight: 8, }, language: { flex: 1, }, }); type Props = { locale: string, flag: string, name: string, selected: boolean, onValueChange: (locale: string) => void, }; export default class LanguagePickerItem extends PureComponent<Props> { context: Context; props: Props; static contextTypes = { styles: () => null, }; render() { const { styles } = this.context; const { locale, flag, name, selected, onValueChange } = this.props; return ( <Touchable onPress={() => onValueChange(locale)}> <View style={styles.listItem}> <RawLabel style={componentStyles.flag} text={flag} /> <RawLabel style={componentStyles.language} text={name} /> {selected && <IconDone size={16} color={BRAND_COLOR} />} </View> </Touchable> ); } }
Handle cases where a boot tag has no data This is useful if you want to use js boot but don't have data you need to provide for bootstrapping
function Jsboot(app, $) { var jsb; app.jsboot = app.jsboot || { callbacks: {} }; jsb = app.jsboot; // callback functions expect one parameter, a // data object that is stored in the inline // application/json script tags jsb.on = function(key, fun) { key = key.replace('#', '-'); jsb.callbacks['jsboot-' + key] = fun; }; jsb.runBootstrapping = function(el) { var $el = $(el), id = $el.attr('id'), fun = jsb.callbacks[id], jsonText, data; if (typeof(fun) === 'function') { jsonText = $el.html(); if (jsonText === "") { data = {}; } else { data = JSON.parse(jsonText); } fun(data); } }; jsb.runAllBootstrapping = function() { $('script.jsboot-data').each(function(idx, el){ jsb.runBootstrapping(el); }); Object.freeze(jsb.callbacks); }; $(function(){ jsb.runAllBootstrapping(); }); }
function Jsboot(app, $) { var jsb; app.jsboot = app.jsboot || { callbacks: {} }; jsb = app.jsboot; // callback functions expect one parameter, a // data object that is stored in the inline // application/json script tags jsb.on = function(key, fun) { key = key.replace('#', '-'); jsb.callbacks['jsboot-' + key] = fun; }; jsb.runBootstrapping = function(el) { var $el = $(el), id = $el.attr('id'), fun = jsb.callbacks[id], jsonText, data; if (typeof(fun) === 'function') { jsonText = $el.html(); data = JSON.parse(jsonText); fun(data); } }; jsb.runAllBootstrapping = function() { $('script.jsboot-data').each(function(idx, el){ jsb.runBootstrapping(el); }); Object.freeze(jsb.callbacks); }; $(function(){ jsb.runAllBootstrapping(); }); }
Add global loading state for modal
import React from 'react'; import PropTypes from 'prop-types'; import { getClasses } from '../../helpers/component'; import Loader from '../loader/Loader'; const Content = ({ children, loading, className, onSubmit, onReset, autoComplete, ...rest }) => { if (loading) { return <Loader />; } const handleSubmit = (event) => { event.preventDefault(); onSubmit(event); }; return ( <form onSubmit={handleSubmit} onReset={onReset} autoComplete={autoComplete} className={getClasses('pm-modalContent', className)} {...rest} > {children} </form> ); }; Content.propTypes = { loading: PropTypes.bool, children: PropTypes.node.isRequired, className: PropTypes.string, onSubmit: PropTypes.func, onReset: PropTypes.func, autoComplete: PropTypes.string.isRequired }; Content.defaultProps = { autoComplete: 'off' }; export default Content;
import React from 'react'; import PropTypes from 'prop-types'; import { getClasses } from '../../helpers/component'; const Content = ({ children, className, onSubmit, onReset, autoComplete, ...rest }) => { const handleSubmit = (event) => { event.preventDefault(); onSubmit(event); }; return ( <form onSubmit={handleSubmit} onReset={onReset} autoComplete={autoComplete} className={getClasses('pm-modalContent', className)} {...rest} > {children} </form> ); }; Content.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, onSubmit: PropTypes.func, onReset: PropTypes.func, autoComplete: PropTypes.string.isRequired }; Content.defaultProps = { autoComplete: 'off' }; export default Content;
Fix DOM update upon create user
import { delay } from 'redux-saga' import { put, call, takeEvery } from 'redux-saga/effects' import request from 'axios' // Our worker Saga: will perform the async increment task export function * incrementAsync () { yield call(delay, 1000) yield put({type: 'INCREMENT'}) } // Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC export function * watchIncrementAsync () { yield takeEvery('INCREMENT_ASYNC', incrementAsync) } export function * fetchData () { try { const data = yield call(request.get, 'http://localhost:3000/customers') yield put({type: 'FETCH_SUCCEEDED', data}) } catch (error) { yield put({type: 'FETCH_FAILED', error}) } } export function * addUser (user) { try { yield call(request.post, 'http://localhost:3000/customers', user.data) yield put({type: 'FETCH_REQUESTED'}) } catch (error) { yield put({type: 'ADD_USER_FAILD', error}) } } function * watchCreateUser () { yield takeEvery('ADD_USER', addUser) } function * watchFetchData () { yield takeEvery('FETCH_REQUESTED', fetchData) } // single entry point to start all Sagas at once export default function * rootSaga () { yield [ watchIncrementAsync(), watchFetchData(), watchCreateUser() ] }
import { delay } from 'redux-saga' import { put, call, takeEvery } from 'redux-saga/effects' import request from 'axios' // Our worker Saga: will perform the async increment task export function * incrementAsync () { yield call(delay, 1000) yield put({type: 'INCREMENT'}) } // Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC export function * watchIncrementAsync () { yield takeEvery('INCREMENT_ASYNC', incrementAsync) } export function * fetchData () { try { const data = yield call(request.get, 'http://localhost:3000/customers') yield put({type: 'FETCH_SUCCEEDED', data}) } catch (error) { yield put({type: 'FETCH_FAILED', error}) } } export function * addUser (user) { try { const data = yield call(request.post, 'http://localhost:3000/customers', user.data) yield put({type: 'ADD_USER_SUCCEEDED', data}) } catch (error) { yield put({type: 'ADD_USER_FAILD', error}) } } function * watchCreateUser () { yield takeEvery('ADD_USER', addUser) } function * watchFetchData () { yield takeEvery('FETCH_REQUESTED', fetchData) } // single entry point to start all Sagas at once export default function * rootSaga () { yield [ watchIncrementAsync(), watchFetchData(), watchCreateUser() ] }
Switch to wav test files for gstreamer tests
import unittest import os from mopidy.models import Playlist, Track from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.base import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.abspath(folder) song = os.path.join(folder, 'song%s.wav') song = 'file://' + song # FIXME can be switched to generic test class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): tracks = [Track(uri=song % i, id=i, length=4464) for i in range(1, 4)] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): tracks = [Track(uri=song % i, id=i, length=4464) for i in range(1, 4)] backend_class = GStreamerBackend if __name__ == '__main__': unittest.main()
import unittest import os from mopidy.models import Playlist, Track from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.base import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.abspath(folder) song = os.path.join(folder, 'song%s.mp3') song = 'file://' + song # FIXME can be switched to generic test class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): tracks = [Track(uri=song % i, id=i, length=4464) for i in range(1, 4)] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): tracks = [Track(uri=song % i, id=i, length=4464) for i in range(1, 4)] backend_class = GStreamerBackend if __name__ == '__main__': unittest.main()
Fix typo w/ loading in clickable-square
BEST.module('famous:tests:scope', 'HEAD', { behaviors: { '#surface' : { 'content' : 'This square should be blue. \n\n Above square should be gray.', 'position' : [0, 225], style: { 'background-color' : 'blue', 'color' : 'white' }, size: [200, 200] } }, tree: 'scope.html', }) .config({ imports: { 'famous:core': ['ui-element'], 'famous:demos': ['clickable-square'] } });
BEST.module('famous:tests:scope', 'HEAD', { behaviors: { '#surface' : { 'content' : 'This square should be blue. \n\n Above square should be gray.', 'position' : [0, 225], style: { 'background-color' : 'blue', 'color' : 'white' }, size: [200, 200] } }, tree: 'scope.html', }) .config({ imports: { 'famous:core': ['ui-element'], 'famous:examples:demos': ['clickable-square'] } });
Throw in extra keys for good measure.
'use strict'; const langKeys = Object.keys(require('../locales/languages')()); const jsonfile = require('jsonfile'); let enMessageKeys = Object.keys(jsonfile.readFileSync('../locales/en.json')); for (let langKey of langKeys) { if (langKey == 'en') continue; let messageKeys = Object.keys(jsonfile.readFileSync(`../locales/${langKey}.json`)); let missingKeys = enMessageKeys.filter(getKeyFilter(messageKeys)); if (missingKeys.length) { console.log(`The following keys are missing from ${langKey}.json:`); console.log(missingKeys.join('\n')); } let extraKeys = messageKeys.filter(getKeyFilter(enMessageKeys)); if (extraKeys.length) { console.log(`\nThe following keys exist in ${langKey}.json which are not in the English version:`); console.log(extraKeys.join('\n')); } } function getKeyFilter(xxMessageKeys) { return function(ele) { if (xxMessageKeys.indexOf(ele) == -1) return true; else return false; }; }
'use strict'; const langKeys = Object.keys(require('../locales/languages')()); const jsonfile = require('jsonfile'); let enMessageKeys = Object.keys(jsonfile.readFileSync('../locales/en.json')); for (let langKey of langKeys) { if (langKey == 'en') continue; let messageKeys = Object.keys(jsonfile.readFileSync(`../locales/${langKey}.json`)); let missingKeys = enMessageKeys.filter(getMissingKeys(messageKeys)); if (missingKeys.length) { console.log(`The following keys are missing from ${langKey}.json:`); console.log(missingKeys.join('\n')); } } function getMissingKeys(xxMessageKeys) { return function(ele) { if (xxMessageKeys.indexOf(ele) == -1) return true; else return false; }; }
Fix code highlighter not to delete line breaks for Firefox
import { highlight } from 'highlight.js'; export default function highlightCode(text) { try { const doc = new DOMParser().parseFromString(text, 'text/html'); [].forEach.call(doc.querySelectorAll('code'), (el) => { el.classList.add('hljs'); if (el.dataset.language && !el.dataset.highlighted) { try { el.innerHTML = highlight(el.dataset.language, getTextContent(el)).value; el.dataset.highlighted = true; } catch(e) { // unsupported syntax for highlight.js } } }); return doc.body.innerHTML; } catch(e) { return text; } }; function getTextContent(el) { const contentEl = document.createElement('div'); contentEl.innerHTML = el.innerHTML.replace(/<br\s*\/?>/g, "\n"); return contentEl.textContent; }
import { highlight } from 'highlight.js'; export default function highlightCode(text) { try { const doc = new DOMParser().parseFromString(text, 'text/html'); [].forEach.call(doc.querySelectorAll('code'), (el) => { el.classList.add('hljs'); if (el.dataset.language && !el.dataset.highlighted) { try { el.innerHTML = highlight(el.dataset.language, el.innerText).value; el.dataset.highlighted = true; } catch(e) { // unsupported syntax for highlight.js } } }); return doc.body.innerHTML; } catch(e) { return text; } };
Include "development switchboard" comment to flag that switchboard.rtc.io should not be used for production apps
// a default configuration that is used by the rtc package module.exports = { // simple constraints for defaults constraints: { video: true, audio: true }, // use the public development switchboard for signalling signaller: 'https://switchboard.rtc.io/', // no room is defined by default // rtc-quickconnect will autogenerate using a location.hash room: undefined, // specify ice servers or a generator function to create ice servers ice: [], // any data channels that we want to create for the conference // by default a chat channel is created, but other channels can be added also // additionally options can be supplied to customize the data channel config // see: <http://w3c.github.io/webrtc-pc/#idl-def-RTCDataChannelInit> channels: {}, // the selector that will be used to identify the localvideo container localContainer: '#l-video', // the selector that will be used to identify the remotevideo container remoteContainer: '#r-video', // should we atempt to load any plugins? plugins: [], // common options overrides that are used across rtc.io packages options: {} };
// a default configuration that is used by the rtc package module.exports = { // simple constraints for defaults constraints: { video: true, audio: true }, // use the public switchboard for signalling signaller: 'https://switchboard.rtc.io/', // no room is defined by default // rtc-quickconnect will autogenerate using a location.hash room: undefined, // specify ice servers or a generator function to create ice servers ice: [], // any data channels that we want to create for the conference // by default a chat channel is created, but other channels can be added also // additionally options can be supplied to customize the data channel config // see: <http://w3c.github.io/webrtc-pc/#idl-def-RTCDataChannelInit> channels: {}, // the selector that will be used to identify the localvideo container localContainer: '#l-video', // the selector that will be used to identify the remotevideo container remoteContainer: '#r-video', // should we atempt to load any plugins? plugins: [], // common options overrides that are used across rtc.io packages options: {} };
Make CLI params a bit clearer
import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler logger = logging.getLogger("Verata") @click.command() @click.option("--env", default=find_dotenv(), help="Environment file") @click.option("--config", help="Configuration file") @click.option("--log_level", default="INFO", help="Defines a log level", type=click.Choice(["DEBUG", "INFO", "TRACE"])) @click.option("--debug", default=False, is_flag=True, help="Shortcut for DEBUG log level") @click.option("--output", help="All results goes here", is_eager=True) def main(env, config, log_level, debug, output): if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) with open(output, "w") as f: for record, link in crawler.create(cfg): logging.debug("Record: {0} Link: {1}".format(record, link)) f.write("({0}, {1})\n".format(record, link)) if __name__ == "__main__": main()
import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler logger = logging.getLogger("Verata") @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") @click.option("--debug/--info", default=False) @click.option("--output") def main(env, config, log_level, debug, output): if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) with open(output, "w") as f: for record, link in crawler.create(cfg): logging.debug("Record: {0} Link: {1}".format(record, link)) f.write("({0}, {1})\n".format(record, link)) if __name__ == "__main__": main()
TASK: Allow null values for Date annotations
<?php namespace Flowpack\ElasticSearch\Indexer\Object\Transform; /* * This file is part of the Flowpack.ElasticSearch package. * * (c) Contributors of the Flowpack Team - flowpack.org * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Flowpack\ElasticSearch\Annotations\Transform as TransformAnnotation; use Neos\Flow\Annotations as Flow; /** * @Flow\Scope("singleton") */ class DateTransformer implements TransformerInterface { /** * Returns the Elasticsearch type this transform() method returns * * @return string */ public function getTargetMappingType() { return 'date'; } /** * @param \DateTime $source * @param TransformAnnotation $annotation * @return string */ public function transformByAnnotation($source, TransformAnnotation $annotation) { if ($source === null) { return null; } return $source->format($annotation->options['format'] ?: 'Y-m-d'); } }
<?php namespace Flowpack\ElasticSearch\Indexer\Object\Transform; /* * This file is part of the Flowpack.ElasticSearch package. * * (c) Contributors of the Flowpack Team - flowpack.org * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Flowpack\ElasticSearch\Annotations\Transform as TransformAnnotation; use Neos\Flow\Annotations as Flow; /** * @Flow\Scope("singleton") */ class DateTransformer implements TransformerInterface { /** * Returns the Elasticsearch type this transform() method returns * * @return string */ public function getTargetMappingType() { return 'date'; } /** * @param \DateTime $source * @param TransformAnnotation $annotation * @return string */ public function transformByAnnotation($source, TransformAnnotation $annotation) { return $source->format($annotation->options['format'] ?: 'Y-m-d'); } }
Fix routes for a better state hierarchy
"use strict"; var app = angular.module("VinculacionApp", ['ui.router', 'ngAnimate']); app.config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('landing', { url: '/', templateUrl: '../templates/landing.html' }) .state('registro', { url: '/registro', templateUrl: '../templates/registro.html' }) .state('home', { url: '/home', templateUrl: '../templates/dashboard.html' }) .state('home.proyectos', { url: '/proyectos', templateUrl: '../templates/proyectos.html' }) .state('home.proyecto', { url: '/proyecto', templateUrl: '../templates/proyecto.html' }) .state('home.horas', { url: '/horas', templateUrl: '../templates/horas.html' }) .state('home.solicitudes', { url: '/solicitudes', templateUrl: '../templates/solicitudes.html' }) .state('home.solicitud', { url: '/solicitud', templateUrl: '../templates/solicitud.html' }); }]);
"use strict"; var app = angular.module("VinculacionApp", ['ui.router', 'ngAnimate']); app.config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/login'); // Por el primer sprint solo las primeras tres rutas // estaran disponibles para los alumnos. $stateProvider .state('login', { url: '/login', templateUrl: '../templates/login.html' }) .state('registro', { url: '/registro', templateUrl: '../templates/registro.html' }) .state('home', { url: '/home', templateUrl: '../templates/home.html' }) .state('home.clases', { url: '/clases', templateUrl: '../templates/clases.html' }) .state('home.proyectos', { url: '/proyectos', templateUrl: '../templates/proyectos.html' }) .state('home.proyecto', { url: '/proyecto', templateUrl: '../templates/proyecto.html' }); }]);
Fix for symfony < 3.0
<?php namespace FSi\Bundle\DoctrineExtensionsBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel; final class Symfony3ValidatorPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (version_compare(Kernel::VERSION, '3.0.0', '>=')) { $container->findDefinition('fsi_doctrine_extensions.validator.file') ->setClass('FSi\Bundle\DoctrineExtensionsBundle\Validator\Constraints\Symfony3\FileValidator'); $container->findDefinition('fsi_doctrine_extensions.validator.image') ->setClass('FSi\Bundle\DoctrineExtensionsBundle\Validator\Constraints\Symfony3\ImageValidator'); } } }
<?php namespace FSi\Bundle\DoctrineExtensionsBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel; final class Symfony3ValidatorPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (version_compare(Kernel::VERSION, '3.0.0', '<')) { $container->findDefinition('fsi_doctrine_extensions.validator.file') ->setClass('FSi\Bundle\DoctrineExtensionsBundle\Validator\Constraints\Symfony3\FileValidator'); $container->findDefinition('fsi_doctrine_extensions.validator.image') ->setClass('FSi\Bundle\DoctrineExtensionsBundle\Validator\Constraints\Symfony3\ImageValidator'); } } }
Test preSetup and preTeardown callbacks
import { TestModule } from 'ember-test-helpers'; import test from 'tests/test-support/qunit-test'; import qunitModuleFor from 'tests/test-support/qunit-module-for'; import { setResolverRegistry } from 'tests/test-support/resolver'; function moduleFor(fullName, description, callbacks) { var module = new TestModule(fullName, description, callbacks); qunitModuleFor(module); } var registry = { 'component:x-foo': Ember.Component.extend() }; var a = 0; var b = 0; var preSetupOk = false; var preTeardownOk = false; moduleFor('component:x-foo', 'TestModule callbacks', { preSetup: function() { setResolverRegistry(registry); preSetupOk = (a === 0); b += 1; }, setup: function() { a += 1; }, preTeardown: function() { preTeardownOk = (a === 1); b -= 1; }, teardown: function() { a -= 1; } }); test("preSetup callback is called prior to any test setup", function() { ok(preSetupOk); equal(b, 1); }); test("setup callback is called prior to test", function() { equal(a, 1); }); test("teardown callback is called after test", function() { equal(a, 1); }); test("preTeardown callback is called prior to any test teardown", function() { ok(preTeardownOk); equal(b, 1); });
import { TestModule } from 'ember-test-helpers'; import test from 'tests/test-support/qunit-test'; import qunitModuleFor from 'tests/test-support/qunit-module-for'; import { setResolverRegistry } from 'tests/test-support/resolver'; function moduleFor(fullName, description, callbacks) { var module = new TestModule(fullName, description, callbacks); qunitModuleFor(module); } var registry = { 'component:x-foo': Ember.Component.extend() }; var a = 0; moduleFor('component:x-foo', 'TestModule callbacks', { preSetup: function() { setResolverRegistry(registry); }, setup: function() { a += 1; }, teardown: function() { a -= 1; } }); test("setup callback is called prior to test", function() { equal(a, 1); }); test("teardown callback is called after test", function() { equal(a, 1); });
Leverage convenience method of Optional object
package org.dotwebstack.framework; import java.util.Objects; import java.util.Optional; import org.eclipse.rdf4j.model.IRI; class InformationProduct { private IRI identifier; private String label; private InformationProduct(Builder builder) { identifier = builder.identifier; label = builder.label; } public IRI getIdentifier() { return identifier; } public String getLabel() { return label; } public static class Builder { private IRI identifier; private String label; public Builder(IRI identifier) { this.identifier = Objects.requireNonNull(identifier); } public Builder label(String label) { this.label = Objects.requireNonNull(label); return this; } public Builder label(Optional<String> label) { this.label = label.orElse(null); return this; } public InformationProduct build() { return new InformationProduct(this); } } }
package org.dotwebstack.framework; import java.util.Objects; import java.util.Optional; import org.eclipse.rdf4j.model.IRI; class InformationProduct { private IRI identifier; private String label; private InformationProduct(Builder builder) { identifier = builder.identifier; label = builder.label; } public IRI getIdentifier() { return identifier; } public String getLabel() { return label; } public static class Builder { private IRI identifier; private String label; public Builder(IRI identifier) { this.identifier = Objects.requireNonNull(identifier); } public Builder label(String label) { this.label = Objects.requireNonNull(label); return this; } public Builder label(Optional<String> label) { this.label = label.isPresent() ? label.get() : null; return this; } public InformationProduct build() { return new InformationProduct(this); } } }
Add name to comunication model;
/** * Copyright 2016 PT Inovação e Sistemas SA * Copyright 2016 INESC-ID * Copyright 2016 QUOBIS NETWORKS SL * Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V * Copyright 2016 ORANGE SA * Copyright 2016 Deutsche Telekom AG * Copyright 2016 Apizee * Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN * * 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. **/ export const CommunicationStatus = { OPEN: 'open', PENDING: 'pending', CLOSED: 'closed', PAUSED: 'paused', FAILED: 'failed' }; let communication = { id: '', name: '', host: '', owner: '', startingTime: '', lastModified: '', duration: '', communicationStatus: '', communicationQuality: '', participants: [], chatMessage: {} }; export default communication;
/** * Copyright 2016 PT Inovação e Sistemas SA * Copyright 2016 INESC-ID * Copyright 2016 QUOBIS NETWORKS SL * Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V * Copyright 2016 ORANGE SA * Copyright 2016 Deutsche Telekom AG * Copyright 2016 Apizee * Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN * * 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. **/ export const CommunicationStatus = { OPEN: 'open', PENDING: 'pending', CLOSED: 'closed', PAUSED: 'paused', FAILED: 'failed' }; let communication = { id: '', host: '', owner: '', startingTime: '', lastModified: '', duration: '', communicationStatus: '', communicationQuality: '', participants: [], chatMessage: {} }; export default communication;
Change validation run to on input. This way when the user starts correcting the box, the error messages go away immediately.
var app = angular.module('app', [ 'ngResource', 'ngRoute' ]); app.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token'; $httpProvider.defaults.xsrfCookieName = 'CSRF-Token'; }]); app.directive('serverError', function() { return { restrict: 'A', require: '?ngModel', link: function(scope, element, attrs, ctrl) { element.on('input', function() { scope.$apply( function() { ctrl.$setValidity('server', true); }) } ); } }; });
var app = angular.module('app', [ 'ngResource', 'ngRoute' ]); app.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token'; $httpProvider.defaults.xsrfCookieName = 'CSRF-Token'; }]); app.directive('serverError', function() { return { restrict: 'A', require: '?ngModel', link: function(scope, element, attrs, ctrl) { element.on('change', function() { scope.$apply( function() { ctrl.$setValidity('server', true); }) } ); } }; });
Resolve Django 1.10 deprecation warnings
from django.conf.urls import url from django.contrib.auth import views as auth_views from .views import (DocumentationRecordListView, DocumentationRecordDetailView, MaintenanceRecordDetailView, MaintenanceRecordListView, system_maintenance_home_view) urlpatterns = [ url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'), url(r'^authentication/$', auth_views.login, {'template_name': 'system_maintenance/authentication.html'}, name='authentication'), url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'), url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'), url(r'^logout/$', auth_views.logout, {'next_page': '/system_maintenance/'}, name='logout'), url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'), url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'), ]
from django.conf.urls import patterns, url from .views import (DocumentationRecordListView, DocumentationRecordDetailView, MaintenanceRecordDetailView, MaintenanceRecordListView, system_maintenance_home_view) urlpatterns = patterns('', url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'), url(r'^authentication/$', 'django.contrib.auth.views.login', {'template_name': 'system_maintenance/authentication.html'}, name='authentication'), url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'), url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/system_maintenance/'}, name='logout'), url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'), url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'), )
Switch over to loading .js file Gerrit no longer supports html plugins so we have to use the .js version. Bug: Issue 14335 Change-Id: Ied8a2ddcd9dcc13e341dd5a108738418631afc30
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.codemirror; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.restapi.RestApiModule; import com.google.gerrit.extensions.webui.JavaScriptPlugin; import com.google.gerrit.extensions.webui.WebUiPlugin; public class CodemirrorModule extends RestApiModule { @Override protected void configure() { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("codemirror_editor.js")); } }
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.codemirror; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.restapi.RestApiModule; import com.google.gerrit.extensions.webui.JavaScriptPlugin; import com.google.gerrit.extensions.webui.WebUiPlugin; public class CodemirrorModule extends RestApiModule { @Override protected void configure() { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("codemirror_editor.html")); } }
Add method to http request
<?php namespace Technosailor\OpenCalais; class OpenCalais { const METHOD = 'POST'; const APIURL = 'https://api.thomsonreuters.com/permid/calais'; protected $_calais_options; protected $_token; protected $_headers; public function __construct() { $this->_token = get_option( 'calais_token', '' ); $this->_headers = array( 'X-AG-Access-Token' => $this->_token, 'Content-Type' => 'text/raw', 'outputformat' => 'application/json' ); } public function send( $content ) { $request = wp_remote_request( self::APIURL, array( 'method' => self::METHOD, 'headers' => $this->_headers, 'body' => wp_kses( $content, array() ) ) ); if( is_wp_error( $request ) ) { return $request->get_error_message(); } return wp_remote_retrieve_body( $request ); } } $api_url = esc_url_raw( sprintf( 'https://api.edgecast.com/v2/mcc/customers/%s/edge/purge', $account ) ); $headers = array( );
<?php namespace Technosailor\OpenCalais; class OpenCalais { const METHOD = 'POST'; const APIURL = 'https://api.thomsonreuters.com/permid/calais'; protected $_calais_options; protected $_token; protected $_headers; public function __construct() { $this->_token = get_option( 'calais_token', '' ); $this->_headers = array( 'X-AG-Access-Token' => $this->_token, 'Content-Type' => 'text/raw', 'outputformat' => 'application/json' ); } public function send( $content ) { $request = wp_remote_request( self::APIURL, array( 'headers' => $this->_headers, 'body' => wp_kses( $content, array() ) ) ); if( is_wp_error( $request ) ) { return $request->get_error_message(); } return wp_remote_retrieve_body( $request ); } } $api_url = esc_url_raw( sprintf( 'https://api.edgecast.com/v2/mcc/customers/%s/edge/purge', $account ) ); $headers = array( );
Add reconnect backoff and refactor for easier testing
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='gobblegobble', version='0.1.3', packages=find_packages(), include_package_data=True, license='BSD License', # example license description='A Django app-based slackbot', long_description=README, url='https://github.com/ejesse/gobblegobble', author='Jesse Emery', author_email='jesse@jesseemery.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 9.x', # replace "X.Y" as appropriate 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', # Replace these appropriately if you are stuck on Python 2. 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], install_requires=['slackclient'] )
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='gobblegobble', version='0.1.2', packages=find_packages(), include_package_data=True, license='BSD License', # example license description='A Django app-based slackbot', long_description=README, url='https://github.com/ejesse/gobblegobble', author='Jesse Emery', author_email='jesse@jesseemery.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 9.x', # replace "X.Y" as appropriate 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', # Replace these appropriately if you are stuck on Python 2. 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], install_requires=['slackclient'] )
Swap '2016' for '1996' to stop faulty logic from passing unit test [This leap solution](http://exercism.io/submissions/7ef5b0ab93b540f79cdee9f153e0a21c) should not pass the unit test, since it checks whether `year % 100` and `year % 400` are equal in order to tell whether the year it has been passed is a leap year. This works for 2016 because `2016 % 100` and `2016 % 400` both evaluate to 16. 1996, another leap year that is divisible by 4 but not 100, does not have this property and, under that solution, would falsely not be classed as a leap year.
import unittest from leap import is_leap_year # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class YearTest(unittest.TestCase): def test_year_not_divisible_by_4(self): self.assertIs(is_leap_year(2015), False) def test_year_divisible_by_4_not_divisible_by_100(self): self.assertIs(is_leap_year(1996), True) def test_year_divisible_by_100_not_divisible_by_400(self): self.assertIs(is_leap_year(2100), False) def test_year_divisible_by_400(self): self.assertIs(is_leap_year(2000), True) if __name__ == '__main__': unittest.main()
import unittest from leap import is_leap_year # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class YearTest(unittest.TestCase): def test_year_not_divisible_by_4(self): self.assertIs(is_leap_year(2015), False) def test_year_divisible_by_4_not_divisible_by_100(self): self.assertIs(is_leap_year(2016), True) def test_year_divisible_by_100_not_divisible_by_400(self): self.assertIs(is_leap_year(2100), False) def test_year_divisible_by_400(self): self.assertIs(is_leap_year(2000), True) if __name__ == '__main__': unittest.main()
Add arguments to clang entries. Summary: http://reviews.llvm.org/rL245036 added a new attribute to clang compilation database entries, `arguments`. Test Plan: CI create a compilation database with clang format, see it has `arguments`
/* * Copyright 2015-present Facebook, 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. */ package com.facebook.buck.cxx; import com.facebook.buck.util.Escaper; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import org.immutables.value.Value; @BuckStyleImmutable @Value.Immutable abstract class AbstractClangCxxCompilationDatabaseEntry implements CxxCompilationDatabaseEntry { @Value.Parameter public abstract String getDirectory(); @Override @Value.Parameter public abstract String getFile(); @Value.Parameter public abstract ImmutableList<String> getArguments(); @Override @Value.Derived public String getCommand() { return Joiner.on(' ').join( Iterables.transform( getArguments(), Escaper.SHELL_ESCAPER)); } }
/* * Copyright 2015-present Facebook, 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. */ package com.facebook.buck.cxx; import com.facebook.buck.util.Escaper; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import org.immutables.value.Value; @BuckStyleImmutable @Value.Immutable abstract class AbstractClangCxxCompilationDatabaseEntry implements CxxCompilationDatabaseEntry { @Value.Parameter public abstract String getDirectory(); @Override @Value.Parameter public abstract String getFile(); @JsonIgnore @Value.Parameter public abstract ImmutableList<String> getArgs(); @Override @Value.Derived public String getCommand() { return Joiner.on(' ').join( Iterables.transform( getArgs(), Escaper.SHELL_ESCAPER)); } }
Replace facebook options with crowdtangle
angular.module('Aggie') .value('mediaOptions', ['twitter', 'rss', 'elmo', 'smsgh', 'whatsapp', 'crowdtangle']) .value('apiSettingsOptions', ['twitter', 'elmo', 'gplaces', 'crowdtangle']) .value('widgetSettingsOptions', ['incident map']) .value('statusOptions', ['Read', 'Unread', 'Flagged', 'Unflagged', 'Read & Unflagged']) .value('linkedtoIncidentOptions', [{ _id: 'any', title: '* Any Incident' }, { _id: 'none', title: '* Without Incident' }]) .value('userRoles', ['viewer', 'monitor', 'admin']) .value('incidentStatusOptions', ['open', 'closed']) .value('veracityOptions', ['unconfirmed', 'confirmed true', 'confirmed false']) .value('escalatedOptions', ['escalated', 'unescalated']) .value('publicOptions', ['public', 'private']) .value('paginationOptions', { perPage: 25 }) .value('emailTransportOptions', { SES: ['accessKeyId', 'secretAccessKey', 'region'], SMTP: ['host', 'port', 'secure', 'user', 'pass'], SendGrid: ['apiKey'] });
angular.module('Aggie') .value('mediaOptions', ['twitter', 'facebook', 'rss', 'elmo', 'smsgh', 'whatsapp', 'crowdtangle']) .value('apiSettingsOptions', ['twitter', 'facebook', 'elmo', 'gplaces']) .value('widgetSettingsOptions', ['incident map']) .value('statusOptions', ['Read', 'Unread', 'Flagged', 'Unflagged', 'Read & Unflagged']) .value('linkedtoIncidentOptions', [{ _id: 'any', title: '* Any Incident' }, { _id: 'none', title: '* Without Incident' }]) .value('userRoles', ['viewer', 'monitor', 'admin']) .value('incidentStatusOptions', ['open', 'closed']) .value('veracityOptions', ['unconfirmed', 'confirmed true', 'confirmed false']) .value('escalatedOptions', ['escalated', 'unescalated']) .value('publicOptions', ['public', 'private']) .value('paginationOptions', { perPage: 25 }) .value('emailTransportOptions', { SES: ['accessKeyId', 'secretAccessKey', 'region'], SMTP: ['host', 'port', 'secure', 'user', 'pass'], SendGrid: ['apiKey'] });
Fix some failing unit tests evpCipher can be null to handle re-initialization of CIPHER_CTX instances. Make the constructor of OpenSSLCipherContext public so it can be used in testing. Fix all of the things hidden by JNI_DEBUG that were not correct. Throw a BadPaddingException when a decrypt fails. This particular error is returned by OpenSSL in evp_enc.c from EVP_DecryptFinal_ex when the padding check fails. Change-Id: I77cad024db52986fe726443cd9b3ff52430a30dd
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.xnet.provider.jsse; public class OpenSSLCipherContext { private final int context; public OpenSSLCipherContext(int ctx) { if (ctx == 0) { throw new NullPointerException("ctx == 0"); } this.context = ctx; } @Override protected void finalize() throws Throwable { try { NativeCrypto.EVP_CIPHER_CTX_cleanup(context); } finally { super.finalize(); } } int getContext() { return context; } }
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.xnet.provider.jsse; public class OpenSSLCipherContext { private final int context; OpenSSLCipherContext(int ctx) { if (ctx == 0) { throw new NullPointerException("ctx == 0"); } this.context = ctx; } @Override protected void finalize() throws Throwable { try { NativeCrypto.EVP_CIPHER_CTX_cleanup(context); } finally { super.finalize(); } } int getContext() { return context; } }
Fix warning message to use 'varify' package instead of 'src'
import os from global_settings import * try: from local_settings import * except ImportError: import warnings warnings.warn('Local settings have not been found (varify.conf.local_settings)') # FORCE_SCRIPT_NAME overrides the interpreted 'SCRIPT_NAME' provided by the # web server. since the URLs below are used for various purposes outside of # the WSGI application (static and media files), these need to be updated to # reflect this alteration if FORCE_SCRIPT_NAME: ADMIN_MEDIA_PREFIX = os.path.join(FORCE_SCRIPT_NAME, ADMIN_MEDIA_PREFIX[1:]) STATIC_URL = os.path.join(FORCE_SCRIPT_NAME, STATIC_URL[1:]) MEDIA_URL = os.path.join(FORCE_SCRIPT_NAME, MEDIA_URL[1:]) LOGIN_URL = os.path.join(FORCE_SCRIPT_NAME, LOGIN_URL[1:]) LOGOUT_URL = os.path.join(FORCE_SCRIPT_NAME, LOGOUT_URL[1:]) LOGIN_REDIRECT_URL = os.path.join(FORCE_SCRIPT_NAME, LOGIN_REDIRECT_URL[1:])
import os from global_settings import * try: from local_settings import * except ImportError: import warnings warnings.warn('Local settings have not been found (src.conf.local_settings)') # FORCE_SCRIPT_NAME overrides the interpreted 'SCRIPT_NAME' provided by the # web server. since the URLs below are used for various purposes outside of # the WSGI application (static and media files), these need to be updated to # reflect this alteration if FORCE_SCRIPT_NAME: ADMIN_MEDIA_PREFIX = os.path.join(FORCE_SCRIPT_NAME, ADMIN_MEDIA_PREFIX[1:]) STATIC_URL = os.path.join(FORCE_SCRIPT_NAME, STATIC_URL[1:]) MEDIA_URL = os.path.join(FORCE_SCRIPT_NAME, MEDIA_URL[1:]) LOGIN_URL = os.path.join(FORCE_SCRIPT_NAME, LOGIN_URL[1:]) LOGOUT_URL = os.path.join(FORCE_SCRIPT_NAME, LOGOUT_URL[1:]) LOGIN_REDIRECT_URL = os.path.join(FORCE_SCRIPT_NAME, LOGIN_REDIRECT_URL[1:])
Handle deprecated system method enrollEntities
beforeEach(function () { jasmine.addMatchers({ toBeInSystem() { return { compare(actual, expected) { const entity = actual; const system = expected; const entities = system.getMatchingEntities(); return { pass: entities.includes(entity) }; }, }; }, toMatchNumberOfEntities() { return { compare(actual, expected) { const system = actual; const entities = system.getMatchingEntities(); return { pass: entities.length === expected }; }, }; }, }); });
beforeEach(function () { jasmine.addMatchers({ toBeInSystem() { return { compare(actual, expected) { const entity = actual; const system = expected; system.enrollEntities(); return { pass: system.entities.includes(entity) }; }, }; }, toMatchNumberOfEntities() { return { compare(actual, expected) { const system = actual; system.enrollEntities(); return { pass: system.entities.length === expected }; }, }; }, }); });
Fix visibility of internal class. Change visibility of 'MSegList' to package private and make it final.
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at) */ package org.jenetics.util; /** * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a> * @version 3.4 * @since 3.4 */ final class MSeqList<T> extends SeqList<T> { private static final long serialVersionUID = 1L; MSeqList(final MSeq<T> array) { super(array); } @Override public T set(final int index, final T element) { final T oldElement = seq.get(index); ((MSeq<T>)seq).set(index, element); return oldElement; } }
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at) */ package org.jenetics.util; /** * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a> * @version 3.4 * @since 3.4 */ public class MSeqList<T> extends SeqList<T> { private static final long serialVersionUID = 1L; MSeqList(final MSeq<T> array) { super(array); } @Override public T set(final int index, final T element) { final T oldElement = seq.get(index); ((MSeq<T>)seq).set(index, element); return oldElement; } }
Deal with CASA's empty header keywords
''' Swap the axes in a header, without losing keys to WCS ''' from astropy.wcs import WCS def header_swapaxes(header, ax1, ax2): ''' ''' mywcs = WCS(header) new_hdr = mywcs.swapaxes(ax1, ax2).to_header() lost_keys = list(set(header.keys()) - set(new_hdr.keys())) for key in lost_keys: # CASA sometimes gives empty keys? "" if len(key) == 0: continue if str(ax1+1) in key: new_hdr[key.replace(str(ax1+1), str(ax2+1))] = header[key] elif str(ax2+1) in key: new_hdr[key.replace(str(ax2+1), str(ax1+1))] = header[key] else: new_hdr[key] = header[key] return new_hdr
''' Swap the axes in a header, without losing keys to WCS ''' from astropy.wcs import WCS def header_swapaxes(header, ax1, ax2): ''' ''' mywcs = WCS(header) new_hdr = mywcs.swapaxes(ax1, ax2).to_header() lost_keys = list(set(header.keys()) - set(new_hdr.keys())) for key in lost_keys: if str(ax1+1) in key: new_hdr[key.replace(str(ax1+1), str(ax2+1))] = header[key] elif str(ax2+1) in key: new_hdr[key.replace(str(ax2+1), str(ax1+1))] = header[key] else: new_hdr[key] = header[key] return new_hdr
Fix GlossaryTerm with TermComment relationship and test
package org.zanata.rest.client; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.jboss.resteasy.client.ClientResponse; import org.zanata.common.LocaleId; import org.zanata.rest.MediaTypes; import org.zanata.rest.dto.Glossary; import org.zanata.rest.service.GlossaryResource; @Produces({ MediaTypes.APPLICATION_ZANATA_GLOSSARY_XML, MediaTypes.APPLICATION_ZANATA_GLOSSARY_JSON }) @Consumes({ MediaTypes.APPLICATION_ZANATA_GLOSSARY_XML, MediaTypes.APPLICATION_ZANATA_GLOSSARY_JSON }) public interface IGlossaryResource extends GlossaryResource { public static final String SERVICE_PATH = "/glossary"; @Override @GET public ClientResponse<Glossary> getEntries(); @Override @GET @Path("{locale}") public ClientResponse<Glossary> get(@PathParam("locale") LocaleId locale); @Override @PUT public ClientResponse<String> put(Glossary glossary); @Override @DELETE @Path("{locale}") public ClientResponse<String> deleteGlossary(@PathParam("locale") LocaleId locale); @Override @DELETE public ClientResponse<String> deleteGlossaries(); }
package org.zanata.rest.client; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.jboss.resteasy.client.ClientResponse; import org.zanata.common.LocaleId; import org.zanata.rest.MediaTypes; import org.zanata.rest.dto.Glossary; import org.zanata.rest.service.GlossaryResource; @Produces({ MediaTypes.APPLICATION_ZANATA_GLOSSARY_XML, MediaTypes.APPLICATION_ZANATA_GLOSSARY_JSON }) @Consumes({ MediaTypes.APPLICATION_ZANATA_GLOSSARY_XML, MediaTypes.APPLICATION_ZANATA_GLOSSARY_JSON }) public interface IGlossaryResource extends GlossaryResource { public static final String SERVICE_PATH = "/glossary"; @Override @GET public ClientResponse<Glossary> getEntries(); @Override @GET @Path("{locale}") public ClientResponse<Glossary> get(@PathParam("locale") LocaleId locale); @Override @PUT public ClientResponse<Glossary> put(Glossary glossary); @Override @DELETE @Path("{locale}") public ClientResponse<String> deleteGlossary(@PathParam("locale") LocaleId locale); @Override @DELETE public ClientResponse<String> deleteGlossaries(); }
Fix automatic update for the 'created' and 'updated' fields
package com.lyubenblagoev.postfixrest.entity; import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Temporal; import javax.persistence.TemporalType; @MappedSuperclass public class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private boolean enabled; @Temporal(TemporalType.TIMESTAMP) private Date created; @Temporal(TemporalType.TIMESTAMP) private Date updated; @PrePersist public void onPrePersist() { this.created = new Date(); } @PreUpdate public void onPreUpdate() { this.updated = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } }
package com.lyubenblagoev.postfixrest.entity; import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; @MappedSuperclass public class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private boolean enabled; @CreatedDate private Date created; @LastModifiedDate private Date updated; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } }
BB-4318: Make sure that user can build grids based on the backend search engine - fixed minor issues after review
<?php namespace Oro\Bundle\SearchBundle\EventListener; use Oro\Bundle\DataGridBundle\Event\BuildAfter; use Oro\Bundle\SearchBundle\Datasource\SearchDatasource; class SearchGridListener { const FROM_PATH = '[source][query][from]'; /** * Reads 'from' part in configuration and adds it to the query * * @param BuildAfter $event */ public function onBuildAfter(BuildAfter $event) { $grid = $event->getDatagrid(); $datasource = $grid->getDatasource(); if ($datasource instanceof SearchDatasource) { $from = $grid->getConfig()->offsetGetByPath(self::FROM_PATH); if (!empty($from)) { $datasource->getQuery()->from($from); } } } }
<?php namespace Oro\Bundle\SearchBundle\EventListener; use Oro\Bundle\DataGridBundle\Event\BuildAfter; use Oro\Bundle\SearchBundle\Datasource\SearchDatasource; class SearchGridListener { const FROM_PATH = '[source][query][from]'; public function onBuildAfter(BuildAfter $event) { $grid = $event->getDatagrid(); $datasource = $grid->getDatasource(); if ($datasource instanceof SearchDatasource) { $from = $grid->getConfig()->offsetGetByPath(self::FROM_PATH); if (!empty($from)) { $datasource->getQuery()->from($from); } } } }
Send an error-message, when the graph-generation is unsuccessful
<?php require_once __DIR__ . '/vendor/autoload.php'; require_once 'scripts/script.php'; use jlawrence\eos\Parser; use jlawrence\eos\Graph; class math extends Script { public function run() { if(strtolower(split(' ', $this->matches[0])[0]) === 'math') { return $this->send($this->message->number, Parser::solve($this->matches[1])); } else { $filepath = __DIR__ . '/ouput.png'; Graph::init(640, 840); Graph::graph($this->matches[1], -10, 10, 0.01, true, false, -10, 10); if(file_exists($filepath)) { unlink($filepath); } if(imagepng(Graph::getImage(), $filepath)) { return $this->send($this->message->number, $filepath, 'image'); } else { return $this->send($this->message->number, 'Graph generation unsuccessful'); } } } }
<?php require_once __DIR__ . '/vendor/autoload.php'; require_once 'scripts/script.php'; use jlawrence\eos\Parser; use jlawrence\eos\Graph; class math extends Script { public function run() { if(strtolower(split(' ', $this->matches[0])[0]) === 'math') { return $this->send($this->message->number, Parser::solve($this->matches[1])); } else { $filepath = __DIR__ . '/ouput.png'; Graph::init(640, 840); Graph::graph($this->matches[1], -10, 10, 0.01, true, false, -10, 10); if(file_exists($filepath)) { unlink($filepath); } imagepng(Graph::getImage(), $filepath); return $this->send($this->message->number, $filepath, 'image'); } } }
Fix for comparing with the wrong data type.
""" DataWriter.py """ from DataController import DataController from DataReader import DataReader from vtk import vtkMetaImageWriter from vtk import vtkXMLImageDataWriter class DataWriter(DataController): """ DataWriter writes an image data object to disk using the provided format. """ def __init__(self): super(DataWriter, self).__init__() self.supportedExtensions = [DataReader.TypeMHD, DataReader.TypeVTI] def WriteToFile(self, imageData, exportFileName, fileType): if fileType == DataReader.TypeMHD: if not exportFileName.endswith(".mhd"): exportFileName = exportFileName + ".mhd" writer = vtkMetaImageWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() elif fileType == DataReader.TypeVTI: writer = vtkXMLImageDataWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() else: raise NotImplementedError("No writing support for type " + str(fileType))
""" DataWriter.py """ from DataController import DataController from DataReader import DataReader from vtk import vtkMetaImageWriter from vtk import vtkXMLImageDataWriter class DataWriter(DataController): """ DataWriter writes an image data object to disk using the provided format. """ def __init__(self): super(DataWriter, self).__init__() self.supportedExtensions = [DataReader.TypeMHD, DataReader.TypeVTI] def WriteToFile(self, imageData, exportFileName, fileType): if fileType == DataReader.TypeMHA: if not exportFileName.endswith(".mhd"): exportFileName = exportFileName + ".mhd" writer = vtkMetaImageWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() elif fileType == DataReader.TypeVTI: writer = vtkXMLImageDataWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() else: raise NotImplementedError("No writing support for type " + str(fileType))
Check that editor exists when adding
## Copyright (C) 2011 Aldebaran Robotics """Display the current config """ import os import qitools def configure_parser(parser): """Configure parser for this action """ qitools.qiworktree.work_tree_parser(parser) parser.add_argument("--edit", action="store_true", help="edit the configuration") def do(args): """Main entry point""" qiwt = qitools.qiworktree_open(args.work_tree, use_env=True) if not args.edit: print qiwt.configstore return config_path = qiwt.user_config_path editor = qiwt.configstore.get("general", "env", "editor") if not editor: editor = os.environ.get("VISUAL") if not editor: editor = os.environ.get("EDITOR") if not editor: # Ask the user to choose, and store the answer so # that we never ask again print "Could not find the editor to use." editor = qitools.interact.ask_string("Please enter an editor") qitools.command.check_is_in_path(editor) qitools.configstore.update_config(config_path, "general", "env", "editor", editor) qitools.command.check_call([editor, config_path]) if __name__ == "__main__" : import sys qitools.cmdparse.sub_command_main(sys.modules[__name__])
## Copyright (C) 2011 Aldebaran Robotics """Display the current config """ import os import qitools def configure_parser(parser): """Configure parser for this action """ qitools.qiworktree.work_tree_parser(parser) parser.add_argument("--edit", action="store_true", help="edit the configuration") def do(args): """Main entry point""" qiwt = qitools.qiworktree_open(args.work_tree, use_env=True) if not args.edit: print qiwt.configstore return config_path = qiwt.user_config_path editor = qiwt.configstore.get("general", "env", "editor") if not editor: editor = os.environ.get("VISUAL") if not editor: editor = os.environ.get("EDITOR") if not editor: # Ask the user to choose, and store the answer so # that we never ask again print "Could not find the editor to use." editor = qitools.interact.ask_string("Please enter an editor") qitools.configstore.update_config(config_path, "general", "env", "editor", editor) qitools.command.check_call([editor, config_path]) if __name__ == "__main__" : import sys qitools.cmdparse.sub_command_main(sys.modules[__name__])
Make token-file and cache-path optional
import argparse import logging import os from .client import GithubCachedClient, GithubClient from .search import get_dotfiles, SEARCH_QUERIES def parse_args(): parser = argparse.ArgumentParser(description='Search github for common lines in dotfiles') parser.add_argument('-t', '--token-file', type=os.path.abspath, help='path to file containing Github token') parser.add_argument('-c', '--cache-path', type=os.path.abspath, help='path to cache directory') return parser.parse_args() def main(): args = parse_args() token = open(args.token_file).read().strip() if args.token_file else None if args.cache_path: client = GithubCachedClient(cache_path=args.cache_path, token=token) else: client = GithubClient(token=token) dots = get_dotfiles(client, queries=SEARCH_QUERIES) return dots if __name__ == '__main__': logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) dots = main() for ftype in dots: print print ftype print '-' * 40 print "\n".join("%s\t%d" % i for i in dots[ftype].top_lines())
import argparse import logging import os from .client import GithubCachedClient from .search import get_dotfiles, SEARCH_QUERIES def parse_args(): parser = argparse.ArgumentParser(description='Search github for common lines in dotfiles') parser.add_argument('-t', '--token-file', type=os.path.abspath, help='path to file containing Github token') parser.add_argument('-c', '--cache-path', type=os.path.abspath, help='path to cache directory') return parser.parse_args() def main(): args = parse_args() token = open(args.token_file).read().strip() client = GithubCachedClient(cache_path=args.cache_path, token=token) dots = get_dotfiles(client, queries=SEARCH_QUERIES) return dots if __name__ == '__main__': logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) dots = main() for ftype in dots: print print ftype print '-' * 40 print "\n".join("%s\t%d" % i for i in dots[ftype].top_lines())
Fix name and value name
<? /* Uplodius Multiple image file upload using PHP https://github.com/RDmitriev/Uplodius */ include 'lib/uplodius.php'; if(isset($_POST['images_add'])) { $Uplodius = new Uplodius; $result = $Uplodius->Upload( $_FILES['files'], (object) array( 'dir' => '../upload/', 'name' => 'example', 'width' => 1000, 'height' => 0, 'prevWidth' => 200, 'prevHeight' => 0 ) ); var_dump($result); } ?> <h1>Upload images</h1> <form method="post" enctype="multipart/form-data" class="form"> <input type="file" name="files[]" multiple="multiple"> <input type="submit" name="images_add" value="Upload"> </form>
<? /* Uplodius Multiple image file upload using PHP https://github.com/RDmitriev/Uplodius */ include 'lib/uplodius.php'; if(isset($_POST['images_add'])) { $Uplodius = new Uplodius; $result = $Uplodius->Upload( $_FILES['files'], (object) array( 'dir' => '../upload/', 'name' => $structure['path'], 'width' => 1000, 'height' => 0, 'prevWidth' => 200, 'prevHeight' => 0 ) ); var_dump($result); } ?> <h1>Upload images</h1> <form method="post" enctype="multipart/form-data" class="form"> <input type="file" name="files[]" multiple="multiple"> <input type="submit" name="images_add" value="Загрузить"> </form>
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-spacing/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-spacing/tachyons-spacing.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_spacing.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/spacing/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/layout/spacing/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-spacing/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-spacing/tachyons-spacing.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_spacing.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/spacing/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/layout/spacing/index.html', html)
Fix whitespace issue in SecureTransport test
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip('Could not import SecureTransport: %r' % e) def teardown_module(): try: from urllib3.contrib.securetransport import extract_from_urllib3 extract_from_urllib3() except ImportError: pass from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"")
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip('Could not import SecureTransport: %r' % e) def teardown_module(): try: from urllib3.contrib.securetransport import extract_from_urllib3 extract_from_urllib3() except ImportError: pass from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"")
Support Cordova 7.0 file structure
module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), path = ctx.requireCordovaModule('path'), xml = ctx.requireCordovaModule('cordova-common').xmlHelpers; var manifestSubPaths = ['platforms/android/AndroidManifest.xml', 'platforms/android/app/src/main/AndroidManifest.xml']; var manifestPath = null; for (var i = 0, len = manifestSubPaths.length; i < len; i++) { var candidatePath = path.join(ctx.opts.projectRoot, manifestSubPaths[i]); if (fs.existsSync(candidatePath)) { manifestPath = candidatePath; break; } } if (manifestPath === null) { throw new Error('AndroidManifest.xml not found'); } var doc = xml.parseElementtreeSync(manifestPath); if (doc.getroot().tag !== 'manifest') { throw new Error(manifestPath + ' has incorrect root node name (expected "manifest")'); } //adds the tools namespace to the root node // doc.getroot().attrib['xmlns:tools'] = 'http://schemas.android.com/tools'; //add tools:replace in the application node doc.getroot().find('./application').attrib['android:name'] = 'android.support.multidex.MultiDexApplication'; //write the manifest file fs.writeFileSync(manifestPath, doc.write({indent: 4}), 'utf-8'); };
module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), path = ctx.requireCordovaModule('path'), xml = ctx.requireCordovaModule('cordova-common').xmlHelpers; var manifestPath = path.join(ctx.opts.projectRoot, 'platforms/android/AndroidManifest.xml'); var doc = xml.parseElementtreeSync(manifestPath); if (doc.getroot().tag !== 'manifest') { throw new Error(manifestPath + ' has incorrect root node name (expected "manifest")'); } //adds the tools namespace to the root node // doc.getroot().attrib['xmlns:tools'] = 'http://schemas.android.com/tools'; //add tools:replace in the application node doc.getroot().find('./application').attrib['android:name'] = 'android.support.multidex.MultiDexApplication'; //write the manifest file fs.writeFileSync(manifestPath, doc.write({indent: 4}), 'utf-8'); };
Remove needless and incorrect proptery
var EventEmitter = require("events").EventEmitter; var AppDispatcher = require("../AppDispatcher"); var GroupsEvents = require("../events/GroupsEvents"); var Util = require("../helpers/Util"); var GroupsStore = Util.extendObject(EventEmitter.prototype, {}); AppDispatcher.register(function (action) { switch (action.actionType) { case GroupsEvents.SCALE_SUCCESS: GroupsStore.emit(GroupsEvents.SCALE_SUCCESS); break; case GroupsEvents.SCALE_ERROR: GroupsStore.emit( GroupsEvents.SCALE_ERROR, action.data.body ); break; case GroupsEvents.DELETE_SUCCESS: GroupsStore.emit( GroupsEvents.DELETE_SUCCESS ); break; case GroupsEvents.DELETE_ERROR: GroupsStore.emit( GroupsEvents.DELETE_ERROR, action.data.body ); break; } }); module.exports = GroupsStore;
var EventEmitter = require("events").EventEmitter; var AppDispatcher = require("../AppDispatcher"); var GroupsEvents = require("../events/GroupsEvents"); var Util = require("../helpers/Util"); var GroupsStore = Util.extendObject(EventEmitter.prototype, {}); AppDispatcher.register(function (action) { switch (action.actionType) { case GroupsEvents.SCALE_SUCCESS: GroupsStore.emit(GroupsEvents.SCALE_SUCCESS); break; case GroupsEvents.SCALE_ERROR: GroupsStore.emit( GroupsEvents.SCALE_ERROR, action.data.body ); break; case GroupsEvents.DELETE_SUCCESS: GroupsStore.emit( GroupsEvents.DELETE_SUCCESS, action.appId ); break; case GroupsEvents.DELETE_ERROR: GroupsStore.emit( GroupsEvents.DELETE_ERROR, action.data.body ); break; } }); module.exports = GroupsStore;
Fix return value in the Add method
package hyperdb // DB represents a collection of objects with multitude of attributes, // that can be retrieved based all possible dimensions. type DB struct { } // Open creates and opens a database at the given path. // If the file doesn't exist, it is created automatically. func Open(path string) (*DB, error) { return nil, nil } // Add adds an object to the given namespace - indexes all attributes and stores data // accessible through GetData() method of the HyperObject. // The function returns unique id of the object stored in hyperdb that can // later be used to update or remove object in/from the namespace. func (db *DB) Add(namespace string, obj *HyperObject) (string, error) { return "", nil } // Update updates the object with specified unique id in the given namespace. func (db *DB) Update(namespace string, uid string, obj *HyperObject) error { return nil } // Remove removes passed object from the given namespace // based on the unique id of the object. func (db *DB) Remove(namespace string, uid string) ([]byte, error) { return nil, nil }
package hyperdb // DB represents a collection of objects with multitude of attributes, // that can be retrieved based all possible dimensions. type DB struct { } // Open creates and opens a database at the given path. // If the file doesn't exist, it is created automatically. func Open(path string) (*DB, error) { return nil, nil } // Add adds an object to the given namespace - indexes all attributes and stores data // accessible through GetData() method of the HyperObject. // The function returns unique id of the object stored in hyperdb that can // later be used to update or remove object in/from the namespace. func (db *DB) Add(namespace string, obj *HyperObject) (string, error) { return 0, nil } // Update updates the object with specified unique id in the given namespace. func (db *DB) Update(namespace string, uid string, obj *HyperObject) error { return nil } // Remove removes passed object from the given namespace // based on the unique id of the object. func (db *DB) Remove(namespace string, uid string) ([]byte, error) { return nil, nil }
Improve generate method for uniq locations
'use strict'; const common = require('./../server/common'); export class DungeonBluePrints { constructor (number, worldSize, locationSize) { this.number = number; this.worldSize = worldSize; this.locationSize = locationSize; this.blueprints = {}; } generate () { const idList = []; while (this.number) { let lx = common.getRandomInt(0, this.worldSize - 1); let ly = common.getRandomInt(0, this.worldSize - 1); let locationId = `location_${ly}_${lx}`; if (locationId in idList) continue; idList.push(locationId); this.number--; let dungeonId = `dungeon_${this.number}`; let levels = common.getRandomInt(1, this.worldSize); let entrances = []; for (let l = 0; l < levels; l++) { let x = common.getRandomInt(0, this.locationSize - 1); let y = common.getRandomInt(0, this.locationSize - 1); entrances.push([x, y]); } this.blueprints[dungeonId] = { 'locationId': locationId, 'levels': levels, 'entrances': entrances }; } } }
'use strict'; const common = require('./../server/common'); export class DungeonBluePrints { constructor (number, worldSize, locationSize) { this.number = number; this.worldSize = worldSize; this.locationSize = locationSize; this.blueprints = {}; } generate () { for (let i = 0; i < this.worldSize; i++) { let dungeonId = `dungeon_${i}`; let lx = common.getRandomInt(0, this.worldSize - 1); let ly = common.getRandomInt(0, this.worldSize - 1); let locationId = `location_${ly}_${lx}`; let levels = common.getRandomInt(1, this.worldSize); let entrances = []; for (let l = 0; l < levels; l++) { let x = common.getRandomInt(0, this.locationSize - 1); let y = common.getRandomInt(0, this.locationSize - 1); entrances.push([x, y]); } this.blueprints[dungeonId] = { 'locationId': locationId, 'levels': levels, 'entrances': entrances }; } } }
Improve parsing of short strings by adding period. Former-commit-id: 812679f50e3dc89a10b1bc7c70061d2e6087c041
import re from ufal.udpipe import Model, Pipeline, ProcessingError class Parser: MODELS = { "swe": "data/swedish-ud-2.0-170801.udpipe", } def __init__(self, language): model_path = self.MODELS.get(language, None) if not model_path: raise ParserException("Cannot find model for language '%s'" % language) model = Model.load(model_path) if not model: raise ParserException("Cannot load model from file '%s'\n" % model_path) self.model = model def parse(self, text): text = text.strip() last_character = text.strip()[-1] if re.match(r"\w", last_character, flags=re.UNICODE): text += "." pipeline = Pipeline( self.model, "tokenize", Pipeline.DEFAULT, Pipeline.DEFAULT, "conllu" ) error = ProcessingError() processed = pipeline.process(text, error) if error.occurred(): raise ParserException(error.message) return processed class ParserException(Exception): pass
from ufal.udpipe import Model, Pipeline, ProcessingError class Parser: MODELS = { "swe": "data/swedish-ud-2.0-170801.udpipe", } def __init__(self, language): model_path = self.MODELS.get(language, None) if not model_path: raise ParserException("Cannot find model for language '%s'" % language) model = Model.load(model_path) if not model: raise ParserException("Cannot load model from file '%s'\n" % model_path) self.model = model def parse(self, text): pipeline = Pipeline( self.model, "tokenize", Pipeline.DEFAULT, Pipeline.DEFAULT, "conllu" ) error = ProcessingError() processed = pipeline.process(text, error) if error.occurred(): raise ParserException(error.message) return processed class ParserException(Exception): pass
Make sure that auto-detected task only has one sub-task Be more restrictive with the workflow auto detect for the poly-line-text tool.
def workflow_extractor_config(tasks): extractor_config = {} for task_key, task in tasks.items(): if task['type'] == 'drawing': tools_config = {} for tdx, tool in enumerate(task['tools']): if ((tool['type'] == 'polygon') and (len(tool['details']) == 1) and (tool['details'][0]['type'] == 'text')): # this is very ugly but I can't think of a better way to auto detect this tools_config.setdefault('poly_line_text_extractor'.format(tool['type']), []).append(tdx) else: tools_config.setdefault('{0}_extractor'.format(tool['type']), []).append(tdx) extractor_config[task_key] = tools_config elif task['type'] in ['single', 'multiple']: extractor_config[task_key] = 'question_extractor' elif task['type'] == 'survey': extractor_config[task_key] = 'survey_extractor' return extractor_config
def workflow_extractor_config(tasks): extractor_config = {} for task_key, task in tasks.items(): if task['type'] == 'drawing': tools_config = {} for tdx, tool in enumerate(task['tools']): if ((tool['type'] == 'polygon') and (len(tool['details']) > 0) and (tool['details'][0]['type'] == 'text')): # this is very ugly but I can't think of a better way to auto detect this tools_config.setdefault('poly_line_text_extractor'.format(tool['type']), []).append(tdx) else: tools_config.setdefault('{0}_extractor'.format(tool['type']), []).append(tdx) extractor_config[task_key] = tools_config elif task['type'] in ['single', 'multiple']: extractor_config[task_key] = 'question_extractor' elif task['type'] == 'survey': extractor_config[task_key] = 'survey_extractor' return extractor_config
Fix string conversion of Saga name in thrown error message
<?php /* * This file is part of the broadway/broadway package. * * (c) Qandidate.com <opensource@qandidate.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Broadway\Saga\Metadata; use RuntimeException; class StaticallyConfiguredSagaMetadataFactory implements MetadataFactoryInterface { /** * {@inheritDoc} */ public function create($saga) { $requiredInterface = 'Broadway\Saga\Metadata\StaticallyConfiguredSagaInterface'; if (! is_subclass_of($saga, $requiredInterface)) { throw new RuntimeException( sprintf('Provided saga of class %s must implement %s', get_class($saga), $requiredInterface) ); } $criteria = $saga::configuration(); return new Metadata($criteria); } }
<?php /* * This file is part of the broadway/broadway package. * * (c) Qandidate.com <opensource@qandidate.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Broadway\Saga\Metadata; use RuntimeException; class StaticallyConfiguredSagaMetadataFactory implements MetadataFactoryInterface { /** * {@inheritDoc} */ public function create($saga) { $requiredInterface = 'Broadway\Saga\Metadata\StaticallyConfiguredSagaInterface'; if (! is_subclass_of($saga, $requiredInterface)) { throw new RuntimeException( sprintf('Provided saga of class %s must implement %s', $saga, $requiredInterface) ); } $criteria = $saga::configuration(); return new Metadata($criteria); } }
Split into declaration and assignment #13763:As a developer, I will have implemented the Try My Policy UI and integrated with backend [v3.0]
package gov.samhsa.c2s.c2suiapi.service; import com.netflix.hystrix.exception.HystrixRuntimeException; import feign.FeignException; import gov.samhsa.c2s.c2suiapi.infrastructure.PhrClient; import gov.samhsa.c2s.c2suiapi.service.exception.NoDocumentsFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PhrServiceImpl implements PhrService{ private final PhrClient phrClient; @Autowired public PhrServiceImpl(PhrClient phrClient) { this.phrClient = phrClient; } @Override public List<Object> getAllDocumentTypeCodesList(){ return phrClient.getAllDocumentTypeCodesList(); } @Override public List<Object> getPatientDocumentInfoList(String patientMrn){ List<Object> uploadedDocuments = null; try{ uploadedDocuments = phrClient.getPatientDocumentInfoList(patientMrn); }catch(HystrixRuntimeException err) { Throwable t = err.getCause(); if(t instanceof FeignException && ((FeignException) t).status() == 404){ throw new NoDocumentsFoundException(t.getMessage()); } } return uploadedDocuments; } }
package gov.samhsa.c2s.c2suiapi.service; import com.netflix.hystrix.exception.HystrixRuntimeException; import feign.FeignException; import gov.samhsa.c2s.c2suiapi.infrastructure.PhrClient; import gov.samhsa.c2s.c2suiapi.service.exception.NoDocumentsFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PhrServiceImpl implements PhrService{ private final PhrClient phrClient; @Autowired public PhrServiceImpl(PhrClient phrClient) { this.phrClient = phrClient; } @Override public List<Object> getAllDocumentTypeCodesList(){ return phrClient.getAllDocumentTypeCodesList(); } @Override public List<Object> getPatientDocumentInfoList(String patientMrn){ try{ return phrClient.getPatientDocumentInfoList(patientMrn); }catch(HystrixRuntimeException err) { Throwable t = err.getCause(); if(t instanceof FeignException && ((FeignException) t).status() == 404){ throw new NoDocumentsFoundException(t.getMessage()); } } return null; } }
Fix recursion issues with spell points
package com.elmakers.mine.bukkit.economy; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.api.magic.CasterProperties; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; public class SpellPointCurrency extends CustomCurrency { private final boolean isValid; public SpellPointCurrency(MageController controller, ConfigurationSection configuration) { super(controller, "sp", configuration); isValid = controller.isSPEnabled(); } @Override public double getBalance(Mage mage, CasterProperties caster) { return mage.getSkillPoints(); } @Override public boolean has(Mage mage, CasterProperties caster, double amount) { return mage.getSkillPoints() >= amount; } @Override public void deduct(Mage mage, CasterProperties caster, double amount) { mage.addSkillPoints(-getRoundedAmount(amount)); } @Override public boolean give(Mage mage, CasterProperties caster, double amount) { if (mage.isAtMaxSkillPoints()) { return false; } mage.addSkillPoints(getRoundedAmount(amount)); return true; } @Override public boolean isValid() { return isValid; } @Override public double getDefaultValue() { return defaultValue; } }
package com.elmakers.mine.bukkit.economy; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.api.magic.CasterProperties; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; public class SpellPointCurrency extends BaseMagicCurrency { private final boolean isValid; public SpellPointCurrency(MageController controller, ConfigurationSection configuration) { super(controller, "sp", configuration); isValid = controller.isSPEnabled(); } @Override public double getBalance(Mage mage, CasterProperties caster) { return mage.getSkillPoints(); } @Override public boolean has(Mage mage, CasterProperties caster, double amount) { return mage.getSkillPoints() >= amount; } @Override public void deduct(Mage mage, CasterProperties caster, double amount) { mage.addSkillPoints(-getRoundedAmount(amount)); } @Override public boolean give(Mage mage, CasterProperties caster, double amount) { if (mage.isAtMaxSkillPoints()) { return false; } mage.addSkillPoints(getRoundedAmount(amount)); return true; } @Override public boolean isValid() { return isValid; } @Override public double getDefaultValue() { return defaultValue; } }
Add Nice Search support to WPSEO
<?php namespace Roots\Soil\NiceSearch; /** * Redirects search results from /?s=query to /search/query/, converts %20 to + * * @link http://txfx.net/wordpress-plugins/nice-search/ * * You can enable/disable this feature in functions.php (or lib/config.php if you're using Roots): * add_theme_support('soil-nice-search'); */ function redirect() { global $wp_rewrite; if (!isset($wp_rewrite) || !is_object($wp_rewrite) || !$wp_rewrite->using_permalinks()) { return; } $search_base = $wp_rewrite->search_base; if (is_search() && !is_admin() && strpos($_SERVER['REQUEST_URI'], "/{$search_base}/") === false) { wp_redirect(home_url("/{$search_base}/" . urlencode(get_query_var('s')))); exit(); } } add_action('template_redirect', __NAMESPACE__ . '\\redirect'); function rewrite($url) { return str_replace('/?s=', '/search/', $url); } add_filter('wpseo_json_ld_search_url', __NAMESPACE__ . '\\rewrite');
<?php namespace Roots\Soil\NiceSearch; /** * Redirects search results from /?s=query to /search/query/, converts %20 to + * * @link http://txfx.net/wordpress-plugins/nice-search/ * * You can enable/disable this feature in functions.php (or lib/config.php if you're using Roots): * add_theme_support('soil-nice-search'); */ function redirect() { global $wp_rewrite; if (!isset($wp_rewrite) || !is_object($wp_rewrite) || !$wp_rewrite->using_permalinks()) { return; } $search_base = $wp_rewrite->search_base; if (is_search() && !is_admin() && strpos($_SERVER['REQUEST_URI'], "/{$search_base}/") === false) { wp_redirect(home_url("/{$search_base}/" . urlencode(get_query_var('s')))); exit(); } } add_action('template_redirect', __NAMESPACE__ . '\\redirect');
Add check for disabled format button at start of test
package org.wordpress.aztec.demo; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isChecked; import static android.support.test.espresso.matcher.ViewMatchers.isNotChecked; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static org.wordpress.aztec.demo.TestUtils.enterHTML; @LargeTest @RunWith(AndroidJUnit4.class) public class SimpleTextFormattingTests { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void testSimpleBoldFormatting() { ViewInteraction boldButton = onView(withId(R.id.format_bar_button_bold)); boldButton.check(matches(isNotChecked())); enterHTML("<b>hello world</b>"); boldButton.check(matches(isChecked())); } }
package org.wordpress.aztec.demo; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isChecked; import static android.support.test.espresso.matcher.ViewMatchers.isNotChecked; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static org.wordpress.aztec.demo.TestUtils.enterHTML; @LargeTest @RunWith(AndroidJUnit4.class) public class SimpleTextFormattingTests { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void testSimpleBoldFormatting() { enterHTML("<b>hello world</b>"); ViewInteraction boldButton = onView(withId(R.id.format_bar_button_bold)); boldButton.check(matches(isChecked())); } }
Add templateUrl for default route
// js/routes (function() { "use strict"; angular.module("NoteWrangler") .config(config); function config($routeProvider) { $routeProvider .when("/notes", { templateUrl: "../templates/pages/notes/index.html", controller: "NotesIndexController", controllerAs: "notesIndexCtrl" }) .when("/users", { templateUrl: "../templates/pages/users/index.html" }) .when("/notes/new", { templateUrl: "templates/pages/notes/new.html", controller: "NotesCreateController", controllerAs: "notesCreateCtrl" }) .when("/notes/:id", { templateUrl: "templates/pages/notes/show.html", controller: "NotesShowController", controllerAs: "notesShowCtrl" }) .otherwise({ redirectTo: "/", templateUrl: "templates/pages/index/index.html" }); } })();
// js/routes (function() { "use strict"; angular.module("NoteWrangler") .config(config); function config($routeProvider) { $routeProvider .when("/notes", { templateUrl: "../templates/pages/notes/index.html", controller: "NotesIndexController", controllerAs: "notesIndexCtrl" }) .when("/users", { templateUrl: "../templates/pages/users/index.html" }) .when("/notes/new", { templateUrl: "templates/pages/notes/new.html", controller: "NotesCreateController", controllerAs: "notesCreateCtrl" }) .when("/notes/:id", { templateUrl: "templates/pages/notes/show.html", controller: "NotesShowController", controllerAs: "notesShowCtrl" }) .otherwise({ redirectTo: "/" }); } })();
Make sure quarters are in the format catalyst wants git-svn-id: 24222aecec59d6833d1342da1ba59f27d6df2b08@636 3f86a6b1-f777-4bc2-bf3d-37c8dbe90857
""" This is the interface for interacting w/ Catalyst GradeBook """ from restclients.catalyst import Catalyst from restclients.exceptions import DataFailureException from restclients.dao import Catalyst_DAO class GradeBook(object): def get_grades_for_student_and_term(self, netid, year, quarter): """ returns a restclients.models.catalyst.CourseGradeData object """ quarter = quarter.capitalize() url = "/rest/gradebook/v1/grades/%s/%s/%s" % (netid, year, quarter) dao = Catalyst_DAO() response = dao.getURL(url, { "Accept": "application/json" }) if response.status != 200: raise DataFailureException(url, response.status, response.data) return Catalyst().parse_grade_data("GradeBook", response.data)
""" This is the interface for interacting w/ Catalyst GradeBook """ from restclients.catalyst import Catalyst from restclients.exceptions import DataFailureException from restclients.dao import Catalyst_DAO class GradeBook(object): def get_grades_for_student_and_term(self, netid, year, quarter): """ returns a restclients.models.catalyst.CourseGradeData object """ url = "/rest/gradebook/v1/grades/%s/%s/%s" % (netid, year, quarter) dao = Catalyst_DAO() response = dao.getURL(url, { "Accept": "application/json" }) if response.status != 200: raise DataFailureException(url, response.status, response.data) return Catalyst().parse_grade_data("GradeBook", response.data)
Fix the output when there is wrong usage
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time from watchdog.observers import Observer from specchio.handlers import SpecchioEventHandler from specchio.utils import init_logger, logger def main(): """Main function for specchio Example: specchio test/ user@host:test/ :return: None """ if len(sys.argv) == 3: src_path = sys.argv[1].strip() dst_ssh, dst_path = sys.argv[2].strip().split(":") event_handler = SpecchioEventHandler( src_path=src_path, dst_ssh=dst_path, dst_path=dst_path ) init_logger() logger.info("Initialize Specchio") observer = Observer() observer.schedule(event_handler, src_path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() else: print """Usage: specchio src/ user@host:dst/"""
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time from watchdog.observers import Observer from specchio.handlers import SpecchioEventHandler from specchio.utils import init_logger, logger def main(): """Main function for specchio Example: specchio test/ user@host:test/ :return: None """ if len(sys.argv) == 3: src_path = sys.argv[1].strip() dst_ssh, dst_path = sys.argv[2].strip().split(":") event_handler = SpecchioEventHandler( src_path=src_path, dst_ssh=dst_path, dst_path=dst_path ) init_logger() logger.info("Initialize Specchio") observer = Observer() observer.schedule(event_handler, src_path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() else: print """Specchio is a tool that can help you rsync your file, it use `.gitignore` in git to discern which file is ignored. Usage: specchio src/ user@host:dst"""
Revert "Added lil section on keys for vis" This reverts commit 17df8c0ac9a755ef4974d2d5d50fcd24ea14b6e2.
<!DOCTYPE HTML> <html> <head> <?php include 'includes/header.php'; ?> <title>Game</title> <link href="lib/bootstrap.min.css" rel="stylesheet"> <link href="style/general.css" rel="stylesheet"> </head> <body> <div id="container" class="container"> <?php include 'includes/navbar.php'; ?> <div id="pageContent" class="pageContent"> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.0/seedrandom.min.js"></script> <script src="script/general.js"></script> <script src="script/backend.js"></script> <script src="lib/pixi.min.js"></script> <script src="script/parsereplay.js"></script> <script src="script/visualizer.js"></script> <script src="script/game.js"></script> </body> </html>
<!DOCTYPE HTML> <html> <head> <?php include 'includes/header.php'; ?> <title>Game</title> <link href="lib/bootstrap.min.css" rel="stylesheet"> <link href="style/general.css" rel="stylesheet"> </head> <body> <div id="container" class="container"> <?php include 'includes/navbar.php'; ?> <div id="pageContent" class="pageContent"> </div> </div> <div> <h2>Keys that do something: WASDZX+-\<\>P[UP][DOWN][LEFT][RIGHT][SPACE]</h2> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.0/seedrandom.min.js"></script> <script src="script/general.js"></script> <script src="script/backend.js"></script> <script src="lib/pixi.min.js"></script> <script src="script/parsereplay.js"></script> <script src="script/visualizer.js"></script> <script src="script/game.js"></script> </body> </html>
Add element to defaultProps and assign 'a' to it
import React, { Fragment, PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; class Link extends PureComponent { render() { const { children, className, icon, iconPlacement, element, inherit, ...others } = this.props; const classNames = cx( theme['link'], { [theme['inherit']]: inherit, }, className, ); const ChildrenWrapper = icon ? 'span' : Fragment; const Element = element; return ( <Element className={classNames} data-teamleader-ui="link" {...others}> {icon && iconPlacement === 'left' && icon} <ChildrenWrapper>{children}</ChildrenWrapper> {icon && iconPlacement === 'right' && icon} </Element> ); } } Link.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, /** The icon displayed inside the button. */ icon: PropTypes.element, /** The position of the icon inside the button. */ iconPlacement: PropTypes.oneOf(['left', 'right']), inherit: PropTypes.bool, element: PropTypes.element, }; Link.defaultProps = { className: '', element: 'a', inherit: true, }; export default Link;
import React, { Fragment, PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; class Link extends PureComponent { render() { const { children, className, icon, iconPlacement, element, inherit, ...others } = this.props; const classNames = cx( theme['link'], { [theme['inherit']]: inherit, }, className, ); const ChildrenWrapper = icon ? 'span' : Fragment; const Element = element || 'a'; return ( <Element className={classNames} data-teamleader-ui="link" {...others}> {icon && iconPlacement === 'left' && icon} <ChildrenWrapper>{children}</ChildrenWrapper> {icon && iconPlacement === 'right' && icon} </Element> ); } } Link.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, /** The icon displayed inside the button. */ icon: PropTypes.element, /** The position of the icon inside the button. */ iconPlacement: PropTypes.oneOf(['left', 'right']), inherit: PropTypes.bool, element: PropTypes.element, }; Link.defaultProps = { className: '', inherit: true, }; export default Link;
Add a comment about audience
package api import ( "errors" "fmt" ) var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience") type OidcToken struct { Token string `json:"token"` } func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) { type oidcTokenRequest struct { Audience string `json:"audience"` } var m *oidcTokenRequest switch len(audience) { case 0: m = nil case 1: m = &oidcTokenRequest{Audience: audience[0]} default: // While the spec supports multiple audiences in an Id JWT, our API does // not support issuing them. // See: https://openid.net/specs/openid-connect-core-1_0.html#IDToken. return nil, nil, ErrAudienceTooLong } u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId) req, err := c.newRequest("POST", u, m) if err != nil { return nil, nil, err } t := &OidcToken{} resp, err := c.doRequest(req, t) if err != nil { return nil, nil, err } return t, resp, err }
package api import ( "errors" "fmt" ) var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience") type OidcToken struct { Token string `json:"token"` } func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) { type oidcTokenRequest struct { Audience string `json:"audience"` } var m *oidcTokenRequest switch len(audience) { case 0: m = nil case 1: m = &oidcTokenRequest{Audience: audience[0]} default: return nil, nil, ErrAudienceTooLong } u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId) req, err := c.newRequest("POST", u, m) if err != nil { return nil, nil, err } t := &OidcToken{} resp, err := c.doRequest(req, t) if err != nil { return nil, nil, err } return t, resp, err }
Send post data as form-urlencoded
(function(window){ window.ajax = function(route, options) { var data = options.data || {}, success = options.success || function(response){}, error = options.error || function(response){}, request = new XMLHttpRequest(); request.open(route.method, route.url, true); request.setRequestHeader("X-Requested-With", "XMLHttpRequest"); request.addEventListener("load", function(evt) { success(JSON.parse(request.responseText), request); }); request.addEventListener("error", function(evt) { error(request); }); if(route.method === 'POST') { request.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8"); request.send(data); } else { request.send(); } }; })(window);
(function(window){ window.ajax = function(route, options) { var data = options.data || {}, success = options.success || function(response){}, error = options.error || function(response){}, request = new XMLHttpRequest(); request.open(route.method, route.url, true); request.setRequestHeader("X-Requested-With", "XMLHttpRequest"); request.addEventListener("load", function(evt) { success(JSON.parse(request.responseText), request); }); request.addEventListener("error", function(evt) { error(request); }); if(route.method === 'POST') { request.send(data); } else { request.send(); } }; })(window);
Use function instead of React Component Class * Extract logic from view.
import React from 'react'; import { movePiece } from '../actions'; import { connect } from 'react-redux'; import _ from 'lodash'; import { getPieceImage } from '../images/shogiPieces/index'; const mapStateToProps = (state) => { return { board: state.board, turn: state.turn }; }; const mapDispatchToProps = (dispatch) => { return { onPieceClick: (board, piece) => { dispatch(movePiece(board, piece)); } }; }; const shogiPiece = ({ piece, board, onPieceClick }) => { return ( <div className="piece" onClick={() => onPieceClick(board, piece)}> <img src={getPieceImage(piece)}></img> </div> ); }; const Piece = connect( mapStateToProps, mapDispatchToProps )(shogiPiece); export default Piece;
import React from 'react'; import { movePiece } from '../actions'; import { connect } from 'react-redux'; import _ from 'lodash'; import { getPieceImage } from '../images/shogiPieces/index'; const mapStateToProps = (state) => { return { board: state.board, turn: state.turn }; }; const mapDispatchToProps = (dispatch) => { return { onPieceClick: (board, piece) => { dispatch(movePiece(board, piece)); } }; }; export default class ShogiPiece extends React.Component { render() { return( <div className="piece" onClick={() => this.props.onPieceClick(this.props.board, this.props.piece)}> <img src={getPieceImage(this.props.piece)}></img> </div> ); } } const Piece = connect( mapStateToProps, mapDispatchToProps )(ShogiPiece); export default Piece;
Set the focus highlight correctly if an element has focus while the page is being loaded. Signed-off-by: Daniel Greenfeld <8363115a959be51f40dc0f39f5da6050bb507aa3@gmail.com>
jQuery.fn.uniform = function(settings) { settings = jQuery.extend({ valid_class : 'valid', invalid_class : 'invalid', focused_class : 'focused', holder_class : 'ctrlHolder', field_selector : 'input, select, textarea' }, settings); return this.each(function() { var form = jQuery(this); // Focus specific control holder var focusControlHolder = function(element) { element.parents("." + settings.holder_class).addClass(settings.focused_class) }; // Select form fields and attach them higlighter functionality form.find(settings.field_selector).focus(function() { form.find('.' + settings.focused_class).removeClass(settings.focused_class); focusControlHolder(jQuery(this)); }).blur(function() { form.find('.' + settings.focused_class).removeClass(settings.focused_class); }); }); }; // Auto set on page load... $(document).ready(function() { jQuery('form.uniForm').uniform(); $(document.activeElement).focus() //safari doesn't support this and has no alternative });
jQuery.fn.uniform = function(settings) { settings = jQuery.extend({ valid_class : 'valid', invalid_class : 'invalid', focused_class : 'focused', holder_class : 'ctrlHolder', field_selector : 'input, select, textarea' }, settings); return this.each(function() { var form = jQuery(this); // Focus specific control holder var focusControlHolder = function(element) { element.parents("." + settings.holder_class).addClass(settings.focused_class) }; // Select form fields and attach them higlighter functionality form.find(settings.field_selector).focus(function() { form.find('.' + settings.focused_class).removeClass(settings.focused_class); focusControlHolder(jQuery(this)); }).blur(function() { form.find('.' + settings.focused_class).removeClass(settings.focused_class); }); }); }; // Auto set on page load... $(document).ready(function() { jQuery('form.uniForm').uniform(); });
Allow to specify custom host and port
package main import ( "flag" "fmt" "net/http" "os" "runtime" "bitbucket.org/tebeka/nrsc" "github.com/alexcesaro/log" "github.com/alexcesaro/log/golog" ) var logger *golog.Logger var address *string var storage storageHandler func requestLog(handler http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { logger.Infof("%s %s", r.Method, r.URL) handler.ServeHTTP(rw, r) }) } func init() { runtime.GOMAXPROCS(runtime.NumCPU()) address = flag.String("address", "127.0.0.1:8080", "serve requests to this host[:port]") flag.Parse() logger = golog.New(os.Stdout, log.Info) var err error if storage, err = newMongoHandler(); err != nil { os.Exit(1) } } func main() { // Static assets nrsc.Handle("/static/") // RESTful API http.Handle("/", newRouter()) // Banner and launcher banner := fmt.Sprintf("\n\t:-:-: perfkeeper :-:-:\t\t\tserving http://%s/\n", *address) fmt.Println(banner) logger.Critical(http.ListenAndServe(*address, requestLog(http.DefaultServeMux))) }
package main import ( "fmt" "net/http" "os" "runtime" "bitbucket.org/tebeka/nrsc" "github.com/alexcesaro/log" "github.com/alexcesaro/log/golog" ) var logger *golog.Logger var storage storageHandler func requestLog(handler http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { logger.Infof("%s %s", r.Method, r.URL) handler.ServeHTTP(rw, r) }) } func init() { runtime.GOMAXPROCS(runtime.NumCPU()) logger = golog.New(os.Stdout, log.Info) var err error if storage, err = newMongoHandler(); err != nil { os.Exit(1) } } func main() { // Static assets nrsc.Handle("/static/") // RESTful API http.Handle("/", newRouter()) // Banner and launcher fmt.Println("\n\t:-:-: perfkeeper :-:-:\t\t\tserving http://0.0.0.0:8080/\n") logger.Critical(http.ListenAndServe("0.0.0.0:8080", requestLog(http.DefaultServeMux))) }
Correct bug in producer; producer always writes to partition 0 even if a specific partition is set in the payload.
var _ = require('lodash'); 'use strict'; function DefaultPartitioner() { this.getPartition = function (partitions) { if (partitions && _.isArray(partitions) && partitions.length > 0) { return partitions[0]; } else { return 0; } } } function RandomPartitioner() { this.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } } function KeyedPartitioner() { // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. function hashCode(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } this.getPartition = function (partitions, key) { key = key || '' var index = hashCode(key) % partitions.length; return partitions[index]; } } exports.DefaultPartitioner = DefaultPartitioner; exports.RandomPartitioner = RandomPartitioner; exports.KeyedPartitioner = KeyedPartitioner;
'use strict'; function DefaultPartitioner() { this.getPartition = function () { return 0; } } function RandomPartitioner() { this.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } } function KeyedPartitioner() { // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. function hashCode(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } this.getPartition = function (partitions, key) { key = key || '' var index = hashCode(key) % partitions.length; return partitions[index]; } } exports.DefaultPartitioner = DefaultPartitioner; exports.RandomPartitioner = RandomPartitioner; exports.KeyedPartitioner = KeyedPartitioner;
Enforce unique to column categoryName OPEN - task 54: Create Category CRUD packages http://github.com/DevOpsDistilled/OpERP/issues/issue/54
package devopsdistilled.operp.server.data.entity.items; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import devopsdistilled.operp.server.data.entity.Entiti; @Entity public class Category extends Entiti implements Serializable { private static final long serialVersionUID = -3809686715120885998L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long categoryId; @Column(unique = true) private String categoryName; @ManyToMany(mappedBy = "categories") private List<Product> products; public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } }
package devopsdistilled.operp.server.data.entity.items; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import devopsdistilled.operp.server.data.entity.Entiti; @Entity public class Category extends Entiti implements Serializable { private static final long serialVersionUID = -3809686715120885998L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long categoryId; private String categoryName; @ManyToMany(mappedBy = "categories") private List<Product> products; public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } }
Fix a little bug: mainpage jump link
<?php /* @var $this yii\web\View */ $this->title = 'Welcome To Biser'; ?> <div class="site-index"> <div class="jumbotron"> <h1>Welcome!</h1> <p class="lead">欢迎来到Biser数据聚合服务</p> </div> <div class="body-content"> <div class="row"> <?php foreach($summary as $s) {?> <div class="col-lg-4"> <h2><?php echo $s['title'];?></h2> <p><?php echo $s['post_name']; ?></p> <p><a class="btn btn-default" href="/feed/index?post_id=<?php echo $s['post_id']; ?>">Read more</a></p> </div> <?php } ?> </div> </div> </div>
<?php /* @var $this yii\web\View */ $this->title = 'Welcome To Biser'; ?> <div class="site-index"> <div class="jumbotron"> <h1>Welcome!</h1> <p class="lead">欢迎来到Biser数据聚合服务</p> </div> <div class="body-content"> <div class="row"> <?php foreach($summary as $s) {?> <div class="col-lg-4"> <h2><?php echo $s['title'];?></h2> <p><?php echo $s['post_name']; ?></p> <p><a class="btn btn-default" href="./feed/index?post_id=<?php echo $s['post_id']; ?>">Read more</a></p> </div> <?php } ?> </div> </div> </div>
Fix lint error and update JSDoc examples
'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); var RE = require( '@stdlib/regexp/function-name' ); var isBuffer = require( '@stdlib/assert/is-buffer' ); // MAIN // /** * Determines the name of a value's constructor. * * @param {*} v - input value * @returns {string} name of a value's constructor * * @example * var v = constructorName( 'a' ); * // returns 'String' * * @example * var v = constructorName( 5 ); * // returns 'Number' * * @example * var v = constructorName( null ); * // returns 'Null' * * @example * var v = constructorName( undefined ); * // returns 'Undefined' * * @example * var v = constructorName( function noop() {} ); * // returns 'Function' */ function constructorName( v ) { var name; var ctor; name = nativeClass( v ).slice( 8, -1 ); if ( (name === 'Object' || name === 'Error') && v.constructor ) { ctor = v.constructor; if ( typeof ctor.name === 'string' ) { return ctor.name; } return RE.exec( ctor.toString() )[ 1 ]; } if ( isBuffer( v ) ) { return 'Buffer'; } return name; } // end FUNCTION constructorName() // EXPORTS // module.exports = constructorName;
'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); var RE = require( '@stdlib/regexp/function-name' ); var isBuffer = require( '@stdlib/assert/is-buffer' ); // MAIN // /** * Determines the name of a value's constructor. * * @param {*} v - input value * @returns {string} name of a value's constructor * * @example * var v = constructorName( 'a' ); * // returns 'String' * @example * var v = constructorName( 5 ); * // returns 'Number' * @example * var v = constructorName( null ); * // returns 'Null' * @example * var v = constructorName( undefined ); * // returns 'Undefined' * @example * var v = constructorName( function noop(){} ); * // returns 'Function' */ function constructorName( v ) { var name; var ctor; name = nativeClass( v ).slice( 8, -1 ); if ( (name === 'Object' || name === 'Error') && v.constructor ) { ctor = v.constructor; if ( typeof ctor.name === 'string' ) { return ctor.name; } return RE.exec( ctor.toString() )[ 1 ]; } if ( isBuffer( v ) ) { return 'Buffer'; } return name; } // end FUNCTION constructorName() // EXPORTS // module.exports = constructorName;
Change error class to function
""" Оповещение администратора о возникших ошибках """ from traceback import format_exception, format_exc from contextlib import contextmanager from lib.config import emergency_id from lib.commands import vk, api @contextmanager def ErrorManager(name): """ Упрощенное оповещение об ошибках str name: название скрипта (обычно укороченное) Использование: with ErrorManager(name): main() """ try: yield except Exception as e: sendErrorMessage(name) raise e def sendErrorMessage(name, exception=None): """ Использует либо полученную ошибку, либо ту, что возникла последней """ exception = format_error(exception) message = "{}:\n{}".format(name, exception) vk(api.messages.send, user_id=emergency_id, message=message) def format_error(error): if error is not None: error_info = format_exception(type(error), error, error.__traceback__) return "".join(error_info) else: return format_exc()
""" Оповещение администратора о возникших ошибках """ from traceback import format_exception, format_exc from lib.config import emergency_id from lib.commands import vk, api class ErrorManager: """ Упрощенное оповещение об ошибках str name: название скрипта (обычно укороченное) Использование: with ErrorManager(name): main() """ def __init__(self, name): self.name = name def __enter__(self): pass def __exit__(self, *args): if args[0] is not None: sendErrorMessage(self.name) def sendErrorMessage(name, exception=None): """ Использует либо полученную ошибку, либо ту, что возникла последней """ exception = format_error(exception) message = "{}:\n{}".format(name, exception) vk(api.messages.send, user_id=emergency_id, message=message) def format_error(error): if error is not None: error_info = format_exception(type(error), error, error.__traceback__) return "".join(error_info) else: return format_exc()
Add an environment variable to override the server backend instance This is useful for testing.
package core import ( "google.golang.org/grpc" "log" "os" msg "qpm.io/common/messages" "google.golang.org/grpc/credentials" ) const ( Version = "0.0.1" PackageFile = "qpm.json" SignatureFile = "qpm.asc" Vendor = "vendor" Address = "pkg.qpm.io:7000" LicenseFile = "LICENSE" ) type Context struct { Log *log.Logger Client msg.QpmClient } func NewContext() *Context { log := log.New(os.Stderr, "QPM: ", log.LstdFlags) creds := credentials.NewClientTLSFromCert(nil, "") address := os.Getenv("SERVER") if address == "" { address = Address } conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds)) if err != nil { log.Fatalf("did not connect: %v", err) } return &Context{ Log: log, Client: msg.NewQpmClient(conn), } }
package core import ( "google.golang.org/grpc" "log" "os" msg "qpm.io/common/messages" "google.golang.org/grpc/credentials" ) const ( Version = "0.0.1" PackageFile = "qpm.json" SignatureFile = "qpm.asc" Vendor = "vendor" Address = "pkg.qpm.io:7000" LicenseFile = "LICENSE" ) type Context struct { Log *log.Logger Client msg.QpmClient } func NewContext() *Context { log := log.New(os.Stderr, "QPM: ", log.LstdFlags) creds := credentials.NewClientTLSFromCert(nil, "") conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(creds)) if err != nil { log.Fatalf("did not connect: %v", err) } return &Context{ Log: log, Client: msg.NewQpmClient(conn), } }
Update file server routes with API version Signed-off-by: Max Brunsfeld <8ee73e75b50cc292b5052b11f2ca25336d3e974e@pivotallabs.com>
package router const ( FS_STATIC = "static" FS_UPLOAD_DROPLET = "upload_droplet" FS_UPLOAD_BUILD_ARTIFACTS = "upload_build_artifacts" FS_DOWNLOAD_BUILD_ARTIFACTS = "download_build_artifacts" ) func NewFileServerRoutes() Routes { return Routes{ {Path: "/v1/static/", Method: "GET", Handler: FS_STATIC}, {Path: "/v1/droplet/:guid", Method: "POST", Handler: FS_UPLOAD_DROPLET}, {Path: "/v1/build_artifacts/:app_guid", Method: "POST", Handler: FS_UPLOAD_BUILD_ARTIFACTS}, {Path: "/v1/build_artifacts/:app_guid", Method: "GET", Handler: FS_DOWNLOAD_BUILD_ARTIFACTS}, } }
package router const ( FS_STATIC = "static" FS_UPLOAD_DROPLET = "upload_droplet" FS_UPLOAD_BUILD_ARTIFACTS = "upload_build_artifacts" FS_DOWNLOAD_BUILD_ARTIFACTS = "download_build_artifacts" ) func NewFileServerRoutes() Routes { return Routes{ {Path: "/static/", Method: "GET", Handler: FS_STATIC}, {Path: "/droplet/:guid", Method: "POST", Handler: FS_UPLOAD_DROPLET}, {Path: "/build_artifacts/:app_guid", Method: "POST", Handler: FS_UPLOAD_BUILD_ARTIFACTS}, {Path: "/build_artifacts/:app_guid", Method: "GET", Handler: FS_DOWNLOAD_BUILD_ARTIFACTS}, } }
Use the world hashcode instead of the world instance.
package tld.testmod.common.animation; import net.minecraft.world.World; import net.minecraftforge.client.model.animation.Animation; public enum ModAnimation { INSTANCE; static long timeOffset; static int lastWorldHashCode; /** * Get the global world time for the current tick, in seconds. */ public static float getWorldTime(World world) { return getWorldTime(world, 0); } /** * Get the global world time for the current tick + partial tick progress, in seconds. */ public static float getWorldTime(World world, float tickProgress) { int worldHashCode = world.hashCode(); if (worldHashCode != lastWorldHashCode) { timeOffset = world.getTotalWorldTime(); lastWorldHashCode = worldHashCode; } //long diff = world.getTotalWorldTime() - timeOffset; //ModLogger.info("Animation#getWorldTime: World: %s, time: %d, offset %d, diff: %d", lastWorldHashCode, world.getTotalWorldTime(), timeOffset, diff); return (world.getTotalWorldTime() - timeOffset + tickProgress) / 20; } /** * Get current partialTickTime. */ public static float getPartialTickTime() { return Animation.getPartialTickTime(); } }
package tld.testmod.common.animation; import net.minecraft.world.World; import net.minecraftforge.client.model.animation.Animation; import tld.testmod.ModLogger; public enum ModAnimation { INSTANCE; static long timeOffset; static Object lastWorld; /** * Get the global world time for the current tick, in seconds. */ public static float getWorldTime(World world) { return getWorldTime(world, 0); } /** * Get the global world time for the current tick + partial tick progress, in seconds. */ public static float getWorldTime(World world, float tickProgress) { if (!world.equals(lastWorld)) { timeOffset = world.getTotalWorldTime(); lastWorld = world; } long diff = world.getTotalWorldTime() - timeOffset; //ModLogger.info("Animation#getWorldTime: World: %s, time: %d, offset %d, diff: %d", lastWorld, world.getTotalWorldTime(), timeOffset, diff); return (world.getTotalWorldTime() - timeOffset + tickProgress) / 20; } /** * Get current partialTickTime. */ public static float getPartialTickTime() { return Animation.getPartialTickTime(); } }
Send message on success and set error message from config.
var config = require('./config'); var nodemailer = require('nodemailer'); module.exports = function (req, res, next) { var smtpTransport = nodemailer.createTransport(config.smtp); console.log('about to send'); res.render('emails/contact-form', req.body, function (err, html) { smtpTransport.sendMail({ from: config.from, replyTo: req.body.email, to: config.to, subject: config.subject, html: html }, function (err) { // TODO try to get a hold page object if (err) { err.message = config.error[err.status] || config.error.default; } else { res.locals.message = config.success; } next(err); }); }); };
var config = require('./config'); var nodemailer = require('nodemailer'); module.exports = function (req, res, next) { var smtpTransport = nodemailer.createTransport(config.smtp); console.log('about to send'); res.render('emails/contact-form', req.body, function (err, html) { smtpTransport.sendMail({ from: config.from, replyTo: req.body.email, to: config.to, subject: config.subject, html: html }, function (err) { // TODO try to get a hold page object //if (err) { // console.log(err); res.status(500).locals.message = config.error; //} else { // res.locals.formStatus = config.success; //} next(); }); }); };
Siggen: Tidy up basic siggen example
from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time, logging import matplotlib import matplotlib.pyplot as plt logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("example") i = m.discover_instrument() if i is None or i.type != 'signal_generator': print "No or wrong instrument deployed" i = SignalGenerator() m.attach_instrument(i) else: print "Attached to existing Signal Generator" i.set_defaults() try: i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10) i.commit() finally: m.close()
from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time, logging import matplotlib import matplotlib.pyplot as plt logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("Aqua") i = m.discover_instrument() if i is None or i.type != 'signal_generator': print "No or wrong instrument deployed" i = SignalGenerator() m.attach_instrument(i) else: print "Attached to existing Signal Generator" i.set_defaults() i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) i.commit() try: while True: try: i.out1_offset += 0.05 except ValueOutOfRangeException: i.out1_offset = -1 print i.out1_offset i.commit() finally: m.close()
Fix fatal during redirection safety check for searching for Phabricator base-uri with no trailing slash Summary: Fixes T13412. If you search for "https://phabricator.example.com" with no trailing slash, we currently redirect you to "", which is fouled by a safety check in the redirection flow. Test Plan: - Searched for "https://local.phacility.com"; before: fatal in redirection; after: clean redirect. - Searched for other self-URIs, got normal redirects. Maniphest Tasks: T13412 Differential Revision: https://secure.phabricator.com/D20794
<?php final class PhabricatorDatasourceURIEngineExtension extends PhabricatorDatasourceEngineExtension { public function newQuickSearchDatasources() { return array(); } public function newJumpURI($query) { // If you search for a URI on the local install, just redirect to that // URI as though you had pasted it into the URI bar. if (PhabricatorEnv::isSelfURI($query)) { // Strip off the absolute part of the URI. If we don't, the URI redirect // validator will get upset that we're performing an unmarked external // redirect. // The correct host and protocol may also differ from the host and // protocol used in the search: for example, if you search for "http://" // we want to redirect to "https://" if an install is HTTPS, and // the "isSelfURI()" check includes alternate domains in addition to the // canonical domain. $uri = id(new PhutilURI($query)) ->setDomain(null) ->setProtocol(null) ->setPort(null); $uri = phutil_string_cast($uri); // See T13412. If the URI was in the form "http://dev.example.com" with // no trailing slash, there may be no path. Redirecting to the empty // string is considered an error by safety checks during redirection, // so treat this like the user entered the URI with a trailing slash. if (!strlen($uri)) { $uri = '/'; } return $uri; } return null; } }
<?php final class PhabricatorDatasourceURIEngineExtension extends PhabricatorDatasourceEngineExtension { public function newQuickSearchDatasources() { return array(); } public function newJumpURI($query) { // If you search for a URI on the local install, just redirect to that // URI as though you had pasted it into the URI bar. if (PhabricatorEnv::isSelfURI($query)) { // Strip off the absolute part of the URI. If we don't, the URI redirect // validator will get upset that we're performing an unmarked external // redirect. // The correct host and protocol may also differ from the host and // protocol used in the search: for example, if you search for "http://" // we want to redirect to "https://" if an install is HTTPS, and // the "isSelfURI()" check includes alternate domains in addition to the // canonical domain. $uri = id(new PhutilURI($query)) ->setDomain(null) ->setProtocol(null) ->setPort(null); return phutil_string_cast($uri); } return null; } }
Make sure to properly patch the Zepto object in IE, not any global $ object.
// Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function($){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })(Zepto)
// Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function(){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })()
Allow for the task view to take an item with a getId getter as well as a pure item id
jsio('from shared.javascript import Class, capitalize') jsio('import fan.tasks.panels.Panel') jsio('import fan.tasks.views.TaskItemView') jsio('import fan.query') exports = Class(fan.tasks.panels.Panel, function(supr) { this._className += ' ItemPanel' this._createContent = function() { supr(this, '_createContent') this.position(this._lastLeft, this._lastMaxWidth) fan.query.subscribe('HashChanged', this, '_onHashChanged') } this._onHashChanged = function(newItemId) { this.viewTask(newItemId) } this.position = function(left, availableWidth) { this._lastLeft = left this._lastMaxWidth = availableWidth if (!this._element) { return } this._element.style.left = left + 'px' if (this._currentView) { this._resize() } } this.setView = function(view) { this.appendTo(gBody) this._setView(view) } this.viewTask = function(taskItemId) { if (taskItemId.getId) { taskItemId = taskItemId.getId() } var currentView = this._currentView, currentTaskId = currentView && currentView.getTaskId && currentView.getTaskId() if (currentTaskId == taskItemId) { return } var view = new fan.tasks.views.TaskItemView(taskItemId) this.setView(view) fan.query.setHash(taskItemId) } })
jsio('from shared.javascript import Class, capitalize') jsio('import fan.tasks.panels.Panel') jsio('import fan.tasks.views.TaskItemView') jsio('import fan.query') exports = Class(fan.tasks.panels.Panel, function(supr) { this._className += ' ItemPanel' this._createContent = function() { supr(this, '_createContent') this.position(this._lastLeft, this._lastMaxWidth) fan.query.subscribe('HashChanged', this, '_onHashChanged') } this._onHashChanged = function(newItemId) { this.viewTask(newItemId) } this.position = function(left, availableWidth) { this._lastLeft = left this._lastMaxWidth = availableWidth if (!this._element) { return } this._element.style.left = left + 'px' if (this._currentView) { this._resize() } } this.setView = function(view) { this.appendTo(gBody) this._setView(view) } this.viewTask = function(taskItemId) { var currentView = this._currentView, currentTaskId = currentView && currentView.getTaskId && currentView.getTaskId() if (currentTaskId == taskItemId) { return } var view = new fan.tasks.views.TaskItemView(taskItemId) this.setView(view) fan.query.setHash(taskItemId) } })
Update slug of our "Learn more about langpacks" link The url of the SUMO article linked from our "Learn more..." button in the Add-ons Manager changed a time ago. Preventing the remote redirection lets to Thunderbird to detect and reuse the tab displaying that contents when it deemed appropiate.
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //pref("extensions.simplels.applyOnQuit.matchOS", false); //pref("extensions.simplels.applyOnQuit.locale", "en-US"); //pref("extensions.simplels.button.migrated", false); pref("extensions.simplels.button.restartAfterSwitch", true); pref("extensions.simplels.button.showDescriptions", false); pref("extensions.simplels.getMoreLanguages", 2); //pref("extensions.simplels.getMoreLanguagesURL", "https://addons.mozilla.org/language-tools/"); pref("extensions.simplels.learnMoreAboutLanguagesURL", "https://support.mozilla.org/%LOCALE%/kb/use-firefox-interface-other-languages-language-pack"); pref("extensions.simplels.provider", "global");
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //pref("extensions.simplels.applyOnQuit.matchOS", false); //pref("extensions.simplels.applyOnQuit.locale", "en-US"); //pref("extensions.simplels.button.migrated", false); pref("extensions.simplels.button.restartAfterSwitch", true); pref("extensions.simplels.button.showDescriptions", false); pref("extensions.simplels.getMoreLanguages", 2); //pref("extensions.simplels.getMoreLanguagesURL", "https://addons.mozilla.org/language-tools/"); pref("extensions.simplels.learnMoreAboutLanguagesURL", "https://support.mozilla.org/%LOCALE%/kb/install-language-packs-get-more-languages"); pref("extensions.simplels.provider", "global");
Support native objects in getter
import {inspect} from "util"; import {getProperties, isImmutable, isNumeric} from "./helpers"; // LENS ============================================================================================ function createGetter(key) { return function getter(data) { if (key) { if (isImmutable(data)) { throw new Error(`can't get key ${inspect(key)} from immutable data ${inspect(data)}`); } else { if (data.meta && data.meta.kind == "dict") { return data.meta.codomain; } else if (data.meta && data.meta.kind == "struct") { return data.meta.props[key]; } else if (data.meta && data.meta.kind == "list") { return data.meta.type; } else { return data[key]; } } } else { return data; } }; } function createLens(getter) { return { get: getter, compose(nextLens) { return createLens( (data) => nextLens.get(getter(data)) ); } }; } export default function Lens(key) { if (typeof key != "string") { throw new Error(`key must be of string type, got ${typeof key}`); } let lens = key.split(".").map(k => createLens(createGetter(k))); return lens.reduce((lens, nextLens) => lens.compose(nextLens)); }
import {inspect} from "util"; import {getProperties, isImmutable, isNumeric} from "./helpers"; // LENS ============================================================================================ function createGetter(key) { return function getter(data) { if (key) { if (isImmutable(data)) { throw new Error(`can't get key ${inspect(key)} from immutable data ${inspect(data)}`); } else { if (data.meta.kind == "dict") { return data.meta.codomain; } else if (data.meta.kind == "struct") { return data.meta.props[key]; } else if (data.meta.kind == "list") { return data.meta.type; } else { // TODO possible situation?! return data[key]; } } } else { return data; } }; } function createLens(getter) { return { get: getter, compose(nextLens) { return createLens( (data) => nextLens.get(getter(data)) ); } }; } export default function Lens(key) { if (typeof key != "string") { throw new Error(`key must be of string type, got ${typeof key}`); } let lens = key.split(".").map(k => createLens(createGetter(k))); return lens.reduce((lens, nextLens) => lens.compose(nextLens)); }
Fix bug where multiple chunks joined with an extra comma
const fs = require('fs'); const debug = require('debug')('graph-wrangle:io'); const util = require('util'); function loadGraphFromStdIn() { debug(`Reading graph from stdin...`); return new Promise(resolve => { const chunks = []; process.stdin.setEncoding('utf8'); process.stdin.on('data', chunk => { chunks.push(chunk); }); process.stdin.on('end', () => { const jsonStr = chunks.join(''); const graph = JSON.parse(jsonStr); debug( `Loaded graph: ${graph.nodes.length} nodes, ${graph.links .length} links.` ); resolve(graph); }); }); } async function loadGraph(filePath) { debug(`Reading graph from ${filePath}...`); const readFile = util.promisify(fs.readFile); const jsonStr = await readFile(filePath, 'utf8'); const graph = JSON.parse(jsonStr); debug( `Loaded graph: ${graph.nodes.length} nodes, ${graph.links.length} links.` ); return graph; } function writeGraph(filePath, graph, format) { debug(`Writing graph to ${filePath}...`); let jsonStr; if (format) { jsonStr = JSON.stringify(graph, null, 2); } else { jsonStr = JSON.stringify(graph); } fs.writeFileSync(filePath, jsonStr); debug('Successfully wrote graph to file.'); } module.exports = { loadGraph, loadGraphFromStdIn, writeGraph, };
const fs = require('fs'); const debug = require('debug')('graph-wrangle:io'); const util = require('util'); function loadGraphFromStdIn() { debug(`Reading graph from stdin...`); return new Promise(resolve => { const chunks = []; process.stdin.setEncoding('utf8'); process.stdin.on('data', chunk => { chunks.push(chunk); }); process.stdin.on('end', () => { const jsonStr = chunks.join(); const graph = JSON.parse(jsonStr); debug( `Loaded graph: ${graph.nodes.length} nodes, ${graph.links .length} links.` ); resolve(graph); }); }); } async function loadGraph(filePath) { debug(`Reading graph from ${filePath}...`); const readFile = util.promisify(fs.readFile); const jsonStr = await readFile(filePath, 'utf8'); const graph = JSON.parse(jsonStr); debug( `Loaded graph: ${graph.nodes.length} nodes, ${graph.links.length} links.` ); return graph; } function writeGraph(filePath, graph, format) { debug(`Writing graph to ${filePath}...`); let jsonStr; if (format) { jsonStr = JSON.stringify(graph, null, 2); } else { jsonStr = JSON.stringify(graph); } fs.writeFileSync(filePath, jsonStr); debug('Successfully wrote graph to file.'); } module.exports = { loadGraph, loadGraphFromStdIn, writeGraph, };
Speed up some count tests.
<?php class FormalTheory_RegularExpression_Tests_CountTest extends PHPUnit_Framework_TestCase { function dataProviderForTestSimpleCount() { return array( array( "", NULL ), array( "$^", 0 ), array( "^$", 1 ), array( "^1*$", NULL ), array( "^1?$", 2 ), array( "^1{0,2}$", 3 ), array( "^1{0,9}$", 10 ), array( "^(1{1,3}){1,3}$", 9 ), array( "^(0|1){5}$", 32 ), array( "^(0|1){4,5}$", 16 + 32 ), ); } /** * @dataProvider dataProviderForTestSimpleCount */ function testSimpleCount( $regex_string, $expected_solution_count ) { $lexer = new FormalTheory_RegularExpression_Lexer(); $dfa = $lexer->lex( $regex_string )->getDFA(); $this->assertSame( $dfa->countSolutions(), $expected_solution_count ); } } ?>
<?php class FormalTheory_RegularExpression_Tests_CountTest extends PHPUnit_Framework_TestCase { function dataProviderForTestSimpleCount() { return array( array( "", NULL ), array( "$^", 0 ), array( "^$", 1 ), array( "^1*$", NULL ), array( "^1?$", 2 ), array( "^1{0,2}$", 3 ), array( "^1{0,9}$", 10 ), array( "^(1{1,3}){1,4}$", 12 ), array( "^(0|1){10}$", 1024 ), array( "^(0|1){9,10}$", 512 + 1024 ), ); } /** * @dataProvider dataProviderForTestSimpleCount */ function testSimpleCount( $regex_string, $expected_solution_count ) { $lexer = new FormalTheory_RegularExpression_Lexer(); $dfa = $lexer->lex( $regex_string )->getDFA(); $this->assertSame( $dfa->countSolutions(), $expected_solution_count ); } } ?>
Update client out from appointmentItem
var Mystique = require('mystique'); var AppointmentItemTransformer = Mystique.Transformer.extend({ resourceName: 'appointmentItem', mapOut: function(appointmentItem) { return { id: appointmentItem.id, service: appointmentItem.service, name: appointmentItem.name, startTime: appointmentItem.startTime, length: appointmentItem.length, title: appointmentItem.title, client: appointmentItem.client, }; }, mapIn(req) { return { service: req.getJson('appointmentItem.service'), name: req.getJson('appointmentItem.name'), startTime: req.getJson('appointmentItem.startTime'), length: req.getJson('appointmentItem.length'), title: req.getJson('appointmentItem.title'), }; }, }); Mystique.registerTransformer('AppointmentItem', AppointmentItemTransformer);
var Mystique = require('mystique'); var AppointmentItemTransformer = Mystique.Transformer.extend({ resourceName: 'appointmentItem', mapOut: function(appointmentItem) { return { id: appointmentItem.id, service: appointmentItem.service, name: appointmentItem.name, startTime: appointmentItem.startTime, length: appointmentItem.length, title: appointmentItem.title, }; }, mapIn(req) { return { service: req.getJson('appointmentItem.service'), name: req.getJson('appointmentItem.name'), startTime: req.getJson('appointmentItem.startTime'), length: req.getJson('appointmentItem.length'), title: req.getJson('appointmentItem.title'), }; }, }); Mystique.registerTransformer('AppointmentItem', AppointmentItemTransformer);