text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Integrate the hashtable Unit testcases. * tests/AllTests.java (suite): added HashtableTests
package org.tigris.subversion.lib; /** * ==================================================================== * Copyright (c) 2000-2001 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * */ public class StatusKind { public final static int NONE=1; public final static int NORMAL=2; public final static int ADDED=3; public final static int ABSENT=4; public final static int DELETED=5; public final static int REPLACED=6; public final static int MODIFIED=7; public final static int MERGED=8; public final static int CONFLICTED=9; private int kind = NONE; public StatusKind(int kind) { super(); this.kind = kind; } public StatusKind() { this(NONE); } public void setKind(int _kind) { kind = _kind; } public int getKind() { return kind; } }
package org.tigris.subversion.lib; /** * ==================================================================== * Copyright (c) 2000-2001 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * */ public class StatusKind { public final static int NONE=1; public final static int NORMAL=2; public final static int ADDED=3; public final static int ABSENT=4; public final static int DELETED=5; public final static int REPLACED=6; public final static int MODIFIED=7; public final static int MERGED=8; public final static int CONFLICTED=9; public final int kind; public StatusKind(int kind) { this.kind = kind; } }
Fix race condition at server shutdown
package main import ( "github.com/yuin/gopher-lua" "sync" ) // The LState pool pattern, as recommended by the author of gopher-lua: // https://github.com/yuin/gopher-lua#the-lstate-pool-pattern type lStatePool struct { m sync.Mutex saved []*lua.LState } func (pl *lStatePool) Get() *lua.LState { pl.m.Lock() defer pl.m.Unlock() n := len(pl.saved) if n == 0 { return pl.New() } x := pl.saved[n-1] pl.saved = pl.saved[0 : n-1] return x } func (pl *lStatePool) New() *lua.LState { L := lua.NewState() // setting the L up here. // load scripts, set global variables, share channels, etc... return L } func (pl *lStatePool) Put(L *lua.LState) { pl.m.Lock() defer pl.m.Unlock() pl.saved = append(pl.saved, L) } func (pl *lStatePool) Shutdown() { // The following line causes a race condition with the // graceful shutdown package at server shutdown: //for _, L := range pl.saved { // L.Close() //} }
package main import ( "github.com/yuin/gopher-lua" "sync" ) // The LState pool pattern, as recommended by the author of gopher-lua: // https://github.com/yuin/gopher-lua#the-lstate-pool-pattern type lStatePool struct { m sync.Mutex saved []*lua.LState } func (pl *lStatePool) Get() *lua.LState { pl.m.Lock() defer pl.m.Unlock() n := len(pl.saved) if n == 0 { return pl.New() } x := pl.saved[n-1] pl.saved = pl.saved[0 : n-1] return x } func (pl *lStatePool) New() *lua.LState { L := lua.NewState() // setting the L up here. // load scripts, set global variables, share channels, etc... return L } func (pl *lStatePool) Put(L *lua.LState) { pl.m.Lock() defer pl.m.Unlock() pl.saved = append(pl.saved, L) } func (pl *lStatePool) Shutdown() { for _, L := range pl.saved { L.Close() } }
Change name of post type
<?php add_action('init', 'register_post_types'); function register_post_types() { /**** NEWSLETTER POST TYPE ****/ $labels = array( 'name' => _x('Newsletters', 'post type general name'), 'singular_name' => _x('Newsletter', 'post type singular name'), 'add_new' => _x('Add New Newsletter', 'portfolio item'), 'add_new_item' => __('Add New Newsletter'), 'edit_item' => __('Edit Newsletter'), 'new_item' => __('New Newsletter'), 'view_item' => __('View Newsletter'), 'search_items' => __('Search Newsletters'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => null, 'supports' => array('title','editor'), //"menu_position" => 21 ); register_post_type( 'anw_newsletter' , $args ); flush_rewrite_rules(); } ?>
<?php add_action('init', 'register_post_types'); function register_post_types() { /**** NEWSLETTER POST TYPE ****/ $labels = array( 'name' => _x('Newsletters', 'post type general name'), 'singular_name' => _x('Newsletter', 'post type singular name'), 'add_new' => _x('Add New Newsletter', 'portfolio item'), 'add_new_item' => __('Add New Newsletter'), 'edit_item' => __('Edit Newsletter'), 'new_item' => __('New Newsletter'), 'view_item' => __('View Newsletter'), 'search_items' => __('Search Newsletters'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => null, 'supports' => array('title','editor'), //"menu_position" => 21 ); register_post_type( 'newsletter' , $args ); flush_rewrite_rules(); } ?>
Add new URL for NDEx service
import requests import json import time ndex_base_url = 'http://general.bigmech.ndexbio.org:8082' #ndex_base_url = 'http://52.37.175.128' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code # If response is immediate, we get 200 if status == 200: return res.text # If there is a continuation of the message # we get status 300, handled below. # Otherwise we return None. elif status != 300: return None task_id = res.json()['task_id'] print 'NDEx task submitted...' time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None print 'NDEx task complete.' return res.text
import requests import json import time #ndex_base_url = 'http://services.bigmech.ndexbio.org' ndex_base_url = 'http://52.37.175.128' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code # If response is immediate, we get 200 if status == 200: return res.text # If there is a continuation of the message # we get status 300, handled below. # Otherwise we return None. elif status != 300: return None task_id = res.json()['task_id'] print 'NDEx task submitted...' time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None print 'NDEx task complete.' return res.text
Fix typos discovered by the Debian Lintian tool
/* Package sentences is a golang package that will convert a blob of text into a list of sentences. This package attempts to support a multitude of languages: Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Greek, Italian, Norwegian, Polish, Portuguese, Slovene, Spanish, Swedish, and Turkish. An unsupervised multilingual sentence boundary detection library for golang. The goal of this library is to be able to break up any text into a list of sentences in multiple languages. The way the punkt system accomplishes this goal is through training the tokenizer with text in that given language. Once the likelihoods of abbreviations, collocations, and sentence starters are determined, finding sentence boundaries becomes easier. There are many problems that arise when tokenizing text into sentences, the primary issue being abbreviations. The punkt system attempts to determine whether a word is an abbreviation, an end to a sentence, or even both through training the system with text in the given language. The punkt system incorporates both token- and type-based analysis on the text through two different phases of annotation. Original research article: http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=BAE5C34E5C3B9DC60DFC4D93B85D8BB1?doi=10.1.1.85.5017&rep=rep1&type=pdf */ package sentences
/* Package sentences is a golang package will convert a blob of text into a list of sentences. This package attempts to support a multitude of languages: czech, danish, dutch, english, estonian, finnish, french, german, greek, italian, norwegian, polish, portuguese, slovene, spanish, swedish, and turkish. An unsupervised multilingual sentence boundary detection library for golang. The goal of this library is to be able to break up any text into a list of sentences in multiple languages. The way the punkt system accomplishes this goal is through training the tokenizer with text in that given language. Once the likelyhoods of abbreviations, collocations, and sentence starters are determined, finding sentence boundaries becomes easier. There are many problems that arise when tokenizing text into sentences, the primary issue being abbreviations. The punkt system attempts to determine whether a word is an abbrevation, an end to a sentence, or even both through training the system with text in the given language. The punkt system incorporates both token- and type-based analysis on the text through two different phases of annotation. Original research article: http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=BAE5C34E5C3B9DC60DFC4D93B85D8BB1?doi=10.1.1.85.5017&rep=rep1&type=pdf */ package sentences
Fix Cancel and Complete Transaction
'use strict'; // CartsCheckout controller var cartsApp = angular.module('carts'); cartsApp.controller('CartCheckoutController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { //$scope.authentication = Authentication; $scope.user = Authentication.user; // If user is not signed in then redirect back home if (!$scope.user) $location.path('/'); $scope.completeTransaction = function() { var params = $location.search(); $http.post('/cart/checkout/complete/transaction', params); $location.path('/board/posts'); console.log('Success Paid!'); }; $scope.cancelTransaction = function() { $http.post('/cart/checkout/cancel/transaction', {status: 'cancelled'}); $location.path('/board/posts'); console.log('Cancel Transaction!'); }; } ]);
'use strict'; // CartsCheckout controller var cartsApp = angular.module('carts'); cartsApp.controller('CartCheckoutController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { //$scope.authentication = Authentication; $scope.user = Authentication.user; // If user is not signed in then redirect back home if (!$scope.user) $location.path('/'); $scope.completeTransaction = function() { var params = $location.search(); $http.post('/cart/checkout/complete/transaction', params).success(function (response) { $location.path('/board/posts'); console.log('Success Paid!'); }); }; $scope.cancelTransaction = function() { $http.post('/cart/checkout/cancel/transaction', {status: 'cancelled'}).success(function (response) { $location.path('/board/posts'); console.log('Cancel Transaction!'); }); }; } ]);
Add test for uppercade keywords
<?php declare(strict_types=1); namespace Rector\NodeValueResolver\Tests; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\ArrayItem; use PhpParser\Node\Expr\ConstFetch; use PhpParser\Node\Name; use PhpParser\Node\Scalar\String_; use Rector\NodeValueResolver\NodeValueResolver; use Rector\Tests\AbstractContainerAwareTestCase; final class NodeValueResolverTest extends AbstractContainerAwareTestCase { /** * @var NodeValueResolver */ private $nodeValueResolver; protected function setUp(): void { $this->nodeValueResolver = $this->container->get(NodeValueResolver::class); } public function testArrayNode(): void { $arrayNode = new Array_([ new ArrayItem(new String_('hi')), new ArrayItem(new ConstFetch(new Name('true'))), new ArrayItem(new ConstFetch(new Name('FALSE'))), ]); $resolved = $this->nodeValueResolver->resolve($arrayNode); $this->assertSame(['hi', true, false], $resolved); } }
<?php declare(strict_types=1); namespace Rector\NodeValueResolver\Tests; use PhpParser\BuilderHelpers; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\ArrayItem; use PhpParser\Node\Scalar\String_; use Rector\NodeValueResolver\NodeValueResolver; use Rector\Tests\AbstractContainerAwareTestCase; final class NodeValueResolverTest extends AbstractContainerAwareTestCase { /** * @var NodeValueResolver */ private $nodeValueResolver; protected function setUp(): void { $this->nodeValueResolver = $this->container->get(NodeValueResolver::class); } public function testArrayNode(): void { $arrayNode = new Array_([ new ArrayItem(new String_('hi')), new ArrayItem(BuilderHelpers::normalizeValue(true)), new ArrayItem(BuilderHelpers::normalizeValue(false)), ]); $resolved = $this->nodeValueResolver->resolve($arrayNode); $this->assertSame(['hi', true, false], $resolved); } }
Add test for creating story
var should = require("should") var request = require('supertest') // var url = "http://localhost:3000" var url = 'http://corpsebook-server.herokuapp.com/' var request = request(url); describe('Stories', function(){ describe('POST /stories', function(){ it('gets success and returns json', function(done){ var story = {story: {title: "Supernatural Winnipeg", contribution_limit: 12, lat:-41.270833, lng: 173.283889}} request.post('/stories') .set('Accept', 'application/json') .send(story) .expect('Content-Type', /json/) .end(function(err, res){ console.log(res.body.story.title); (res.body.story.title).should.be.eql(story.story.title) done() }); }) }) describe('GET /stories', function(){ it('gets success and returns json', function(done){ request.get('/stories') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200, done); }) }) })
var should = require("should") var request = require('supertest') var url = "http://localhost:3000" var request = request(url); describe('Stories', function(){ describe('POST /stories', function(){ it('gets success and returns json', function(done){ var story = {story: {title: "Supernatural Winnipeg", contribution_limit: 12, lat:-41.270833, lng: 173.283889}} request.post('/stories') .set('Accept', 'application/json') .send(story) .expect('Content-Type', /json/) .end(function(err, res){ console.log(res.body.story.title); (res.body.story.title).should.be.eql(story.story.title) done() }); }) }) describe('GET /stories', function(){ it('gets success and returns json', function(done){ request.get('/stories') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200, done); }) }) })
Add "Upload" to the add button This makes it so it's "Add/Open/Upload". Change-Id: I17167d48c6782d4679a489ec883cf0c9065d628e
/** * @license * 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. */ export const GrEditConstants = { // Order corresponds to order in the UI. Actions: { OPEN: {label: 'Add/Open/Upload', id: 'open'}, DELETE: {label: 'Delete', id: 'delete'}, RENAME: {label: 'Rename', id: 'rename'}, RESTORE: {label: 'Restore', id: 'restore'}, }, };
/** * @license * 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. */ export const GrEditConstants = { // Order corresponds to order in the UI. Actions: { OPEN: {label: 'Add/Open', id: 'open'}, DELETE: {label: 'Delete', id: 'delete'}, RENAME: {label: 'Rename', id: 'rename'}, RESTORE: {label: 'Restore', id: 'restore'}, }, };
Fix the functional testcase name
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version__ _require_installed = skipUnless(which("flocker-changestate"), "flocker-changestate not installed") class FlockerChangeStateTests(TestCase): """Tests for ``flocker-changestate``.""" @_require_installed def setUp(self): pass def test_version(self): """ ``flocker-changestate`` is a command available on the system path """ result = check_output([b"flocker-changestate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,))
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version__ _require_installed = skipUnless(which("flocker-changestate"), "flocker-changestate not installed") class FlockerDeployTests(TestCase): """Tests for ``flocker-changestate``.""" @_require_installed def setUp(self): pass def test_version(self): """ ``flocker-changestate`` is a command available on the system path """ result = check_output([b"flocker-changestate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,))
Fix relevance-sorting on tag page
import { TagRels } from './collection.js'; import { ensureIndex } from '../../collectionUtils'; TagRels.addDefaultView(terms => { return { selector: { deleted: false, }, options: { sort: {baseScore: -1}, }, }; }); TagRels.addView('postsWithTag', terms => { return { selector: { tagId: terms.tagId, baseScore: {$gt: 0}, }, } }); TagRels.addView('tagsOnPost', terms => { return { selector: { postId: terms.postId, baseScore: {$gt: 0}, }, } }); ensureIndex(TagRels, {postId:1}); ensureIndex(TagRels, {tagId:1});
import { TagRels } from './collection.js'; import { ensureIndex } from '../../collectionUtils'; TagRels.addDefaultView(terms => { return { selector: { deleted: false, }, }; }); TagRels.addView('postsWithTag', terms => { return { selector: { tagId: terms.tagId, baseScore: {$gt: 0}, }, sort: {baseScore: -1}, } }); TagRels.addView('tagsOnPost', terms => { return { selector: { postId: terms.postId, baseScore: {$gt: 0}, }, sort: {baseScore: -1}, } }); ensureIndex(TagRels, {postId:1}); ensureIndex(TagRels, {tagId:1});
Allow absolute paths as destDir
'use strict'; var Y = require('yuidocjs'); var rsvp = require('rsvp'); var path = require('path'); var CachingWriter = require('broccoli-caching-writer'); BroccoliYuidoc.prototype = Object.create(CachingWriter.prototype); BroccoliYuidoc.prototype.constructor = BroccoliYuidoc; function BroccoliYuidoc(inputNodes, options) { this.options = options || {}; CachingWriter.call(this, inputNodes, { annotation: this.options.annotation }); }; BroccoliYuidoc.prototype.build = function() { this.paths = this.inputPaths; this.outdir = path.resolve(this.outputPath, this.options.destDir); var json = (new Y.YUIDoc(this)).run(); if (this.options.yuidoc.parseOnly) { return; } var builder = new Y.DocBuilder(this, json); return new rsvp.Promise(function(resolve) { builder.compile(function() { resolve(); }); }); } module.exports = BroccoliYuidoc;
'use strict'; var Y = require('yuidocjs'); var rsvp = require('rsvp'); var CachingWriter = require('broccoli-caching-writer'); BroccoliYuidoc.prototype = Object.create(CachingWriter.prototype); BroccoliYuidoc.prototype.constructor = BroccoliYuidoc; function BroccoliYuidoc(inputNodes, options) { this.options = options || {}; CachingWriter.call(this, inputNodes, { annotation: this.options.annotation }); }; BroccoliYuidoc.prototype.build = function() { this.paths = this.inputPaths; this.outdir = [this.outputPath, this.options.destDir].join('/'); var json = (new Y.YUIDoc(this)).run(); if (this.options.yuidoc.parseOnly) { return; } var builder = new Y.DocBuilder(this, json); return new rsvp.Promise(function(resolve) { builder.compile(function() { resolve(); }); }); } module.exports = BroccoliYuidoc;
Allow for Authorization URL to already contain '?' This will allow to use an authorization URL that already contains a query string as it checks when adding the OAuth2 parameter whether a '?' is already present on the authorization URL and will use the appropriate append character
import querystring from 'query-string' import cuid from 'cuid' import openPopup from './util/popup' const listenForCredentials = (popup, state, resolve, reject) => { let hash try { hash = popup.location.hash } catch (err) { if (process.env.NODE_ENV !== 'production') { /* eslint-disable no-console */ console.error(err) /* eslint-enable no-console */ } } if (hash) { popup.close() const response = querystring.parse(hash.substr(1)) if (response.state !== state) { reject('Invalid state returned.') } if (response.access_token) { resolve(response.access_token) } else { reject(response.error || 'Unknown error.') } } else if (popup.closed) { reject('Authentication was cancelled.') } else { setTimeout(() => listenForCredentials(popup, state, resolve, reject), 100) } } const authorize = (config) => { const state = cuid() const query = querystring.stringify({ state, response_type: 'token', client_id: config.client, scope: config.scope, redirect_uri: config.redirect }) const popup = openPopup(config.url + (config.url.indexOf('?') === -1 ? '?' : '&') + query, 'oauth2') return new Promise((resolve, reject) => listenForCredentials(popup, state, resolve, reject)) } export default authorize
import querystring from 'query-string' import cuid from 'cuid' import openPopup from './util/popup' const listenForCredentials = (popup, state, resolve, reject) => { let hash try { hash = popup.location.hash } catch (err) { if (process.env.NODE_ENV !== 'production') { /* eslint-disable no-console */ console.error(err) /* eslint-enable no-console */ } } if (hash) { popup.close() const response = querystring.parse(hash.substr(1)) if (response.state !== state) { reject('Invalid state returned.') } if (response.access_token) { resolve(response.access_token) } else { reject(response.error || 'Unknown error.') } } else if (popup.closed) { reject('Authentication was cancelled.') } else { setTimeout(() => listenForCredentials(popup, state, resolve, reject), 100) } } const authorize = (config) => { const state = cuid() const query = querystring.stringify({ state, response_type: 'token', client_id: config.client, scope: config.scope, redirect_uri: config.redirect }) const popup = openPopup(config.url + '?' + query, 'oauth2') return new Promise((resolve, reject) => listenForCredentials(popup, state, resolve, reject)) } export default authorize
Speed up test by reducing iterations.
/* Copyright 2011-2017 Frederic Langlet 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 kanzi.test; import kanzi.util.sort.BucketSort; import org.junit.Assert; import org.junit.Test; public class TestBucketSort extends TestAbstractSort { @Test public void testBucketSort() { Assert.assertTrue(testCorrectness("BucketSort", new BucketSort(8), 20)); testSpeed("BucketSort", new BucketSort(16), 10000, 0xFFFF); } }
/* Copyright 2011-2017 Frederic Langlet 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 kanzi.test; import kanzi.util.sort.BucketSort; import org.junit.Assert; import org.junit.Test; public class TestBucketSort extends TestAbstractSort { @Test public void testBucketSort() { Assert.assertTrue(testCorrectness("BucketSort", new BucketSort(8), 20)); testSpeed("BucketSort", new BucketSort(16), 20000, 0xFFFF); } }
Sort search results based on Levenshtein distance from query
package main import ( "github.com/labstack/echo" "github.com/texttheater/golang-levenshtein/levenshtein" "net/http" "sort" ) // So that we can sort var query string func setupRoutes(e *echo.Echo) { e.GET("/", route_main) e.GET("/search/:query", route_search) } func route_main(c echo.Context) error { return c.String(http.StatusOK, "You've reached /") } type ByLevenshteinDistance []SearchResult func (r ByLevenshteinDistance) Len() int { return len(r) } func (r ByLevenshteinDistance) Swap(i int, j int) { r[i], r[j] = r[j], r[i] } func (r ByLevenshteinDistance) Less(i int, j int) bool { return levenshtein.DistanceForStrings([]rune(query), []rune(r[i].Title), levenshtein.DefaultOptions) < levenshtein.DistanceForStrings([]rune(query), []rune(r[j].Title), levenshtein.DefaultOptions) } func route_search(c echo.Context) error { allResults := make(map[string][]SearchResult) query = c.Param("query") if len(query) < 5 { return c.String(http.StatusBadRequest, "Search query is too short") } for _, b := range BACKENDS { results, err := b.Search(query) if err != nil { log.Error(err) continue } sort.Sort(ByLevenshteinDistance(results)) allResults[b.Name()] = results } return c.JSON(http.StatusOK, allResults) }
package main import ( "github.com/labstack/echo" "net/http" ) func setupRoutes(e *echo.Echo) { e.GET("/", route_main) e.GET("/search/:query", route_search) } func route_main(c echo.Context) error { return c.String(http.StatusOK, "You've reached /") } func route_search(c echo.Context) error { allResults := make(map[string][]SearchResult) query := c.Param("query") if len(query) < 5 { return c.String(http.StatusBadRequest, "Search query is too short") } for _, b := range BACKENDS { results, err := b.Search(query) if err != nil { log.Error(err) continue } allResults[b.Name()] = results } return c.JSON(http.StatusOK, allResults) }
docs: Add missing godocs for Commander type Signed-off-by: deadprogram <b937b287f61b7a223d4aac55072db1a5381d3bb3@hybridgroup.com>
package gobot type commander struct { commands map[string]func(map[string]interface{}) interface{} } // Commander is the interface which describes the behaviour for a Driver or Adaptor // which exposes API commands. type Commander interface { // Command returns a command given a name. Returns nil if the command is not found. Command(string) (command func(map[string]interface{}) interface{}) // Commands returns a map of commands. Commands() (commands map[string]func(map[string]interface{}) interface{}) // AddCommand adds a command given a name. AddCommand(name string, command func(map[string]interface{}) interface{}) } // NewCommander returns a new Commander. func NewCommander() Commander { return &commander{ commands: make(map[string]func(map[string]interface{}) interface{}), } } // Command returns the command interface whene passed a valid command name func (c *commander) Command(name string) (command func(map[string]interface{}) interface{}) { command, _ = c.commands[name] return } // Commands returns the entire map of valid commands func (c *commander) Commands() map[string]func(map[string]interface{}) interface{} { return c.commands } // AddCommand adds a new command, when passed a command name and the command interface. func (c *commander) AddCommand(name string, command func(map[string]interface{}) interface{}) { c.commands[name] = command }
package gobot type commander struct { commands map[string]func(map[string]interface{}) interface{} } // Commander is the interface which describes the behaviour for a Driver or Adaptor // which exposes API commands. type Commander interface { // Command returns a command given a name. Returns nil if the command is not found. Command(string) (command func(map[string]interface{}) interface{}) // Commands returns a map of commands. Commands() (commands map[string]func(map[string]interface{}) interface{}) // AddCommand adds a command given a name. AddCommand(name string, command func(map[string]interface{}) interface{}) } // NewCommander returns a new Commander. func NewCommander() Commander { return &commander{ commands: make(map[string]func(map[string]interface{}) interface{}), } } func (c *commander) Command(name string) (command func(map[string]interface{}) interface{}) { command, _ = c.commands[name] return } func (c *commander) Commands() map[string]func(map[string]interface{}) interface{} { return c.commands } func (c *commander) AddCommand(name string, command func(map[string]interface{}) interface{}) { c.commands[name] = command }
Test for Envoy logs format Signed-off-by: Alvaro Saurin <5b2d0c210c4a9fd6aeaf2eaedf8273be993c90c2@datawire.io>
import pytest, re from kat.utils import ShellCommand from abstract_tests import AmbassadorTest, ServiceType, HTTP access_log_entry_regex = re.compile('^MY_REQUEST 200 .*') class EnvoyLogTest(AmbassadorTest): target: ServiceType log_path: str def init(self): self.target = HTTP() self.log_path = '/tmp/ambassador/ambassador.log' self.log_format = 'MY_REQUEST %RESPONSE_CODE% \"%REQ(:AUTHORITY)%\" \"%REQ(USER-AGENT)%\" \"%REQ(X-REQUEST-ID)%\" \"%UPSTREAM_HOST%\"' def config(self): yield self, self.format(""" --- apiVersion: ambassador/v1 kind: Module name: ambassador ambassador_id: {self.ambassador_id} config: envoy_log_path: {self.log_path} envoy_log_format: {self.log_format} """) def check(self): cmd = ShellCommand("kubectl", "exec", self.path.k8s, "cat", self.log_path) if not cmd.check("check envoy access log"): pytest.exit("envoy access log does not exist") for line in cmd.stdout.splitlines(): assert access_log_entry_regex.match(line), f"{line} does not match {access_log_entry_regex}"
import pytest, re from kat.utils import ShellCommand from abstract_tests import AmbassadorTest, ServiceType, HTTP access_log_entry_regex = re.compile('^ACCESS \\[.*?\\] \\\"GET \\/ambassador') class EnvoyLogPathTest(AmbassadorTest): target: ServiceType log_path: str def init(self): self.target = HTTP() self.log_path = '/tmp/ambassador/ambassador.log' def config(self): yield self, self.format(""" --- apiVersion: ambassador/v1 kind: Module name: ambassador ambassador_id: {self.ambassador_id} config: envoy_log_path: {self.log_path} """) def check(self): cmd = ShellCommand("kubectl", "exec", self.path.k8s, "cat", self.log_path) if not cmd.check("check envoy access log"): pytest.exit("envoy access log does not exist") for line in cmd.stdout.splitlines(): assert access_log_entry_regex.match(line)
Refactor test incase results are backwards Looks like results can come in either way in this file. Loosen the ordering constraints. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@331945 91177308-0d34-0410-b5e6-96231b3b80d8
# RUN: %{lit} -j 1 -v %{inputs}/test-data --output %t.results.out > %t.out # RUN: FileCheck < %t.results.out %s # CHECK: { # CHECK: "__version__" # CHECK: "elapsed" # CHECK-NEXT: "tests": [ # CHECK-NEXT: { # CHECK-NEXT: "code": "PASS", # CHECK-NEXT: "elapsed": {{[0-9.]+}}, # CHECK-NEXT: "metrics": { # CHECK-NEXT: "value0": 1, # CHECK-NEXT: "value1": 2.3456 # CHECK-NEXT: } # CHECK: "name": "test-data :: bad&name.ini", # CHECK: "output": "& < > \"" # CHECK: ] # CHECK-NEXT: }
# RUN: %{lit} -j 1 -v %{inputs}/test-data --output %t.results.out > %t.out # RUN: FileCheck < %t.results.out %s # CHECK: { # CHECK: "__version__" # CHECK: "elapsed" # CHECK-NEXT: "tests": [ # CHECK-NEXT: { # CHECK-NEXT: "code": "PASS", # CHECK-NEXT: "elapsed": {{[0-9.]+}}, # CHECK-NEXT: "metrics": { # CHECK-NEXT: "value0": 1, # CHECK-NEXT: "value1": 2.3456 # CHECK-NEXT: } # CHECK-NEXT: "name": "test-data :: bad&name.ini", # CHECK-NEXT: "output": "& < > \"" # CHECK-NEXT: }, # CHECK-NEXT: { # CHECK-NEXT: "code": "PASS", # CHECK-NEXT: "elapsed": {{[0-9.]+}}, # CHECK-NEXT: "metrics": { # CHECK-NEXT: "value0": 1, # CHECK-NEXT: "value1": 2.3456 # CHECK-NEXT: } # CHECK-NEXT: "name": "test-data :: metrics.ini", # CHECK-NEXT: "output": "Test passed." # CHECK-NEXT: } # CHECK-NEXT: ] # CHECK-NEXT: }
Make sure test works with new API
import luigi import sciluigi as sl import os TESTFILE_PATH = '/tmp/test.out' class TestTask(sl.Task): def out_data(self): return sl.TargetInfo(self, TESTFILE_PATH) def run(self): with self.out_data().open('w') as outfile: outfile.write('File written by luigi\n') class TestRunTask(): def setup(self): self.t = sl.new_task(self, TestTask, 'testtask') def teardown(self): self.t = None os.remove(TESTFILE_PATH) def test_run(self): # Run a task with a luigi worker w = luigi.worker.Worker() w.add(self.t) w.run() w.stop() assert os.path.isfile(TESTFILE_PATH)
import luigi import sciluigi as sl import os TESTFILE_PATH = '/tmp/test.out' class TestTask(sl.Task): def out_data(self): return sl.TargetInfo(self, TESTFILE_PATH) def run(self): with self.out_data().open('w') as outfile: outfile.write('File written by luigi\n') class TestRunTask(): def setup(self): self.t = sl.new_task(TestTask) def teardown(self): self.t = None os.remove(TESTFILE_PATH) def test_run(self): # Run a task with a luigi worker w = luigi.worker.Worker() w.add(self.t) w.run() w.stop() assert os.path.isfile(TESTFILE_PATH)
Fix mised autoload dependency for dissect
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2012, Lissachenko Alexander <lisachenko.it@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ use Doctrine\Common\Annotations\AnnotationRegistry; include '../src/Go/Core/AspectKernel.php'; include 'DemoAspectKernel.php'; // Initialize demo aspect container DemoAspectKernel::getInstance()->init(array( // Configuration for autoload namespaces 'autoload' => array( 'Go' => realpath(__DIR__ . '/../src'), 'TokenReflection' => realpath(__DIR__ . '/../vendor/andrewsville/php-token-reflection/'), 'Doctrine\\Common' => realpath(__DIR__ . '/../vendor/doctrine/common/lib/'), 'Dissect' => realpath(__DIR__ . '/../vendor/jakubledl/dissect/src/'), ), // Default application directory 'appDir' => __DIR__ . '/../demos', // Cache directory for Go! generated classes 'cacheDir' => __DIR__ . '/cache', // Include paths for aspect weaving 'includePaths' => array(), 'debug' => true )); AnnotationRegistry::registerFile('./Annotation/Cacheable.php');
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2012, Lissachenko Alexander <lisachenko.it@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ use Doctrine\Common\Annotations\AnnotationRegistry; include '../src/Go/Core/AspectKernel.php'; include 'DemoAspectKernel.php'; // Initialize demo aspect container DemoAspectKernel::getInstance()->init(array( // Configuration for autoload namespaces 'autoload' => array( 'Go' => realpath(__DIR__ . '/../src'), 'TokenReflection' => realpath(__DIR__ . '/../vendor/andrewsville/php-token-reflection/'), 'Doctrine\\Common' => realpath(__DIR__ . '/../vendor/doctrine/common/lib/') ), // Default application directory 'appDir' => __DIR__ . '/../demos', // Cache directory for Go! generated classes 'cacheDir' => __DIR__ . '/cache', // Include paths for aspect weaving 'includePaths' => array(), 'debug' => true )); AnnotationRegistry::registerFile('./Annotation/Cacheable.php');
Tweak thank-you page route logic.
window.addEventListener('DOMContentLoaded', function () { // get the form elements defined in your form HTML above var form = document.getElementById('my-form'); var button = document.getElementById('my-form-button'); var status = document.getElementById('my-form-status'); const page = document.body.classList[0]; // Success and Error functions for after the form is submitted function success() { form.reset(); window.location = `https://getbiblefirst.com/${page}/thanks/`; } function error() { status.innerHTML = 'Oops! There was a problem. Please try again later.'; } // handle the form submission event form.addEventListener('submit', function (ev) { ev.preventDefault(); var data = new FormData(form); ajax(form.method, form.action, data, success, error); }); }); // helper function for sending an AJAX request function ajax(method, url, data, success, error) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.setRequestHeader('Accept', 'application/json'); xhr.onreadystatechange = function () { if (xhr.readyState !== XMLHttpRequest.DONE) return; if (xhr.status === 200) { success(xhr.response, xhr.responseType); } else { error(xhr.status, xhr.response, xhr.responseType); } }; xhr.send(data); }
window.addEventListener("DOMContentLoaded", function() { // get the form elements defined in your form HTML above var form = document.getElementById("my-form"); var button = document.getElementById("my-form-button"); var status = document.getElementById("my-form-status"); const page = (document.getElementsByTagName('h1')[0].innerHTML == 'Contact') ? "contact" : "purchase"; // Success and Error functions for after the form is submitted function success() { form.reset(); window.location = `https://getbiblefirst.com/${page}/thanks/`; } function error() { status.innerHTML = "Oops! There was a problem. Please try again later."; } // handle the form submission event form.addEventListener("submit", function(ev) { ev.preventDefault(); var data = new FormData(form); ajax(form.method, form.action, data, success, error); }); }); // helper function for sending an AJAX request function ajax(method, url, data, success, error) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.setRequestHeader("Accept", "application/json"); xhr.onreadystatechange = function() { if (xhr.readyState !== XMLHttpRequest.DONE) return; if (xhr.status === 200) { success(xhr.response, xhr.responseType); } else { error(xhr.status, xhr.response, xhr.responseType); } }; xhr.send(data); }
Include trailing separator in comparisons
const path = require('path') const Module = require('module') // Clear Node's global search paths. Module.globalPaths.length = 0 // Clear current and parent(init.js)'s search paths. module.paths = [] module.parent.paths = [] // Prevent Node from adding paths outside this app to search paths. const originalNodeModulePaths = Module._nodeModulePaths Module._nodeModulePaths = function (from) { const paths = originalNodeModulePaths(from) // If "from" is outside the app then we do nothing. const rootPath = process.resourcesPath + path.sep const fromPath = path.resolve(from) + path.sep const skipOutsidePaths = fromPath.startsWith(rootPath) if (skipOutsidePaths) { return paths.filter(function (candidate) { return candidate.startsWith(rootPath) }) } return paths } // Patch Module._resolveFilename to always require the Electron API when // require('electron') is done. const electronPath = path.join(__dirname, '..', process.type, 'api', 'exports', 'electron.js') const originalResolveFilename = Module._resolveFilename Module._resolveFilename = function (request, parent, isMain) { if (request === 'electron') { return electronPath } else { return originalResolveFilename(request, parent, isMain) } }
const path = require('path') const Module = require('module') // Clear Node's global search paths. Module.globalPaths.length = 0 // Clear current and parent(init.js)'s search paths. module.paths = [] module.parent.paths = [] // Prevent Node from adding paths outside this app to search paths. const originalNodeModulePaths = Module._nodeModulePaths Module._nodeModulePaths = function (from) { const paths = originalNodeModulePaths(from) const rootPath = process.resourcesPath // If "from" is outside the app then we do nothing. const skipOutsidePaths = path.resolve(from).startsWith(rootPath) if (skipOutsidePaths) { return paths.filter(function (candidate) { return candidate.startsWith(rootPath) }) } return paths } // Patch Module._resolveFilename to always require the Electron API when // require('electron') is done. const electronPath = path.join(__dirname, '..', process.type, 'api', 'exports', 'electron.js') const originalResolveFilename = Module._resolveFilename Module._resolveFilename = function (request, parent, isMain) { if (request === 'electron') { return electronPath } else { return originalResolveFilename(request, parent, isMain) } }
Fix imports for Django 1.6 and above
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # 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. try: from django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Add from headers in mail
<?php namespace Criterion\Helper; class Notifications { public static function failedEmail($test, $project) { $config = json_decode(file_get_contents(CONFIG_FILE), true); if (isset($project['email']) && $project['email'] && isset($config['email'])) { $subject = '['.$project['repo'].'] Tests Failed (' . $test . ')'; $message = "This is a short email to let you know that the following project's tests are failing: \n\n"; $message .= $config['url'] . '/test/' . $test . "\n\n"; $message .= 'Thanks'; return self::email($project['email'], $config['email'], $subject, $message); } return false; } private static function email($to, $from, $subject, $message) { $headers = "From:" . $from; return mail($to, $subject, $message, $headers); } }
<?php namespace Criterion\Helper; class Notifications { public static function failedEmail($test, $project) { $config = json_decode(file_get_contents(CONFIG_FILE), true); if (isset($project['email']) && $project['email'] && isset($config['email'])) { $subject = '['.$project['repo'].'] Tests Failed (' . $test . ')'; $message = "This is a short email to let you know that the following project's tests are failing: \n\n"; $message .= $config['url'] . '/test/' . $test . "\n\n"; $message .= 'Thanks'; return self::email($project['email'], $config['email'], $subject, $message); } return false; } private static function email($to, $from, $subject, $message) { return mail($to, $subject, $message); } }
Make DEBUG default to False in production settings It is dangerous to keep the template file for production settings without explicitly specifying that DEBUG needs to be False.
""" A template for settings which should be used in production. In order for the settings to be truly useful, they need to be filled out with corresponding values. Use the template to create a ``production.py`` file and then create a symlink to it from a ``local_settings.py`` file, i.e.:: settings/local_settings.py -> settings/production.py """ #: DEBUG should never be set to True in production DEBUG = False #: Make sure to provide a real celery broker # BROKER_URL = 'amqp://guest:guest@localhost//' #: Make sure that GCM notifications are enabled TCA_ENABLE_GCM_NOTIFICATIONS = True #: In production HTTPS should be used # TCA_SCHEME = 'https' #: Domain name # TCA_DOMAIN_NAME = '' #: Make sure to provide an API key for GCM # TCA_GCM_API_KEY = "" #: Make sure to provide the credentials to the SMTP server (if any) # EMAIL_HOST_USER = '' # EMAIL_HOST_PASSWORD = ''
""" A template for settings which should be used in production. In order for the settings to be truly useful, they need to be filled out with corresponding values. Use the template to create a ``production.py`` file and then create a symlink to it from a ``local_settings.py`` file, i.e.:: settings/local_settings.py -> settings/production.py """ #: Make sure to provide a real celery broker # BROKER_URL = 'amqp://guest:guest@localhost//' #: Make sure that GCM notifications are enabled TCA_ENABLE_GCM_NOTIFICATIONS = True #: In production HTTPS should be used # TCA_SCHEME = 'https' #: Domain name # TCA_DOMAIN_NAME = '' #: Make sure to provide an API key for GCM # TCA_GCM_API_KEY = "" #: Make sure to provide the credentials to the SMTP server (if any) # EMAIL_HOST_USER = '' # EMAIL_HOST_PASSWORD = ''
Use oslotest instead of common test module Module openstack.common.test is obsolete, so we should use oslotest library instead of it. Modified tests and common database code, new requirement added. Change-Id: I853e548f11a4c3785eaf75124510a6d789536634
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base as test_base from openstack.common import context class ContextTest(test_base.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.common import context from openstack.common import test class ContextTest(test.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
Test extra args are used
import os from arteria.web.app import AppService from unittest import TestCase class AppServiceTest(TestCase): this_file_path = os.path.dirname(os.path.realpath(__file__)) def test_can_load_configuration(self): app_svc = AppService.create( product_name="arteria-test", config_root="{}/../templates/".format(self.this_file_path)) self.assertIsNotNone(app_svc.config_svc) app_config = app_svc.config_svc.get_app_config() logger_config = app_svc.config_svc.get_logger_config() self.assertEquals(app_config["port"], 10000) self.assertEquals(logger_config["version"], 1) def test_can_use_args(self): app_svc = AppService.create( product_name="arteria-test", config_root="{}/../templates/".format(self.this_file_path), args=['--port', '1234']) self.assertEquals(app_svc._port, 1234)
import os from arteria.web.app import AppService from unittest import TestCase class AppServiceTest(TestCase): this_file_path = os.path.dirname(os.path.realpath(__file__)) def test_can_load_configuration(self): app_svc = AppService.create( product_name="arteria-test", config_root="{}/../templates/".format(self.this_file_path)) self.assertIsNotNone(app_svc.config_svc) app_config = app_svc.config_svc.get_app_config() logger_config = app_svc.config_svc.get_logger_config() self.assertEquals(app_config["port"], 10000) self.assertEquals(logger_config["version"], 1)
Allow the photo to be blank.
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p', blank=True, null=True) homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p') homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
Change to panel based look
/* * * About * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { FormattedMessage } from 'react-intl'; import { createStructuredSelector } from 'reselect'; import makeSelectAbout from './selectors'; import messages from './messages'; export class About extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className="container"> <div className="panel panel-default"> <div className="panel-body"> <FormattedMessage {...messages.header} /> </div> </div> </div> ); } } About.propTypes = { dispatch: PropTypes.func.isRequired, }; const mapStateToProps = createStructuredSelector({ About: makeSelectAbout(), }); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(About);
/* * * About * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { FormattedMessage } from 'react-intl'; import { createStructuredSelector } from 'reselect'; import makeSelectAbout from './selectors'; import messages from './messages'; export class About extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <FormattedMessage {...messages.header} /> </div> ); } } About.propTypes = { dispatch: PropTypes.func.isRequired, }; const mapStateToProps = createStructuredSelector({ About: makeSelectAbout(), }); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(About);
Fix path to python interpreter to make it work with chroot builds
var nijs = require('nijs'); exports.pkg = function(args) { return args.stdenv().mkDerivation({ name : "node-0.10.26", src : args.fetchurl()({ url : new nijs.NixURL("http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz"), sha256 : "1ahx9cf2irp8injh826sk417wd528awi4l1mh7vxg7k8yak4wppg" }), preConfigure : 'sed -i -e "s|#!/usr/bin/env python|#! $(type -p python)|" configure', configureFlags : [ "--shared-openssl", "--shared-zlib" ], buildInputs : [ args.python(), args.openssl(), args.zlib(), args.utillinux() ], setupHook : new nijs.NixFile({ value : "setup-hook.sh", module : module }), meta : { homepage : new nijs.NixURL("http://nodejs.org"), description : "Platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications" } }); };
var nijs = require('nijs'); exports.pkg = function(args) { return args.stdenv().mkDerivation({ name : "node-0.10.26", src : args.fetchurl()({ url : new nijs.NixURL("http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz"), sha256 : "1ahx9cf2irp8injh826sk417wd528awi4l1mh7vxg7k8yak4wppg" }), configureFlags : [ "--shared-openssl", "--shared-zlib" ], buildInputs : [ args.python(), args.openssl(), args.zlib(), args.utillinux() ], setupHook : new nijs.NixFile({ value : "setup-hook.sh", module : module }), meta : { homepage : new nijs.NixURL("http://nodejs.org"), description : "Platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications" } }); };
Change version to "auto" mode
package com.ferreusveritas.dynamictrees; public class ModConstants { public static final String MODID = "dynamictrees"; public static final String NAME = "Dynamic Trees"; public static final String VERSIONDEV = "1.12.2-9.9.9z"; public static final String VERSIONAUTO = "@VERSION@"; public static final String VERSION = VERSIONAUTO; public static final String AFTER = "after:"; public static final String BEFORE = "before:"; public static final String NEXT = ";"; //Other mods can use this string to depend on the latest version of Dynamic Trees public static final String DYNAMICTREES_LATEST = MODID + "@[" + VERSION + ",)"; //Other Mods public static final String DYNAMICTREESBOP = "dynamictreesbop"; public static final String DYNAMICTREESTC = "dynamictreestc"; //Other Mods public static final String DYNAMICTREESBOP_VER = "@[1.3.1b,)"; public static final String DYNAMICTREESTC_VER = "@[1.0,)"; public static final String DEPENDENCIES = BEFORE + DYNAMICTREESBOP + DYNAMICTREESBOP_VER + NEXT + BEFORE + DYNAMICTREESTC + DYNAMICTREESTC_VER ; }
package com.ferreusveritas.dynamictrees; public class ModConstants { public static final String MODID = "dynamictrees"; public static final String NAME = "Dynamic Trees"; public static final String VERSIONDEV = "1.12.2-9.9.9z"; public static final String VERSIONAUTO = "@VERSION@"; public static final String VERSION = VERSIONDEV; public static final String AFTER = "after:"; public static final String BEFORE = "before:"; public static final String NEXT = ";"; //Other mods can use this string to depend on the latest version of Dynamic Trees public static final String DYNAMICTREES_LATEST = MODID + "@[" + VERSION + ",)"; //Other Mods public static final String DYNAMICTREESBOP = "dynamictreesbop"; public static final String DYNAMICTREESTC = "dynamictreestc"; //Other Mods public static final String DYNAMICTREESBOP_VER = "@[1.3.1b,)"; public static final String DYNAMICTREESTC_VER = "@[1.0,)"; public static final String DEPENDENCIES = BEFORE + DYNAMICTREESBOP + DYNAMICTREESBOP_VER + NEXT + BEFORE + DYNAMICTREESTC + DYNAMICTREESTC_VER ; }
Fix controller and action names
function load(options, fn) { $(function(){ var body = $("body"); var currentController = body.data("controller"); var currentAction = body.data("action"); if (typeof options === "string") { var splitOption = options.split("#"); if (splitOption[0] != currentController || splitOption[1] != currentAction) { return; } fn(controller, action); } else if (typeof options.controllers !== "undefined") { for (var controller in options.controllers) { var actions = options.controllers[controller]; if (controller == currentController && actions.length == 0) { fn(controller, action); } else { for (var i = 0, length = actions.length; i < length; ++i) { if (actions[i] == currentAction) { fn(controller, action); break; } } } } } else { if (options.controller != currentController) { return; } if (typeof options.action === "undefined" || options.action == currentAction) { fn(currentController, currentAction); } } }); }
function load(options, fn) { $(function(){ var body = $("body"); var currentController = body.data("controller"); var currentAction = body.data("action"); if (typeof options === "string") { var splitOption = options.split("#"); if (splitOption[0] != currentController || splitOption[1] != currentAction) { return; } fn(controller, action); } else if (typeof options.controllers !== "undefined") { for (var controller in options.controllers) { var actions = options.controllers[controller]; if (controller == currentController && actions.length == 0) { fn(controller, action); } else { for (var i = 0, length = actions.length; i < length; ++i) { if (actions[i] == currentAction) { fn(controller, action); break; } } } } } else { if (options.controller != currentController) { return; } if (typeof options.action === "undefined" || options.action == currentAction) { fn(controller, action); } } }); }
Add 'api' folder to exports
var fs = require('fs'), path = require('path'), extend = require('extend'); function load() { // Recursively load one or more directories passed as arguments. var dir, result = {}; function processFilename(fn) { var fp = path.join(dir, fn), // If the given filename is a directory, recursively load it. extra = fs.statSync(fp).isDirectory() ? load(fp) : require(fp); // The JSON data is independent of the actual file // hierarchy, so it is essential to extend "deeply". result = extend(true, result, extra); } for (dir of arguments) { dir = path.resolve(__dirname, dir); fs.readdirSync(dir).forEach(processFilename); } return result; } module.exports = load( 'api', 'css', // 'http', // 'javascript', 'webextensions' );
var fs = require('fs'), path = require('path'), extend = require('extend'); function load() { // Recursively load one or more directories passed as arguments. var dir, result = {}; function processFilename(fn) { var fp = path.join(dir, fn), // If the given filename is a directory, recursively load it. extra = fs.statSync(fp).isDirectory() ? load(fp) : require(fp); // The JSON data is independent of the actual file // hierarchy, so it is essential to extend "deeply". result = extend(true, result, extra); } for (dir of arguments) { dir = path.resolve(__dirname, dir); fs.readdirSync(dir).forEach(processFilename); } return result; } module.exports = load( // 'api', 'css', // 'http', // 'javascript', 'webextensions' );
Change to a temporary directory before executing pngcrush Pngcrush writes temporary files in the current working directory. Sometimes the user running PHP does not have write permissions in the current working directory, so change to a temporary directory first, then change back afterwards.
<?php namespace PHPImageOptim\Tools\Png; use Exception; use PHPImageOptim\Tools\Common; use PHPImageOptim\Tools\ToolsInterface; class PngCrush extends Common implements ToolsInterface { public function optimise() { // Pngcrush attempts to write a temporary file to the current directory; // make sure we're somewhere we can write a file $prevDir = getcwd(); chdir(sys_get_temp_dir()); exec($this->binaryPath . ' -rem gAMA -rem cHRM -rem iCCP -rem sRGB -brute -q -l 9 -reduce -ow ' . escapeshellarg($this->imagePath), $aOutput, $iResult); // Switch back to previous directory chdir($prevDir); if ($iResult != 0) { throw new Exception('PNGCrush was unable to optimise image, result:' . $iResult . ' File: ' . $this->imagePath); } return $this; } public function checkVersion() { exec($this->binaryPath . ' --version', $aOutput, $iResult); } }
<?php namespace PHPImageOptim\Tools\Png; use Exception; use PHPImageOptim\Tools\Common; use PHPImageOptim\Tools\ToolsInterface; class PngCrush extends Common implements ToolsInterface { public function optimise() { exec($this->binaryPath . ' -rem gAMA -rem cHRM -rem iCCP -rem sRGB -brute -q -l 9 -reduce -ow ' . escapeshellarg($this->imagePath), $aOutput, $iResult); if ($iResult != 0) { throw new Exception('PNGCrush was unable to optimise image, result:' . $iResult . ' File: ' . $this->imagePath); } return $this; } public function checkVersion() { exec($this->binaryPath . ' --version', $aOutput, $iResult); } }
Use input event not keyup The `oninput` event is a more performant way to detect changes to a textbox’s contents (compared to `onkeydown`, `onpaste`, etc). It’s not supported in older browsers, but since this is a likely to be used by platform admin users only that’s OK.
(function(Modules) { "use strict"; let isSixDigitHex = value => value.match(/^#[0-9A-F]{6}$/i); let colourOrWhite = value => isSixDigitHex(value) ? value : '#FFFFFF'; Modules.ColourPreview = function() { this.start = component => { this.$input = $('input', component); $(component).append( this.$preview = $('<span class="textbox-colour-preview"></span>') ); this.$input .on('input', this.update) .trigger('change'); }; this.update = () => this.$preview.css( 'background', colourOrWhite(this.$input.val()) ); }; })(window.GOVUK.Modules);
(function(Modules) { "use strict"; let isSixDigitHex = value => value.match(/^#[0-9A-F]{6}$/i); let colourOrWhite = value => isSixDigitHex(value) ? value : '#FFFFFF'; Modules.ColourPreview = function() { this.start = component => { this.$input = $('input', component); $(component).append( this.$preview = $('<span class="textbox-colour-preview"></span>') ); this.$input .on('change keyup', this.update) .trigger('change'); }; this.update = () => this.$preview.css( 'background', colourOrWhite(this.$input.val()) ); }; })(window.GOVUK.Modules);
Add {{application}}{{platform}} to log filename
/* * Copyright (C) 2016 VSCT * * 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.vsct.dt.strowgr.admin.template.template; import java.util.StringJoiner; public class DefaultTemplates { public static final String SYSLOG_DEFAULT_TEMPLATE = new StringJoiner("\n") .add("source s_{{application}}_{{platform}} { udp(ip(127.0.0.1) port({{syslog_port}})); };") .add("destination d_{{application}}_{{platform}} { file(\"/HOME/hapadm/{{application}}/logs/{{application}}{{platform}}/haproxy{{application}}{{platform}}.log\", perm(0664)); };") .add("log { source(s_{{application}}_{{platform}}); filter(f_local0); destination(d_{{application}}_{{platform}}); };") .add("\n") .toString(); }
/* * Copyright (C) 2016 VSCT * * 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.vsct.dt.strowgr.admin.template.template; import java.util.StringJoiner; public class DefaultTemplates { public static final String SYSLOG_DEFAULT_TEMPLATE = new StringJoiner("\n") .add("source s_{{application}}_{{platform}} { udp(ip(127.0.0.1) port({{syslog_port}})); };") .add("destination d_{{application}}_{{platform}} { file(\"/HOME/hapadm/{{application}}/logs/{{application}}{{platform}}/haproxy.log\", perm(0664)); };") .add("log { source(s_{{application}}_{{platform}}); filter(f_local0); destination(d_{{application}}_{{platform}}); };") .add("\n") .toString(); }
Improve pagination in block store
function filterBlocks() { jQuery('#block-store #block-types').slick('slickFilter', function() { var name = $(this).data('block-name'); var filter = $('#block-store #block-store-filter').val(); return name.toLowerCase().indexOf(filter.toLowerCase()) > -1; }); } function cloneDraggableBlock(el, blockIcon) { el.addClass('ui-draggable-dragging'); return blockIcon; } function startDragBlock() { $('#box-organizer').addClass('shadow'); } function stopDragBlock() { $('#box-organizer').removeClass('shadow'); $('.ui-draggable-dragging').removeClass('ui-draggable-dragging'); } function initBlockStore() { var store = jQuery('#block-store #block-types').slick({ infinite: false, dots: true, draggable: false, respondTo: 'slider', slidesToShow: 7, slidesToScroll: 6, responsive: [ { breakpoint: 2048, settings: { slidesToShow: 10, slidesToScroll: 9, } }, { breakpoint: 1024, settings: { slidesToShow: 8, slidesToScroll: 7, } } ] }); jQuery('#block-store').show(); jQuery('#block-store #block-store-filter').keyup(filterBlocks); }
function filterBlocks() { jQuery('#block-store #block-types').slick('slickFilter', function() { var name = $(this).data('block-name'); var filter = $('#block-store #block-store-filter').val(); return name.toLowerCase().indexOf(filter.toLowerCase()) > -1; }); } function cloneDraggableBlock(el, blockIcon) { el.addClass('ui-draggable-dragging'); return blockIcon; } function startDragBlock() { $('#box-organizer').addClass('shadow'); } function stopDragBlock() { $('#box-organizer').removeClass('shadow'); $('.ui-draggable-dragging').removeClass('ui-draggable-dragging'); } function initBlockStore() { var store = jQuery('#block-store #block-types').slick({ infinite: true, dots: true, draggable: false, respondTo: 'slider', slidesToShow: 7, slidesToScroll: 4, responsive: [ { breakpoint: 2048, settings: { slidesToShow: 10, slidesToScroll: 4, } }, { breakpoint: 1024, settings: { slidesToShow: 8, slidesToScroll: 4, } } ] }); jQuery('#block-store').show(); jQuery('#block-store #block-store-filter').keyup(filterBlocks); }
Use userCache as filestore's storage Co-authored-by: Delisa <af4f0ea8b5fc1012c4f5f436ed6f406c522717bf@users.noreply.github.com>
const electron = require('electron') const Client = require('@bugsnag/core/client') const makeDelivery = require('@bugsnag/delivery-electron') const { FileStore } = require('@bugsnag/electron-filestore') const { schema } = require('../config/main') // noop native client for now const NativeClient = { setApp () {}, setDevice () {} } module.exports = (opts) => { const filestore = new FileStore( opts.apiKey, electron.app.getPath('userCache'), electron.app.getPath('crashDumps') ) const internalPlugins = [ // main internal plugins go here require('@bugsnag/plugin-electron-state-sync'), require('@bugsnag/plugin-electron-ipc'), require('@bugsnag/plugin-electron-app')(NativeClient, process, electron.app, electron.BrowserWindow), require('@bugsnag/plugin-electron-app-breadcrumbs')(electron.app, electron.BrowserWindow), require('@bugsnag/plugin-electron-device')(electron.app, electron.screen, process, filestore, NativeClient, electron.powerMonitor) ] const bugsnag = new Client(opts, schema, internalPlugins, require('../id')) bugsnag._setDelivery(makeDelivery(filestore, electron.net)) // noop session delegate for now bugsnag._sessionDelegate = { startSession: () => bugsnag, resumeSession: () => {}, pauseSession: () => {} } bugsnag._logger.debug('Loaded! In main process.') return bugsnag }
const electron = require('electron') const Client = require('@bugsnag/core/client') const makeDelivery = require('@bugsnag/delivery-electron') const { FileStore } = require('@bugsnag/electron-filestore') const { schema } = require('../config/main') // noop native client for now const NativeClient = { setApp () {}, setDevice () {} } module.exports = (opts) => { const filestore = new FileStore( opts.apiKey, electron.app.getPath('cache'), electron.app.getPath('crashDumps') ) const internalPlugins = [ // main internal plugins go here require('@bugsnag/plugin-electron-state-sync'), require('@bugsnag/plugin-electron-ipc'), require('@bugsnag/plugin-electron-app')(NativeClient, process, electron.app, electron.BrowserWindow), require('@bugsnag/plugin-electron-app-breadcrumbs')(electron.app, electron.BrowserWindow), require('@bugsnag/plugin-electron-device')(electron.app, electron.screen, process, filestore, NativeClient, electron.powerMonitor) ] const bugsnag = new Client(opts, schema, internalPlugins, require('../id')) bugsnag._setDelivery(makeDelivery(filestore, electron.net)) // noop session delegate for now bugsnag._sessionDelegate = { startSession: () => bugsnag, resumeSession: () => {}, pauseSession: () => {} } bugsnag._logger.debug('Loaded! In main process.') return bugsnag }
Switch to map as request body
package com.github.vlsidlyarevich.unity.controller; import com.github.vlsidlyarevich.unity.service.WorkerProfileSearchService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Map; /** * Created by vlad on 30.09.16. */ @RestController @RequestMapping("/api/workers/search") public class WorkerProfileSearchController { @Autowired private WorkerProfileSearchService service; @RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> getWorkersByFilters(@RequestBody Map<String, String> filters) { return new ResponseEntity<>(service.findByFilters(filters), HttpStatus.OK); } }
package com.github.vlsidlyarevich.unity.controller; import com.github.vlsidlyarevich.unity.service.WorkerProfileSearchService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Created by vlad on 30.09.16. */ @RestController @RequestMapping("/api/workers/search") public class WorkerProfileSearchController { @Autowired private WorkerProfileSearchService service; @RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> getWorkersByFilters(MultiValueMap<String, String> filters) { return new ResponseEntity<>(service.findByFilters(filters), HttpStatus.OK); } }
Check input dtype before creating pcm device.
import numpy as np from _alsa import card_name, card_indexes, asoundlib_version from _alsa import Device, AlsaException def play(input, samplerate = 48000): if input.ndim == 1: n = input.size nc = 1 elif input.ndim == 2: n, nc = input.shape else: raise ValueError("Only ndim 1 or 2 supported") if not input.dtype in (np.float32, np.float64): raise ValueError("input should be array of float32 or float64 !") try: dev = Device(samplerate = samplerate, channels = nc) dev.play_short((16384 * input).astype(np.int16)) except AlsaException, e: raise IOError(str(e)) if __name__ == '__main__': print "Asoundlib version is", asoundlib_version() for i in card_indexes(): print card_name(i) dev = Device() print "Device name:", dev.name a = 0.2 * np.random.randn(4e4) play(a, 16000) play(a, 8000) play(a, 22050)
import numpy as np from _alsa import card_name, card_indexes, asoundlib_version from _alsa import Device, AlsaException def play(input, samplerate = 48000): if input.ndim == 1: n = input.size nc = 1 elif input.ndim == 2: n, nc = input.shape else: raise ValueError("Only ndim 1 or 2 supported") try: dev = Device(samplerate = samplerate, channels = nc) assert nc == dev.channels assert input.dtype == np.float32 or input.dtype == np.float64 dev.play_short((16384 * input).astype(np.int16)) except AlsaException, e: raise IOError(str(e)) if __name__ == '__main__': print "Asoundlib version is", asoundlib_version() for i in card_indexes(): print card_name(i) dev = Device() print "Device name:", dev.name a = 0.2 * np.random.randn(4e4) play(a, 16000) play(a, 8000) play(a, 22050)
Update field name in the JSON. see https://github.com/takezoe/gitbucket/pull/884
package gitbucket import ( "fmt" "net/http" ) type RepositoriesService struct { client *Client } // Repository represents a API user. type Repository struct { Name *string `json:"name"` FullName *string `json:"full_name"` Description *string `json:"description"` Watchers *int `json:"watchers"` Forks *int `json:"forks"` Private *bool `json:"private"` DefaultBranch *string `json:"default_branch"` Owner *User `json:"owner"` ForksCount *int `json:"forks_count"` WatchersCount *int `json:"watchers_count"` URL *string `json:"url"` HTTPURL *string `json:"http_url"` CloneURL *string `json:"clone_url"` HTMLURL *string `json:"html_url"` } func (s *RepositoriesService) Get(owner, repo string) (*Repository, *http.Response, error) { u := fmt.Sprintf("/repos/%v/%v", owner, repo) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } r := new(Repository) resp, err := s.client.Do(req, r) if err != nil { return nil, resp, err } return r, resp, err }
package gitbucket import ( "fmt" "net/http" ) type RepositoriesService struct { client *Client } // Repository represents a API user. type Repository struct { Name *string `json:"name"` FullName *string `json:"full_name"` Description *string `json:"description"` Watchers *int `json:"watchers"` Forks *int `json:"forks"` Private *bool `json:"private"` DefaultBranch *string `json:"default_branch"` Owner *User `json:"owner"` ForksCount *int `json:"forks_count"` WatchersCount *int `json:"watchers_coun"` URL *string `json:"url"` HTTPURL *string `json:"http_url"` CloneURL *string `json:"clone_url"` HTMLURL *string `json:"html_url"` } func (s *RepositoriesService) Get(owner, repo string) (*Repository, *http.Response, error) { u := fmt.Sprintf("/repos/%v/%v", owner, repo) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } r := new(Repository) resp, err := s.client.Do(req, r) if err != nil { return nil, resp, err } return r, resp, err }
Set the charset to UTF-8
/* Restful api for communicating with mobile app. */ package api import ( "encoding/json" "github.com/gorilla/mux" "net/http" ) func (webapp *WebApp) BindRoute() { // 按名字bind/按照资源划分... 这个以后改 webapp.Router.HandleFunc("/users/{id}", getUserHandler).Methods("GET") webapp.Router.HandleFunc("/users/{id}", postUserHandler).Methods("POST") } func getUserHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") userid := mux.Vars(r)["id"] // test data user := map[string]string{ "id": userid, "name": "名字", "department": "院系", "type": "undergraduate", // master, phd, teacher // Only in full type. "class": "班级", // 可能为null "gender": "male", // female, unknown "email": "email", // 可能为null "phone": "phone number"} j, _ := json.Marshal(user) w.Write(j) } func postUserHandler(w http.ResponseWriter, r *http.Request) { }
/* Restful api for communicating with mobile app. */ package api import ( "encoding/json" "github.com/gorilla/mux" "net/http" ) func (webapp *WebApp) BindRoute() { // 按名字bind/按照资源划分... 这个以后改 webapp.Router.HandleFunc("/users/{id}", getUserHandler).Methods("GET") webapp.Router.HandleFunc("/users/{id}", postUserHandler).Methods("POST") } func getUserHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") userid := mux.Vars(r)["id"] // test data user := map[string]string{ "id": userid, "name": "名字", "department": "院系", "type": "undergraduate", // master, phd, teacher // Only in full type. "class": "班级", // 可能为null "gender": "male", // female, unknown "email": "email", // 可能为null "phone": "phone number"} j, _ := json.Marshal(user) w.Write(j) } func postUserHandler(w http.ResponseWriter, r *http.Request) { }
Fix tabulate adapter test with numparse on.
# -*- coding: utf-8 -*- """Test the tabulate output adapter.""" from __future__ import unicode_literals from textwrap import dedent from cli_helpers.tabular_output import tabulate_adapter def test_tabulate_wrapper(): """Test the *output_formatter.tabulate_wrapper()* function.""" data = [['abc', 1], ['d', 456]] headers = ['letters', 'number'] output = tabulate_adapter.adapter(data, headers, table_format='psql') assert output == dedent('''\ +-----------+----------+ | letters | number | |-----------+----------| | abc | 1 | | d | 456 | +-----------+----------+''')
# -*- coding: utf-8 -*- """Test the tabulate output adapter.""" from __future__ import unicode_literals from textwrap import dedent from cli_helpers.tabular_output import tabulate_adapter def test_tabulate_wrapper(): """Test the *output_formatter.tabulate_wrapper()* function.""" data = [['abc', 1], ['d', 456]] headers = ['letters', 'number'] output = tabulate_adapter.adapter(data, headers, table_format='psql') assert output == dedent('''\ +-----------+----------+ | letters | number | |-----------+----------| | abc | 1 | | d | 456 | +-----------+----------+''')
Add timestamp to article meta
@extends('layouts.frontend') @section('content') @foreach ($articles as $article) <div class="article" id="article-{{ $article->id }}"> <h1 class="article-title"><a href="#">{{ $article->title }}</a></h1> @if ($article->featured_image) <div class="article-featured-image"> <a href="#"><img src="{{ $article->featuredImagePath() }}" alt="{{ $article->title }}"></a> </div> @endif <ul class="list-inline article-meta text-muted"> <li><i class="fa fa-clock-o"></i> {{ $article->created_at->diffForHumans() }}</li> <li><i class="fa fa-user"></i> <a href="#">{{ $article->author->name }}</a></li> <li><i class="fa fa-th-list"></i> <a href="#">{{ $article->category->name }}</a></li> @if ($article->tags->count()) <li> <i class="fa fa-tag"></i> @foreach ($article->tags as $tag) <a href="#" class="label label-default">{{ $tag->name }}</a> @endforeach </li> @endif </ul> <p> {!! $article->excerptFormatted(600) !!} </p> <a href="#" class="btn btn-default btn-sm">Continue reading &rarr;</a> </div> @endforeach @stop
@extends('layouts.frontend') @section('content') @foreach ($articles as $article) <div class="article" id="article-{{ $article->id }}"> <h1 class="article-title"><a href="#">{{ $article->title }}</a></h1> @if ($article->featured_image) <div class="article-featured-image"> <a href="#"><img src="{{ $article->featuredImagePath() }}" alt="{{ $article->title }}"></a> </div> @endif <ul class="list-inline article-meta text-muted"> <li><i class="fa fa-user"></i> <a href="#">{{ $article->author->name }}</a></li> <li><i class="fa fa-th-list"></i> <a href="#">{{ $article->category->name }}</a></li> @if ($article->tags->count()) <li> <i class="fa fa-tag"></i> @foreach ($article->tags as $tag) <a href="#" class="label label-default">{{ $tag->name }}</a> @endforeach </li> @endif </ul> <p> {!! $article->excerptFormatted(600) !!} </p> <a href="#" class="btn btn-default btn-sm">Continue reading &rarr;</a> </div> @endforeach @stop
Fix typo in persistent connect test
<?php $connectionOpts = ['host' => '127.0.0.1', 'user' => 'ndo', 'password' => 'ndo', 'dbname' => 'ndo']; $poolOpts = ['persistent' => true, 'pool_size' => 1]; function get_pg_pid($pool) { $query = new Enigma\Query('select pg_backend_pid() as pid'); $resultset = \HH\Asio\join($pool->query($query)); $results = $resultset->fetchArrays(); return reset($results)['pid']; } $pool1 = Enigma\create_pool($connectionOpts, $poolOpts); $pid1 = get_pg_pid($pool1); $pool2 = Enigma\create_pool($connectionOpts, $poolOpts); $pid2 = get_pg_pid($pool2); $poolNonpersistent = Enigma\create_pool($connectionOpts); $pidNonpersistent = get_pg_pid($poolNonpersistent); echo ($pid1 === $pid2 && $pidNonpersistent !== $pid1) ? 'OK' : 'FAIL';
<?php $connectionOpts = ['host' => '127.0.0.1', 'user' => 'ndo', 'password' => 'ndo', 'dbname' => 'ndo']; $poolOpts = ['persistent' => true, 'poolSize' => 1]; function get_pg_pid($pool) { $query = new Enigma\Query('select pg_backend_pid() as pid'); $resultset = \HH\Asio\join($pool->query($query)); $results = $resultset->fetchArrays(); return reset($results)['pid']; } $pool1 = Enigma\create_pool($connectionOpts, $poolOpts); $pid1 = get_pg_pid($pool1); $pool2 = Enigma\create_pool($connectionOpts, $poolOpts); $pid2 = get_pg_pid($pool2); $poolNonpersistent = Enigma\create_pool($connectionOpts); $pidNonpersistent = get_pg_pid($poolNonpersistent); echo ($pid1 === $pid2 && $pidNonpersistent !== $pid1) ? 'OK' : 'FAIL';
Fix 'onRevisit' callback calls wrongly issue. - LEARNER-3953
package org.edx.mobile.base; import android.app.Activity; import android.os.Bundle; import org.edx.mobile.event.NewRelicEvent; import de.greenrobot.event.EventBus; import roboguice.fragment.RoboFragment; public class BaseFragment extends RoboFragment { private boolean isFirstVisit = true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); } @Override public void onResume() { super.onResume(); if (isFirstVisit) { isFirstVisit = false; } else { onRevisit(); } } /** * Called when a Fragment is re-displayed to the user (the user has navigated back to it). * Defined to mock the behavior of {@link Activity#onRestart() Activity.onRestart} function. */ protected void onRevisit() { } }
package org.edx.mobile.base; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.edx.mobile.event.NewRelicEvent; import de.greenrobot.event.EventBus; import roboguice.fragment.RoboFragment; public class BaseFragment extends RoboFragment { private boolean isFirstVisit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { isFirstVisit = true; return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onResume() { super.onResume(); if (isFirstVisit) { isFirstVisit = false; } else { onRevisit(); } } /** * Called when a Fragment is re-displayed to the user (the user has navigated back to it). * Defined to mock the behavior of {@link Activity#onRestart() Activity.onRestart} function. */ protected void onRevisit() { } }
Fix skip logic in SecureTransport tests
# -*- 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, inject_into_urllib3, extract_from_urllib3 ) except ImportError as e: pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e) from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def setup_module(): inject_into_urllib3() def teardown_module(): extract_from_urllib3() 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"")
Add maintainer and download URL
from setuptools import setup, find_packages def get_long_description(): with open('./README.rst', 'r') as readme: return readme.read() setup( name='django-email-tracker', version='0.2', description='Email Tracker for Django', author='Venelina Yanakieva', author_email='vili@magicsolutions.bg', maintainer='Venelin Stoykov', maintainer_email='venelin@magicsolutions.bg', url='https://github.com/MagicSolutions/django-email-tracker', download_url='https://github.com/MagicSolutions/django-email-tracker/releases', long_description=get_long_description(), packages=find_packages(), zip_safe=False, install_requires=['django>=1.4'], include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
from setuptools import setup, find_packages def get_long_description(): with open('./README.rst', 'r') as readme: return readme.read() setup( name='django-email-tracker', version='0.2', description='Email Tracker for Django', author='Venelina Yanakieva', author_email='vili@magicsolutions.bg', url='https://github.com/MagicSolutions/django-email-tracker', long_description=get_long_description(), packages=find_packages(), zip_safe=False, install_requires=['django>=1.4'], include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
[HtmlSanitizer] Fix default config service ID
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Loader\Configurator; use Symfony\Component\HtmlSanitizer\HtmlSanitizer; use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig; use Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface; return static function (ContainerConfigurator $container) { $container->services() ->set('html_sanitizer.config.default', HtmlSanitizerConfig::class) ->call('allowSafeElements') ->set('html_sanitizer.sanitizer.default', HtmlSanitizer::class) ->args([service('html_sanitizer.config.default')]) ->tag('html_sanitizer', ['name' => 'default']) ->alias('html_sanitizer', 'html_sanitizer.sanitizer.default') ->alias(HtmlSanitizerInterface::class, 'html_sanitizer') ; };
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Loader\Configurator; use Symfony\Component\HtmlSanitizer\HtmlSanitizer; use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig; use Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface; return static function (ContainerConfigurator $container) { $container->services() ->set('html_sanitizer.config.default', HtmlSanitizerConfig::class) ->call('allowSafeElements') ->set('html_sanitizer.sanitizer.default', HtmlSanitizer::class) ->args([service('html_sanitizer.config')]) ->tag('html_sanitizer', ['name' => 'default']) ->alias('html_sanitizer', 'html_sanitizer.sanitizer.default') ->alias(HtmlSanitizerInterface::class, 'html_sanitizer') ; };
Fix matching actions with routes on their prototype.
import match from './requirejs-finder/match'; export default function matchAction(method, url, regex, params) { if (url) { return match(m => m.prototype && m.prototype.type === method && m.prototype.route === url ); } else if (regex) { return match(m => { if (!m.prototype || m.prototype.type !== method) { return false; } const fakeInstance = Object.assign(Object.create(m.prototype), { execute() {}, }); Object.defineProperty(fakeInstance, '_super', { get () { return () => {}; }, set (fn) {}, }); try { m.prototype.init.apply(fakeInstance, params || []); } catch (e) { return false; } return fakeInstance.route && ( typeof regex === 'string' ? fakeInstance.route.indexOf(regex) === 0 : regex.test(fakeInstance.route) ); }); } }
import match from './requirejs-finder/match'; const fakeInstance = { get _super() { return () => {}; }, set _super(fn) {}, execute() {}, }; export default function matchAction(method, url, regex, params) { if (url) { return match(m => m.prototype && m.prototype.type === method && m.prototype.route === url ); } else if (regex) { return match(m => { if (!m.prototype || m.prototype.type !== method) { return false; } try { m.prototype.init.apply(fakeInstance, params || []); } catch (e) { return false; } return fakeInstance.route && ( typeof regex === 'string' ? fakeInstance.route.indexOf(regex) === 0 : regex.test(fakeInstance.route) ); }); } }
Check if SMART_CONFIG_DIR env var exists
import convict from 'convict'; import path from 'path'; import fs from 'fs'; const configDir = process.env.SMART_CONFIG_DIR; if (!configDir) { throw new Error(`[smart-config] You must configure "SMART_CONFIG_DIR" environment variable`); } // check and load convict schema const schemaFile = path.join(process.env.SMART_CONFIG_DIR, 'schema')); try { fs.statSync(schemaFile + '.js')); } catch (e) { throw new Error(`[smart-config] Schema file "${e.path}" does not exists.`); } const conf = convict(require(schemaFile)); // check and load related environment config const configFile = path.join(process.env.SMART_CONFIG_DIR, conf.get('env')); try { fs.statSync(configFile + '.js')); } catch (e) { throw new Error(`[smart-config] Config file "${e.path}" does not exists.`); } const envConf = require(configFile); conf.load(envConf); // export utility methods and current config properties export function validate() { return conf.validate({ strict: true }); } export function show() { return conf.toString(); } export default conf.getProperties();
import convict from 'convict'; import path from 'path'; import fs from 'fs'; // check and load convict schema const schemaFile = path.join(process.env.SMART_CONFIG_DIR, 'schema')); try { fs.statSync(schemaFile + '.js')); } catch (e) { throw new Error(`[smart-config] Schema file "${e.path}" does not exists.`); } const conf = convict(require(schemaFile)); // check and load related environment config const configFile = path.join(process.env.SMART_CONFIG_DIR, conf.get('env')); try { fs.statSync(configFile + '.js')); } catch (e) { throw new Error(`[smart-config] Config file "${e.path}" does not exists.`); } const envConf = require(configFile); conf.load(envConf); // export utility methods and current config properties export function validate() { return conf.validate({ strict: true }); } export function show() { return conf.toString(); } export default conf.getProperties();
Tweak the way that on_production_server is determined
import os from google.appengine.api import apiproxy_stub_map from google.appengine.api.app_identity import get_application_id have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3')) if not have_appserver: from .boot import PROJECT_DIR from google.appengine.tools import dev_appserver appconfig = dev_appserver.LoadAppConfig(PROJECT_DIR, {}, default_partition='dev')[0] def appid(): if have_appserver: return get_application_id() else: try: return appconfig.application.split('~', 1)[-1] except ImportError, e: raise Exception("Could not get appid. Is your app.yaml file missing? " "Error was: %s" % e) on_production_server = 'SERVER_SOFTWARE' in os.environ and not os.environ['SERVER_SOFTWARE'].startswith("Development")
import os from google.appengine.api import apiproxy_stub_map from google.appengine.api.app_identity import get_application_id have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3')) if not have_appserver: from .boot import PROJECT_DIR from google.appengine.tools import dev_appserver appconfig = dev_appserver.LoadAppConfig(PROJECT_DIR, {}, default_partition='dev')[0] def appid(): if have_appserver: return get_application_id() else: try: return appconfig.application.split('~', 1)[-1] except ImportError, e: raise Exception("Could not get appid. Is your app.yaml file missing? " "Error was: %s" % e) on_production_server = have_appserver and \ not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
Add new Stripe webhook config values See https://github.com/laravel/cashier/pull/565
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, SparkPost and others. This file provides a sane | default location for this type of information, allowing packages | to have a conventional place to find your various credentials. | */ 'mailgun' => [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), ], 'ses' => [ 'key' => env('SES_KEY'), 'secret' => env('SES_SECRET'), 'region' => env('SES_REGION', 'us-east-1'), ], 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), 'webhook' => [ 'secret' => env('STRIPE_WEBHOOK_SECRET'), 'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300), ], ], ];
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, SparkPost and others. This file provides a sane | default location for this type of information, allowing packages | to have a conventional place to find your various credentials. | */ 'mailgun' => [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), ], 'ses' => [ 'key' => env('SES_KEY'), 'secret' => env('SES_SECRET'), 'region' => env('SES_REGION', 'us-east-1'), ], 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], ];
Remove scope isolated scope from navigation directive
(function () { 'use strict'; module.exports = ['Config', '$location', function (Config, $location) { function link(scope) { // Set key to watch for active class scope.item.active = false; /** * Check if passed href is a location of current page * @param {String} href - href of the link * @return {Boolean} */ function isActive(href) { return '/' + href === $location.path(); } /** * Assign checked expression to the item active key */ function check() { scope.item.active = isActive(scope.item.href); } // Set watcher onRouteChangeSuccess and destroyer for it var destroyWatcher = scope.$on('$routeChangeSuccess', check); // Initial check for active link check(); // Clean up scope.$on('$destroy', destroyWatcher); } return { templateUrl: Config.rootPath + 'shared/navigation/navigation-view.html', link: link, replace: true }; }]; }());
(function () { 'use strict'; module.exports = ['Config', '$location', function (Config, $location) { function link(scope) { // Set key to watch for active class scope.item.active = false; /** * Check if passed href is a location of current page * @param {String} href - href of the link * @return {Boolean} */ function isActive(href) { return '/' + href === $location.path(); } /** * Assign checked expression to the item active key */ function check() { scope.item.active = isActive(scope.item.href); } // Set watcher onRouteChangeSuccess and destroyer for it var destroyWatcher = scope.$on('$routeChangeSuccess', check); // Initial check for active link check(); // Clean up scope.$on('$destroy', destroyWatcher); } return { templateUrl: Config.rootPath + 'shared/navigation/navigation-view.html', link: link, sope: {}, replace: true }; }]; }());
Move alias registration to the `register` method
<?php namespace Illuminate\Html; use Illuminate\Support\ServiceProvider; class HtmlServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->registerHtmlBuilder(); $this->registerFormBuilder(); $this->app->alias('html', 'Illuminate\Html\HtmlBuilder'); $this->app->alias('form', 'Illuminate\Html\FormBuilder'); } /** * Register the HTML builder instance. * * @return void */ protected function registerHtmlBuilder() { $this->app->bindShared('html', function($app) { return new HtmlBuilder($app['url']); }); } /** * Register the form builder instance. * * @return void */ protected function registerFormBuilder() { $this->app->bindShared('form', function($app) { $form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken()); return $form->setSessionStore($app['session.store']); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('html', 'form'); } }
<?php namespace Illuminate\Html; use Illuminate\Support\ServiceProvider; class HtmlServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->registerHtmlBuilder(); $this->registerFormBuilder(); } /** * Register the HTML builder instance. * * @return void */ protected function registerHtmlBuilder() { $this->app->alias('html', 'Illuminate\Html\HtmlBuilder'); $this->app->bindShared('html', function($app) { return new HtmlBuilder($app['url']); }); } /** * Register the form builder instance. * * @return void */ protected function registerFormBuilder() { $this->app->alias('form', 'Illuminate\Html\FormBuilder'); $this->app->bindShared('form', function($app) { $form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken()); return $form->setSessionStore($app['session.store']); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('html', 'form'); } }
Fix Python CloudI Service API interface using JSON-RPC.
#-*-Mode:python;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*- # ex: set ft=python fenc=utf-8 sts=4 ts=4 sw=4 et nomod: """ CloudI Service API <https://cloudi.org/api.html#2_Intro>. """ # pylint: disable=wrong-import-position import sys import os _FILE_DIRECTORY = os.path.dirname(os.path.abspath(__file__)).split(os.path.sep) sys.path.extend([ os.path.sep.join(_FILE_DIRECTORY + ['jsonrpclib']), ]) import jsonrpclib class CloudI(object): """ CloudI Service API object (communicating with JSON-RPC) """ # pylint: disable=too-few-public-methods # initialize with configuration file defaults def __init__(self, host='localhost', port=6464): address = 'http://%s:%d/cloudi/api/rpc.json' % (host, port) self.__server = jsonrpclib.Server(address) def __getattr__(self, name): return self.__server.__getattr__(name)
#-*-Mode:python;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*- # ex: set ft=python fenc=utf-8 sts=4 ts=4 sw=4 et nomod: """ CloudI Service API <https://cloudi.org/api.html#2_Intro>. """ # pylint: disable=wrong-import-position import sys import os _FILE_DIRECTORY = os.path.dirname(os.path.abspath(__file__)).split(os.path.sep) sys.path.extend([ os.path.sep.join(_FILE_DIRECTORY + ['jsonrpclib']), os.path.sep.join(_FILE_DIRECTORY[:-2] + ['api', 'python']), ]) import jsonrpclib import erlang class _ServiceDescription(object): # pylint: disable=too-few-public-methods def __init__(self, *args): self.__args = args def __str__(self): return str(self.__args) class CloudI(object): """ CloudI Service API object (communicating with JSON-RPC) """ # pylint: disable=too-few-public-methods # initialize with configuration file defaults def __init__(self, host='localhost', port=6464): address = 'http://%s:%d/cloudi/api/rpc.json' % (host, port) self.__server = jsonrpclib.Server(address) def __getattr__(self, name): return self.__server.__getattr__(name)
Revert "Test with infinite scroll" This reverts commit f74a07788b16063fbbd22facbe6f86c95afb111d.
<?php if ( ! isset( $content_width ) ) { $content_width = 600; } function enqueue_comment_reply() { if ( get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'comment_form_before', 'enqueue_comment_reply' ); function baw_hack_wp_title_for_home( $title ){ if( empty( $title ) && ( is_home() || is_front_page() ) ): return get_bloginfo( 'name' ) . ' | ' . get_bloginfo( 'description' ); else: return get_bloginfo( 'name' ) . ' | ' . $title; endif; return $title; } add_filter( 'wp_title', 'baw_hack_wp_title_for_home' ); add_theme_support( 'automatic-feed-links' ); add_action('after_setup_theme', 'my_theme_setup'); function my_theme_setup(){ load_theme_textdomain('material-for-coders', get_template_directory() . '/languages'); } ?>
<?php if ( ! isset( $content_width ) ) { $content_width = 600; } function enqueue_comment_reply() { if ( get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'comment_form_before', 'enqueue_comment_reply' ); function baw_hack_wp_title_for_home( $title ){ if( empty( $title ) && ( is_home() || is_front_page() ) ): return get_bloginfo( 'name' ) . ' | ' . get_bloginfo( 'description' ); else: return get_bloginfo( 'name' ) . ' | ' . $title; endif; return $title; } add_filter( 'wp_title', 'baw_hack_wp_title_for_home' ); add_theme_support( 'automatic-feed-links' ); add_action('after_setup_theme', 'my_theme_setup'); function my_theme_setup(){ load_theme_textdomain('material-for-coders', get_template_directory() . '/languages'); add_theme_support( 'infinite-scroll', array( 'type' => 'scroll', 'container' => 'articles', 'posts_per_page' => 2 ) ); } ?>
Update bnetServer argument to accept some shorthand
export const cardName = { key: 'cardName', prompt: 'what card are you searching for?\n', type: 'string' } export const soundKind = { key: 'soundKind', prompt: '', type: 'string', default: 'play' } const bnetServerChoices = ['americas', 'na', 'europe', 'eu', 'asia'] export const bnetServer = { key: 'bnetServer', prompt: 'which battle.net server do you play on?\n', type: 'string', parse: value => { value = value.toLowerCase() if (value === 'na') { return 'americas' } if (value === 'eu') { return 'europe'} return value }, validate: value => { if (bnetServerChoices.includes(value.toLowerCase())) { return true } return `please choose a server from \`${bnetServerChoices.join('`, `')}\`.\n` } } export const bnetId = { key: 'bnetId', prompt: 'what is your battle.net id?\n', type: 'string' }
export const cardName = { key: 'cardName', prompt: 'what card are you searching for?\n', type: 'string' } export const soundKind = { key: 'soundKind', prompt: '', type: 'string', default: 'play' } export const bnetServer = { key: 'bnetServer', prompt: 'which battle.net server do you play on?\n', type: 'string', parse: value => { return value.toLowerCase() }, validate: value => { if (['americas', 'europe', 'asia'].includes(value.toLowerCase())) { return true } return 'please choose a server from `americas`, `europe`, `asia`.\n' } } export const bnetId = { key: 'bnetId', prompt: 'what is your battle.net id?\n', type: 'string' }
Fix typo in docs websocket_async code example
import logging logging.basicConfig(level=logging.INFO) from gql import gql, Client, WebsocketsTransport import asyncio async def main(): transport = WebsocketsTransport(url='wss://countries.trevorblades.com/graphql') # Using `async with` on the client will start a connection on the transport # and provide a `session` variable to execute queries on this connection async with Client( transport=transport, fetch_schema_from_transport=True, ) as session: # Execute single query query = gql(''' query getContinents { continents { code name } } ''') result = await session.execute(query) print(result) # Request subscription subscription = gql(''' subscription { somethingChanged { id } } ''') async for result in session.subscribe(subscription): print(result) asyncio.run(main())
import logging logging.basicConfig(level=logging.INFO) from gql import gql, Client, WebsocketsTransport import asyncio async def main(): transport = WebsocketsTransport(url='wss://countries.trevorblades.com/graphql') # Using `async with` on the client will start a connection on the transport # and provide a `session` variable to execute queries on this connection async with Client( transport=sample_transport, fetch_schema_from_transport=True, ) as session: # Execute single query query = gql(''' query getContinents { continents { code name } } ''') result = await session.execute(query) print(result) # Request subscription subscription = gql(''' subscription { somethingChanged { id } } ''') async for result in session.subscribe(subscription): print(result) asyncio.run(main())
Add support for Meteor 1.2
var Fibers = Npm.require('fibers'); var originalYield = Fibers.yield; Fibers.yield = function() { var kadiraInfo = Kadira._getInfo(); if(kadiraInfo) { var eventId = Kadira.tracer.event(kadiraInfo.trace, 'async');; if(eventId) { Fibers.current._apmEventId = eventId; } } return originalYield(); }; var originalRun = Fibers.prototype.run; Fibers.prototype.run = function(val) { if(this._apmEventId) { var kadiraInfo = Kadira._getInfo(this); if(kadiraInfo) { Kadira.tracer.eventEnd(kadiraInfo.trace, this._apmEventId); this._apmEventId = null; } } return originalRun.call(this, val); };
var Fibers = Npm.require('fibers'); var originalYield = Fibers.yield; Fibers.yield = function() { var kadiraInfo = Kadira._getInfo(); if(kadiraInfo) { var eventId = Kadira.tracer.event(kadiraInfo.trace, 'async');; if(eventId) { Fibers.current._apmEventId = eventId; } } originalYield(); }; var originalRun = Fibers.prototype.run; Fibers.prototype.run = function(val) { if(this._apmEventId) { var kadiraInfo = Kadira._getInfo(this); if(kadiraInfo) { Kadira.tracer.eventEnd(kadiraInfo.trace, this._apmEventId); this._apmEventId = null; } } originalRun.call(this, val); };
Use code as id attribute for module model
define(['backbone', 'common/utils/padTwo'], function(Backbone, padTwo) { 'use strict'; // Convert exam in Unix time to 12-hour date/time format. We add 8 hours to // the UTC time, then use the getUTC* methods so that they will correspond to // Singapore time regardless of the local time zone. var examStr = function(exam) { if (exam) { var date = new Date(exam + 288e5); var hours = date.getUTCHours(); return padTwo(date.getUTCDate()) + '-' + padTwo(date.getUTCMonth() + 1) + '-' + date.getUTCFullYear() + ' ' + (hours % 12 || 12) + ':' + padTwo(date.getUTCMinutes()) + ' ' + (hours < 12 ? 'AM' : 'PM'); } return null; }; return Backbone.Model.extend({ idAttribute: 'code', initialize: function() { this.set('examStr', examStr(this.get('exam'))); } }); });
define(['backbone', 'common/utils/padTwo'], function(Backbone, padTwo) { 'use strict'; // Convert exam in Unix time to 12-hour date/time format. We add 8 hours to // the UTC time, then use the getUTC* methods so that they will correspond to // Singapore time regardless of the local time zone. var examStr = function(exam) { if (exam) { var date = new Date(exam + 288e5); var hours = date.getUTCHours(); return padTwo(date.getUTCDate()) + '-' + padTwo(date.getUTCMonth() + 1) + '-' + date.getUTCFullYear() + ' ' + (hours % 12 || 12) + ':' + padTwo(date.getUTCMinutes()) + ' ' + (hours < 12 ? 'AM' : 'PM'); } return null; }; return Backbone.Model.extend({ initialize: function() { this.set('examStr', examStr(this.get('exam'))); } }); });
Remove debug prints in test.
package yum import ( "testing" "github.com/hnakamur/commango/jsonutil" ) func TestInstalled(t *testing.T) { result, err := Installed("kernel") if err != nil { t.Fatal(err) } _, err = jsonutil.Encode(result) if err != nil { t.Fatal(err) } } func TestNotInstalled(t *testing.T) { result, err := Installed("no_such_package") if err != nil { t.Fatal(err) } _, err = jsonutil.Encode(result) if err != nil { t.Fatal(err) } } func TestInstallGroup(t *testing.T) { result, err := Install("@'Development tools'") if err != nil { t.Fatal(err) } _, err = jsonutil.Encode(result) if err != nil { t.Fatal(err) } } func TestInstall(t *testing.T) { result, err := Install("make") if err != nil { t.Fatal(err) } _, err = jsonutil.Encode(result) if err != nil { t.Fatal(err) } }
package yum import ( "testing" "github.com/hnakamur/commango/jsonutil" ) func TestInstalled(t *testing.T) { result, err := Installed("kernel") if err != nil { t.Fatal(err) } _, err = jsonutil.Encode(result) if err != nil { t.Fatal(err) } } func TestNotInstalled(t *testing.T) { result, err := Installed("no_such_package") if err != nil { t.Fatal(err) } _, err = jsonutil.Encode(result) if err != nil { t.Fatal(err) } } func TestInstallGroup(t *testing.T) { result, err := Install(`@'Development tools'`) if err != nil { t.Fatal(err) } json, err := jsonutil.Encode(result) if err != nil { t.Fatal(err) } t.Error(json) } func TestInstall(t *testing.T) { result, err := Install("make") if err != nil { t.Fatal(err) } json, err := jsonutil.Encode(result) if err != nil { t.Fatal(err) } t.Error(json) }
Add error handling to initial connection in repl
#!/usr/bin/env node var repl = require("repl"); var massive = require("../index"); var program = require('commander'); var assert = require("assert"); program .version('0.0.1') .option('-d, --database', 'The local db you want to connect to ') .option('-c, --connection', 'The full connection string') .parse(process.argv); var connectionString; if(program.database){ connectionString = "postgres://localhost/" + program.args[0]; //assume local user has rights }else if(program.connection) { connectionString = program.args[0]; }else{ console.log("The options to pass in are:"); console.log(" -d or --database to connect locally to a database"); console.log(" -c or --connection to enter the full connection string: postgres://user:password@server/tablename"); } if(connectionString){ massive.connect({connectionString : connectionString}, function(err,db){ if(err) { console.log("Failed loading Massive: "+err); process.exit(1); } var context = repl.start({ prompt: "db > ", }).context; context.db = db; console.log("Massive loaded and listening"); }); }
#!/usr/bin/env node var repl = require("repl"); var massive = require("../index"); var program = require('commander'); var assert = require("assert"); program .version('0.0.1') .option('-d, --database', 'The local db you want to connect to ') .option('-c, --connection', 'The full connection string') .parse(process.argv); var connectionString; if(program.database){ connectionString = "postgres://localhost/" + program.args[0]; //assume local user has rights }else if(program.connection) { connectionString = program.args[0]; }else{ console.log("The options to pass in are:"); console.log(" -d or --database to connect locally to a database"); console.log(" -c or --connection to enter the full connection string: postgres://user:password@server/tablename"); } if(connectionString){ massive.connect({connectionString : connectionString}, function(err,db){ var context = repl.start({ prompt: "db > ", }).context; context.db = db; console.log("Massive loaded and listening"); }); }
Add comment to script to describe what this script is good for
<?php /** * Just copy this into your bootstrap to find out which components have to be checked * It's returning a list of every page containing a component with alternative preview-image */ $data = Kwf_Registry::get('db')->query('SELECT * FROM `kwc_basic_image` WHERE data like \'%preview_image":true%\'')->fetchAll(); foreach ($data as $row) { $component = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row['component_id'], array('ignoreVisible' => false)); if ($component) { if ($component->componentClass != 'Kwc_Basic_LinkTag_Empty_Component') { if ($component->getComponent()->getRow()->kwf_upload_id) { //d($component->componentClass); $components[$component->getAbsoluteUrl()] = '<a href="'.$component->getAbsoluteUrl().'">'.$component->getAbsoluteUrl().'</a>'; } } // $components[] = $component->getUrl(); } } d(array_values($components));
<?php $data = Kwf_Registry::get('db')->query('SELECT * FROM `kwc_basic_image` WHERE data like \'%preview_image":true%\'')->fetchAll(); foreach ($data as $row) { $component = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row['component_id'], array('ignoreVisible' => false)); if ($component) { if ($component->componentClass != 'Kwc_Basic_LinkTag_Empty_Component') { if ($component->getComponent()->getRow()->kwf_upload_id) { //d($component->componentClass); $components[$component->getAbsoluteUrl()] = '<a href="'.$component->getAbsoluteUrl().'">'.$component->getAbsoluteUrl().'</a>'; } } // $components[] = $component->getUrl(); } } d(array_values($components));
Add clone and update serialization
import Vector2 from 'flockn/types/vector2'; class Rect { constructor(x = 0, y = 0, w = 0, h = 0) { this.x = x; this.y = y; this.w = w; this.h = h; } clone() { return new Rect({x: this.x, y: this.y, w: this.w, h: this.h}); } toJSON() { return {x: this.x, y: this.y, w: this.w, h: this.h}; } toString() { return JSON.stringify(this.toJSON()); } static fromString(str) { var obj = JSON.parse(str); return new Rect(obj.x, obj.y, obj.w, obj.h); } center() { return new Vector2(this.w / 2, this.h / 2); } contains(vector) { return (vector.x >= this.x) && (vector.y >= this.y) && (vector.x < this.x + this.w) && (vector.y < this.y + this.h); } } export default Rect;
import Vector2 from 'flockn/types/vector2'; class Rect { constructor(x = 0, y = 0, w = 0, h = 0) { this.x = x; this.y = y; this.w = w; this.h = h; } toString() { return JSON.stringify({ x: this.x, y: this.y, w: this.w, h: this.h }); } static fromString(str) { var obj = JSON.parse(str); return new Rect(obj.x, obj.y, obj.w, obj.h); } center() { return new Vector2(this.w / 2, this.h / 2); } contains(vector) { return (vector.x >= this.x) && (vector.y >= this.y) && (vector.x < this.x + this.w) && (vector.y < this.y + this.h); } } export default Rect;
Add name to anonymous function for bunyan -- restify automatically uses the function name in the timers list, so this sets a name so it's not handler-0
var cookie = require('cookie'); module.exports = { /** * Parse function to be handed to restify server.use * * @param {object} req * @param {object} res * @param {Function} next * @return {undefined} */ parse: function parseCookies (req, res, next){ var self = this; var cookieHeader = req.headers.cookie; if(cookieHeader){ req.cookies = cookie.parse(cookieHeader); } else { req.cookies = {}; } /** * Add a cookie to our response. Uses a Set-Cookie header * per cookie added. * * @param {String} key - Cookie name * @param {String} val - Cookie value * @param {[type]} opts - Options object can contain path, secure, * expires, domain, http */ res.setCookie = function setCookie (key, val, opts){ var HEADER = "Set-Cookie"; if(res.header(HEADER)){ var curCookies = res.header(HEADER); if( !(curCookies instanceof Array) ) { curCookies = [curCookies]; } curCookies.push( cookie.serialize(key, val, opts) ); res.header(HEADER, curCookies); } else { res.header(HEADER, cookie.serialize(key,val, opts)); } }; next(); } };
var cookie = require('cookie'); module.exports = { /** * Parse function to be handed to restify server.use * * @param {object} req * @param {object} res * @param {Function} next * @return {undefined} */ parse: function(req, res, next){ var self = this; var cookieHeader = req.headers.cookie; if(cookieHeader){ req.cookies = cookie.parse(cookieHeader); } else { req.cookies = {}; } /** * Add a cookie to our response. Uses a Set-Cookie header * per cookie added. * * @param {String} key - Cookie name * @param {String} val - Cookie value * @param {[type]} opts - Options object can contain path, secure, * expires, domain, http */ res.setCookie = function(key, val, opts){ var HEADER = "Set-Cookie"; if(res.header(HEADER)){ var curCookies = res.header(HEADER); if( !(curCookies instanceof Array) ) { curCookies = [curCookies]; } curCookies.push( cookie.serialize(key, val, opts) ); res.header(HEADER, curCookies); } else { res.header(HEADER, cookie.serialize(key,val, opts)); } }; next(); } };
Use a terse doc comment. [skip ci]
"use strict"; var $ = require("gulp-load-plugins")(); var gulp = require("gulp"); var notify = require("./gulp/utils/notify"); /** * Load all tasks from the gulp directory. */ require("require-dir")("gulp"); /** * Build * Creates a build artifact, ready for deployment. */ gulp.task("build", ["style:compile", "markup:minify", "script:minify", "image:minify", "source"], function(callback) { notify.showNotification({ subtitle: "Task build", message: "Build complete!" }); callback(); }); /** * Default * Lists all available tasks. */ gulp.task("default", function () { $.util.log("Available tasks:"); Object.keys(gulp.tasks).forEach(function (taskName) { $.util.log("\t", $.util.colors.yellow(taskName)); }); $.util.log("Use", $.util.colors.green("gulp serve"), "to get started."); });
"use strict"; var $ = require("gulp-load-plugins")(); var gulp = require("gulp"); var notify = require("./gulp/utils/notify"); /** * Load all tasks from the gulp directory. */ require("require-dir")("gulp"); /** * Build * Runs style-related, script-related and image-related tasks to create a * distribution directory at `/dist`. */ gulp.task("build", ["style:compile", "markup:minify", "script:minify", "image:minify", "source"], function(callback) { notify.showNotification({ subtitle: "Task build", message: "Build complete!" }); callback(); }); /** * Default * Lists all available tasks. */ gulp.task("default", function () { $.util.log("Available tasks:"); Object.keys(gulp.tasks).forEach(function (taskName) { $.util.log("\t", $.util.colors.yellow(taskName)); }); $.util.log("Use", $.util.colors.green("gulp serve"), "to get started."); });
Set custom map tiles everywhere.
// Map creation + initialisation var map = L.map('map') .setView([55.95, -3.2], 14) .addLayer(L.mapbox.tileLayer('socialsoundsproject.h9hbe4l4', { detectRetina: true })); var soundIcon = L.icon({ iconUrl: '/static/img/marker.png', iconRetinaUrl: '/static/img/marker@2X.png', iconSize: [12,12] }); position_marker = L.marker([55.946, -3.186], { icon: soundIcon, draggable: true }); // Events function onMapClick(e) { $('#latitude').val(e.latlng.lat); $('#longitude').val(e.latlng.lng); position_marker.setLatLng(e.latlng).addTo(map); } function onMarkerDrag (e) { $('#latitude').val(e.target._latlng.lat); $('#longitude').val(e.target._latlng.lng); } map.on('click', onMapClick); position_marker.on('drag', onMarkerDrag);
// Map creation + initialisation var map = L.map('map') .setView([55.95, -3.2], 14) .addLayer(L.mapbox.tileLayer('jeffbr13.h81gnbgn', { detectRetina: true })); var soundIcon = L.icon({ iconUrl: '/static/img/marker.png', iconRetinaUrl: '/static/img/marker@2X.png', iconSize: [12,12] }); position_marker = L.marker([55.946, -3.186], { icon: soundIcon, draggable: true }); // Events function onMapClick(e) { $('#latitude').val(e.latlng.lat); $('#longitude').val(e.latlng.lng); position_marker.setLatLng(e.latlng).addTo(map); } function onMarkerDrag (e) { $('#latitude').val(e.target._latlng.lat); $('#longitude').val(e.target._latlng.lng); } map.on('click', onMapClick); position_marker.on('drag', onMarkerDrag);
Remove Git-based package version detection Instead, allow package version overriding by setting a BEANSTALKC_PKG_VERSION environment variable.
#!/usr/bin/env python import os from distutils.spawn import find_executable from setuptools import setup from beanstalkc import __version__ as src_version pkg_version = os.environ.get('BEANSTALKC_PKG_VERSION', src_version) setup( name='beanstalkc', version=pkg_version, py_modules=['beanstalkc'], author='Andreas Bolka', author_email='a@bolka.at', description='A simple beanstalkd client library', long_description=''' beanstalkc is a simple beanstalkd client library for Python. `beanstalkd <http://kr.github.com/beanstalkd/>`_ is a fast, distributed, in-memory workqueue service. ''', url='http://github.com/earl/beanstalkc', license='Apache License, Version 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
#!/usr/bin/env python import os from setuptools import setup from beanstalkc import __version__ as version pkg_version = version git_version = os.popen('git describe --tags --abbrev=6').read().strip()[7:] if git_version: pkg_version += '.dev' + git_version setup( name='beanstalkc', version=pkg_version, py_modules=['beanstalkc'], author='Andreas Bolka', author_email='a@bolka.at', description='A simple beanstalkd client library', long_description=''' beanstalkc is a simple beanstalkd client library for Python. `beanstalkd <http://kr.github.com/beanstalkd/>`_ is a fast, distributed, in-memory workqueue service. ''', url='http://github.com/earl/beanstalkc', license='Apache License, Version 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add color component array getter
package com.haxademic.core.draw.color; import processing.core.PApplet; import com.haxademic.core.app.P; public class ColorUtil { public static int colorWithIntAndAlpha( PApplet p, int color, int alpha ) { // from: http://processing.org/discourse/beta/num_1261125421.html return (color & 0xffffff) | (alpha << 24); } public static int colorFromHex( String hex ) { return P.unhex("FF"+hex.substring(1)); } public static float componentByPercent( float percent ) { return percent * 255f; } public final static int alphaFromColorInt( int c ) { return (c >> 24) & 0xFF; } public final static int redFromColorInt( int c ) { return (c >> 16) & 0xFF; } public final static int greenFromColorInt( int c ) { return (c >> 8) & 0xFF; } public final static int blueFromColorInt( int c ) { return c & 0xFF; } public final static int[] rgbFromColorInt( int c ) { return new int[]{redFromColorInt(c), greenFromColorInt(c), blueFromColorInt(c)}; } }
package com.haxademic.core.draw.color; import processing.core.PApplet; import com.haxademic.core.app.P; public class ColorUtil { public static int colorWithIntAndAlpha( PApplet p, int color, int alpha ) { // from: http://processing.org/discourse/beta/num_1261125421.html return (color & 0xffffff) | (alpha << 24); } public static int colorFromHex( String hex ) { return P.unhex("FF"+hex.substring(1)); } public static float componentByPercent( float percent ) { return percent * 255f; } public final static int alphaFromColorInt( int c ) { return (c >> 24) & 0xFF; } public final static int redFromColorInt( int c ) { return (c >> 16) & 0xFF; } public final static int greenFromColorInt( int c ) { return (c >> 8) & 0xFF; } public final static int blueFromColorInt( int c ) { return c & 0xFF; } }
Undo temp change for standalone attr replacement
<?php /** * Template for web-story post type. * * @package Google\Web_Stories * @copyright 2020 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://github.com/google/web-stories-wp */ use Google\Web_Stories\Story_Renderer; /** * Copyright 2020 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. */ the_post(); $current_post = get_post(); if ( $current_post instanceof WP_Post ) { echo '<!DOCTYPE html>'; $renderer = new Story_Renderer( $current_post ); echo $renderer->render(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped }
<?php /** * Template for web-story post type. * * @package Google\Web_Stories * @copyright 2020 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://github.com/google/web-stories-wp */ use Google\Web_Stories\Story_Renderer; /** * Copyright 2020 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. */ the_post(); $current_post = get_post(); if ( $current_post instanceof WP_Post ) { echo '<!DOCTYPE html>'; $renderer = new Story_Renderer( $current_post ); $rendered = $renderer->render(); $rendered = str_replace( ' standalone="standalone"', ' standalone', $rendered ); // @todo Remove! Temporary workaround for AMP plugin validation issue. echo $rendered; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped }
[IMP] Improve warning "Email sending not enabled"
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import api, models, tools from openerp.addons.mail.mail_mail import _logger class MailMail(models.Model): _inherit = 'mail.mail' @api.cr_uid def process_email_queue(self, cr, uid, ids=None, context=None): if not tools.config.get('enable_email_sending'): _logger.warning('Email sending not enabled') return True return super(MailMail, self).process_email_queue(cr, uid, ids, context)
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import api, models, tools from openerp.addons.mail.mail_mail import _logger class MailMail(models.Model): _inherit = 'mail.mail' @api.cr_uid def process_email_queue(self, cr, uid, ids=None, context=None): if not tools.config.get('enable_email_sending'): _logger.warning('Email sending not enable') return True return super(MailMail, self).process_email_queue(cr, uid, ids, context)
Fix "version" and "_http" swapped in argument list
<?php namespace Vresh\TwilioBundle\Service; /** * This file is part of the VreshTwilioBundle. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Fridolin Koch <info@fridokoch.de> */ class TwilioWrapper extends \Services_Twilio { /** * @param string $sid * @param string $token * @param null $version * @param int $retryAttempts */ public function __construct($sid, $token, $version = null, $retryAttempts = 1) { parent::__construct($sid, $token, $version, null, $retryAttempts); } /** * Returns a new \Services_Twilio instance from the given parameters * * @param $sid * @param $token * @param null $version * @param int $retryAttempts * * @return \Services_Twilio */ public function createInstance($sid ,$token, $version = null, $retryAttempts = 1) { return new \Services_Twilio($sid, $token, $version, null, $retryAttempts); } }
<?php namespace Vresh\TwilioBundle\Service; /** * This file is part of the VreshTwilioBundle. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Fridolin Koch <info@fridokoch.de> */ class TwilioWrapper extends \Services_Twilio { /** * @param string $sid * @param string $token * @param null $version * @param int $retryAttempts */ public function __construct($sid, $token, $version = null, $retryAttempts = 1) { parent::__construct($sid, $token, $version, null, $retryAttempts); } /** * Returns a new \Services_Twilio instance from the given parameters * * @param $sid * @param $token * @param null $version * @param int $retryAttempts * * @return \Services_Twilio */ public function createInstance($sid ,$token, $version = null, $retryAttempts = 1) { return new \Services_Twilio($sid, $token, null, $version, $retryAttempts); } }
Revert "Switch to tuple for pref set data key list" This reverts commit 302d9797b7ccb46e7b9575513c0a2c5461e156a5.
# yvs.set_pref # coding=utf-8 from __future__ import unicode_literals import json import sys import yvs.shared as shared # Parse pref set data from the given JSON string def parse_pref_set_data_str(pref_set_data_str): pref_set_data = json.loads( pref_set_data_str)['alfredworkflow']['variables'] return [pref_set_data[key] for key in ['pref_id', 'pref_name', 'value_id', 'value_name']] # Set the YouVersion Suggest preference with the given key def set_pref(pref_id, value_id): user_prefs = shared.get_user_prefs() user_prefs[pref_id] = value_id # If new language is set, ensure that preferred version is updated also if pref_id == 'language': bible = shared.get_bible_data(language_id=value_id) user_prefs['version'] = bible['default_version'] shared.clear_cache() shared.set_user_prefs(user_prefs) def main(pref_set_data_str): pref_id, pref_name, value_id, value_name = parse_pref_set_data_str( pref_set_data_str) set_pref(pref_id, value_id) print(pref_set_data_str.encode('utf-8')) if __name__ == '__main__': main(sys.argv[1].decode('utf-8'))
# yvs.set_pref # coding=utf-8 from __future__ import unicode_literals import json import sys import yvs.shared as shared # Parse pref set data from the given JSON string def parse_pref_set_data_str(pref_set_data_str): pref_set_data = json.loads( pref_set_data_str)['alfredworkflow']['variables'] return [pref_set_data[key] for key in ('pref_id', 'pref_name', 'value_id', 'value_name')] # Set the YouVersion Suggest preference with the given key def set_pref(pref_id, value_id): user_prefs = shared.get_user_prefs() user_prefs[pref_id] = value_id # If new language is set, ensure that preferred version is updated also if pref_id == 'language': bible = shared.get_bible_data(language_id=value_id) user_prefs['version'] = bible['default_version'] shared.clear_cache() shared.set_user_prefs(user_prefs) def main(pref_set_data_str): pref_id, pref_name, value_id, value_name = parse_pref_set_data_str( pref_set_data_str) set_pref(pref_id, value_id) print(pref_set_data_str.encode('utf-8')) if __name__ == '__main__': main(sys.argv[1].decode('utf-8'))
Clarify comment re: Participant class This refers to the old participant class, which is going away.
import uuid from gittip.orm import db from gittip.models.participant import Participant class User(Participant): """Represent a website user. Every current website user is also a participant, though if the user is anonymous then the methods from gittip.Participant will fail with NoParticipantId. The methods """ @classmethod def from_session_token(cls, token): user = User.query.filter_by(session_token=token).first() if user and not user.is_suspicious: user = user else: user = User() return user @classmethod def from_id(cls, user_id): user = User.query.filter_by(id=user_id).first() if user and not user.is_suspicious: user.session_token = uuid.uuid4().hex db.session.add(user) db.session.commit() else: user = User() return user @property def ADMIN(self): return self.id is not None and self.is_admin @property def ANON(self): return self.id is None def __unicode__(self): return '<User: %s>' % getattr(self, 'id', 'Anonymous')
import uuid from gittip.orm import db from gittip.models.participant import Participant class User(Participant): """Represent a website user. Every current website user is also a participant, though if the user is anonymous then the methods from Participant will fail with NoParticipantId. """ @classmethod def from_session_token(cls, token): user = User.query.filter_by(session_token=token).first() if user and not user.is_suspicious: user = user else: user = User() return user @classmethod def from_id(cls, user_id): user = User.query.filter_by(id=user_id).first() if user and not user.is_suspicious: user.session_token = uuid.uuid4().hex db.session.add(user) db.session.commit() else: user = User() return user @property def ADMIN(self): return self.id is not None and self.is_admin @property def ANON(self): return self.id is None def __unicode__(self): return '<User: %s>' % getattr(self, 'id', 'Anonymous')
Fix Regimen Summary Report Mapper Regimen Query
package org.openlmis.report.mapper.lookup; import org.apache.ibatis.annotations.Select; import org.openlmis.report.model.dto.Regimen; import org.springframework.stereotype.Repository; import java.util.List; /** * Created with IntelliJ IDEA. * User: hassan * Date: 11/21/13 * Time: 12:03 PM * To change this template use File | Settings | File Templates. */ @Repository public interface RegimenReportMapper{ @Select("SELECT * FROM regimens R INNER JOIN regimen_categories RC ON R.categoryId = RC.id\n" + " ORDER BY RC.displayOrder,R.displayOrder") List<Regimen> getByProgram(); @Select("SELECT * FROM regimens ORDER BY displayOrder, name") List<Regimen> getAll(); @Select("SELECT * FROM regimens R INNER JOIN regimen_categories RC ON R.categoryId = RC.id\n" + " where categoryid = #{categoryid} ORDER BY RC.displayOrder,R.displayOrder") List<Regimen>getRegimenByCategory(Long id); }
package org.openlmis.report.mapper.lookup; import org.apache.ibatis.annotations.Select; import org.openlmis.report.model.dto.Regimen; import org.springframework.stereotype.Repository; import java.util.List; /** * Created with IntelliJ IDEA. * User: hassan * Date: 11/21/13 * Time: 12:03 PM * To change this template use File | Settings | File Templates. */ @Repository public interface RegimenReportMapper{ @Select("SELECT * FROM regimens R INNER JOIN regimen_categories RC ON R.categoryId = RC.id\n" + " ORDER BY RC.displayOrder,R.displayOrder") List<Regimen> getByProgram(); @Select("SELECT * FROM regimen ORDER BY displayOrder, name") List<Regimen> getAll(); @Select("SELECT * FROM regimens R INNER JOIN regimen_categories RC ON R.categoryId = RC.id\n" + " where categoryid = #{categoryid} ORDER BY RC.displayOrder,R.displayOrder") List<Regimen>getRegimenByCategory(Long id); }
Remove unused getter for duration
package de.kimminich.kata.botwars.effects; import de.kimminich.kata.botwars.Bot; import de.kimminich.kata.botwars.messages.Message; public abstract class AbstractEffect implements Effect { private Bot invoker; private int duration; public AbstractEffect(Bot invoker, Integer duration) { this.invoker = invoker; this.duration = duration; } @Override public boolean isExpired() { return duration == 0; } @Override public Message apply(Bot target) { duration--; return applyEffect(invoker, target); } @Override public Message revoke(Bot target) { return revokeEffect(invoker, target); } public abstract Message applyEffect(Bot invoker, Bot target); public abstract Message revokeEffect(Bot invoker, Bot target); @Override public String toString() { return this.getClass().getSimpleName() + "(" + duration + ")"; } }
package de.kimminich.kata.botwars.effects; import de.kimminich.kata.botwars.Bot; import de.kimminich.kata.botwars.messages.Message; public abstract class AbstractEffect implements Effect { private Bot invoker; private int duration; public AbstractEffect(Bot invoker, Integer duration) { this.invoker = invoker; this.duration = duration; } public int getDuration() { return duration; } @Override public boolean isExpired() { return duration == 0; } @Override public Message apply(Bot target) { duration--; return applyEffect(invoker, target); } @Override public Message revoke(Bot target) { return revokeEffect(invoker, target); } public abstract Message applyEffect(Bot invoker, Bot target); public abstract Message revokeEffect(Bot invoker, Bot target); @Override public String toString() { return this.getClass().getSimpleName() + "(" + duration + ")"; } }
Check for appropriate long type on Python 2 The extension always returns a long, which is not an "int" on Python 2. Fix the test.
import sys import unittest import zstd if sys.version_info[0] >= 3: int_type = int else: int_type = long class TestTrainDictionary(unittest.TestCase): def test_no_args(self): with self.assertRaises(TypeError): zstd.train_dictionary() def test_bad_args(self): with self.assertRaises(TypeError): zstd.train_dictionary(8192, u'foo') with self.assertRaises(ValueError): zstd.train_dictionary(8192, [u'foo']) def test_basic(self): samples = [] for i in range(128): samples.append(b'foo' * 64) samples.append(b'bar' * 64) samples.append(b'foobar' * 64) samples.append(b'baz' * 64) samples.append(b'foobaz' * 64) samples.append(b'bazfoo' * 64) d = zstd.train_dictionary(8192, samples) self.assertLessEqual(len(d), 8192) dict_id = zstd.dictionary_id(d) self.assertIsInstance(dict_id, int_type)
import unittest import zstd class TestTrainDictionary(unittest.TestCase): def test_no_args(self): with self.assertRaises(TypeError): zstd.train_dictionary() def test_bad_args(self): with self.assertRaises(TypeError): zstd.train_dictionary(8192, u'foo') with self.assertRaises(ValueError): zstd.train_dictionary(8192, [u'foo']) def test_basic(self): samples = [] for i in range(128): samples.append(b'foo' * 64) samples.append(b'bar' * 64) samples.append(b'foobar' * 64) samples.append(b'baz' * 64) samples.append(b'foobaz' * 64) samples.append(b'bazfoo' * 64) d = zstd.train_dictionary(8192, samples) self.assertLessEqual(len(d), 8192) dict_id = zstd.dictionary_id(d) self.assertIsInstance(dict_id, int)
Use version from udev module instead of declaring it manually
#!/usr/bin/python # -*- coding: utf-8 -*- from setuptools import setup import udev with open('README.rst') as stream: long_description = stream.read().decode('utf-8') setup( name='pyudev', version=udev.__version__, url='http://packages.python.org/pyudev', author='Sebastian Wiesner', author_email='lunaryorn@googlemail.com', description='A libudev binding', long_description=long_description, platforms='Linux', license='MIT/X11', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Hardware', 'Topic :: System :: Operating System Kernels :: Linux', ], py_modules=['udev', '_udev', 'qudev'], )
#!/usr/bin/python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as stream: long_description = stream.read().decode('utf-8') setup( name='pyudev', version='0.3', url='http://packages.python.org/pyudev', author='Sebastian Wiesner', author_email='lunaryorn@googlemail.com', description='A libudev binding', long_description=long_description, platforms='Linux', license='MIT/X11', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Hardware', 'Topic :: System :: Operating System Kernels :: Linux', ], py_modules=['udev', '_udev', 'qudev'], )
Fix bug of self injection into injector function
from functools import wraps from typing import Callable from ._scope import Scope class Injector(Callable): """ class decorator to inject dependencies into a callable decorated function """ def __init__(self, dependencies: dict, fun: Callable): self.dependencies = dependencies self.fun = fun @property def scope(self) -> Scope: return Scope() def __call__(self, *args, **kwargs): injections = {} for dependency_name, service_name in self.dependencies.items(): injections[dependency_name] = kwargs.get(dependency_name) or self.scope[service_name] kwargs.update(injections) return self.fun(*args, **kwargs) class Inject(Callable): """ class to recive the callable dependencies """ __injector__ = Injector def __init__(self, **dependencies): self.dependencies = dependencies def __call__(self, fun: Callable): def call(*args, **kwargs): return self.__injector__(self.dependencies, fun).__call__(*args, **kwargs) return wraps(fun).__call__(call)
from functools import wraps from typing import Callable from ._scope import Scope class Injector(Callable): """ class decorator to inject dependencies into a callable decorated function """ def __init__(self, dependencies: dict, fun: Callable): self.dependencies = dependencies self.fun = fun @property def scope(self) -> Scope: return Scope() def __call__(self, *args, **kwargs): injections = {} for dependency_name, service_name in self.dependencies.items(): injections[dependency_name] = kwargs.get(dependency_name) or self.scope[service_name] kwargs.update(injections) return self.fun(*args, **kwargs) class Inject(Callable): """ class to recive the callable dependencies """ __injector__ = Injector def __init__(self, **dependencies): self.dependencies = dependencies def __call__(self, fun: Callable): return wraps(fun).__call__(self.__injector__(self.dependencies, fun))
Check the message in advice
var express = require('express'); var app = express(); var request = require('request'); var adviceArray = ["I am God's vessel. But my greatest pain in life is that I will never be able to see myself perform live.", "Would you believe in what you believe in if you were the only one who believed it?"]; var currentAdvice = 0; var adviceMax = adviceArray.length; function getAdvice() { var message = adviceArray[currentAdvice]; currentAdvice++; if (currentAdvice >= adviceMax) { currentAdvice = 0; } return message; } // The main app can hit this when an SMS is received app.get('/sms', function(req, res) { if (req.query.message.toLowerCase() != "advice") { res.status(400).end(); } var message = getAdvice(); request("http://localhost:80/sendsms?message=" + message + "&number=" + encodeURIComponent(req.query.number)); res.status(200).end() }); app.listen(3000);
var express = require('express'); var app = express(); var request = require('request'); var adviceArray = ["I am God's vessel. But my greatest pain in life is that I will never be able to see myself perform live.", "Would you believe in what you believe in if you were the only one who believed it?"]; var currentAdvice = 0; var adviceMax = adviceArray.length; function getAdvice() { var message = adviceArray[currentAdvice]; currentAdvice++; if (currentAdvice >= adviceMax) { currentAdvice = 0; } return message; } // The main app can hit this when an SMS is received app.get('/sms', function(req, res) { var message = getAdvice(); request("http://localhost:80/sendsms?message=" + message + "&number=" + encodeURIComponent(req.query.number)); res.status(200).end() }); app.listen(3000);
Fix e2e tests after default region change The tests expected the region selection popup to appear, but right now we default to the Tallinn region instead, in which case, to select the Tartu region, the test must select that region from the dropdown.
describe('Praad App', function() { 'use strict'; describe('Offer list view', function() { var offers, regionSelectedPromise; beforeEach(function() { browser.manage().deleteAllCookies(); browser.get('/'); regionSelectedPromise = element(by.css('.icon-22')).click().then(function() { var EC = protractor.ExpectedConditions; var tartuButton = element(by.cssContainingText('.dropdown label', 'Tartu')); browser.wait(EC.elementToBeClickable(tartuButton), 500); return tartuButton.click(); }); offers = element.all(by.repeater('offer in restaurant.offers')); }); it('should initially have 3 offers', function() { regionSelectedPromise.then(function() { expect(offers.count()).toBe(37); }); }); it('should filter the offer list as user types into the search box', function() { regionSelectedPromise.then(function() { element(by.model('search.query')).sendKeys('kana'); expect(offers.count()).toBe(7); var title = offers.first().element(by.binding('offer.title')).getText(); expect(title).toBe('Kana-riisisupp'); }); }); }); });
describe('Praad App', function() { 'use strict'; describe('Offer list view', function() { var offers, clickPromise; beforeEach(function() { browser.manage().deleteAllCookies(); browser.get('/'); clickPromise = element(by.css('.popup')).element(by.css('label')).click(); offers = element.all(by.repeater('offer in restaurant.offers')); }); it('should initially have 3 offers', function() { clickPromise.then(function() { expect(offers.count()).toBe(37); }); }); it('should filter the offer list as user types into the search box', function() { clickPromise.then(function() { element(by.model('search.query')).sendKeys('kana'); expect(offers.count()).toBe(7); var title = offers.first().element(by.binding('offer.title')).getText(); expect(title).toBe('Kana-riisisupp'); }); }); }); });
Use URL regex as per main Django project
from django.conf.urls import patterns, url from cellcounter.accounts import views urlpatterns = patterns('', url('^new/$', views.RegistrationView.as_view(), name='register'), url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'), url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'), url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'), url('^password/reset/$', views.PasswordResetView.as_view(), name='password-reset'), url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.PasswordResetConfirmView.as_view(), name='password-reset-confirm'), url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'), )
from django.conf.urls import patterns, url from cellcounter.accounts import views urlpatterns = patterns('', url('^new/$', views.RegistrationView.as_view(), name='register'), url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'), url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'), url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'), url('^password/reset/$', views.PasswordResetView.as_view(), name='password-reset'), url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$', views.PasswordResetConfirmView.as_view(), name='password-reset-confirm'), url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'), )
Maintain an internal stack of keystroke handlers - when blurring the element with current control, return to the previous element with keystroke control
jsio('from common.javascript import Singleton') jsio('import browser.events as events'); exports = Singleton(function(){ this.init = function() { events.add(window, 'keypress', bind(this, '_onKeyPress')); this._handlerStack = []; } this.requestFocus = function(handler) { if (this._keystrokeHandler) { this._handlerStack.push(this._keystrokeHandler); } this._keystrokeHandler = handler; return this._keystrokeHandler; } this.release = function(handler) { if (handler != this._keystrokeHandler) { return; } this._keystrokeHandler = this._handlerStack.pop(); } this.handleKeys = function(keyMap) { return this.requestFocus(bind(this, function(e) { var code; if (e.charCode != 0) { code = String.fromCharCode(e.charCode); } else if (e.keyCode != 0) { code = events.keyCodes[e.keyCode]; } if (keyMap[code]) { keyMap[code](); events.cancel(e); } })); } this._onKeyPress = function(e) { if (!this._keystrokeHandler) { return; } this._keystrokeHandler(e); } })
jsio('from common.javascript import Singleton') jsio('import browser.events as events'); exports = Singleton(function(){ this.init = function() { events.add(window, 'keypress', bind(this, '_onKeyPress')); } this.requestFocus = function(handler) { this._keystrokeHandler = handler; return this._keystrokeHandler; } this.release = function(handler) { if (handler != this._keystrokeHandler) { return; } this._keystrokeHandler = null; } this.handleKeys = function(keyMap) { return this.requestFocus(bind(this, function(e) { var code; if (e.charCode != 0) { code = String.fromCharCode(e.charCode); } else if (e.keyCode != 0) { code = events.keyCodes[e.keyCode]; } if (keyMap[code]) { keyMap[code](); events.cancel(e); } })); } this._onKeyPress = function(e) { if (!this._keystrokeHandler) { return; } this._keystrokeHandler(e); } })
Move helper to end of module and remove double spaces.
from __future__ import unicode_literals from conllu.models import TokenList from conllu.parser import parse_token_and_metadata def parse(data, fields=None): return [ TokenList(*parse_token_and_metadata(sentence, fields=fields)) for sentence in data.split("\n\n") if sentence ] def parse_incr(in_file, fields=None): for sentence in _iter_sents(in_file): yield TokenList(*parse_token_and_metadata(sentence, fields=fields)) def parse_tree(data): tokenlists = parse(data) sentences = [] for tokenlist in tokenlists: sentences.append(tokenlist.to_tree()) return sentences def parse_tree_incr(in_file): for tokenlist in parse_incr(in_file): yield tokenlist.to_tree() def _iter_sents(in_file): buf = [] for line in in_file: if line == "\n": yield "".join(buf)[:-1] buf = [] else: buf.append(line) if buf: yield "".join(buf)
from __future__ import unicode_literals from conllu.models import TokenList from conllu.parser import parse_token_and_metadata def parse(data, fields=None): return [ TokenList(*parse_token_and_metadata(sentence, fields=fields)) for sentence in data.split("\n\n") if sentence ] def _iter_sents(in_file): buf = [] for line in in_file: if line == "\n": yield "".join(buf)[:-1] buf = [] else: buf.append(line) if buf: yield "".join(buf) def parse_incr(in_file, fields=None): for sentence in _iter_sents(in_file): yield TokenList(*parse_token_and_metadata(sentence, fields=fields)) def parse_tree(data): tokenlists = parse(data) sentences = [] for tokenlist in tokenlists: sentences.append(tokenlist.to_tree()) return sentences def parse_tree_incr(in_file): for tokenlist in parse_incr(in_file): yield tokenlist.to_tree()
Use path.join instead of concating directories.
const path = require('path'); const sandwich = require('sandwich'); const fs = require('fs'); function fileToArray(file) { return ( fs.readFileSync(path.join(__dirname, '/', file)) .toString() .trim() .split('\n') ); } const ADVERBS = fileToArray('adverbs.txt'); const ADJECTIVES = fileToArray('adjectives.txt'); const NOUNS = fileToArray('nouns.txt'); const iterator = sandwich(ADVERBS, ADJECTIVES, NOUNS); function phrases(count) { const matches = {}; const results = []; var length = 0; var word; while (length < count) { word = iterator.random().join('-'); if (!matches[word]) { matches[word] = results.push(word); length++; } } return results; } phrases.iterator = iterator; module.exports = phrases;
function fileToArray(file) { return ( fs.readFileSync(__dirname + '/' +file) .toString() .trim() .split('\n') ); } const sandwich = require('sandwich'); const fs = require('fs'); const ADVERBS = fileToArray('adverbs.txt'); const ADJECTIVES = fileToArray('adjectives.txt'); const NOUNS = fileToArray('nouns.txt'); const iterator = sandwich(ADVERBS, ADJECTIVES, NOUNS); function phrases(count) { const matches = {}; const results = []; var length = 0; var word; while (length < count) { word = iterator.random().join('-'); if (!matches[word]) { matches[word] = results.push(word); length++; } } return results; }; phrases.iterator = iterator; module.exports = phrases;
Set show count option to 20 default
package mil.nga.giat.geowave.analytic.javaspark.sparksql.operations; import com.beust.jcommander.Parameter; public class SparkSqlOptions { @Parameter(names = { "-o", "--out" }, description = "The output datastore name") private String outputStoreName = null; @Parameter(names = { "--outtype" }, description = "The output type name") private String outputTypeName = null; @Parameter(names = { "-s", "--show" }, description = "Number of result rows to display") private int showResults = 20; public SparkSqlOptions() {} public String getOutputStoreName() { return outputStoreName; } public void setOutputStoreName( String outputStoreName ) { this.outputStoreName = outputStoreName; } public int getShowResults() { return showResults; } public void setShowResults( int showResults ) { this.showResults = showResults; } public String getOutputTypeName() { return outputTypeName; } public void setOutputTypeName( String outputTypeName ) { this.outputTypeName = outputTypeName; } }
package mil.nga.giat.geowave.analytic.javaspark.sparksql.operations; import com.beust.jcommander.Parameter; public class SparkSqlOptions { @Parameter(names = { "-o", "--out" }, description = "The output datastore name") private String outputStoreName = null; @Parameter(names = { "--outtype" }, description = "The output type name") private String outputTypeName = null; @Parameter(names = { "-s", "--show" }, description = "Number of result rows to display") private int showResults = 0; public SparkSqlOptions() {} public String getOutputStoreName() { return outputStoreName; } public void setOutputStoreName( String outputStoreName ) { this.outputStoreName = outputStoreName; } public int getShowResults() { return showResults; } public void setShowResults( int showResults ) { this.showResults = showResults; } public String getOutputTypeName() { return outputTypeName; } public void setOutputTypeName( String outputTypeName ) { this.outputTypeName = outputTypeName; } }
Change endpoint for 2 other free services
import React from 'react'; const withCountry = component => class extends React.Component { static displayName = `withCountry(${component.displayName || component.name})`; constructor(props) { super(props); this.state = { country: 'US', }; } async componentDidMount() { try { const response = await fetch('//ipinfo.io/json'); const data = await response.json(); this.setState({country: data.country}); } catch (err) { // Failed to fetch can happen if the user has a blocker (ad, tracker...) window.trackJs.track(`Error when getting the country: ${err.message}`); // trying another server just to be sure try { const response = await fetch('//get.geojs.io/v1/ip/country.json'); const data = await response.json(); this.setState({country: data.country}); } catch (err2) { // giving up window.trackJs.track( `Error when getting the country: ${err2.message}`, ); } } } render() { const {country} = this.state; return React.createElement(component, { ...this.props, country, }); } }; export default withCountry;
import React from 'react'; const withCountry = component => class extends React.Component { static displayName = `withCountry(${component.displayName || component.name})`; constructor(props) { super(props); this.state = { country: 'US', }; } async componentDidMount() { try { const response = await fetch('//freegeoip.net/json/'); const data = await response.json(); this.setState({country: data.country_code}); } catch (err) { // Failed to fetch can happen if the user has a blocker (ad, tracker...) trackJs.track(`Error when getting the country: ${err.message}`); } } render() { const {country} = this.state; return React.createElement(component, { ...this.props, country, }); } }; export default withCountry;
Store configuartion data in a variable
/*----------------------------------------------------------------- Modular - JS Extension Made by @esr360 http://github.com/esr360/Modular/ -----------------------------------------------------------------*/ //----------------------------------------------------------------- // Convert CSS config to JS //----------------------------------------------------------------- // Get styles' configuration var stylesConfigJSON = document.getElementById("stylesConfigJSON"); // Remove quotes from computed JSON function removeQuotes(json) { json = json.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, ''); return json; } // Convert computed JSON to camelCase function camelCase(json) { json = json.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); return json; } // Convert the config to JS function getStylesConfig(camelCase) { var style = null; style = window.getComputedStyle(stylesConfigJSON, '::before'); style = style.content; style = removeQuotes(style); if(camelCase) { style = camelCase(style); } return JSON.parse(style); } // Store configuartion data in a variable var module = getStylesConfig();
/*----------------------------------------------------------------- Modular - JS Extension Made by @esr360 http://github.com/esr360/Modular/ -----------------------------------------------------------------*/ //----------------------------------------------------------------- // Convert CSS config to JS //----------------------------------------------------------------- // Get styles' configuration var stylesConfigJSON = document.getElementById("stylesConfigJSON"); // Remove quotes from computed JSON function removeQuotes(json) { json = json.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, ''); return json; } // Convert computed JSON to camelCase function camelCase(json) { json = json.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); return json; } // Convert the config to JS function getStylesConfig(camelCase) { var style = null; style = window.getComputedStyle(stylesConfigJSON, '::before'); style = style.content; style = removeQuotes(style); if(camelCase) { style = camelCase(style); } return JSON.parse(style); }
Initialize the checkout when the order is loaded
import Ember from 'ember'; import layout from '../templates/components/yebo-checkout'; /** A single page checkout that reactively responds to changes in the `yebo.checkouts` service. **To Override:** You'll need to run the components generator: ```bash ember g yebo-ember-storefront-components ``` This will install all of the Yebo Ember Storefront component files into your host application at `app/components/yebo-*.js`, ready to be extended or overriden. @class YeboCheckout @namespace Component @extends Ember.Component */ export default Ember.Component.extend({ layout: layout, action: 'transitionCheckoutState', /** * */ init() { // Call the super this._super(); // Set initialize it // TODO: Move this to an initialzer this.get('yebo').on('orderLoaded', () => { this.get('yebo').get('checkouts').trigger('checkoutCalled'); }); }, actions: { transitionCheckoutState: function(stateName) { this.sendAction('action', stateName); }, setShipment: function(rateId) { // Trigger the event this.get('yebo').get('checkouts').trigger('setShipment', rateId); }, checkout: function() { // Trigger the event this.get('yebo').get('checkouts').trigger('checkout'); }, editAddress: function(name) { // Trigger the event this.get('yebo').get('checkouts').trigger('editAddress', name); } } });
import Ember from 'ember'; import layout from '../templates/components/yebo-checkout'; /** A single page checkout that reactively responds to changes in the `yebo.checkouts` service. **To Override:** You'll need to run the components generator: ```bash ember g yebo-ember-storefront-components ``` This will install all of the Yebo Ember Storefront component files into your host application at `app/components/yebo-*.js`, ready to be extended or overriden. @class YeboCheckout @namespace Component @extends Ember.Component */ export default Ember.Component.extend({ layout: layout, action: 'transitionCheckoutState', /** * */ init() { // Call the super this._super(); // Set initialize it // TODO: Move this to an initialzer this.get('yebo')._restoreCurrentOrder().then(()=> { this.get('yebo').get('checkouts').trigger('checkoutCalled'); }); }, actions: { transitionCheckoutState: function(stateName) { this.sendAction('action', stateName); }, setShipment: function(rateId) { // Trigger the event this.get('yebo').get('checkouts').trigger('setShipment', rateId); }, checkout: function() { // Trigger the event this.get('yebo').get('checkouts').trigger('checkout'); }, editAddress: function(name) { // Trigger the event this.get('yebo').get('checkouts').trigger('editAddress', name); } } });
Set URL to null on close
package com.freshplanet.ane.AirAACPlayer.functions; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; import com.freshplanet.ane.AirAACPlayer.Extension; import com.freshplanet.ane.AirAACPlayer.ExtensionContext; public class CloseFunction implements FREFunction { @Override public FREObject call(FREContext context, FREObject[] arg1) { try { ExtensionContext extensionContext = (ExtensionContext) context; extensionContext.getPlayer().stop(); extensionContext.getPlayer().release(); extensionContext.setMediaUrl(null); extensionContext.setPlayer(null); } catch (Exception e) { Extension.context.dispatchStatusEventAsync("LOGGING", "[Error] Error on close"); e.printStackTrace(); } return null; } }
package com.freshplanet.ane.AirAACPlayer.functions; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; import com.freshplanet.ane.AirAACPlayer.Extension; import com.freshplanet.ane.AirAACPlayer.ExtensionContext; public class CloseFunction implements FREFunction { @Override public FREObject call(FREContext context, FREObject[] arg1) { try { ExtensionContext extensionContext = (ExtensionContext) context; extensionContext.getPlayer().stop(); extensionContext.getPlayer().release(); extensionContext.setPlayer(null); } catch (Exception e) { Extension.context.dispatchStatusEventAsync("LOGGING", "[Error] Error on close"); e.printStackTrace(); } return null; } }
Change a fastmap to a map
var _ = require('_'), _regex = require('../../regex'), _cache = require('../../cache'), _isCache = _cache(), Selector = require('./Selector'), _isMatch = require('./match'), _normalizeSelector = require('./normalizeSelector'); var Is = function(str) { str = _normalizeSelector(str); this._selectors = _.map(_regex.selector.commandSplit(str), function(selector) { return new Selector(selector); }); }; Is.prototype = { exec: function(arr) { return _.any(arr, function(elem) { return _isMatch(elem, selector); }); } }; module.exports = function(str) { return _isCache.getOrSet(str, function() { return new Is(str); }); };
var _ = require('_'), _regex = require('../../regex'), _cache = require('../../cache'), _isCache = _cache(), Selector = require('./Selector'), _isMatch = require('./match'), _normalizeSelector = require('./normalizeSelector'); var Is = function(str) { str = _normalizeSelector(str); this._selectors = _.fastmap(_regex.selector.commandSplit(str), function(selector) { return new Selector(selector); }); }; Is.prototype = { exec: function(arr) { return _.any(arr, function(elem) { return _isMatch(elem, selector); }); } }; module.exports = function(str) { return _isCache.getOrSet(str, function() { return new Is(str); }); };
Update partner authorize URL to match changes by Xero
# Public/Private XERO_BASE_URL = "https://api.xero.com" REQUEST_TOKEN_URL = "%s/oauth/RequestToken" % XERO_BASE_URL AUTHORIZE_URL = "%s/oauth/Authorize" % XERO_BASE_URL ACCESS_TOKEN_URL = "%s/oauth/AccessToken" % XERO_BASE_URL XERO_API_URL = "%s/api.xro/2.0" % XERO_BASE_URL # Partner PARTNER_XERO_BASE_URL = "https://api-partner.network.xero.com" PARTNER_REQUEST_TOKEN_URL = "%s/oauth/RequestToken" % PARTNER_XERO_BASE_URL PARTNER_AUTHORIZE_URL = "%s/oauth/Authorize" % PARTNER_XERO_BASE_URL PARTNER_ACCESS_TOKEN_URL = "%s/oauth/AccessToken" % PARTNER_XERO_BASE_URL PARTNER_XERO_API_URL = "%s/api.xro/2.0" % PARTNER_XERO_BASE_URL
# Public/Private XERO_BASE_URL = "https://api.xero.com" REQUEST_TOKEN_URL = "%s/oauth/RequestToken" % XERO_BASE_URL AUTHORIZE_URL = "%s/oauth/Authorize" % XERO_BASE_URL ACCESS_TOKEN_URL = "%s/oauth/AccessToken" % XERO_BASE_URL XERO_API_URL = "%s/api.xro/2.0" % XERO_BASE_URL # Partner PARTNER_XERO_BASE_URL = "https://api-partner.network.xero.com" PARTNER_REQUEST_TOKEN_URL = "%s/oauth/RequestToken" % PARTNER_XERO_BASE_URL PARTNER_AUTHORIZE_URL = AUTHORIZE_URL PARTNER_ACCESS_TOKEN_URL = "%s/oauth/AccessToken" % PARTNER_XERO_BASE_URL PARTNER_XERO_API_URL = "%s/api.xro/2.0" % PARTNER_XERO_BASE_URL
Use setreuid instead of seteuid for compatibility
// +build darwin linux package main import ( "log" "strconv" "syscall" ) var realUid int func init() { sudoUid, ok := syscall.Getenv("SUDO_UID") if ok { var err error realUid, err = strconv.Atoi(sudoUid) if err != nil { log.Fatal("SUDO_UID", err) } } else { realUid = syscall.Getuid() } } func gainRoot(reason string) { e := syscall.Setreuid(-1, 0) if e != nil { log.Fatalf(msgErrGainRoot, e, reason) } debug("euid", syscall.Geteuid()) } func dropRoot() { e := syscall.Setreuid(-1, realUid) if e != nil { log.Fatal(e) } debug("euid", syscall.Geteuid()) }
// +build darwin linux package main import ( "log" "strconv" "syscall" ) var realUid int func init() { sudoUid, ok := syscall.Getenv("SUDO_UID") if ok { var err error realUid, err = strconv.Atoi(sudoUid) if err != nil { log.Fatal("SUDO_UID", err) } } else { realUid = syscall.Getuid() } } func gainRoot(reason string) { e := syscall.Seteuid(0) if e != nil { log.Fatalf(msgErrGainRoot, e, reason) } debug("euid", syscall.Geteuid()) } func dropRoot() { e := syscall.Seteuid(realUid) if e != nil { log.Fatal(e) } debug("euid", syscall.Geteuid()) }
Clean it up a little bit
import { runInContext, createContext } from 'vm'; import { stripIndent } from 'common-tags'; import importFrom from 'import-from'; import Promise from 'bluebird'; function safe(val) { return JSON.stringify(val); } function createScriptBlock(node) { return `;${node.value};` } function createExpressionBlock(node) { return stripIndent` if (true) { const { createContext, runInContext } = require('vm'); const ctx = createContext(module.exports); $print(await runInContext(${safe(node.value)}, ctx)); } `; } function createTextBlock(node) { return `;$print(${safe(node.value)});` } export default function execute(ast, module, dir) { const blocks = ast.map(node => { switch(node.type) { case 'script': return createScriptBlock(node); case 'expression': return createExpressionBlock(node); default: return createTextBlock(node); } }); const code = stripIndent` const $text = []; const $print = data => $text.push(data); const $fn = async () => { ${blocks.join('\n')}; return $text.join('') } $fn(); `; const ctx = createContext({ ...global, require: id => importFrom(dir, id), module: module, exports: module.exports, }); return Promise.resolve(runInContext(code, ctx)); }
import { runInContext, createContext } from 'vm'; import { stripIndent } from 'common-tags'; import importFrom from 'import-from'; import Promise from 'bluebird'; function createScriptBlock(node) { return `;${node.value};` } function createExpressionBlock(node) { return `;$print($eval(${JSON.stringify(node.value)}))`; } function createTextBlock(node) { return `;$print(${JSON.stringify(node.value)});` } export default function execute(ast, module, dir) { const code = stripIndent` const $text = []; const $print = async data => $text.push(await data); const $eval = code => { const vm = require('vm'); const ctx = vm.createContext(module.exports); return vm.runInContext(code, ctx); }; const $fn = async () => { ${ast.map(node => { switch(node.type) { case 'script': return createScriptBlock(node); case 'expression': return createExpressionBlock(node); default: return createTextBlock(node); } }).join('\n')} } $fn().then(() => $text.join('')); `; const ctx = createContext({ ...global, require: id => importFrom(dir, id), module: module, exports: module.exports, }); return Promise.resolve(runInContext(code, ctx)); }
Make it really obvious in the logs if AutoML is enabled.
package water.automl; import water.api.AbstractRegister; import water.api.RequestServer; import water.automl.api.AutoMLBuilderHandler; import water.automl.api.AutoMLHandler; import water.automl.api.AutoMLJSONSchemaHandler; import water.util.Log; public class Register extends AbstractRegister{ @Override public void register(String relativeResourcePath) throws ClassNotFoundException { // H2O.register("POST /3/AutoMLBuilder", AutoMLBuilderHandler.class, "POST", "automl", "automatically build models"); // H2O.register("GET /3/AutoML/{automl_id}", AutoMLHandler.class,"refresh", "GET", "refresh the model key"); // H2O.register("GET /3/AutoMLJSONSchemaHandler", AutoMLJSONSchemaHandler.class, "GET", "getJSONSchema", "Get the json schema for the AutoML input fields."); RequestServer.registerEndpoint("automl_build", "POST /3/AutoMLBuilder", AutoMLBuilderHandler.class, "build", "Start an AutoML build process."); RequestServer.registerEndpoint("automl_refresh", "GET /3/AutoML/{automl_id}", AutoMLHandler.class, "refresh", "Refresh the model key."); RequestServer.registerEndpoint("automl_schema", "GET /3/AutoMLJSONSchemaHandler", AutoMLJSONSchemaHandler.class, "getJSONSchema", "Get the json schema for the AutoML input fields."); Log.info("H2O AutoML extensions enabled."); } }
package water.automl; import water.api.AbstractRegister; import water.api.RequestServer; import water.automl.api.AutoMLBuilderHandler; import water.automl.api.AutoMLHandler; import water.automl.api.AutoMLJSONSchemaHandler; public class Register extends AbstractRegister{ @Override public void register(String relativeResourcePath) throws ClassNotFoundException { // H2O.register("POST /3/AutoMLBuilder", AutoMLBuilderHandler.class, "POST", "automl", "automatically build models"); // H2O.register("GET /3/AutoML/{automl_id}", AutoMLHandler.class,"refresh", "GET", "refresh the model key"); // H2O.register("GET /3/AutoMLJSONSchemaHandler", AutoMLJSONSchemaHandler.class, "GET", "getJSONSchema", "Get the json schema for the AutoML input fields."); RequestServer.registerEndpoint("automl_build", "POST /3/AutoMLBuilder", AutoMLBuilderHandler.class, "build", "Start an AutoML build process."); RequestServer.registerEndpoint("automl_refresh", "GET /3/AutoML/{automl_id}", AutoMLHandler.class, "refresh", "Refresh the model key."); RequestServer.registerEndpoint("automl_schema", "GET /3/AutoMLJSONSchemaHandler", AutoMLJSONSchemaHandler.class, "getJSONSchema", "Get the json schema for the AutoML input fields."); } }
Divide and conquer update JSDoc
"use strict"; let fetch = require('node-fetch'); let Converter = require("csvtojson"); let Promise = require('bluebird'); let _ = require("lodash"); let writeFile = Promise.promisify(require('fs').writeFile); const updateTimestampFile = require("./helpers/update-timestamp-file"); const input = require("./input"); const output = require("./output"); /** * * @param {Array} judges * @param {Array} dictionary * @returns {PromiseLike<*[]>|Promise<*[]>|JQueryPromise<*[]>|JQueryPromise<void>|Promise.<*[]>} */ module.exports = function zipJudges (judges, dictionary) { judges = _.map(judges, (judge) => { return { d: _.get(dictionary, judge.d), // department p: _.get(dictionary, judge.p), // position r: _.get(dictionary, judge.r), // region n: judge.n, // Surname Name Patronymic k: judge.k // key of JSON file under http://prosud.info/declarations/AbdukadirovaKarineEskenderivna.json }; }); var content = JSON.stringify(judges); return updateTimestampFile(output.judges, content) .then(() => writeFile(output.judges, content)) .then(() => judges); };
"use strict"; let fetch = require('node-fetch'); let Converter = require("csvtojson"); let Promise = require('bluebird'); let _ = require("lodash"); let writeFile = Promise.promisify(require('fs').writeFile); const updateTimestampFile = require("./helpers/update-timestamp-file"); const input = require("./input"); const output = require("./output"); /** * * @param {Array} judges * @returns {PromiseLike<*[]>|Promise<*[]>|JQueryPromise<*[]>|JQueryPromise<void>|Promise.<*[]>} */ module.exports = function zipJudges (judges, dictionary) { judges = _.map(judges, (judge) => { return { d: _.get(dictionary, judge.d), // department p: _.get(dictionary, judge.p), // position r: _.get(dictionary, judge.r), // region n: judge.n, // Surname Name Patronymic k: judge.k // key of JSON file under http://prosud.info/declarations/AbdukadirovaKarineEskenderivna.json }; }); var content = JSON.stringify(judges); return updateTimestampFile(output.judges, content) .then(() => writeFile(output.judges, content)) .then(() => judges); };
Adjust '410 Gone' exception in service broker negative tests Tempest-lib 0.12.0 contains necessary code for checking correct exception. This patch replaces 'UnexpectedResponceCode' exception to correct 'Gone' exception. Aslo, this patch add expectedFail for negative test. Change-Id: Ib460b6fc495060a1bd6dd7d0443ff983f8e9f06b Related-Bug: #1527949
# Copyright (c) 2015 Mirantis, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import unittest from tempest import test from tempest_lib import exceptions from murano_tempest_tests.tests.api.service_broker import base from murano_tempest_tests import utils class ServiceBrokerNegativeTest(base.BaseServiceBrokerAdminTest): # NOTE(freerunner): Tempest will fail with this test, because its # _parse_resp function trying to parse a nullable JSON. # https://review.openstack.org/#/c/260659/ # XFail until this one merged and tempest-lib released. @unittest.expectedFailure @test.attr(type=['gate', 'negative']) def test_get_status_with_not_present_instance_id(self): not_present_instance_id = utils.generate_uuid() self.assertRaises( exceptions.Gone, self.service_broker_client.get_last_status, not_present_instance_id)
# Copyright (c) 2015 Mirantis, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import test from tempest_lib import exceptions from murano_tempest_tests.tests.api.service_broker import base from murano_tempest_tests import utils class ServiceBrokerNegativeTest(base.BaseServiceBrokerAdminTest): @test.attr(type=['gate', 'negative']) def test_get_status_with_not_present_instance_id(self): not_present_instance_id = utils.generate_uuid() # TODO(freerunner) Tempest REST client can't catch code 410 yet. # Need to update the test, when tempest-lib will have this code. self.assertRaises( exceptions.UnexpectedResponseCode, self.service_broker_client.get_last_status, not_present_instance_id)
Add _kill_and_join to async actor stub
"""Asynchronous support for garage.threads.actors.""" __all__ = [ 'StubAdapter', ] from garage.asyncs import futures class StubAdapter: """Wrap all method calls, adding FutureAdapter on their result. While this simple adapter does not work for all corner cases, for common cases, it should work fine. """ def __init__(self, stub): super().__setattr__('_stub', stub) def __getattr__(self, name): method = getattr(self._stub, name) # Simple foolproof detection of non-message-sending access if name.startswith('_'): return method return lambda *args, **kwargs: \ futures.FutureAdapter(method(*args, **kwargs)) def _get_future(self): return futures.FutureAdapter(self._stub._get_future()) def _send_message(self, func, args, kwargs): """Enqueue a message into actor's message queue. Since this does not block, it may raise Full when the message queue is full. """ future = self._stub._send_message(func, args, kwargs, block=False) return futures.FutureAdapter(future) async def _kill_and_join(self, graceful=True): self._kill(graceful=graceful) await self._get_future().result()
"""Asynchronous support for garage.threads.actors.""" __all__ = [ 'StubAdapter', ] from garage.asyncs import futures class StubAdapter: """Wrap all method calls, adding FutureAdapter on their result. While this simple adapter does not work for all corner cases, for common cases, it should work fine. """ def __init__(self, stub): super().__setattr__('_stub', stub) def __getattr__(self, name): method = getattr(self._stub, name) # Simple foolproof detection of non-message-sending access if name.startswith('_'): return method return lambda *args, **kwargs: \ futures.FutureAdapter(method(*args, **kwargs)) def _get_future(self): return futures.FutureAdapter(self._stub._get_future()) def _send_message(self, func, args, kwargs): """Enqueue a message into actor's message queue. Since this does not block, it may raise Full when the message queue is full. """ future = self._stub._send_message(func, args, kwargs, block=False) return futures.FutureAdapter(future)
Fix type of complement of
var SetOperatorNode = require("../SetOperatorNode.js"); module.exports = (function () { var o = function (graph) { SetOperatorNode.apply(this, arguments); var that = this; this.styleClass("complementof") .type("owl:complementOf"); this.drawNode = function (element) { that.nodeElement(element); element.append("circle") .attr("class", that.type()) .classed("class", true) .classed("special", true) .attr("r", that.actualRadius()); var symbol = element.append("g").classed("embedded", true); symbol.append("circle") .attr("class", "symbol") .classed("fineline", true) .attr("r", (that.radius() - 15)); symbol.append("path") .attr("class", "nofill") .attr("d", "m -7,-1.5 12,0 0,6"); symbol.attr("transform", "translate(-" + (that.radius() - 15) / 100 + ",-" + (that.radius() - 15) / 100 + ")"); that.postDrawActions(); }; }; o.prototype = Object.create(SetOperatorNode.prototype); o.prototype.constructor = o; return o; }());
var SetOperatorNode = require("../SetOperatorNode.js"); module.exports = (function () { var o = function (graph) { SetOperatorNode.apply(this, arguments); var that = this; this.styleClass("intersectionof") .type("owl:intersectionOf"); this.drawNode = function (element) { that.nodeElement(element); element.append("circle") .attr("class", that.type()) .classed("class", true) .classed("special", true) .attr("r", that.actualRadius()); var symbol = element.append("g").classed("embedded", true); symbol.append("circle") .attr("class", "symbol") .classed("fineline", true) .attr("r", (that.radius() - 15)); symbol.append("path") .attr("class", "nofill") .attr("d", "m -7,-1.5 12,0 0,6"); symbol.attr("transform", "translate(-" + (that.radius() - 15) / 100 + ",-" + (that.radius() - 15) / 100 + ")"); that.postDrawActions(); }; }; o.prototype = Object.create(SetOperatorNode.prototype); o.prototype.constructor = o; return o; }());