text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add all the J* colormaps
import numpy as np import Image import scipy.io as sio def makeImage(cmap, fname): cmarr = (cmap*255).astype(np.uint8) im = Image.fromarray(cmarr[np.newaxis]) im.save(fname) def cmList(additional): cmaps = {} values = np.linspace(0, 1, 256) from matplotlib import cm, colors for cmname in dir(cm): cmap = getattr(cm, cmname) if isinstance(cmap, colors.Colormap): cmaps[cmname] = cmap(values) for name, cmap in additional.items(): cmaps[name] = colors.LinearSegmentedColormap.from_list(name, cmap)(values) return cmaps if __name__ == "__main__": import os import sys path = sys.argv[1] matfile = sio.loadmat("/auto/k2/share/mritools_store/colormaps.mat") del matfile['__globals__'] del matfile['__header__'] del matfile['__version__'] for name, cm in cmList(matfile).items(): fname = os.path.join(path, "%s.png"%name) makeImage(cm, fname)
import numpy as np import Image def makeImage(cmap, fname): cmarr = (cmap*255).astype(np.uint8) im = Image.fromarray(cmarr[np.newaxis]) im.save(fname) def cmList(additional): cmaps = {} values = np.linspace(0, 1, 256) from matplotlib import cm, colors for cmname in dir(cm): cmap = getattr(cm, cmname) if isinstance(cmap, colors.Colormap): cmaps[cmname] = cmap(values) for name, cmap in additional.items(): cmaps[name] = colors.LinearSegmentedColormap.from_list(name, cmap)(values) return cmaps if __name__ == "__main__": import os import sys path = sys.argv[1] matfile = sio.loadmat("/auto/k2/share/mritools_store/colormaps.mat") del matfile['__globals__'] del matfile['__header__'] del matfile['__version__'] for name, cm in cmList(matfile).items(): fname = os.path.join(path, "%s.png"%name) makeImage(cm, fname)
Handle error in case img service is down.
var middleware = require('../middleware'); var Router = require('express').Router(); var request = require('superagent'); const IMG_URL = process.env.IMG_URL || 'http://localhost:9003'; Router.route('/version/api') .get(middleware.authenticate('user', 'guest')) .get(function(req, res) { var version = process.env.VERSION || 'unknown'; version = {"version":version}; return res.json(200, version); }); Router.route('/version/img') .get(middleware.authenticate('user', 'guest')) .get(function(req, res) { var version = {"version":"unknown"}; request.get(IMG_URL+'/version') .end(function(err, response){ try{ version = {"version":response.body.version}; } catch(exception) { version = {"version":"error"}; } return res.json(200, version); }); }); module.exports = Router;
var middleware = require('../middleware'); var Router = require('express').Router(); var request = require('superagent'); const IMG_URL = process.env.IMG_URL || 'http://localhost:9003'; Router.route('/version/api') .get(middleware.authenticate('user', 'guest')) .get(function(req, res) { var version = process.env.VERSION || 'unknown'; version = {"version":version}; return res.json(200, version); }); Router.route('/version/img') .get(middleware.authenticate('user', 'guest')) .get(function(req, res) { var version = {"version":"unknown"}; request.get(IMG_URL+'/version') .end(function(err, response){ version = {"version":response.body.version}; return res.json(200, version); }); }); module.exports = Router;
Add onClick event to space placeLabel
import React, { PropTypes } from 'react'; import DestinationListingCard from '../DestinationListingCard/DestinationListingCard'; import Link from '../../Link/Link'; import css from './SpaceListingCard.css'; const SpaceListingCard = (props) => { const { placeLabel, placeHref, location, size, onPlaceLabelClick, ...rest, } = props; return ( <DestinationListingCard carouselOverlay={ placeLabel && placeHref && ( <Link onPlaceLabelClick={ onPlaceLabelClick } href={ placeHref } className={ css.placeLink } iconClassName={ css.placeLinkIcon } > { placeLabel } </Link> ) } information={ [location, size] } { ...rest } /> ); }; SpaceListingCard.propTypes = { placeLabel: PropTypes.node, placeHref: PropTypes.string, location: PropTypes.node, size: PropTypes.node, price: PropTypes.node, priceUnit: PropTypes.node, onPlaceLabelClick: PropTypes.func, }; export default SpaceListingCard;
import React, { PropTypes } from 'react'; import DestinationListingCard from '../DestinationListingCard/DestinationListingCard'; import Link from '../../Link/Link'; import css from './SpaceListingCard.css'; const SpaceListingCard = (props) => { const { placeLabel, placeHref, location, size, ...rest, } = props; return ( <DestinationListingCard carouselOverlay={ placeLabel && placeHref && ( <Link href={ placeHref } className={ css.placeLink } iconClassName={ css.placeLinkIcon } > { placeLabel } </Link> ) } information={ [location, size] } { ...rest } /> ); }; SpaceListingCard.propTypes = { placeLabel: PropTypes.node, placeHref: PropTypes.string, location: PropTypes.node, size: PropTypes.node, price: PropTypes.node, priceUnit: PropTypes.node, }; export default SpaceListingCard;
Add full post to amp_skip_post filter
<?php function amp_get_permalink( $post_id ) { if ( '' != get_option( 'permalink_structure' ) ) { $amp_url = trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( AMP_QUERY_VAR, 'single_amp' ); } else { $amp_url = add_query_arg( AMP_QUERY_VAR, absint( $post_id ), home_url() ); } return apply_filters( 'amp_get_permalink', $amp_url, $post_id ); } function post_supports_amp( $post ) { // Because `add_rewrite_endpoint` doesn't let us target specific post_types :( if ( ! post_type_supports( $post->post_type, AMP_QUERY_VAR ) ) { return false; } if ( true === apply_filters( 'amp_skip_post', false, $post->ID, $post ) ) { return false; } return true; } /** * Are we currently on an AMP URL? * * Note: will always return `false` if called before the `parse_query` hook. */ function is_amp_endpoint() { return false !== get_query_var( AMP_QUERY_VAR, false ); } function amp_get_asset_url( $file ) { return plugins_url( sprintf( 'assets/%s', $file ), AMP__FILE__ ); }
<?php function amp_get_permalink( $post_id ) { if ( '' != get_option( 'permalink_structure' ) ) { $amp_url = trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( AMP_QUERY_VAR, 'single_amp' ); } else { $amp_url = add_query_arg( AMP_QUERY_VAR, absint( $post_id ), home_url() ); } return apply_filters( 'amp_get_permalink', $amp_url, $post_id ); } function post_supports_amp( $post ) { // Because `add_rewrite_endpoint` doesn't let us target specific post_types :( if ( ! post_type_supports( $post->post_type, AMP_QUERY_VAR ) ) { return false; } if ( true === apply_filters( 'amp_skip_post', false, $post->ID ) ) { return false; } return true; } /** * Are we currently on an AMP URL? * * Note: will always return `false` if called before the `parse_query` hook. */ function is_amp_endpoint() { return false !== get_query_var( AMP_QUERY_VAR, false ); } function amp_get_asset_url( $file ) { return plugins_url( sprintf( 'assets/%s', $file ), AMP__FILE__ ); }
Disable debug mode (so there are no messages written to the javascript console)
jQuery(document).ready(function($){ $('notices_primary').infinitescroll({ debug: false, infiniteScroll : false, nextSelector : 'body#public li.nav_next a,'+ 'body#all li.nav_next a,'+ 'body#showstream li.nav_next a,'+ 'body#replies li.nav_next a,'+ 'body#showfavorites li.nav_next a,'+ 'body#showgroup li.nav_next a,'+ 'body#favorited li.nav_next a', loadingImg : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif', text : "<em>Loading the next set of posts...</em>", donetext : "<em>Congratulations, you\'ve reached the end of the Internet.</em>", navSelector : "div.pagination", contentSelector : "#notices_primary ol.notices", itemSelector : "#notices_primary ol.notices li" },function(){ NoticeAttachments(); NoticeReply(); NoticeFavors(); }); });
jQuery(document).ready(function($){ $('notices_primary').infinitescroll({ debug: true, infiniteScroll : false, nextSelector : 'body#public li.nav_next a,'+ 'body#all li.nav_next a,'+ 'body#showstream li.nav_next a,'+ 'body#replies li.nav_next a,'+ 'body#showfavorites li.nav_next a,'+ 'body#showgroup li.nav_next a,'+ 'body#favorited li.nav_next a', loadingImg : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif', text : "<em>Loading the next set of posts...</em>", donetext : "<em>Congratulations, you\'ve reached the end of the Internet.</em>", navSelector : "div.pagination", contentSelector : "#notices_primary ol.notices", itemSelector : "#notices_primary ol.notices li" },function(){ NoticeAttachments(); NoticeReply(); NoticeFavors(); }); });
Include cmt in installed packages.
from setuptools import setup, find_packages import versioneer def read_requirements(): import os path = os.path.dirname(os.path.abspath(__file__)) requirements_file = os.path.join(path, "requirements.txt") try: with open(requirements_file, "r") as req_fp: requires = req_fp.read().split() except IOError: return [] else: return [require.split() for require in requires] setup( name="pymt", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description="The CSDMS Python Modeling Toolkit", author="Eric Hutton", author_email="huttone@colorado.edu", url="http://csdms.colorado.edu", setup_requires=["setuptools"], packages=find_packages(exclude=("tests*",)), entry_points={"console_scripts": ["cmt-config=cmt.cmd.cmt_config:main"]}, )
from setuptools import setup, find_packages import versioneer def read_requirements(): import os path = os.path.dirname(os.path.abspath(__file__)) requirements_file = os.path.join(path, 'requirements.txt') try: with open(requirements_file, 'r') as req_fp: requires = req_fp.read().split() except IOError: return [] else: return [require.split() for require in requires] setup(name='PyMT', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='The CSDMS Python Modeling Toolkit', author='Eric Hutton', author_email='huttone@colorado.edu', url='http://csdms.colorado.edu', setup_requires=['setuptools', ], packages=find_packages(exclude=("tests*", "cmt")), entry_points={ 'console_scripts': [ 'cmt-config=cmt.cmd.cmt_config:main', ], }, )
Fix bug introduced in merge
/* * Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller * * 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. */ // instances/init.js // Handles discovery and display of Docker host instances var containerController = require('./containerController'), createContainerController = require('./createContainerController'), instanceDetailController = require('./instanceDetailController'), instanceModel = require('./instanceModel'), instanceService = require('./instanceService'); // init angular module var instances = angular.module('lighthouse.instances', []); // register module components instances.controller('containerController', containerController); instances.controller('createContainerController', createContainerController); instances.controller('instanceDetailController', instanceDetailController); instances.factory('instanceService', instanceService); instances.store('instanceModel', instanceModel); module.exports = instances;
/* * Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller * * 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. */ // instances/init.js // Handles discovery and display of Docker host instances var containerController = require('./containerController'), createContainerController = require('./createContainerController'), instanceController = require('./instanceController'), instanceDetailController = require('./instanceDetailController'), instanceModel = require('./instanceModel'), instanceService = require('./instanceService'); // init angular module var instances = angular.module('lighthouse.instances', []); // register module components instances.controller('containerController', containerController); instances.controller('createContainerController', createContainerController); instances.controller('instanceController', instanceController); instances.controller('instanceDetailController', instanceDetailController); instances.factory('instanceService', instanceService); instances.store('instanceModel', instanceModel); module.exports = instances;
Add starting position to the list of visited locations
x = y = direction = 0 moves = open('input.txt', 'r').readline().strip().split(', ') visited = set((0, 0)) for move in moves: if move[0] == 'L': if direction == 0: direction = 3 else: direction -= 1 elif move[0] == 'R': if direction == 3: direction = 0 else: direction += 1 dist = int(''.join(move[1:])) for _ in range(dist): if direction == 0: y -= 1 elif direction == 1: x += 1 elif direction == 2: y += 1 elif direction == 3: x -= 1 if (x, y) in visited: print(abs(x) + abs(y)) input() exit() else: visited.add((x, y))
x = y = direction = 0 moves = open('input.txt', 'r').readline().strip().split(', ') visited = set() for move in moves: if move[0] == 'L': if direction == 0: direction = 3 else: direction -= 1 elif move[0] == 'R': if direction == 3: direction = 0 else: direction += 1 dist = int(''.join(move[1:])) for _ in range(dist): if direction == 0: y -= 1 elif direction == 1: x += 1 elif direction == 2: y += 1 elif direction == 3: x -= 1 if (x, y) in visited: print(abs(x) + abs(y)) input() exit() else: visited.add((x, y))
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-letter-spacing/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-letter-spacing/tachyons-letter-spacing.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_letter-spacing.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/tracking/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/typography/tracking/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-letter-spacing/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-letter-spacing/tachyons-letter-spacing.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_letter-spacing.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/tracking/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/tracking/index.html', html)
Use array_reduce() to generate pipeline of callbacks.
<?php namespace estvoyage\statsd; use estvoyage\statsd\world as statsd ; class packet implements statsd\packet { private $metrics ; function __construct() { $this->metrics = []; } function writeOn(statsd\connection $connection, callable $callback) { $callback = function($connection) use ($callback) { $connection->endPacket($callback); }; $callback = array_reduce($this->metrics, function($callback, $metric) { return function($connection) use ($metric, $callback) { $connection->writeData($metric, $callback); }; }, $callback); $callback = function($connection) use ($callback) { $connection->startPacket($callback); }; $callback($connection); return $this; } function add(statsd\metric $metric, callable $callback) { $packet = clone $this; array_unshift($packet->metrics, $metric); $callback($packet); return $this; } }
<?php namespace estvoyage\statsd; use estvoyage\statsd\world as statsd ; class packet implements statsd\packet { private $metrics ; function __construct() { $this->metrics = []; } function writeOn(statsd\connection $connection, callable $callback) { $callback = function($connection) use ($callback) { $connection->endPacket($callback); }; $metric = end($this->metrics); while ($metric) { $callback = function($connection) use ($metric, $callback) { $connection->writeData($metric, $callback); }; $metric = prev($this->metrics); } $callback = function($connection) use ($callback) { $connection->startPacket($callback); }; $callback($connection); return $this; } function add(statsd\metric $metric, callable $callback) { $packet = clone $this; $packet->metrics[] = $metric; $callback($packet); return $this; } }
Use set to compare list of values
# -*- coding: utf-8 -*- import pytest from junction.feedback import service from .. import factories pytestmark = pytest.mark.django_db def test_get_feedback_questions_without_conference(): result = service.get_feedback_questions(conference_id=23) assert result == {} def test_get_feedback_questions_with_conference(): schedule_item_types = set(['Workshop', 'Talk']) num_choice_questions = 2 num_text_questions = 1 objects = factories.create_feedback_questions( schedule_item_types=schedule_item_types, num_text_questions=num_text_questions, num_choice_questions=num_choice_questions) conference = objects['conference'] result = service.get_feedback_questions(conference_id=conference.id) assert set(result.keys()) == schedule_item_types for item_type in schedule_item_types: assert len(result[item_type]['text']) == num_text_questions assert len(result[item_type]['choice']) == num_choice_questions
# -*- coding: utf-8 -*- import pytest from junction.feedback import service from .. import factories pytestmark = pytest.mark.django_db def test_get_feedback_questions_without_conference(): result = service.get_feedback_questions(conference_id=23) assert result == {} def test_get_feedback_questions_with_conference(): schedule_item_types = ['Workshop', 'Talk'] num_choice_questions = 2 num_text_questions = 1 objects = factories.create_feedback_questions( schedule_item_types=schedule_item_types, num_text_questions=num_text_questions, num_choice_questions=num_choice_questions) conference = objects['conference'] result = service.get_feedback_questions(conference_id=conference.id) assert list(result.keys()) == schedule_item_types for item_type in schedule_item_types: assert len(result[item_type]['text']) == num_text_questions assert len(result[item_type]['choice']) == num_choice_questions
Update text/Welcome.php to match changes in html version The html version of mailer view Welcome.php was updated. This change makes similar changes in the text version.
<?php /* * This file is part of the Dektrium project. * * (c) Dektrium project <http://github.com/dektrium> * * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ /** * @var dektrium\user\models\User */ ?> <?= Yii::t('user', 'Hello') ?>, <?= Yii::t('user', 'Your account on {0} has been created', Yii::$app->name) ?>. <?php if ($module->enableGeneratingPassword): ?> <?= Yii::t('user', 'We have generated a password for you') ?>: <?= $user->password ?> <?php endif ?> <?php if ($token !== null): ?> <?= Yii::t('user', 'In order to complete your registration, please click the link below') ?>. <?= $token->url ?> <?= Yii::t('user', 'If you cannot click the link, please try pasting the text into your browser') ?>. <?php endif ?> <?= Yii::t('user', 'If you did not make this request you can ignore this email') ?>.
<?php /* * This file is part of the Dektrium project. * * (c) Dektrium project <http://github.com/dektrium> * * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ /** * @var dektrium\user\models\User */ ?> <?= Yii::t('user', 'Hello') ?>, <?= Yii::t('user', 'Your account on {0} has been created', Yii::$app->name) ?>. <?= Yii::t('user', 'You can now log in with the following credentials:') ?>. <?= Yii::t('user', 'Email') ?>: <?= $user->email ?> <?= Yii::t('user', 'Username') ?>: <?= $user->username ?> <?= Yii::t('user', 'Password') ?>: <?= $user->password ?> <?= Yii::t('user', 'If you did not make this request you can ignore this email') ?>.
Formatting: Replace double quotes with single quotes
(function() { 'use strict'; angular.module('angular.jsgrid', []) .directive('ngJsgrid', function() { return { restrict: 'A', replace: false, transclude: false, scope: { config: '=ngJsgrid' }, link: function(scope, $element, attrs) { $element.jsGrid(scope.config); $.each(scope.config, function(key) { scope.$watch('config.' + key, function(value) { $element.jsGrid('option', key, value); }); }); } }; }); })();
(function() { "use strict"; angular.module("angular.jsgrid", []) .directive("ngJsgrid", function() { return { restrict: "A", replace: false, transclude: false, scope: { config: "=ngJsgrid" }, link: function(scope, $element, attrs) { $element.jsGrid(scope.config); $.each(scope.config, function(key) { scope.$watch("config." + key, function(value) { $element.jsGrid("option", key, value); }); }); } }; }); })();
Add Constant for Loging request (used with startActivityForResult)
package com.simplenote.android; public class Constants { /** Name of stored preferences */ public static final String PREFS_NAME = "SimpleNotePrefs"; /** Logging tag prefix */ public static final String TAG = "SimpleNote:"; // Message Codes public static final int MESSAGE_UPDATE_NOTE = 12398; // Activity for result request Codes public static final int REQUEST_LOGIN = 32568; // API Base URL public static final String API_BASE_URL = "https://simple-note.appspot.com/api"; public static final String API_LOGIN_URL = API_BASE_URL + "/login"; // POST public static final String API_NOTES_URL = API_BASE_URL + "/index"; // GET public static final String API_NOTE_URL = API_BASE_URL + "/note"; // GET public static final String API_UPDATE_URL = API_BASE_URL + "/note"; // POST public static final String API_DELETE_URL = API_BASE_URL + "/delete"; // GET public static final String API_SEARCH_URL = API_BASE_URL + "/search"; // GET }
package com.simplenote.android; public class Constants { /** Name of stored preferences */ public static final String PREFS_NAME = "SimpleNotePrefs"; /** Logging tag prefix */ public static final String TAG = "SimpleNote:"; // Message Codes public static final int MESSAGE_UPDATE_NOTE = 12398; // API Base URL public static final String API_BASE_URL = "https://simple-note.appspot.com/api"; public static final String API_LOGIN_URL = API_BASE_URL + "/login"; // POST public static final String API_NOTES_URL = API_BASE_URL + "/index"; // GET public static final String API_NOTE_URL = API_BASE_URL + "/note"; // GET public static final String API_UPDATE_URL = API_BASE_URL + "/note"; // POST public static final String API_DELETE_URL = API_BASE_URL + "/delete"; // GET public static final String API_SEARCH_URL = API_BASE_URL + "/search"; // GET }
Fix Flyway dev console link
package io.quarkus.flyway.devconsole; import static io.quarkus.deployment.annotations.ExecutionTime.RUNTIME_INIT; import io.quarkus.deployment.IsDevelopment; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.Record; import io.quarkus.devconsole.spi.DevConsoleRouteBuildItem; import io.quarkus.devconsole.spi.DevConsoleRuntimeTemplateInfoBuildItem; import io.quarkus.flyway.runtime.FlywayContainersSupplier; import io.quarkus.flyway.runtime.devconsole.FlywayDevConsoleRecorder; public class DevConsoleProcessor { @BuildStep(onlyIf = IsDevelopment.class) public DevConsoleRuntimeTemplateInfoBuildItem collectBeanInfo() { return new DevConsoleRuntimeTemplateInfoBuildItem("containers", new FlywayContainersSupplier()); } @BuildStep @Record(value = RUNTIME_INIT, optional = true) DevConsoleRouteBuildItem invokeEndpoint(FlywayDevConsoleRecorder recorder) { return new DevConsoleRouteBuildItem("datasources", "POST", recorder.handler()); } }
package io.quarkus.flyway.devconsole; import static io.quarkus.deployment.annotations.ExecutionTime.RUNTIME_INIT; import io.quarkus.deployment.IsDevelopment; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.Record; import io.quarkus.devconsole.spi.DevConsoleRouteBuildItem; import io.quarkus.devconsole.spi.DevConsoleRuntimeTemplateInfoBuildItem; import io.quarkus.flyway.runtime.FlywayContainersSupplier; import io.quarkus.flyway.runtime.devconsole.FlywayDevConsoleRecorder; public class DevConsoleProcessor { @BuildStep(onlyIf = IsDevelopment.class) public DevConsoleRuntimeTemplateInfoBuildItem collectBeanInfo() { return new DevConsoleRuntimeTemplateInfoBuildItem("containers", new FlywayContainersSupplier()); } @BuildStep @Record(value = RUNTIME_INIT, optional = true) DevConsoleRouteBuildItem invokeEndpoint(FlywayDevConsoleRecorder recorder) { return new DevConsoleRouteBuildItem("containers", "POST", recorder.handler()); } }
Fix unit test fixtures files
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() def tearDown(self): shutil.rmtree('media/photos') from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() def tearDown(self): shutil.rmtree('media-tmp/photos') from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
Fix error / keyboard side effect because of problem between the chair and the keyboard
/* * Copyright (C)2015 D. Plaindoux. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2, 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.smallibs.suitcase.cases.genlex; public class UnexpectedCharException extends Exception { public UnexpectedCharException(int index, char c) { super("char <" + c + "> at position <" + index + ">"); } }
/* * Copyright (C)2015 D. Plaindoux. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2, 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.smallibs.suitcase.cases.genlex; public class UnexpectedCharException extends Exception { public UnexpectedCharException(int index, char c) { sper("char <" + c + "> at position <" + index + ">"); } }
Fix import of common module
#!/usr/bin/env python def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': # HACK HACK HACK # Put Python script dir at the end, as script and module clash :-( import sys sys.path = sys.path[1:] + [sys.path[0]] main()
#!/usr/bin/env python def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': main()
Change cloudify-plugin-common version back to 3.2a6
######### # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. from setuptools import setup setup( zip_safe=True, name='cloudify-vcloud-plugin', version='1.2m6', packages=[ 'vcloud_plugin_common', 'server_plugin', 'network_plugin' ], license='LICENSE', description='Cloudify plugin for vmWare vCloud infrastructure.', install_requires=[ 'cloudify-plugins-common==3.2a6', 'pyvcloud==12c2', 'requests==2.4.3', 'IPy==0.81' ] )
######### # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. from setuptools import setup setup( zip_safe=True, name='cloudify-vcloud-plugin', version='1.2m6', packages=[ 'vcloud_plugin_common', 'server_plugin', 'network_plugin' ], license='LICENSE', description='Cloudify plugin for vmWare vCloud infrastructure.', install_requires=[ 'cloudify-plugins-common==3.2a7', 'pyvcloud==12c2', 'requests==2.4.3', 'IPy==0.81' ] )
Fix group by for mysql 5.7
<?php namespace Mja\Mail\Controllers; use BackendMenu; use Backend\Classes\Controller; use Mja\Mail\Models\Email; use Mja\Mail\Models\EmailOpens; /** * Back-end Controller */ class Mail extends Controller { public $hide_hints = false; public $implement = [ 'Backend.Behaviors.FormController', 'Backend.Behaviors.ListController', 'Backend.Behaviors.RelationController', ]; public $formConfig = 'config_form.yaml'; public $listConfig = 'config_list.yaml'; public $relationConfig = 'config_relation.yaml'; public $requiredPermissions = ['mja.mail.mail']; public $bodyClass = 'compact-container'; /** * Ensure that by default our menu sidebar is active */ public function __construct() { parent::__construct(); BackendMenu::setContext('Mja.Mail', 'mail', 'mail'); } public function index() { $this->vars['opens'] = EmailOpens::count(); $this->vars['sent'] = Email::whereSent(true)->count(); $this->vars['bounced'] = Email::whereSent(false)->count(); $this->vars['emails'] = Email::select('code')->groupBy('code')->get(); $this->asExtension('ListController')->index(); } }
<?php namespace Mja\Mail\Controllers; use BackendMenu; use Backend\Classes\Controller; use Mja\Mail\Models\Email; use Mja\Mail\Models\EmailOpens; /** * Back-end Controller */ class Mail extends Controller { public $hide_hints = false; public $implement = [ 'Backend.Behaviors.FormController', 'Backend.Behaviors.ListController', 'Backend.Behaviors.RelationController', ]; public $formConfig = 'config_form.yaml'; public $listConfig = 'config_list.yaml'; public $relationConfig = 'config_relation.yaml'; public $requiredPermissions = ['mja.mail.mail']; public $bodyClass = 'compact-container'; /** * Ensure that by default our menu sidebar is active */ public function __construct() { parent::__construct(); BackendMenu::setContext('Mja.Mail', 'mail', 'mail'); } public function index() { $this->vars['opens'] = EmailOpens::count(); $this->vars['sent'] = Email::whereSent(true)->count(); $this->vars['bounced'] = Email::whereSent(false)->count(); $this->vars['emails'] = Email::groupBy('code')->get(); $this->asExtension('ListController')->index(); } }
Add no-trailing-spaces rule to eslint. Change-Id: I00d938706613b041b2896f40f70edf71c3f943d1
module.exports = { extends: ['eslint:recommended', 'google'], env: { es6: true, node: true, mocha: true, }, parserOptions: { ecmaVersion: 2018, sourceType: 'script', }, rules: { 'indent': [ 'error', 2, {'MemberExpression': 2}, ], 'max-len': ['error', 80, { ignoreStrings: true, ignoreUrls: true, }], 'prefer-const': 'error', 'prefer-arrow-callback': 'error', 'arrow-body-style': ['error', 'as-needed'], // TODO: enable once go/github-eslint/issues/9949 is fixed 'valid-jsdoc': 'off', 'sort-requires/sort-requires': 2, 'space-infix-ops': ['error', {'int32Hint': false}], 'no-trailing-spaces': 'error', }, plugins: [ 'sort-requires' ] };
module.exports = { extends: ['eslint:recommended', 'google'], env: { es6: true, node: true, mocha: true, }, parserOptions: { ecmaVersion: 2018, sourceType: 'script', }, rules: { 'indent': [ 'error', 2, {'MemberExpression': 2}, ], 'max-len': ['error', 80, { ignoreStrings: true, ignoreUrls: true, }], 'prefer-const': 'error', 'prefer-arrow-callback': 'error', 'arrow-body-style': ['error', 'as-needed'], // TODO: enable once go/github-eslint/issues/9949 is fixed 'valid-jsdoc': 'off', 'sort-requires/sort-requires': 2, "space-infix-ops": ["error", {"int32Hint": false}], }, plugins: [ 'sort-requires' ] };
Correct controller for person look up (for type ahead). It returns the full list of objects matching the person
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.org.rbc1b.roms.controller.person; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import uk.org.rbc1b.roms.db.Person; /** * Control access to the underlying person data. * * @author oliver */ @Controller @RequestMapping("/persons") public class PersonsController { @Autowired private PersonDao personDao; /** * Person search. Pass in a candidate, match this against the user * first/last name and return the person object in JSON format * * @param query person match lookup * @return model containing the list of people */ @RequestMapping(value = "search", method = RequestMethod.GET, headers = "Accept=application/json") //@PreAuthorize - not clear who will not be allowed to access @Transactional(readOnly = true) @ResponseBody public List<Person> handleList(@RequestParam String query) { return personDao.findPersons(query); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.org.rbc1b.roms.controller.person; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import uk.org.rbc1b.roms.db.Person; /** * Control access to the underlying person data. * * @author oliver */ @Controller @RequestMapping("/persons") public class PersonsController { @Autowired private PersonDao personDao; /** * Person search. Pass in a candidate, match this against the user * first/last name and return the person object in JSON format * * @param query person match lookup * @return model containing the list of qualifications */ @RequestMapping(value = "search", method = RequestMethod.GET, headers = "Accept=application/json") //@PreAuthorize - not clear who will not be allowed to access @Transactional(readOnly = true) public List<Person> handleList(@PathVariable String query) { return personDao.findPersons(query); } }
Fix name attribute in impuestos locales
<?php namespace CfdiUtils\Elements\ImpLocal10; use CfdiUtils\Elements\Common\AbstractElement; class ImpuestosLocales extends AbstractElement { public function addRetencionLocal(array $attributes = []): RetencionesLocales { $retencion = new RetencionesLocales($attributes); $this->addChild($retencion); return $retencion; } public function addTrasladoLocal(array $attributes = []): TrasladosLocales { $traslado = new TrasladosLocales($attributes); $this->addChild($traslado); return $traslado; } public function getElementName(): string { return 'implocal:ImpuestosLocales'; } public function getChildrenOrder(): array { return ['implocal:RetencionesLocales', 'implocal:TrasladosLocales']; } public function getFixedAttributes(): array { return [ 'xmlns:implocal' => 'http://www.sat.gob.mx/implocal', 'xsi:schemaLocation' => 'http://www.sat.gob.mx/implocal' . ' http://www.sat.gob.mx/sitio_internet/cfd/implocal/implocal.xsd', 'version' => '1.0', ]; } }
<?php namespace CfdiUtils\Elements\ImpLocal10; use CfdiUtils\Elements\Common\AbstractElement; class ImpuestosLocales extends AbstractElement { public function addRetencionLocal(array $attributes = []): RetencionesLocales { $retencion = new RetencionesLocales($attributes); $this->addChild($retencion); return $retencion; } public function addTrasladoLocal(array $attributes = []): TrasladosLocales { $traslado = new TrasladosLocales($attributes); $this->addChild($traslado); return $traslado; } public function getElementName(): string { return 'implocal:ImpuestosLocales'; } public function getChildrenOrder(): array { return ['implocal:RetencionesLocales', 'implocal:TrasladosLocales']; } public function getFixedAttributes(): array { return [ 'xmlns:implocal' => 'http://www.sat.gob.mx/implocal', 'xsi:schemaLocation' => 'http://www.sat.gob.mx/implocal' . ' http://www.sat.gob.mx/sitio_internet/cfd/implocal/implocal.xsd', 'Version' => '1.0', ]; } }
Add method to launch a Runnable in a new thread
package org.jtheque.utils; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /* * Copyright JTheque (Baptiste Wicht) * * 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. */ public class ThreadUtils { private static final int PROCESSORS = Runtime.getRuntime().availableProcessors(); public static int processors(){ return PROCESSORS; } public static void inNewThread(Runnable runnable){ ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(runnable); executor.shutdown(); } public static void joinAll(Iterable<Thread> threads) { for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { LoggerFactory.getLogger(ThreadUtils.class).error(e.getMessage(), e); } } } }
package org.jtheque.utils; import org.slf4j.LoggerFactory; /* * Copyright JTheque (Baptiste Wicht) * * 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. */ public class ThreadUtils { private static final int PROCESSORS = Runtime.getRuntime().availableProcessors(); public static int processors(){ return PROCESSORS; } public static void joinAll(Iterable<Thread> threads) { for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { LoggerFactory.getLogger(ThreadUtils.class).error(e.getMessage(), e); } } } }
Add code for collisions (untested)
import { translate, rand, vLog, objToArr, getR, massToRadius, filterClose, vectorToString } from './VectorHelpers'; import { GRAVITY, PLANET_SPRING } from './Constants'; const getGravityAccel = (vR, mass) => { const rMag2 = vR.lengthSq(); const rNorm = vR.normalize(); return rNorm.multiplyScalar(GRAVITY * mass / rMag2); }; const getCollisionAccel = (vR, m1, r1, r2) => { return new THREE.Vector3(vR).normalize().multiplyScalar(PLANET_SPRING / m1 * (vR.length() - (r1 + r2))); }; const getNetAccel = (originBody, otherBodies) => { return otherBodies.reduce((netAccel, otherBody) => { const vR = getR(originBody, otherBody); if (vR.length() < originBody.radius + otherBody.radius) { netAccel.add(getCollisionAccel(vR, originBody.mass, originBody.radius, otherBody.radius)); } return netAccel.add(getGravityAccel(vR, otherBody.mass)); }, new THREE.Vector3()); }; export { getNetAccel, }
import { translate, rand, vLog, objToArr, getR, massToRadius, filterClose, vectorToString } from './VectorHelpers'; import { GRAVITY, PLANET_SPRING } from './Constants'; const getGravityAccel = (vR, mass) => { const rMag2 = vR.lengthSq(); const rNorm = vR.normalize(); const accel = rNorm.multiplyScalar(GRAVITY * mass / rMag2); return accel; }; // const getCollisionAccel = (vR, m1, r1, r2) => { // return vr.normalize().multiplyScalar(PLANET_SPRING / m1 * (vr.length() - (r1 + r2))); // }; const getNetAccel = (originBody, otherBodies) => { let netAccel = new THREE.Vector3(); let vR; for (var i = 0; i < otherBodies.length; i++) { vR = getR(originBody, otherBodies[i]); netAccel.add(getGravityAccel(vR, otherBodies[i].mass)) } return netAccel; }; export { getNetAccel, }
Remove password from editable fields
<div class="wrapper"> <div class="content profile-content"> <div id="body"> <div id="add-video"> <p class="logo">Edit profile</p> <form method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="title">Username</label> <input type="text" class="form-control" name="username" value="{{ $user->username }}" placeholder="username"> </div> <div class="form-group"> <label for="title">Email</label> <input type="email" class="form-control" name="email" value="{{ $user->email }}" placeholder="Email"> </div> <div class="form-group"> <label for="title">Avatar</label> <input type="file" id="file" class="" name="avatar"> </div> <input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" /> <button type="submit" name="update" class="btn btn-large btn-success">Save</button> </form>
<div class="wrapper"> <div class="content profile-content"> <div id="body"> <div id="add-video"> <p class="logo">Edit profile</p> <form method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="title">Username</label> <input type="text" class="form-control" name="username" value="{{ $user->username }}" placeholder="username"> </div> <div class="form-group"> <label for="title">Email</label> <input type="email" class="form-control" name="email" value="{{ $user->email }}" placeholder="Email"> </div> <div class="form-group"> <label for="title">Password</label> <input type="password" class="form-control" name="password" placeholder="password"> </div> <div class="form-group"> <label for="title">Avatar</label> <input type="file" id="file" class="" name="avatar"> </div> <input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" /> <button type="submit" name="update" class="btn btn-large btn-success">Save</button> </form>
Correct support for ngl NPM commands
'use strict'; const spawn = require('child_process').spawn; module.exports = function (rootDir, type) { const args = Array.from(arguments).slice(2); const cmd = /^win/.test(process.platform) ? 'npm.cmd' : 'npm'; spawn(cmd, ['run'].concat(getNpmCommand(type, args)), { stdio: 'inherit' }); }; const getNpmCommand = (command, args) => { switch (command) { case 'b': case 'build': return 'build'; case 'l': case 'lint': return 'lint'; case 'p': case 'publish': return ['tagVersion'].concat(args); case 'v': case 'serve': return 'start'; case 't': case 'test': return ['test'].concat(args); default: return ''; }; }
'use strict'; const spawn = require('child_process').spawn; module.exports = function (rootDir, type) { const args = Array.from(arguments).slice(2); spawn('npm', ['run'].concat(getNpmCommand(type, args)), { stdio: 'inherit' }); }; const getNpmCommand = (command, args) => { switch (command) { case 'b': case 'build': return 'build'; case 'l': case 'lint': return 'lint'; case 'p': case 'publish': return ['tagVersion'].concat(args); case 'v': case 'serve': return 'start'; case 't': case 'test': return ['test'].concat(args); default: return ''; }; }
Add missing file level doc-block
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Config; use Zend\ServiceManager\AbstractPluginManager; class WriterPluginManager extends AbstractPluginManager { protected $invokableClasses = array( 'php' => 'Zend\Config\Writer\PhpArray', 'ini' => 'Zend\Config\Writer\Ini', 'json' => 'Zend\Config\Writer\Json', 'yaml' => 'Zend\Config\Writer\Yaml', 'xml' => 'Zend\Config\Writer\Xml', ); public function validatePlugin($plugin) { if ($plugin instanceOf Writer\AbstractWriter) { return; } $type = is_object($plugin) ? get_class($plugin) : gettype($plugin); throw new Exception\InvalidArgumentException( "Plugin of type {$type} is invalid. Plugin must extend ". __NAMESPACE__.'\Writer\AbstractWriter' ); } }
<?php namespace Zend\Config; use Zend\ServiceManager\AbstractPluginManager; class WriterPluginManager extends AbstractPluginManager { protected $invokableClasses = array( 'php' => 'Zend\Config\Writer\PhpArray', 'ini' => 'Zend\Config\Writer\Ini', 'json' => 'Zend\Config\Writer\Json', 'yaml' => 'Zend\Config\Writer\Yaml', 'xml' => 'Zend\Config\Writer\Xml', ); public function validatePlugin($plugin) { if ($plugin instanceOf Writer\AbstractWriter) { return; } $type = is_object($plugin) ? get_class($plugin) : gettype($plugin); throw new Exception\InvalidArgumentException( "Plugin of type {$type} is invalid. Plugin must extend ". __NAMESPACE__.'\Writer\AbstractWriter' ); } }
Add more responsiveness for user without organizations
var description = d3.select("#text") .html("<b>Title: </b><br/><b>Number: </b><br/><b>Body: </b><br/><b>ID: </b><br/><b>Assignee: </b><br/><b>Milestone: </b><br/><b>Repo: </b>"); $.getJSON("orgs.json") .done(function (data, textStatus, jqXHR) { var orgs = data; render(orgs); }) .fail(); var render = function (orgs) { document.getElementById('user').addEventListener("click", function userClick(){ document.getElementById('orgdrop').disabled = "true"; document.getElementById('publictext').disabled = "true"; }, false); document.getElementById('public').addEventListener("click", function pubClick(){ document.getElementById('publictext').disabled = null; document.getElementById('orgdrop').disabled = "true"; }, false); if (orgs.length !== 0){ document.getElementById('org').addEventListener("click", function orgClick(){ document.getElementById('orgdrop').disabled = null; document.getElementById('publictext').disabled = "true"; }, false); orgs.forEach(function (org) { d3.select('select').append('option').append('text').text(org); }); } else { document.getElementById('org').disabled = "true"; d3.select('select').append('option').append('text').text("User has no Orgs"); } };
var description = d3.select("#text") .html("<b>Title: </b><br/><b>Number: </b><br/><b>Body: </b><br/><b>ID: </b><br/><b>Assignee: </b><br/><b>Milestone: </b><br/><b>Repo: </b>"); $.getJSON("orgs.json") .done(function (data, textStatus, jqXHR) { var orgs = data; render(orgs); }) .fail(); var render = function (orgs) { document.getElementById('user').addEventListener("click", userClick, false); function userClick(){ document.getElementById('orgdrop').disabled = "true"; document.getElementById('publictext').disabled = "true"; } document.getElementById('org').addEventListener("click", orgClick, false); function orgClick(){ document.getElementById('orgdrop').disabled = null; document.getElementById('publictext').disabled = "true"; } document.getElementById('public').addEventListener("click", pubClick, false); function pubClick(){ document.getElementById('publictext').disabled = null; document.getElementById('orgdrop').disabled = "true"; } orgs.forEach(function (org) { d3.select('select').append('option').append('text').text(org); }); };
Change version for next release
# # markdown/__version__.py # # version_info should conform to PEP 386 # (major, minor, micro, alpha/beta/rc/final, #) # (1, 1, 2, 'alpha', 0) => "1.1.2.dev" # (1, 2, 0, 'beta', 2) => "1.2b2" version_info = (2, 6, 0, 'zds', 8) def _get_version(): " Returns a PEP 386-compliant version number from version_info. " assert len(version_info) == 5 assert version_info[3] in ('alpha', 'beta', 'rc', 'final', 'zds') parts = 2 if version_info[2] == 0 else 3 main = '.'.join(map(str, version_info[:parts])) sub = '' if version_info[3] == 'alpha' and version_info[4] == 0: # TODO: maybe append some sort of git info here?? sub = '.dev' elif version_info[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c', 'zds': 'post'} sub = mapping[version_info[3]] + str(version_info[4]) return str(main + sub) version = _get_version()
# # markdown/__version__.py # # version_info should conform to PEP 386 # (major, minor, micro, alpha/beta/rc/final, #) # (1, 1, 2, 'alpha', 0) => "1.1.2.dev" # (1, 2, 0, 'beta', 2) => "1.2b2" version_info = (2, 6, 0, 'zds', 7) def _get_version(): " Returns a PEP 386-compliant version number from version_info. " assert len(version_info) == 5 assert version_info[3] in ('alpha', 'beta', 'rc', 'final', 'zds') parts = 2 if version_info[2] == 0 else 3 main = '.'.join(map(str, version_info[:parts])) sub = '' if version_info[3] == 'alpha' and version_info[4] == 0: # TODO: maybe append some sort of git info here?? sub = '.dev' elif version_info[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c', 'zds': 'post'} sub = mapping[version_info[3]] + str(version_info[4]) return str(main + sub) version = _get_version()
Install this the right way
'use strict'; // Declare app level module which depends on filters, and services var app = angular.module( 'myApp', [ 'ngRoute', 'myApp.controllers', 'myApp.filters', 'myApp.services', 'myApp.directives', // 3rd party dependencies 'btford.socket-io', 'fully-loaded' ] ); app.config( function ( $routeProvider, $locationProvider ) { $routeProvider. when( '/home', { templateUrl: 'partials/home', controller: 'HomeCtrl' } ). when( '/artist/:artistURI', { templateUrl: 'partials/artist', controller: 'ArtistCtrl' } ). when( '/album/:albumURI', { templateUrl: 'partials/album', controller: 'AlbumCtrl' } ). otherwise( { redirectTo: '/home' } ); $locationProvider.html5Mode( true ); });
'use strict'; // Declare app level module which depends on filters, and services var app = angular.module( 'myApp', [ 'ngRoute', 'myApp.controllers', 'myApp.filters', 'myApp.services', 'myApp.directives', // 3rd party dependencies 'btford.socket-io' ] ); app.config( function ( $routeProvider, $locationProvider ) { $routeProvider. when( '/home', { templateUrl: 'partials/home', controller: 'HomeCtrl' } ). when( '/artist/:artistURI', { templateUrl: 'partials/artist', controller: 'ArtistCtrl' } ). when( '/album/:albumURI', { templateUrl: 'partials/album', controller: 'AlbumCtrl' } ). otherwise( { redirectTo: '/home' } ); $locationProvider.html5Mode( true ); });
Fix unchanged function name for gitPull
/* @method gitPull Takes a flightplan instance and transport @param remote {Object} Flightplan transport instance @param webRoot {string} path to run git pull on the remote server e.g. /var/www/project */ var gitPull = function (remote, webRoot) { // git pull remote.with('cd ' + webRoot, function() { remote.exec('git pull'); }); }; /* @method addToPlan Takes a flightplan instance and adds a task called gitDeploy @param plan {Object} Flightplan instance @param plan.runtime.options.webRoot {String} Remote path to run git pull */ var addToPlan = function (plan) { // Plan to git deploy via ssh remote var webRoot = plan.runtime.options.webRoot; plan.remote('gitDeploy', function(remote) { gitPull(remote, webRoot); }); }; module.exports = { addToPlan: addToPlan, gitPull: gitPull };
/* @method gitPull Takes a flightplan instance and transport @param remote {Object} Flightplan transport instance @param webRoot {string} path to run git pull on the remote server e.g. /var/www/project */ var gitPull = function (remote, webRoot) { // git pull remote.with('cd ' + webRoot, function() { remote.exec('git pull'); }); }; /* @method addToPlan Takes a flightplan instance and adds a task called gitDeploy @param plan {Object} Flightplan instance @param plan.runtime.options.webRoot {String} Remote path to run git pull */ var addToPlan = function (plan) { // Plan to git deploy via ssh remote var webRoot = plan.runtime.options.webRoot; plan.remote('gitDeploy', function(remote) { remoteGitDeploy(remote, webRoot); }); }; module.exports = { addToPlan: addToPlan, remoteGitDeploy: remoteGitDeploy };
Add method to get admin users.
module.exports = function(r) { 'use strict'; return { allByProject: allByProject, adminUsers: adminUsers, }; function allByProject() { return r.table('access').run().then(function(allAccess) { let byProject = {}; allAccess.forEach(function(a) { if (!(a.project_id in byProject)) { byProject[a.project_id] = []; } byProject[a.project_id].push(a); }); return byProject; }); } function adminUsers() { return r.table('users').filter({admin: true}).run(); } };
module.exports = function(r) { 'use strict'; return { allByProject: allByProject }; function allByProject() { return r.table('access').run().then(function(allAccess) { let byProject = {}; allAccess.forEach(function(a) { if (!(a.project_id in byProject)) { byProject[a.project_id] = []; } byProject[a.project_id].push(a); }); return byProject; }); } };
Make map property of ol.MapEvent exportable
goog.provide('ol.MapEvent'); goog.provide('ol.MapEventType'); goog.require('goog.events.Event'); /** * @enum {string} */ ol.MapEventType = { /** * Triggered after a map frame is rendered. * @event ol.MapEvent#postrender * @todo api */ POSTRENDER: 'postrender', /** * Triggered after the map is moved. * @event ol.MapEvent#moveend * @todo api */ MOVEEND: 'moveend' }; /** * @constructor * @extends {goog.events.Event} * @implements {oli.MapEvent} * @param {string} type Event type. * @param {ol.Map} map Map. * @param {?olx.FrameState=} opt_frameState Frame state. */ ol.MapEvent = function(type, map, opt_frameState) { goog.base(this, type); /** * The map where the event occurred. * @type {ol.Map} * @todo api */ this.map = map; /** * @type {?olx.FrameState} */ this.frameState = goog.isDef(opt_frameState) ? opt_frameState : null; }; goog.inherits(ol.MapEvent, goog.events.Event);
goog.provide('ol.MapEvent'); goog.provide('ol.MapEventType'); goog.require('goog.events.Event'); /** * @enum {string} */ ol.MapEventType = { /** * Triggered after a map frame is rendered. * @event ol.MapEvent#postrender * @todo api */ POSTRENDER: 'postrender', /** * Triggered after the map is moved. * @event ol.MapEvent#moveend * @todo api */ MOVEEND: 'moveend' }; /** * @constructor * @extends {goog.events.Event} * @implements {oli.MapEvent} * @param {string} type Event type. * @param {ol.Map} map Map. * @param {?olx.FrameState=} opt_frameState Frame state. */ ol.MapEvent = function(type, map, opt_frameState) { goog.base(this, type); /** * @type {ol.Map} */ this.map = map; /** * @type {?olx.FrameState} */ this.frameState = goog.isDef(opt_frameState) ? opt_frameState : null; }; goog.inherits(ol.MapEvent, goog.events.Event);
Update up to changes in event-emitter package
'use strict'; var noop = require('es5-ext/function/noop') , assign = require('es5-ext/object/assign') , memoize = require('memoizee') , ee = require('event-emitter') , eePipe = require('event-emitter/pipe') , deferred = require('deferred') , isPromise = deferred.isPromise; module.exports = function (fn/*, options*/) { var factory, memoized; if (fn.memoized) return fn; memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true })); factory = function () { var watcher, emitter, pipe, args, def; args = arguments; watcher = memoized.apply(this, arguments); if (isPromise(watcher)) { def = deferred(); emitter = def.promise; def.resolve(watcher); } else { emitter = ee(); } pipe = eePipe(watcher, emitter); emitter.close = function () { emitter.close = noop; pipe.close(); if (memoized.clearRef.apply(this, args)) watcher.close(); }; return emitter; }; factory.clear = memoized.clear; factory.memoized = true; return factory; };
'use strict'; var noop = require('es5-ext/function/noop') , assign = require('es5-ext/object/assign') , memoize = require('memoizee') , ee = require('event-emitter') , eePipe = require('event-emitter/lib/pipe') , deferred = require('deferred') , isPromise = deferred.isPromise; module.exports = function (fn/*, options*/) { var factory, memoized; if (fn.memoized) return fn; memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true })); factory = function () { var watcher, emitter, pipe, args, def; args = arguments; watcher = memoized.apply(this, arguments); if (isPromise(watcher)) { def = deferred(); emitter = def.promise; def.resolve(watcher); } else { emitter = ee(); } pipe = eePipe(watcher, emitter); emitter.close = function () { emitter.close = noop; pipe.close(); if (memoized.clearRef.apply(this, args)) watcher.close(); }; return emitter; }; factory.clear = memoized.clear; factory.memoized = true; return factory; };
Add test change for release
#!/usr/bin/env node const inquirer = require('inquirer') const Listr = require('listr') const steps = [{ type: 'input', name: 'userName', message: 'Whats your name?' }] const tasks = [{ title: 'Preparing', task: (context, task) => new Promise((resolve, reject) => { setTimeout(() => resolve(), 1000) }) },{ title: 'Ask for name', task: (context, task) => new Promise((resolve, reject) => { task.output = 'Starting' setTimeout(() => { task.output = 'Calculating' resolve() }, 500) // setTimeout(() => { // }, 2000) }) }] // Test change for release // Test change for release const listrObject = new Listr(tasks) listrObject.run().then(res => { inquirer .prompt(steps).then(output => { console.log( 'Hello', output.userName ) }).catch(err => console.log(err)) })
#!/usr/bin/env node const inquirer = require('inquirer') const Listr = require('listr') const steps = [{ type: 'input', name: 'userName', message: 'Whats your name?' }] const tasks = [{ title: 'Preparing', task: (context, task) => new Promise((resolve, reject) => { setTimeout(() => resolve(), 1000) }) },{ title: 'Ask for name', task: (context, task) => new Promise((resolve, reject) => { task.output = 'Starting' setTimeout(() => { task.output = 'Calculating' resolve() }, 500) // setTimeout(() => { // }, 2000) }) }] // Test change for release const listrObject = new Listr(tasks) listrObject.run().then(res => { inquirer .prompt(steps).then(output => { console.log( 'Hello', output.userName ) }).catch(err => console.log(err)) })
Add python 3.9 to trove classifiers
from setuptools import find_packages, setup with open("README.rst") as readme_file: readme = readme_file.read() setup( name="homebrew", version="0.2.1", description="Homebrew wrapper", long_description=readme, author="Iwan in 't Groen", author_email="iwanintgroen@gmail.com", url="https://github.com/igroen/homebrew", packages=find_packages(), tests_require=["pytest"], setup_requires=["pytest-runner"], entry_points={"console_scripts": ["hb=homebrew.command_line:main"]}, license="ISCL", classifiers=[ "License :: OSI Approved :: ISC License (ISCL)", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], )
from setuptools import find_packages, setup with open("README.rst") as readme_file: readme = readme_file.read() setup( name="homebrew", version="0.2.1", description="Homebrew wrapper", long_description=readme, author="Iwan in 't Groen", author_email="iwanintgroen@gmail.com", url="https://github.com/igroen/homebrew", packages=find_packages(), tests_require=["pytest"], setup_requires=["pytest-runner"], entry_points={"console_scripts": ["hb=homebrew.command_line:main"]}, license="ISCL", classifiers=[ "License :: OSI Approved :: ISC License (ISCL)", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], )
Add party and state to tooltip
$(document).ready(function() { var $body = $('body'); var className = 'dial-congress'; var senateData; var scan = function() { $.each(senateData, function(i, senator) { var firstLast = senator.firstName + '\\s+' + senator.lastName; var lastFirst = senator.lastName + ',\\s*' + senator.firstName; var withTitle = '(?:Senator\\s+|Sen.\\s+|Congressman\\s+|Congresswoman\\s+)(' + firstLast + '|' + senator.lastName + ')'; var regExp = new RegExp(firstLast + '|' + lastFirst + '|' + withTitle, 'ig'); $body.highlightRegex(regExp, { className: className, attrs: { 'title': senator.party + '/' + senator.state + ': ' + senator.phone } }); }); } var createTooltips = function() { var $critters = $('.' + className); $critters.each(function(i, critter) { var $critter = $(critter); $critter.tooltipster({ interactive: true }); }); } $.when( $.get(chrome.extension.getURL('js/senate.json'), function(data) { senateData = JSON.parse(data); }) ).then(function() { scan(); createTooltips(); }) });
$(document).ready(function() { var $body = $('body'); var className = 'dial-congress'; var senateData; var scan = function() { $.each(senateData, function(i, senator) { var firstLast = senator.firstName + '\\s+' + senator.lastName; var lastFirst = senator.lastName + ',\\s*' + senator.firstName; var withTitle = '(?:Senator\\s+|Sen.\\s+|Congressman\\s+|Congresswoman\\s+)(' + firstLast + '|' + senator.lastName + ')'; var regExp = new RegExp(firstLast + '|' + lastFirst + '|' + withTitle, 'ig'); $body.highlightRegex(regExp, { className: className, attrs: { 'data-phone': senator.phone, 'title': senator.phone } }); }); } var createTooltips = function() { var $critters = $('.' + className); $critters.each(function(i, critter) { var $critter = $(critter); $critter.tooltipster(); }); } $.when( $.get(chrome.extension.getURL('js/senate.json'), function(data) { senateData = JSON.parse(data); }) ).then(function() { scan(); createTooltips(); }) });
Fix incorrect call to logging module
from __future__ import print_function import time import sys import socket import logging def wait_ssh_ready(host, tries=40, delay=3, port=22): # Wait until the SSH is actually up s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Waiting for SSH at %s to be ready to connect' % host, end='') sys.stdout.flush() for _ in xrange(tries): try: s.connect((host, port)) assert s.recv(3) == 'SSH' except KeyboardInterrupt: logging.warn('User stopped the loop.') break except socket.error: time.sleep(delay) print('.', end='') sys.stdout.flush() except AssertionError: time.sleep(delay) print('!', end='') sys.stdout.flush() else: print() # A new line logging.info('SSH is ready to connect') return True else: waited = tries * delay logging.error('SSH is not available after %s seconds.' % waited) return False
from __future__ import print_function import time import sys import socket import logging def wait_ssh_ready(host, tries=40, delay=3, port=22): # Wait until the SSH is actually up s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logging.info('Waiting for SSH at %s to be ready to connect' % host, end='') sys.stdout.flush() for _ in xrange(tries): try: s.connect((host, port)) assert s.recv(3) == 'SSH' except KeyboardInterrupt: logging.warn('User stopped the loop.') break except socket.error: time.sleep(delay) print('.', end='') sys.stdout.flush() except AssertionError: time.sleep(delay) print('!', end='') sys.stdout.flush() else: print() # A new line logging.info('SSH is ready to connect') return True else: waited = tries * delay logging.error('SSH is not available after %s seconds.' % waited) return False
Add one more test and it fails
defaultConf = { height: 100, width: 300, fingerprintLength: 20 }; describe("The constructor is supposed a proper Captcha object", function() { it('Constructor Captcha exists', function(){ expect(Captcha).toBeDefined(); }); var captcha = new Captcha(); it("Captcha object is not null", function(){ expect(captcha).not.toBeNull(); }); it('captcha object should be an instance of Captcha class', function(){ expect(captcha instanceof Captcha).toBeTruthy(); }); it('the height of the svg should be set to the configured height', function(){ expect(Number(captcha.height)).toEqual(defaultConf.height); }); it('the width of the svg should be set to the configured width', function(){ expect(Number(captcha.width)).toEqual(defaultConf.width); }); it('the length of the fingerprint should be set to the configured fingerprintLength', function(){ expect(Number(captcha.fingerprintLength)).toEqual(defaultConf.fingerprintLength); }); });
defaultConf = { height: 100, width: 300, fingerprintLength: 20 }; describe("The constructor is supposed a proper Captcha object", function() { it('Constructor Captcha exists', function(){ expect(Captcha).toBeDefined(); }); var captcha = new Captcha(); it("Captcha object is not null", function(){ expect(captcha).not.toBeNull(); }); it('captcha object should be an instance of Captcha class', function(){ expect(captcha instanceof Captcha).toBeTruthy(); }); it('the height of the svg should be set to the configured height', function(){ expect(Number(captcha.height)).toEqual(defaultConf.height); }); it('the width of the svg should be set to the configured width', function(){ expect(Number(captcha.width)).toEqual(defaultConf.width); }); });
Raise timetout because of race conditions.
/**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH (info@ecsec.de) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.mobile.activation.model; import java.lang.management.ManagementFactory; /** * * @author Neil Crossley */ public final class Timeout { public static final int MIN_WAIT_TIMEOUT = 1500; public static final int WAIT_TIMEOUT = isDebug() ? Integer.MAX_VALUE : MIN_WAIT_TIMEOUT; private Timeout() { } static boolean isDebug() { for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) { if (arg.contains("jdwp=")) { return true; } }; return false; } }
/**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH (info@ecsec.de) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.mobile.activation.model; import java.lang.management.ManagementFactory; /** * * @author Neil Crossley */ public final class Timeout { public static final int MIN_WAIT_TIMEOUT = 1000; public static final int WAIT_TIMEOUT = isDebug() ? Integer.MAX_VALUE : MIN_WAIT_TIMEOUT; private Timeout() { } static boolean isDebug() { for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) { if (arg.contains("jdwp=")) { return true; } }; return false; } }
Fix "No tests were run" After including this packing in our ember app's package.json, was seeing: ``` 1..0 # tests 0 # pass 0 # fail 0 # ok No tests were run, please check whether any errors occurred in the page ``` Config in `ember-cli-build.js`: ``` sassLint: { disableTestGenerator: true } ``` Setup: ``` ember -v version: 1.13.8 Could not find watchman, falling back to NodeWatcher for file system events. Visit http://www.ember-cli.com/user-guide/#watchman for more info. node: 0.12.7 npm: 2.13.4 os: darwin x64 ```
/* jshint node: true */ 'use strict'; var SassLinter = require('broccoli-sass-lint'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-sass-lint', included: function(app) { if (!app.isTestingSassLintAddon) { this._super.included(app); } this.app = app; this.sassLintOptions = app.options.sassLint || {}; }, lintTree: function(type, tree) { var mergedTrees; if (type === 'app') { mergedTrees = mergeTrees([this.app.trees.styles]); return new SassLinter(mergedTrees, this.sassLintOptions); } else { return this.app.trees.styles; } }, };
/* jshint node: true */ 'use strict'; var SassLinter = require('broccoli-sass-lint'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-sass-lint', included: function(app) { if (!app.isTestingSassLintAddon) { this._super.included(app); } this.app = app; this.sassLintOptions = app.options.sassLint || {}; }, lintTree: function(type, tree) { var formattedResults, mergedTrees, results; if (type === 'app') { mergedTrees = mergeTrees([this.app.trees.styles]); return new SassLinter(mergedTrees, this.sassLintOptions); } else { return tree; } }, };
Return null from resolveuser since it seems to confuse bluebird
'use strict'; import models from '../../models'; import { GENERIC } from '../../utils/errorTypes.js'; let User = models.User; export default function resolveUser(req, res, next) { let jwtUserId = req.user.id; User.findById(jwtUserId) .then(function (loggedInUser) { if (!loggedInUser) { res.err(404, 'User not found!') } else { req.user = loggedInUser; next(); return null; } }) .catch(function (err) { res.err(500) }) };
'use strict'; import models from '../../models'; import { GENERIC } from '../../utils/errorTypes.js'; let User = models.User; export default function resolveUser(req, res, next) { let jwtUserId = req.user.id; User.findById(jwtUserId) .then(function (loggedInUser) { if (!loggedInUser) { res.err(404, 'User not found!') } else { req.user = loggedInUser; return next(); } }) .catch(function (err) { res.err(500) }) };
Update test to take advantage of new 'server ready' hooks, and stop server when test is done.
require('./common'); var path = require("path"); var file = "numbers"; var default_host_path = path.join(fixturesDir,"default-host"); var fullname = path.join(default_host_path, file); var fileText = require('fs').readFileSync(fullname); var settings = { "port": PORT, "default_host" : { "root": path.join(fixturesDir,"default-host") }, "log_level": 4 //silent } antinode.start(settings, function() { var client = http.createClient(PORT, 'localhost'); var request = client.request('GET', '/'+file); request.addListener('response', function (response) { assert.equal(response.statusCode, 200); response.setEncoding('utf8'); response.addListener('data', function (chunk) { assert.equal(chunk, fileText); puts("OK"); antinode.stop(); }); }); request.end(); });
require('./common'); var path = require("path"); var file = "numbers"; var default_host_path = path.join(fixturesDir,"default-host"); var fullname = path.join(default_host_path, file); var fileText = require('fs').readFileSync(fullname); var settings = { "port": PORT, "default_host" : { "root": path.join(fixturesDir,"default-host") } } antinode.start(settings); setTimeout(function() { var client = http.createClient(PORT, 'localhost'); var request = client.request('GET', '/'+file); request.addListener('response', function (response) { assert.equal(response.statusCode, 200); response.setEncoding('utf8'); response.addListener('data', function (chunk) { assert.equal(chunk, fileText); puts("OK"); }); }); request.end(); }, 1000);
Fix typo in version number
<?php Class extension_markdown_typography extends Extension { /** * @see http://symphony-cms.com/learn/api/2.2/toolkit/extension/#about */ public function about() { return array( 'name' => 'Text Formatter: Markdown Typography', 'version' => '1.1.1', 'release-date' => '2011-12-22', 'author' => array( 'name' => 'Nils Hörrmann', 'website' => 'http://nilshoerrmann.de', 'email' => 'post@nilshoerrmann.de' ), 'description' => 'Markdown with Smartypants and some refinements for German typography.' ); } }
<?php Class extension_markdown_typography extends Extension { /** * @see http://symphony-cms.com/learn/api/2.2/toolkit/extension/#about */ public function about() { return array( 'name' => 'Text Formatter: Markdown Typography', 'version' => '1.1,1', 'release-date' => '2011-12-22', 'author' => array( 'name' => 'Nils Hörrmann', 'website' => 'http://nilshoerrmann.de', 'email' => 'post@nilshoerrmann.de' ), 'description' => 'Markdown with Smartypants and some refinements for German typography.' ); } }
Add module sourceType in options to babylon.
import fs from "fs"; import {parse} from "babylon"; import CodeGenerator from "../CodeGenerator"; import processTokens from "../process-tokens"; function parseText(text) { let ast = parse(text, { preserveParens: true, sourceType: "module", plugins: ["*"] }); let tokens = ast.tokens; let semicolons = ast.tokens.filter(token => token.type.label === ";"); const modifiedTokens = processTokens(text, tokens, semicolons); return { ast: ast.program, tokens: modifiedTokens, semicolons }; } export function formatText(text) { const { ast, tokens, semicolons } = parseText(text); let generator = new CodeGenerator(ast, text, tokens, semicolons); return generator.generate(); } export function formatFile(filename) { try { const text = fs.readFileSync(filename).toString(); return formatText(text); } catch (error) { error.message = `${filename}: ${error.message}`; throw error; } }
import fs from "fs"; import {parse} from "babylon"; import CodeGenerator from "../CodeGenerator"; import processTokens from "../process-tokens"; function parseText(text) { let ast = parse(text, { preserveParens: true, plugins: ["*"] }); let tokens = ast.tokens; let semicolons = ast.tokens.filter(token => token.type.label === ";"); const modifiedTokens = processTokens(text, tokens, semicolons); return { ast: ast.program, tokens: modifiedTokens, semicolons }; } export function formatText(text) { const { ast, tokens, semicolons } = parseText(text); let generator = new CodeGenerator(ast, text, tokens, semicolons); return generator.generate(); } export function formatFile(filename) { try { const text = fs.readFileSync(filename).toString(); return formatText(text); } catch (error) { error.message = `${filename}: ${error.message}`; throw error; } }
Remove location lookup console statements
import CanvasClass from './CanvasClass'; import TextOverlay from './TextOverlay'; import mapboxgl from 'mapbox-gl'; /** * Location Lookup class - Binds Google places to text box and binds google places to map */ export default class LocationLookup { constructor(textOverlay, mapBox) { this.textOverlay = textOverlay; this.mapBox = mapBox; } locationLookupLoaded() { this.setupFields(); } setupFields() { let addressField = document.getElementById('pac-input'); var options = { types: ['(cities)'] }; let autoComplete = new google.maps.places.Autocomplete(addressField, options); let that = this; autoComplete.addListener('place_changed', () => { that.textOverlay.location = this.textOverlay.formatCoord(autoComplete.getPlace().geometry.location.lat(), autoComplete.getPlace().geometry.location.lng()) that.mapBox.map.setCenter([autoComplete.getPlace().geometry.location.lng(), autoComplete.getPlace().geometry.location.lat() ]); }); } }
import CanvasClass from './CanvasClass'; import TextOverlay from './TextOverlay'; import mapboxgl from 'mapbox-gl'; /** * Location Lookup class - Binds Google places to text box and binds google places to map */ export default class LocationLookup { constructor(textOverlay, mapBox) { this.textOverlay = textOverlay; this.mapBox = mapBox; } locationLookupLoaded() { this.setupFields(); } setupFields() { let addressField = document.getElementById('pac-input'); var options = { types: ['(cities)'] }; let autoComplete = new google.maps.places.Autocomplete(addressField, options); console.log(this.autoComplete); let that = this; autoComplete.addListener('place_changed', () => { console.log(autoComplete); that.textOverlay.location = this.textOverlay.formatCoord(autoComplete.getPlace().geometry.location.lat(), autoComplete.getPlace().geometry.location.lng()) that.mapBox.map.setCenter([autoComplete.getPlace().geometry.location.lng(), autoComplete.getPlace().geometry.location.lat() ]); }); } }
Remove hack from position angle test
from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() a = position_angle_of(j.radec(epoch='date'), i.radec(epoch='date')) assert abs(a.degrees - 293.671) < 0.002
from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() a = position_angle_of(j.radec(epoch='date')[1::-1], i.radec(epoch='date')[1::-1]) assert abs(a.degrees - 293.671) < 0.002
Remove old express listen line that causes a server error.
module.exports = function(app) { var mongoose = require('mongoose'); // require mongoose (for mongodb integration var fs = require('fs'); // necessary to read from files fs.readFile(".dbconfig", 'utf8', function(err,data){ if (err) { console.log(err); } else { var dbAccess = JSON.parse(data); // if read successful, parse JSON into object var userAuthString = dbAccess.user + ':' + dbAccess.password; // get username and password mongoose.connect('mongodb://' + userAuthString + '@ds147975.mlab.com:47975/classratdbtest'); // connect to database } }); app.get("/api/hello", function(request, response) { // provide RESTful GET API at /hello response.send("Hello, World!"); // respond with string }); app.listen(process.env.PORT, process.env.IP); // begin app listening on Cloud9 port/IP console.log("API running!"); }
module.exports = function(app) { var mongoose = require('mongoose'); // require mongoose (for mongodb integration var fs = require('fs'); // necessary to read from files fs.readFile(".dbconfig", 'utf8', function(err,data){ if (err) { console.log(err); } else { var dbAccess = JSON.parse(data); // if read successful, parse JSON into object var userAuthString = dbAccess.user + ':' + dbAccess.password; // get username and password mongoose.connect('mongodb://' + userAuthString + '@ds147975.mlab.com:47975/classratdbtest'); // connect to database } }); app.use(express.static("public")); // serve files within the "public" folder app.get("/api/hello", function(request, response) { // provide RESTful GET API at /hello response.send("Hello, World!"); // respond with string }); app.listen(process.env.PORT, process.env.IP); // begin app listening on Cloud9 port/IP console.log("API running!"); }
Add matchMedia to the global scope
require("@babel/register")({ extensions: [".ts", ".js", ".tsx", ".jsx"], }) require("coffeescript/register") require("@babel/polyfill") require("raf/polyfill") require("should") require("./src/lib/jade_hook") // FIXME: Do we need this? // NOTE: Once we do AOT compilation we probably want to re-enable this on the server in development mode only. // require('source-map-support/register') const path = require("path") const Adapter = require("enzyme-adapter-react-16") const Enzyme = require("enzyme") const sd = require("sharify").data // TODO: Look into why this bumps user off of other node command-line tab require("dotenv").config({ path: path.join(process.cwd(), ".env.test"), }) Enzyme.configure({ adapter: new Adapter(), }) try { global.matchMedia = window.matchMedia = window.matchMedia || function() { return { matches: false, addListener: function() {}, removeListener: function() {}, } } } catch (error) {} sd.AP = { loginPagePath: "/login", signupPagePath: "/signup", facebookPath: "/facebook", twitterPath: "/twitter", } sd.APP_URL = "http://artsy.net"
require("@babel/register")({ extensions: [".ts", ".js", ".tsx", ".jsx"], }) require("coffeescript/register") require("@babel/polyfill") require("raf/polyfill") require("should") require("./src/lib/jade_hook") // FIXME: Do we need this? // NOTE: Once we do AOT compilation we probably want to re-enable this on the server in development mode only. // require('source-map-support/register') const path = require("path") const Adapter = require("enzyme-adapter-react-16") const Enzyme = require("enzyme") const sd = require("sharify").data // TODO: Look into why this bumps user off of other node command-line tab require("dotenv").config({ path: path.join(process.cwd(), ".env.test"), }) Enzyme.configure({ adapter: new Adapter(), }) try { window.matchMedia = window.matchMedia || function() { return { matches: false, addListener: function() {}, removeListener: function() {}, } } } catch (error) {} sd.AP = { loginPagePath: "/login", signupPagePath: "/signup", facebookPath: "/facebook", twitterPath: "/twitter", } sd.APP_URL = "http://artsy.net"
Modify from ion_auth to sentinel
<?php defined('BASEPATH') OR exit('No direct script access allowed'); use Library\Auth\Auth; class Login extends CI_Controller { public function __construct() { parent::__construct(); } public function index() { $this->form_validation->set_rules('email', 'Email', 'trim|valid_email|required'); $this->form_validation->set_rules('password', 'Password', 'required'); if ($this->form_validation->run() == FALSE) { $this->template->set_layout('login'); $this->template->build('login'); } else { $email = set_value('email'); $password = set_value('password'); $credentials = compact('email', 'password'); if (sentinel()->authenticate($credentials)) { redirect('/', 'refresh'); } else { set_message_error('Username atau password salah.'); redirect('login', 'refresh'); } } } } /* End of file Login.php */ /* Location: ./application/modules/user/controllers/Login.php */
<?php defined('BASEPATH') OR exit('No direct script access allowed'); use Library\Auth\Auth; class Login extends CI_Controller { public function __construct() { parent::__construct(); } public function index() { $this->form_validation->set_rules('email', 'Email', 'trim|valid_email|required'); $this->form_validation->set_rules('password', 'Password', 'required'); if ($this->form_validation->run() == FALSE) { $this->template->set_layout('login'); $this->template->build('login'); } else { $email = set_value('email'); $password = set_value('password'); $login = $this->ion_auth->login($email, $password); if ($login) { redirect('/', 'refresh'); } else { set_message_error('Username atau password salah.'); redirect('login', 'refresh'); } } } } /* End of file Login.php */ /* Location: ./application/modules/user/controllers/Login.php */
Use more gunicorn threads when pooling database connector isn't available. When using postgres with meinheld, the best you can do so far (as far as I know) is up the number of threads.
import subprocess import sys import setup_util import os from os.path import expanduser home = expanduser("~") def start(args): setup_util.replace_text("django/hello/hello/settings.py", "HOST': '.*'", "HOST': '" + args.database_host + "'") setup_util.replace_text("django/hello/hello/settings.py", "\/home\/ubuntu", home) # because pooling doesn't work with meinheld, it's necessary to create a ton of gunicorn threads (think apache pre-fork) # to allow the OS to switch processes when waiting for socket I/O. args.max_threads *= 8 # and go from there until the database server runs out of memory for new threads (connections) subprocess.Popen("gunicorn hello.wsgi:application --worker-class=\"egg:meinheld#gunicorn_worker\" -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="django/hello") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gunicorn' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) except OSError: pass return 0
import subprocess import sys import setup_util import os from os.path import expanduser home = expanduser("~") def start(args): setup_util.replace_text("django/hello/hello/settings.py", "HOST': '.*'", "HOST': '" + args.database_host + "'") setup_util.replace_text("django/hello/hello/settings.py", "\/home\/ubuntu", home) subprocess.Popen("gunicorn hello.wsgi:application --worker-class=\"egg:meinheld#gunicorn_worker\" -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="django/hello") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gunicorn' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) except OSError: pass return 0
Fix: Use process.env.NODE to find node executable
const fs = require('fs'); const path = require('path'); const exec = require('child_process').exec; // this is from the env of npm, not node const nodePath = process.env.NODE; const version = process.versions.v8; const tmpfile = path.join(__dirname, version+'.flags.json'); if (!fs.existsSync(tmpfile)) { exec(nodePath+' --v8-options', function (execErr, result) { var flags; if (execErr) { throw new Error(execErr); } else { flags = result.match(/\s\s--(\w+)/gm).map(function (match) { return match.substring(2); }); fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' }, function (writeErr) { if (writeErr) { throw new Error(writeErr); } else { console.log('flags for v8 '+version+' cached.'); } } ); } }); } module.exports = require.bind(null, tmpfile);
const fs = require('fs'); const path = require('path'); const exec = require('child_process').exec; const nodepath = process.env._; const version = process.versions.v8; const tmpfile = path.join(__dirname, version+'.flags.json'); if (!fs.existsSync(tmpfile)) { exec(nodepath+' --v8-options', function (execErr, result) { var flags; if (execErr) { throw new Error(execErr); } else { flags = result.match(/\s\s--(\w+)/gm).map(function (match) { return match.substring(2); }); fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' }, function (writeErr) { if (writeErr) { throw new Error(writeErr); } else { console.log('flags for v8 '+version+' cached.'); } } ); } }); } module.exports = require.bind(null, tmpfile);
Use next public path for polyfill loader
import { getOptions, stringifyRequest } from 'loader-utils' module.exports = function (content, sourceMap) { this.cacheable() const options = getOptions(this) const { buildId, modules } = options this.callback(null, ` // Webpack Polyfill Injector function main() {${modules.map(module => `\n require(${stringifyRequest(this, module)});`).join('') + '\n'}} if (require(${stringifyRequest(this, options.test)})) { var js = document.createElement('script'); js.src = __NEXT_DATA__.publicPath + '${buildId}/polyfill.js'; js.onload = main; js.onerror = function onError(message) { console.error('Could not load the polyfills: ' + message); }; document.head.appendChild(js); } else { main(); } `, sourceMap) }
import { getOptions, stringifyRequest } from 'loader-utils' module.exports = function (content, sourceMap) { this.cacheable() const options = getOptions(this) const { buildId, modules } = options this.callback(null, ` // Webpack Polyfill Injector function main() {${modules.map(module => `\n require(${stringifyRequest(this, module)});`).join('') + '\n'}} if (require(${stringifyRequest(this, options.test)})) { var js = document.createElement('script'); js.src = __webpack_public_path__ + '${buildId}/polyfill.js'; js.onload = main; js.onerror = function onError(message) { console.error('Could not load the polyfills: ' + message); }; document.head.appendChild(js); } else { main(); } `, sourceMap) }
Call function to return url
const { renameCompanyList } = require('../repos') const urls = require('../../../lib/urls') // istanbul ignore next: Covered by functional tests async function handleEditCompanyList (req, res, next) { const { token } = req.session const { name, id } = req.body try { await renameCompanyList(token, name, id) req.flash('success', 'List updated') res.send() } catch (error) { next(error) } } // istanbul ignore next: Covered by functional tests async function renderEditCompanyListPage (req, res, next) { const { companyList: { id, name } } = res.locals const props = { id, cancelUrl: `${urls.dashboard()}`, maxLength: 30, listName: name, returnUrl: `${urls.dashboard()}`, } try { res.breadcrumb('Edit list name').render('company-lists/views/edit-list', { props, }) } catch (error) { next(error) } } module.exports = { renderEditCompanyListPage, handleEditCompanyList, }
const { renameCompanyList } = require('../repos') const urls = require('../../../lib/urls') // istanbul ignore next: Covered by functional tests async function handleEditCompanyList (req, res, next) { const { token } = req.session const { name, id } = req.body try { await renameCompanyList(token, name, id) req.flash('success', 'List updated') res.send() } catch (error) { next(error) } } // istanbul ignore next: Covered by functional tests async function renderEditCompanyListPage (req, res, next) { const { companyList: { id, name } } = res.locals const props = { id, cancelUrl: `${urls.dashboard}`, maxLength: 30, listName: name, returnUrl: `${urls.dashboard}`, } try { res.breadcrumb('Edit list name').render('company-lists/views/edit-list', { props, }) } catch (error) { next(error) } } module.exports = { renderEditCompanyListPage, handleEditCompanyList, }
Save and restore workbench state. git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@4697 28e8926c-6b08-0410-baaa-805c5e19b8d6
package org.objectweb.proactive.ic2d; import org.eclipse.ui.IWorkbenchPreferenceConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public void initialize(IWorkbenchConfigurer configurer) { // To restore window preferences //super.initialize(configurer); configurer.setSaveAndRestore(true); // Sets the look of the tabs like Eclipse 3.x PlatformUI.getPreferenceStore().setValue( IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, false); } public String getInitialWindowPerspectiveId() { return "org.objectweb.proactive.ic2d.monitoring.perspectives.MonitoringPerspective";//MonitoringPerspective.ID /*DefaultPerspective.ID*/; } }
package org.objectweb.proactive.ic2d; import org.eclipse.ui.IWorkbenchPreferenceConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public void initialize(IWorkbenchConfigurer configurer) { /*// To restore window preferences super.initialize(configurer); configurer.setSaveAndRestore(true); */ // Sets the look of the tabs like Eclipse 3.x PlatformUI.getPreferenceStore().setValue( IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, false); } public String getInitialWindowPerspectiveId() { return "org.objectweb.proactive.ic2d.monitoring.perspectives.MonitoringPerspective";//MonitoringPerspective.ID /*DefaultPerspective.ID*/; } }
Fix an NPE with Velocity regions
package in.twizmwaz.cardinal.module.modules.appliedRegion.type; import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import in.twizmwaz.cardinal.module.modules.regions.RegionModule; import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.util.Vector; public class VelocityRegion extends AppliedRegion { public final Vector velocity; public VelocityRegion(RegionModule region, FilterModule filter, String message, Vector velocity) { super(region, filter, message); this.velocity = velocity; } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { if (filter == null) { if (region.contains(new BlockRegion(null, event.getTo().toVector()))) event.getPlayer().setVelocity(velocity); } else if (region.contains(new BlockRegion(null, event.getTo().toVector())) && filter.evaluate(event.getPlayer()).equals(FilterState.ALLOW)) { event.getPlayer().setVelocity(velocity); } } }
package in.twizmwaz.cardinal.module.modules.appliedRegion.type; import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import in.twizmwaz.cardinal.module.modules.regions.RegionModule; import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.util.Vector; public class VelocityRegion extends AppliedRegion { public final Vector velocity; public VelocityRegion(RegionModule region, FilterModule filter, String message, Vector velocity) { super(region, filter, message); this.velocity = velocity; } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { if (region.contains(new BlockRegion(null, event.getTo().toVector())) && filter.evaluate(event.getPlayer()).equals(FilterState.ALLOW)) { event.getPlayer().setVelocity(velocity); } } }
Make Role migration's name field nullable
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRolesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::connection('tenant')->create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name')->nullable(); $table->string('slug')->unique(); $table->text('description')->nullable(); $table->boolean('admin')->default(0); $table->timestamps(); }); } /** * Reverse the migration. * * @return void */ public function down() { Schema::connection('tenant')->drop('roles'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRolesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::connection('tenant')->create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('slug')->unique(); $table->text('description')->nullable(); $table->boolean('admin')->default(0); $table->timestamps(); }); } /** * Reverse the migration. * * @return void */ public function down() { Schema::connection('tenant')->drop('roles'); } }
Disable globalShortcut spec on Windows CI
const {globalShortcut} = require('electron').remote const assert = require('assert') const isCI = require('electron').remote.getGlobal('isCi') describe('globalShortcut module', () => { if (isCI && process.platform === 'win32') { return } beforeEach(() => { globalShortcut.unregisterAll() }) it('can register and unregister accelerators', () => { const accelerator = 'CommandOrControl+A+B+C' assert.equal(globalShortcut.isRegistered(accelerator), false) globalShortcut.register(accelerator, () => {}) assert.equal(globalShortcut.isRegistered(accelerator), true) globalShortcut.unregister(accelerator) assert.equal(globalShortcut.isRegistered(accelerator), false) assert.equal(globalShortcut.isRegistered(accelerator), false) globalShortcut.register(accelerator, () => {}) assert.equal(globalShortcut.isRegistered(accelerator), true) globalShortcut.unregisterAll() assert.equal(globalShortcut.isRegistered(accelerator), false) }) })
const {globalShortcut} = require('electron').remote const assert = require('assert') describe('globalShortcut module', () => { beforeEach(() => { globalShortcut.unregisterAll() }) it('can register and unregister accelerators', () => { const accelerator = 'CommandOrControl+A+B+C' assert.equal(globalShortcut.isRegistered(accelerator), false) globalShortcut.register(accelerator, () => {}) assert.equal(globalShortcut.isRegistered(accelerator), true) globalShortcut.unregister(accelerator) assert.equal(globalShortcut.isRegistered(accelerator), false) assert.equal(globalShortcut.isRegistered(accelerator), false) globalShortcut.register(accelerator, () => {}) assert.equal(globalShortcut.isRegistered(accelerator), true) globalShortcut.unregisterAll() assert.equal(globalShortcut.isRegistered(accelerator), false) }) })
Remove explicit type argument since java defines declares it itself
package de.dotwee.rgb.canteen.model.helper; import android.content.Context; import android.widget.ArrayAdapter; import java.util.List; /** * Created by lukas on 19.11.2016. */ public class SpinnerHelper { private static final String TAG = SpinnerHelper.class.getSimpleName(); public static ArrayAdapter<String> load(List<String> values, Context applicationContext) { ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>( applicationContext.getApplicationContext(), android.R.layout.simple_spinner_item, values ); stringArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item ); return stringArrayAdapter; } }
package de.dotwee.rgb.canteen.model.helper; import android.content.Context; import android.widget.ArrayAdapter; import java.util.List; /** * Created by lukas on 19.11.2016. */ public class SpinnerHelper { private static final String TAG = SpinnerHelper.class.getSimpleName(); public static ArrayAdapter<String> load(List<String> values, Context applicationContext) { ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>( applicationContext.getApplicationContext(), android.R.layout.simple_spinner_item, values ); stringArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item ); return stringArrayAdapter; } }
Fix wrong table preferrence for role_user
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRoleUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { $table->increments('id'); $table->integer('role_id')->unsigned()->index(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); $table->integer('user_id')->unsigned()->index(); $table->foreign('user_id')->references('id')->on(config('auth.table'))->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_user'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRoleUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { $table->increments('id'); $table->integer('role_id')->unsigned()->index(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); $table->integer('user_id')->unsigned()->index(); $table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_user'); } }
Fix extension for babel/react loaders.
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index' ], devtool: 'eval-source-map', output: { path: __dirname, filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: [ '', '.js' ] }, module: { loaders: [{ test: /\.js?$/, loaders: ['react-hot', 'babel'], include: path.resolve(__dirname, '..', 'src') }] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index' ], devtool: 'eval-source-map', output: { path: __dirname, filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: [ '', '.js' ] }, module: { loaders: [{ test: /\.jsx?$/, loaders: ['react-hot', 'babel'], include: path.resolve(__dirname, '..', 'src') }] } };
Change Help Scout beacon to show subject field
/* eslint-disable */ export default function initHsBeacon() { !function (e, o, n) { window.HSCW = o, window.HS = n, n.beacon = n.beacon || {}; var t = n.beacon; t.userConfig = {}, t.readyQueue = [], t.config = function (e) { this.userConfig = e; }, t.ready = function (e) { this.readyQueue.push(e); }, o.config = { docs:{ enabled:!1, baseUrl:'' }, contact:{ enabled:!0, formId:'f48f821c-fb20-11e5-a329-0ee2467769ff' } }; var r = e.getElementsByTagName('script')[0], c = e.createElement('script'); c.type = 'text/javascript', c.async = !0, c.src = 'https://djtflbt20bdde.cloudfront.net/', r.parentNode.insertBefore(c, r); }(document, window.HSCW || {}, window.HS || {}); HS.beacon.config({ modal: true, attachment: true, instructions: 'Please make sure to include a link if your question involves a specific repo, build or job.', showSubject: true }); }
/* eslint-disable */ export default function initHsBeacon() { !function (e, o, n) { window.HSCW = o, window.HS = n, n.beacon = n.beacon || {}; var t = n.beacon; t.userConfig = {}, t.readyQueue = [], t.config = function (e) { this.userConfig = e; }, t.ready = function (e) { this.readyQueue.push(e); }, o.config = { docs:{ enabled:!1, baseUrl:'' }, contact:{ enabled:!0, formId:'f48f821c-fb20-11e5-a329-0ee2467769ff' } }; var r = e.getElementsByTagName('script')[0], c = e.createElement('script'); c.type = 'text/javascript', c.async = !0, c.src = 'https://djtflbt20bdde.cloudfront.net/', r.parentNode.insertBefore(c, r); }(document, window.HSCW || {}, window.HS || {}); HS.beacon.config({ modal: true, attachment: true, instructions: 'Please make sure to include a link if your question involves a specific repo, build or job.' }); }
Set up new classifiers. Now production ready.
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "django-jinja", version = "0.13", description = "Jinja2 templating language integrated in Django.", long_description = "", keywords = "django, jinja2", author = "Andrey Antukh", author_email = "niwi@niwi.be", url = "https://github.com/niwibe/django-jinja", license = "BSD", include_package_data = True, packages = find_packages(), install_requires=[ "distribute", "jinja2", ], classifiers = [ "Development Status :: 5 - Production/Stable", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Topic :: Internet :: WWW/HTTP", ] )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = 'django-jinja', version = "0.13", description = "Jinja2 templating language integrated in Django.", long_description = "", keywords = 'django, jinja2', author = 'Andrey Antukh', author_email = 'niwi@niwi.be', url = 'https://github.com/niwibe/django-jinja', license = 'BSD', include_package_data = True, packages = find_packages(), install_requires=[ 'distribute', 'jinja2', ], classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP', ] )
[BUGFIX] Fix bug and refactor 2 step remove.
<?php namespace Deployer; use SourceBroker\DeployerExtended\Utility\FileUtility; task('file:rm2steps:1', function () { $removeRecursiveAtomicItems = get('file_remove2steps_items'); $random = get('random'); // Set active_path so the task can be used before or after "symlink" task or standalone. $activePath = get('deploy_path') . '/' . (test('[ -L {{deploy_path}}/release ]') ? 'release' : 'current'); foreach ($removeRecursiveAtomicItems as $removeRecursiveAtomicItem) { $removeRecursiveAtomicItem = FileUtility::normalizeFolder(trim($removeRecursiveAtomicItem)); if(strlen($removeRecursiveAtomicItem)) { $itemToRename = escapeshellarg("$activePath/$removeRecursiveAtomicItem"); $itemToRenameNewName = escapeshellarg("$activePath/$removeRecursiveAtomicItem$random"); run("if [ -e $itemToRename ]; then mv -f $itemToRename $itemToRenameNewName; fi"); } } })->desc('Remove files and directories in two steps. First step: rename. Second step: remove.');
<?php namespace Deployer; use SourceBroker\DeployerExtended\Utility\FileUtility; task('file:rm2steps:1', function () { $removeRecursiveAtomicItems = get('file_remove2steps_items'); $random = get('random'); // Set active_path so the task can be used before or after "symlink" task or standalone. $activePath = get('deploy_path') . '/' . (test('[ -L {{deploy_path}}/release ]') ? 'release' : 'current'); foreach ($removeRecursiveAtomicItems as $removeRecursiveAtomicItem) { $removeRecursiveAtomicItem = FileUtility::normalizeFolder(trim($removeRecursiveAtomicItem)); if(strlen($removeRecursiveAtomicItem)) { $itemToRename = escapeshellarg("$activePath/$removeRecursiveAtomicItem"); $itemToRenameNewName = escapeshellarg("$activePath/$removeRecursiveAtomicItem$random"); run("if [ -e $itemToRename ]; then mv -f $itemToRename $itemToRenameNewName; fi"); } } })->desc('Remove files and directories in two steps. First step: rename. Second step: remove.');
Put Raleigh-Durham on the map (literally)
$(document).ready(function(){ $(".us_map").mapael({ map : { name : "usa_states", cssClass : "map", tooltip : { cssClass : "mapTooltip" //class name of the tooltip container }, defaultArea : { attrs : { fill : "#282828", stroke: "#9a9a9a", }, attrsHover : { fill : "#d8ae64" } }, defaultPlot : { type : "circle", href : "#", attrs: { fill : "#f95a61" } }, eventHandlers: { click : function (){ this.href="locations/26" } } }, plots: { 'nc' : { latitude: 35.7806, longitude: -78.6389, tooltip: {content : "Raleigh-Durham"} }, } }); });
$(document).ready(function(){ $(".us_map").mapael({ map : { name : "usa_states", cssClass : "map", tooltip : { cssClass : "mapTooltip" //class name of the tooltip container }, defaultArea : { attrs : { fill : "#282828", stroke: "#9a9a9a", }, attrsHover : { fill : "#d8ae64" } }, defaultPlot : { type : "circle", href : "#", attrs: { fill : "#f95a61" } }, eventHandlers: { click : function (){ } } }, plots: { 'ny' : { latitude: 40.717079, longitude: -74.00116, tooltip: {content : "New York"} }, } }); });
Make sure our body part test actually proves we're using the right encoding
package com.vtence.molecule; import org.junit.Test; import java.io.IOException; import static com.vtence.molecule.helpers.Charsets.UTF_16; import static com.vtence.molecule.helpers.Charsets.UTF_8; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class BodyPartTest { @Test public void decodesTextContentAccordingToContentTypeCharset() throws IOException { String originalText = "Les naïfs ægithales hâtifs pondant à Noël où il gèle..."; BodyPart part = new BodyPart().contentType("text/plain; charset=utf-16").content(originalText.getBytes(UTF_16)); assertThat("decoded text", part.content(), equalTo(originalText)); } @Test public void defaultsToUTF8DecodingWhenNoContentTypeIsSpecified() throws IOException { String originalText = "sont sûrs d'être déçus..."; BodyPart part = new BodyPart().content(originalText.getBytes(UTF_8)); assertThat("decoded text", part.content(), equalTo(originalText)); } @Test public void defaultsToUTF8DecodingWhenNoCharsetIsSpecified() throws IOException { String originalText = "en voyant leurs drôles d'oeufs abîmés."; BodyPart part = new BodyPart().contentType("text/plain").content(originalText.getBytes(UTF_8)); assertThat("decoded text", part.content(), equalTo(originalText)); } }
package com.vtence.molecule; import org.junit.Test; import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class BodyPartTest { @Test public void decodesTextContentAccordingToContentTypeCharset() throws IOException { String originalText = "Les naïfs ægithales hâtifs pondant à Noël où il gèle..."; BodyPart part = new BodyPart().contentType("text/plain; charset=utf-16").content(originalText); assertThat("decoded text", part.content(), equalTo(originalText)); } @Test public void defaultsToUTF8DecodingWhenNoContentTypeIsSpecified() throws IOException { String originalText = "sont sûrs d'être déçus..."; BodyPart part = new BodyPart().content(originalText); assertThat("decoded text", part.content(), equalTo(originalText)); } @Test public void defaultsToUTF8DecodingWhenNoCharsetIsSpecified() throws IOException { String originalText = "en voyant leurs drôles d'oeufs abîmés."; BodyPart part = new BodyPart().contentType("text/plain").content(originalText); assertThat("decoded text", part.content(), equalTo(originalText)); } }
Fix endless loop in server
import upload from './upload'; import express from 'express'; import logger from 'winston'; const app = express(); export default app; app.set('port', process.env.PORT || 3000); logger.remove(logger.transports.Console); logger.add(logger.transports.Console, {'timestamp':true,}); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'angeleandgus.com'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); app.use('/upload', upload); app.use((err, req, res, next) => { const status = err.statusCode || err.status || 500; res.status(status); const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; logger.error(`ip: ${ip} err: ${err}`); res.end(`Error ${status}: ${err.shortMessage}`); next(err); }); app.listen(app.get('port'), () => { logger.info(`Server started: http://localhost:${app.get('port')}/`); });
import upload from './upload'; import express from 'express'; import logger from 'winston'; const app = express(); export default app; app.set('port', process.env.PORT || 3000); logger.remove(logger.transports.Console); logger.add(logger.transports.Console, {'timestamp':true,}); app.use((req, res, next) => { // eslint-disable-line no-unused-vars res.header('Access-Control-Allow-Origin', 'angeleandgus.com'); res.header('Access-Control-Allow-Headers', 'Content-Type'); }); app.use('/upload', upload); app.use((err, req, res, next) => { const status = err.statusCode || err.status || 500; res.status(status); const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; logger.error(`ip: ${ip} err: ${err}`); res.end(`Error ${status}: ${err.shortMessage}`); next(err); }); app.listen(app.get('port'), () => { logger.info(`Server started: http://localhost:${app.get('port')}/`); });
Fix typo in method name. This method does not appear to be used within the gxui codebase.
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gl import ( "fmt" "github.com/go-gl/gl/v3.2-core/gl" ) type DrawMode int const ( POINTS DrawMode = gl.POINTS LINE_STRIP DrawMode = gl.LINE_STRIP LINE_LOOP DrawMode = gl.LINE_LOOP LINES DrawMode = gl.LINES TRIANGLE_STRIP DrawMode = gl.TRIANGLE_STRIP TRIANGLE_FAN DrawMode = gl.TRIANGLE_FAN TRIANGLES DrawMode = gl.TRIANGLES ) func (d DrawMode) PrimitiveCount(vertexCount int) int { switch d { case POINTS: return vertexCount case LINE_STRIP: return vertexCount - 1 case LINE_LOOP: return vertexCount case LINES: return vertexCount / 2 case TRIANGLE_STRIP: return vertexCount - 2 case TRIANGLE_FAN: return vertexCount - 2 case TRIANGLES: return vertexCount / 3 default: panic(fmt.Errorf("Unknown DrawMode 0x%.4x", d)) } }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gl import ( "fmt" "github.com/go-gl/gl/v3.2-core/gl" ) type DrawMode int const ( POINTS DrawMode = gl.POINTS LINE_STRIP DrawMode = gl.LINE_STRIP LINE_LOOP DrawMode = gl.LINE_LOOP LINES DrawMode = gl.LINES TRIANGLE_STRIP DrawMode = gl.TRIANGLE_STRIP TRIANGLE_FAN DrawMode = gl.TRIANGLE_FAN TRIANGLES DrawMode = gl.TRIANGLES ) func (d DrawMode) PrimativeCount(vertexCount int) int { switch d { case POINTS: return vertexCount case LINE_STRIP: return vertexCount - 1 case LINE_LOOP: return vertexCount case LINES: return vertexCount / 2 case TRIANGLE_STRIP: return vertexCount - 2 case TRIANGLE_FAN: return vertexCount - 2 case TRIANGLES: return vertexCount / 3 default: panic(fmt.Errorf("Unknown DrawMode 0x%.4x", d)) } }
Use date-format function for file-name
import os from datetime import datetime from time import time class Result: def __init__(self, directory): date = datetime.fromtimestamp(time()) self.file = File(directory, date.strftime('%Y-%m-%d_%H-%M-%S')) class File: def __init__(self, directory, name): if not os.path.exists(directory): os.makedirs(directory) self.path = os.path.join(directory, name) if not os.path.exists(self.path): open(self.path, 'w').close() def write_line(self, text): stream = open(self.path, 'a') stream.write('%s\n' % text) stream.close()
import os from datetime import datetime from time import time class Result: def __init__(self, directory): date = datetime.fromtimestamp(time()) name = '%d-%d-%d_%d-%d-%d' % ( date.year, date.month, date.day, date.hour, date.minute, date.second) self.file = File(directory, name) class File: def __init__(self, directory, name): if not os.path.exists(directory): os.makedirs(directory) self.path = os.path.join(directory, name) if not os.path.exists(self.path): open(self.path, 'w').close() def write_line(self, text): stream = open(self.path, 'a') stream.write('%s\n' % text) stream.close()
Allow to override include dir of xproto
import os import re keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)") class Keysyms(object): __slots__ = ('name_to_code', 'code_to_name', '__dict__') def __init__(self): self.name_to_code = {} self.code_to_name = {} def add_from_file(self, filename): with open(filename, 'rt') as f: for line in f: m = keysym_re.match(line) if not m: continue name = (m.group(1) or '') + m.group(2) code = int(m.group(3), 0) self.__dict__[name] = code self.name_to_code[name] = code self.code_to_name[code] = name def load_default(self): xproto_dir = os.environ.get("XPROTO_DIR", "/usr/include/X11") self.add_from_file(xproto_dir + '/keysymdef.h') self.add_from_file(xproto_dir + '/XF86keysym.h')
import re keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)") class Keysyms(object): __slots__ = ('name_to_code', 'code_to_name', '__dict__') def __init__(self): self.name_to_code = {} self.code_to_name = {} def add_from_file(self, filename): with open(filename, 'rt') as f: for line in f: m = keysym_re.match(line) if not m: continue name = (m.group(1) or '') + m.group(2) code = int(m.group(3), 0) self.__dict__[name] = code self.name_to_code[name] = code self.code_to_name[code] = name def load_default(self): self.add_from_file('/usr/include/X11/keysymdef.h') self.add_from_file('/usr/include/X11/XF86keysym.h')
Remove redundant handle call in TrustedProxies middleware
<?php namespace App\Http\Middleware; use Cache; use Closure; use Illuminate\Http\Request; use Fideloper\Proxy\TrustProxies as Middleware; class TrustProxies extends Middleware { /** * The trusted proxies for this application. * * @var array */ protected $proxies = []; /** * The headers that should be used to detect proxies. * * @var string */ protected $headers = Request::HEADER_X_FORWARDED_AWS_ELB; /** * Add remote address to trusted proxy list */ public function handle(Request $request, Closure $next) { $ips = Cache::remember('list-cloudfront-ips', 60*60, function () { return file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips'); }); $ips = json_decode($ips); $this->proxies = array_merge( $this->proxies, $ips->{"CLOUDFRONT_GLOBAL_IP_LIST"}, $ips->{"CLOUDFRONT_REGIONAL_EDGE_IP_LIST"} ); array_push($this->proxies, $request->server->get('REMOTE_ADDR')); return parent::handle($request, $next); } }
<?php namespace App\Http\Middleware; use Cache; use Closure; use Illuminate\Http\Request; use Fideloper\Proxy\TrustProxies as Middleware; class TrustProxies extends Middleware { /** * The trusted proxies for this application. * * @var array */ protected $proxies = []; /** * The headers that should be used to detect proxies. * * @var string */ protected $headers = Request::HEADER_X_FORWARDED_AWS_ELB; /** * Add remote address to trusted proxy list */ public function handle(Request $request, Closure $next) { $ips = Cache::remember('list-cloudfront-ips', 60*60, function () { return file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips'); }); $ips = json_decode($ips); $this->proxies = array_merge( $this->proxies, $ips->{"CLOUDFRONT_GLOBAL_IP_LIST"}, $ips->{"CLOUDFRONT_REGIONAL_EDGE_IP_LIST"} ); array_push($this->proxies, $request->server->get('REMOTE_ADDR')); parent::handle($request, $next); return $next($request); } }
Fix compile error due to class rename.
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.tasks.testing; import org.gradle.api.reporting.ConfigurableReport; import org.gradle.api.reporting.DirectoryReport; import org.gradle.api.reporting.ReportContainer; /** * The reports produced by the {@link Test} task. */ public interface TestReports extends ReportContainer<ConfigurableReport> { DirectoryReport getHtml(); DirectoryReport getJunitXml(); }
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.tasks.testing; import org.gradle.api.reporting.ConfigureableReport; import org.gradle.api.reporting.DirectoryReport; import org.gradle.api.reporting.ReportContainer; /** * The reports produced by the {@link Test} task. */ public interface TestReports extends ReportContainer<ConfigureableReport> { DirectoryReport getHtml(); DirectoryReport getJunitXml(); }
Append port 80 when a port is not provided
(function() { var __WS_send = WebSocket.prototype.send; window.__WS_send = WebSocket.prototype.send; WebSocket.prototype.send = function(data) { console.log(this.url); try { var ip = /((?:[0-9]{1,3}(?:\.|\-)){1,3}[0-9]{1,3})/.exec(this.url); var port = /\:[0-9]{1,5}/.exec(this.url) || ':80'; console.log("http://agar.io/?sip=" + ip[1].replace(/-/g, '.') + port); } catch (err) { console.error(err.message); } try { __WS_send.apply(this, [data]); WebSocket.prototype.send = __WS_send; } catch (err) { window.__WS_send.apply(this, [data]); WebSocket.prototype.send = window.__WS_send; } } })();
(function() { var __WS_send = WebSocket.prototype.send; window.__WS_send = WebSocket.prototype.send; WebSocket.prototype.send = function(data) { console.log(this.url); try { var re = /((?:[0-9]{1,3}(?:\.|\-)){1,3}[0-9]{1,3})(?:.*?)?(\:[0-9]{1,5})/; var match = re.exec(this.url); console.log("http://agar.io/?sip=" + match[1].replace(/-/g, '.') + match[2]); } catch (err) { console.error(err.message); } try { __WS_send.apply(this, [data]); WebSocket.prototype.send = __WS_send; } catch (err) { window.__WS_send.apply(this, [data]); WebSocket.prototype.send = window.__WS_send; } } })();
Increment version number to 0.2.13 Merged Moritz's new process modules.
__version__ = '0.2.13' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
__version__ = '0.2.12' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
Fix potential NPE in the Capabilities
package com.infinityraider.infinitylib.capability; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nullable; public interface ICapabilityImplementation<C extends ICapabilityProvider, V> { Capability<V> getCapability(); boolean shouldApplyCapability(C carrier); V createNewValue(C carrier); ResourceLocation getCapabilityKey(); Class<C> getCarrierClass(); default LazyOptional<V> getCapability(C carrier) { return carrier == null ? LazyOptional.empty() : carrier.getCapability(this.getCapability()); } default LazyOptional<V> getCapability(C carrier, @Nullable Direction dir) { return carrier.getCapability(this.getCapability(), dir); } }
package com.infinityraider.infinitylib.capability; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nullable; public interface ICapabilityImplementation<C extends ICapabilityProvider, V> { Capability<V> getCapability(); boolean shouldApplyCapability(C carrier); V createNewValue(C carrier); ResourceLocation getCapabilityKey(); Class<C> getCarrierClass(); default LazyOptional<V> getCapability(C carrier) { return carrier.getCapability(this.getCapability()); } default LazyOptional<V> getCapability(C carrier, @Nullable Direction dir) { return carrier.getCapability(this.getCapability(), dir); } }
Quit gracefully after detecting a syntax error
<?php declare(strict_types=1); namespace Mihaeu\PhpDependencies\Analyser; use Mihaeu\PhpDependencies\OS\PhpFile; use Mihaeu\PhpDependencies\OS\PhpFileSet; use PhpParser\Error; use PhpParser\Parser as BaseParser; class Parser { /** @var BaseParser */ private $parser; /** * @param $parser */ public function __construct(BaseParser $parser) { $this->parser = $parser; } /** * @param PhpFileSet $files * * @return Ast */ public function parse(PhpFileSet $files) : Ast { return $files->reduce(new Ast(), function (Ast $ast, PhpFile $file) { try { $nodes = $this->parser->parse($file->code()); } catch (Error $e) { echo 'Syntax error during inspection in file "'.$file.'"'.PHP_EOL .PHP_EOL.$e->getMessage().')'.PHP_EOL; exit; } return $ast->add($file, $nodes); }); } }
<?php declare(strict_types=1); namespace Mihaeu\PhpDependencies\Analyser; use Mihaeu\PhpDependencies\OS\PhpFile; use Mihaeu\PhpDependencies\OS\PhpFileSet; use PhpParser\Parser as BaseParser; class Parser { /** @var BaseParser */ private $parser; /** * @param $parser */ public function __construct(BaseParser $parser) { $this->parser = $parser; } /** * @param PhpFileSet $files * * @return Ast */ public function parse(PhpFileSet $files) : Ast { return $files->reduce(new Ast(), function (Ast $ast, PhpFile $file) { return $ast->add($file, $this->parser->parse($file->code())); }); } }
GF-5039: Add a call for changed method in create time Enyo-DCO-1.1-Signed-off-by: David Um <david.um@lge.com>
/** _moon.Button_ is an <a href="#enyo.Button">enyo.Button</a> with Moonstone styling applied. The color of the button may be customized by specifying a background color. For more information, see the documentation on <a href='https://github.com/enyojs/enyo/wiki/Buttons'>Buttons</a> in the Enyo Developer Guide. */ enyo.kind({ name : 'moon.Button', kind : 'enyo.Button', publiched : { /** _small_ is a parameter to indicates the size of button. If it has true value, diameter of this button is 60px. However, the tap-target for button still has 78px, so it has invisible DOM which wrap this small button to provide wider tap zone. */ small : false, }, classes : 'moon-button enyo-unselectable', spotlight : true, handlers: { onSpotlightSelect : 'depress', onSpotlightKeyUp : 'undepress' }, create: function() { this.inherited(arguments); this.smallChanged(); }, depress: function() { this.addClass('pressed'); }, undepress: function() { this.removeClass('pressed'); }, smallChanged: function() { this.addRemoveClass('small', this.small); } });
/** _moon.Button_ is an <a href="#enyo.Button">enyo.Button</a> with Moonstone styling applied. The color of the button may be customized by specifying a background color. For more information, see the documentation on <a href='https://github.com/enyojs/enyo/wiki/Buttons'>Buttons</a> in the Enyo Developer Guide. */ enyo.kind({ name : 'moon.Button', kind : 'enyo.Button', publiched : { /** _small_ is a parameter to indicates the size of button. If it has true value, diameter of this button is 60px. However, the tap-target for button still has 78px, so it has invisible DOM which wrap this small button to provide wider tap zone. */ small : false, }, classes : 'moon-button enyo-unselectable', spotlight : true, handlers: { onSpotlightSelect : 'depress', onSpotlightKeyUp : 'undepress' }, depress: function() { this.addClass('pressed'); }, undepress: function() { this.removeClass('pressed'); }, smallChanged: function() { this.addRemoveClass(this.small, 'small'); } });
Tweak logging to add space and colon between type and msg
var Logger = function (config) { this.config = config; this.backend = this.config.backend || 'stdout' this.level = this.config.level || "LOG_INFO" if (this.backend == 'stdout') { this.util = require('util'); } else { if (this.backend == 'syslog') { this.util = require('node-syslog'); this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0); } else { throw "Logger: Should be 'stdout' or 'syslog'." } } } Logger.prototype = { log: function (msg, type) { if (this.backend == 'stdout') { if (!type) { type = 'DEBUG'; } this.util.log(type + ": " + msg); } else { if (!type) { type = this.level if (!this.util[type]) { throw "Undefined log level: " + type; } } else if (type == 'debug') { type = "LOG_DEBUG"; } this.util.log(this.util[type], msg); } } } exports.Logger = Logger
var Logger = function (config) { this.config = config; this.backend = this.config.backend || 'stdout' this.level = this.config.level || "LOG_INFO" if (this.backend == 'stdout') { this.util = require('util'); } else { if (this.backend == 'syslog') { this.util = require('node-syslog'); this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0); } else { throw "Logger: Should be 'stdout' or 'syslog'." } } } Logger.prototype = { log: function (msg, type) { if (this.backend == 'stdout') { if (!type) { type = 'DEBUG: '; } this.util.log(type + msg); } else { if (!type) { type = this.level if (!this.util[type]) { throw "Undefined log level: " + type; } } else if (type == 'debug') { type = "LOG_DEBUG"; } this.util.log(this.util[type], msg); } } } exports.Logger = Logger
Make colored terminal output the default log formatter.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from marionette import BaseMarionetteOptions from greenlight import tests class ReleaseTestParser(BaseMarionetteOptions): def parse_args(self, *args, **kwargs): options, test_files = BaseMarionetteOptions.parse_args(self, *args, **kwargs) if not any([(k.startswith('log_') and v is not None and '-' in v) for (k, v) in vars(options).items()]): options.log_mach = '-' if not test_files: test_files = [tests.manifest] return (options, test_files)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from marionette import BaseMarionetteOptions from greenlight import tests class ReleaseTestParser(BaseMarionetteOptions): def parse_args(self, *args, **kwargs): options, test_files = BaseMarionetteOptions.parse_args(self, *args, **kwargs) if not test_files: test_files = [tests.manifest] return (options, test_files)
tests/route-addon: Use alternative blueprint test helpers
'use strict'; var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); var setupTestHooks = blueprintHelpers.setupTestHooks; var emberNew = blueprintHelpers.emberNew; var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; var chai = require('ember-cli-blueprint-test-helpers/chai'); var expect = chai.expect; describe('Acceptance: ember generate and destroy route-addon', function() { setupTestHooks(this); it('route-addon foo', function() { var args = ['route-addon', 'foo']; return emberNew({ target: 'addon' }) .then(() => emberGenerateDestroy(args, _file => { expect(_file('app/routes/foo.js')) .to.contain("export { default } from 'my-addon/routes/foo';"); expect(_file('app/templates/foo.js')) .to.contain("export { default } from 'my-addon/templates/foo';"); })); }); });
'use strict'; var setupTestHooks = require('ember-cli-blueprint-test-helpers/lib/helpers/setup'); var BlueprintHelpers = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper'); var generateAndDestroy = BlueprintHelpers.generateAndDestroy; describe('Acceptance: ember generate and destroy route-addon', function() { setupTestHooks(this); it('route-addon foo', function() { return generateAndDestroy(['route-addon', 'foo'], { target: 'addon', files: [ { file: 'app/routes/foo.js', contains: [ "export { default } from 'my-addon/routes/foo';" ] }, { file: 'app/templates/foo.js', contains: [ "export { default } from 'my-addon/templates/foo';" ] }, ] }); }); });
Convert iterated Python objects to JS.
// JSPyIterableObject.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.lang.python; import java.util.*; import org.python.core.*; public class JSPyIterableObject extends JSPyObjectWrapper implements Iterable { public JSPyIterableObject( PyObject p ){ super(p); } public Iterator iterator(){ return new IterWrapper( _p.asIterable().iterator() ); } class IterWrapper implements Iterator { Iterator _iter; IterWrapper( Iterator i ){ _iter = i; } public Object next(){ return Python.toJS( next() ); } } }
// JSPyIterableObject.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.lang.python; import java.util.*; import org.python.core.*; public class JSPyIterableObject extends JSPyObjectWrapper implements Iterable { public JSPyIterableObject( PyObject p ){ super(p); } public Iterator iterator(){ return _p.asIterable().iterator(); } }
Fix long-standing bug in aws.stringSetToPointers Instead of N pointers, we were returning N null pointers, followed by the real thing. It's not clear why we didn't trip on this until now, maybe there is a new server-side check for empty subnetID strings.
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package aws import ( "github.com/aws/aws-sdk-go/aws" "k8s.io/kubernetes/pkg/util/sets" ) func stringSetToPointers(in sets.String) []*string { if in == nil { return nil } out := make([]*string, 0, len(in)) for k := range in { out = append(out, aws.String(k)) } return out } func stringSetFromPointers(in []*string) sets.String { if in == nil { return nil } out := sets.NewString() for i := range in { out.Insert(orEmpty(in[i])) } return out } func orZero(v *int64) int64 { if v == nil { return 0 } return *v }
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package aws import ( "github.com/aws/aws-sdk-go/aws" "k8s.io/kubernetes/pkg/util/sets" ) func stringSetToPointers(in sets.String) []*string { if in == nil { return nil } out := make([]*string, len(in)) for k := range in { out = append(out, aws.String(k)) } return out } func stringSetFromPointers(in []*string) sets.String { if in == nil { return nil } out := sets.NewString() for i := range in { out.Insert(orEmpty(in[i])) } return out } func orZero(v *int64) int64 { if v == nil { return 0 } return *v }
Use cartodb_id as FID column in gpkg
var ogr = require('./../ogr'); function GeoPackageFormat() {} GeoPackageFormat.prototype = new ogr('gpkg'); GeoPackageFormat.prototype._contentType = "application/x-sqlite3; charset=utf-8"; GeoPackageFormat.prototype._fileExtension = "gpkg"; // As of GDAL 1.10.1 SRID detection is bogus, so we use // our own method. See: // http://trac.osgeo.org/gdal/ticket/5131 // http://trac.osgeo.org/gdal/ticket/5287 // http://github.com/CartoDB/CartoDB-SQL-API/issues/110 // http://github.com/CartoDB/CartoDB-SQL-API/issues/116 // Bug was fixed in GDAL 1.10.2 GeoPackageFormat.prototype._needSRS = true; GeoPackageFormat.prototype.generate = function(options, callback) { options.cmd_params = ['-lco', 'FID=cartodb_id']; this.toOGR_SingleFile(options, 'GPKG', callback); }; module.exports = GeoPackageFormat;
var ogr = require('./../ogr'); function GeoPackageFormat() {} GeoPackageFormat.prototype = new ogr('gpkg'); GeoPackageFormat.prototype._contentType = "application/x-sqlite3; charset=utf-8"; GeoPackageFormat.prototype._fileExtension = "gpkg"; // As of GDAL 1.10.1 SRID detection is bogus, so we use // our own method. See: // http://trac.osgeo.org/gdal/ticket/5131 // http://trac.osgeo.org/gdal/ticket/5287 // http://github.com/CartoDB/CartoDB-SQL-API/issues/110 // http://github.com/CartoDB/CartoDB-SQL-API/issues/116 // Bug was fixed in GDAL 1.10.2 GeoPackageFormat.prototype._needSRS = true; GeoPackageFormat.prototype.generate = function(options, callback) { this.toOGR_SingleFile(options, 'GPKG', callback); }; module.exports = GeoPackageFormat;
Make route to /game/:id/edit link to EditGame
import React from 'react' import { Router, Route, hashHistory } from 'react-router' import App from './App' import Home from './Home' import Overview from './Overview' import MatchReportContainer from './containers/MatchReportContainer' import NewGameContainer from './containers/NewGameContainer' import EditGameContainer from './containers/EditGameContainer' import ScoreGameContainer from './containers/ScoreGameContainer' import NewTeamContainer from './containers/NewTeamContainer' import EditTeamContainer from './containers/EditTeamContainer' import DashboardContainer from './containers/DashboardContainer' export default ( <Router history={hashHistory}> <Route path='/game/:id/score' component={ScoreGameContainer} /> <Route path='/' component={Home} /> <Route path='/' component={App}> <Route path='/game' component={Overview} /> <Route path='/game/new' component={NewGameContainer} /> <Route path='/game/:id' component={Home} /> <Route path='/game/:id/report' component={MatchReportContainer} /> <Route path='/game/:id/edit' component={EditGameContainer} /> <Route path='/dashboard' component={DashboardContainer} /> <Route path='/team/new' component={NewTeamContainer} /> <Route path='/team/:id/edit' component={EditTeamContainer} /> </Route> </Router> )
import React from 'react' import { Router, Route, hashHistory } from 'react-router' import App from './App' import Home from './Home' import Overview from './Overview' import MatchReportContainer from './containers/MatchReportContainer' import NewGameContainer from './containers/NewGameContainer' import ScoreGameContainer from './containers/ScoreGameContainer' import NewTeamContainer from './containers/NewTeamContainer' import EditTeamContainer from './containers/EditTeamContainer' import DashboardContainer from './containers/DashboardContainer' export default ( <Router history={hashHistory}> <Route path='/game/:id/score' component={ScoreGameContainer} /> <Route path='/' component={Home} /> <Route path='/' component={App}> <Route path='/game/new' component={NewGameContainer} /> <Route path='/game' component={Overview} /> <Route path='/game/:id' component={Home} /> <Route path='/game/:id/report' component={MatchReportContainer} /> <Route path='/dashboard' component={DashboardContainer} /> <Route path='/team/new' component={NewTeamContainer} /> <Route path='/team/:id/edit' component={EditTeamContainer} /> </Route> </Router> )
Fix time formatting for queue items
import _ from 'lodash'; export function formatDuration(duration) { var sec_num = parseInt(duration, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (hours < 10) {hours = '0'+hours;} if (minutes < 10) {minutes = '0'+minutes;} if (seconds < 10) {seconds = '0'+seconds;} if (hours === '00') { return minutes+':'+seconds; } else { return hours+':'+minutes+':'+seconds; } } export function getSelectedStream(streams, defaultMusicSource) { let selectedStream = _.find(streams, {source: defaultMusicSource}); return selectedStream === undefined ? streams ? streams[0] : null : selectedStream; }
import _ from 'lodash'; export function formatDuration(duration) { var sec_num = parseInt(duration, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} if (seconds < 10) {seconds = "0"+seconds;} if (hours === 0) { return minutes+':'+seconds; } else { return hours+':'+minutes+':'+seconds; } } export function getSelectedStream(streams, defaultMusicSource) { let selectedStream = _.find(streams, {source: defaultMusicSource}); return selectedStream === undefined ? streams ? streams[0] : null : selectedStream; }
Change example to conform to API
package main import ( "github.com/sean-duffy/xlsx" "strconv" ) func main() { c := []xlsx.Column{ xlsx.Column{Name: "Col1", Width: 10}, xlsx.Column{Name: "Col2", Width: 10}, } sh := xlsx.NewSheetWithColumns(c) sh.Title = "MySheet" for i := 0; i < 10; i++ { r := sh.NewRow() r.Cells[0] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: strconv.Itoa(i + 1), } r.Cells[1] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: "1", } sh.AppendRow(r) } err := sh.SaveToFile("test.xlsx") _ = err }
package main import ( "github.com/sean-duffy/xlsx" "strconv" ) func main() { c := []xlsx.Column{ xlsx.Column{Name: "Col1", Width: 10}, xlsx.Column{Name: "Col2", Width: 10}, } sh := xlsx.NewSheetWithColumns(c, "MySheet") for i := 0; i < 10; i++ { r := sh.NewRow() r.Cells[0] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: strconv.Itoa(i + 1), } r.Cells[1] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: "1", } sh.AppendRow(r) } err := sh.SaveToFile("test.xlsx") _ = err }
Fix incorrect arg to omit
import fetchResource from './helpers/fetchResource'; import omit from './helpers/omit'; import parseUrl from './helpers/parseUrl'; const DEFAULTS = { method: 'GET' }; export default function createResourceAction( options, sendType, successType, errorType ) { let rawUrl, urlCompiler; if (typeof options === 'string') { rawUrl = options; options = {}; } else { rawUrl = options.url; options = omit(options, ['url']); } if (!rawUrl) { throw new Error('Please provide a url for the resource'); } urlCompiler = parseUrl(rawUrl); options = { ...DEFAULTS, ...options }; const resourceSendAction = () => ({ type: sendType }); const resourceSuccessAction = (resource) => ({ type: successType, payload: resource }); const resourceErrorAction = (error) => ({ type: errorType, payload: error }); return (params, data) => (dispatch) => { const url = urlCompiler(params); dispatch(resourceSendAction()); return fetchResource(url, { ...options, data }).then( resource => dispatch(resourceSuccessAction(resource)), error => dispatch(resourceErrorAction(error)) ); }; }
import fetchResource from './helpers/fetchResource'; import omit from './helpers/omit'; import parseUrl from './helpers/parseUrl'; const DEFAULTS = { method: 'GET' }; export default function createResourceAction( options, sendType, successType, errorType ) { let rawUrl, urlCompiler; if (typeof options === 'string') { rawUrl = options; options = {}; } else { rawUrl = options.url; options = omit(options, 'url'); } if (!rawUrl) { throw new Error('Please provide a url for the resource'); } urlCompiler = parseUrl(rawUrl); options = { ...DEFAULTS, ...options }; const resourceSendAction = () => ({ type: sendType }); const resourceSuccessAction = (resource) => ({ type: successType, payload: resource }); const resourceErrorAction = (error) => ({ type: errorType, payload: error }); return (params, data) => (dispatch) => { const url = urlCompiler(params); dispatch(resourceSendAction()); return fetchResource(url, { ...options, data }).then( resource => dispatch(resourceSuccessAction(resource)), error => dispatch(resourceErrorAction(error)) ); }; }
Allow elements within SVG to overflow
function chart(selection) { // Merging the various user params vars.user_vars = vistk.utils.merge(vars.user_vars, vars._user_vars); // Merging with current charts parameters set by the user in the HTML file vars = vistk.utils.merge(vars, vars.user_vars); // Create the top level element conaining the visualization if(!vars.svg) { if(vars.type !== "table") { vars.svg = d3.select(vars.container).append("svg") .attr("width", vars.width) .attr("height", vars.height) .style('overflow', 'visible') .style('z-index', 0) .append("g") .attr("transform", "translate(" + vars.margin.left + "," + vars.margin.top + ")"); } else { // HTML Container for table vars.svg = d3.select(vars.container).append("div") .style({height: vars.height+"px", width: vars.width+"px", overflow: "scroll"}); } }
function chart(selection) { // Merging the various user params vars.user_vars = vistk.utils.merge(vars.user_vars, vars._user_vars); // Merging with current charts parameters set by the user in the HTML file vars = vistk.utils.merge(vars, vars.user_vars); // Create the top level element conaining the visualization if(!vars.svg) { if(vars.type !== "table") { vars.svg = d3.select(vars.container).append("svg") .attr("width", vars.width) .attr("height", vars.height) .append("g") .attr("transform", "translate(" + vars.margin.left + "," + vars.margin.top + ")"); } else { // HTML Container for table vars.svg = d3.select(vars.container).append("div") .style({height: vars.height+"px", width: vars.width+"px", overflow: "scroll"}); } }
Include required echo service in package
from setuptools import setup, find_packages VERSION = '3.0.1' setup( name='django-node', version=VERSION, packages=find_packages(exclude=('tests', 'example',)), package_data={ 'django_node': [ 'node_server.js', 'services/echo.js', 'package.json', ], }, install_requires=[ 'django', 'requests>=2.5.1', ], description='Bindings and utils for integrating Node.js and NPM into a Django application', long_description='Documentation at https://github.com/markfinger/django-node', author='Mark Finger', author_email='markfinger@gmail.com', url='https://github.com/markfinger/django-node', )
from setuptools import setup, find_packages VERSION = '3.0.1' setup( name='django-node', version=VERSION, packages=find_packages(exclude=('tests', 'example',)), package_data={ 'django_node': [ 'node_server.js', 'package.json', ], }, install_requires=[ 'django', 'requests>=2.5.1', ], description='Bindings and utils for integrating Node.js and NPM into a Django application', long_description='Documentation at https://github.com/markfinger/django-node', author='Mark Finger', author_email='markfinger@gmail.com', url='https://github.com/markfinger/django-node', )
Hide 'other' activity on ui.
'use strict'; (function(isNode, isAngular) { var activities = [ {name: 'bike', textOver: 'Велосипед'}, {name: 'running', textOver: 'Бег'}, {name: 'workout', textOver: 'Workout'}, {name: 'hiking', textOver: 'Туризм'}, {name: 'photo', textOver: 'Фото'}, {name: 'en', textOver: 'Языки'}, {name: 'code', textOver: 'IT'}, {name: 'other', textOver: 'Другое', hide: true /*temp*/} // TODO find image for 'other' ]; if (isAngular) { angular.module('myApp.shared') .constant('activities', _.filter(activities, function(activity) { return !activity.hide; })); } else if (isNode) { module.exports.activities = activities; } })(typeof module !== 'undefined' && module.exports, typeof angular !== 'undefined');
'use strict'; (function(isNode, isAngular) { var activities = [ {name: 'bike', textOver: 'Велосипед'}, {name: 'running', textOver: 'Бег'}, {name: 'workout', textOver: 'Workout'}, {name: 'hiking', textOver: 'Туризм'}, {name: 'photo', textOver: 'Фото'}, {name: 'en', textOver: 'Языки'}, {name: 'code', textOver: 'IT'}, {name: 'other', textOver: 'Другое'} // TODO find image for 'other' ]; if (isAngular) { angular.module('myApp.shared') .constant('activities', activities); } else if (isNode) { module.exports.activities = activities; } })(typeof module !== 'undefined' && module.exports, typeof angular !== 'undefined');
Remove button and cover fields from default config
<?php return [ // Class you want to use to represent sections 'sectionClass' => \StartupPalace\Maki\Section::class, // Class you want to use to represent field values 'fieldValueClass' => \StartupPalace\Maki\FieldValue::class, // Path to Maki's templates (from `resources/views`) 'templatePath' => 'maki', // Describe the field types use in your application 'fields' => [ 'title' => [ 'type' => 'input:text', ], 'text' => [ 'type' => 'textarea', ], 'content' => [ 'type' => 'wysiwyg', ], ], // Describe the different section types used in your application 'sectionTypes' => [ 'default' => [ 'template' => 'default', 'fields' => [ 'title', 'text', 'content', ], ], ], ];
<?php return [ // Class you want to use to represent sections 'sectionClass' => \StartupPalace\Maki\Section::class, // Class you want to use to represent field values 'fieldValueClass' => \StartupPalace\Maki\FieldValue::class, // Path to Maki's templates (from `resources/views`) 'templatePath' => 'maki', // Describe the field types use in your application 'fields' => [ 'content' => [ 'type' => 'wysiwyg', ], 'title' => [ 'type' => 'input:text', ], 'cover' => [ 'type' => 'input:file:image', ], 'text' => [ 'type' => 'textarea', ], 'button' => [ 'type' => 'link', ], ], // Describe the different section types used in your application 'sectionTypes' => [ 'default' => [ 'template' => 'default', 'fields' => [ 'title', 'cover', 'content', 'button', ], ], ], ];
Add validation details to the Admin interface
from django.contrib import admin from reddit.models import RedditAccount from reddit.forms import RedditAccountForm from datetime import date class RedditAccountAdmin(admin.ModelAdmin): list_display = ('username', 'user', 'date_created', 'link_karma', 'comment_karma', 'last_update', 'validated', 'is_valid') search_fields = ['username'] fields = ('user', 'username') form = RedditAccountForm def is_valid(self, obj): if not obj.date_created: return False # Account 3 months old? if (date.today() - obj.date_created.date()).days >= 90: return True # Account created after 9/2/10 and before 13/2/10 if obj.date_created.date() >= date(2010, 2, 9) and obj.date_created.date() <= date(2010, 2, 13): return True return False is_valid.short_description = 'Dreddit Eligible' is_valid.boolean = True def save_model(self, request, obj, form, change): obj.api_update() obj.save() admin.site.register(RedditAccount, RedditAccountAdmin)
from django.contrib import admin from reddit.models import RedditAccount from reddit.forms import RedditAccountForm from datetime import date class RedditAccountAdmin(admin.ModelAdmin): list_display = ('username', 'user', 'date_created', 'link_karma', 'comment_karma', 'last_update', 'is_valid') search_fields = ['username', 'user'] fields = ('user', 'username') form = RedditAccountForm def is_valid(self, obj): if not obj.date_created: return False # Account 3 months old? if (date.today() - obj.date_created.date()).days >= 90: return True # Account created after 9/2/10 and before 13/2/10 if obj.date_created.date() >= date(2010, 2, 9) and obj.date_created.date() <= date(2010, 2, 13): return True return False is_valid.short_description = 'Dreddit Eligible' is_valid.boolean = True def save_model(self, request, obj, form, change): obj.api_update() obj.save() admin.site.register(RedditAccount, RedditAccountAdmin)
Make parent server more robust
#!/usr/bin/env python import os import select import json import serf def server(): """A server for serf commands. Commands are a string object that are passed to serf. """ os.mkfifo('/serfnode/parent') pipe = os.fdopen( os.open('/serfnode/parent', os.O_RDONLY | os.O_NONBLOCK), 'r', 0) # open a dummy client to avoid getting EOF when other clients disconnect _pipe = os.fdopen( os.open('/serfnode/parent', os.O_WRONLY | os.O_NONBLOCK), 'w', 0) polling = select.poll() polling.register(pipe.fileno()) while True: polling.poll() cmd = pipe.readline() try: name, payload = json.loads(cmd) except: print("Wrong payload: {}".format(cmd)) try: serf.serf_plain('event', name, json.dumps(payload)) except: print("serf command failed") if __name__ == '__main__': server()
#!/usr/bin/env python import os import select import serf def server(): """A server for serf commands. Commands are a string object that are passed to serf. """ os.mkfifo('/serfnode/parent') pipe = os.fdopen( os.open('/serfnode/parent', os.O_RDONLY | os.O_NONBLOCK), 'r', 0) # open a dummy client to avoid getting EOF when other clients disconnect _pipe = os.fdopen( os.open('/serfnode/parent', os.O_WRONLY | os.O_NONBLOCK), 'w', 0) polling = select.poll() polling.register(pipe.fileno()) while True: polling.poll() cmd = pipe.readline() serf.serf_plain(*cmd.split()) if __name__ == '__main__': server()
Initialize post list when showing post list page
$(document).on('pageshow', '#post-list', function() { initPostList(); }); function initPostList() { var api_uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/select.py?order_by=created_at&order=descend'; $.getJSON(api_uri, function(json) { for (var i = 0; i < json.length; i++) { var $li = createListItem(json[i].title, json[i].comment, json[i].posted_by); $('#post_list').append($li); } $('#post_list').listview('refresh'); }); } function createListItem(title, comment, posted_by) { var $title = $('<h2>').text(title); var $comment = $('<p>').text(comment); var $posted_by = $('<p>').text(posted_by); var $li = $('<li>').append($title).append($comment).append($posted_by); return $li; }
$(function() { var api_uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/select.py?order_by=created_at&order=descend'; $.getJSON(api_uri, function(json) { for (var i = 0; i < json.length; i++) { var $li = createListItem(json[i].title, json[i].comment, json[i].posted_by); $('#post_list').append($li); } $('#post_list').listview('refresh'); }); }); function createListItem(title, comment, posted_by) { var $title = $('<h2>').text(title); var $comment = $('<p>').text(comment); var $posted_by = $('<p>').text(posted_by); var $li = $('<li>').append($title).append($comment).append($posted_by); return $li; }
Handle Google Analytics code initializing in a module
(function loadGapi() { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://apis.google.com/js/client.js?onload=initgapi"; head.appendChild(script); })(); window._gaq = window._gaq || []; var _gaq = window._gaq; _gaq.push(['_setAccount', 'UA-60316581-1']); _gaq.push(['_setCustomVar', 1, 'DIMVersion', '$DIM_VERSION', 3]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://www.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); /* eslint no-unused-vars:0 no-implicit-globals:0 */ var iosDragDropShim = { enableEnterLeave: true };
(function loadGapi() { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://apis.google.com/js/client.js?onload=initgapi"; head.appendChild(script); })(); var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-60316581-1']); _gaq.push(['_setCustomVar', 1, 'DIMVersion', '$DIM_VERSION', 3]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://www.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); /* eslint no-unused-vars:0 no-implicit-globals:0 */ var iosDragDropShim = { enableEnterLeave: true };
Fix up some styling on user show page.
@extends('layout.master') @section('main_content') <h3> {{ $user['first_name'] }}</h3> <a href="{{ url('users/' . $user['_id'] . '/edit') }}"> Edit User <span class="glyphicon glyphicon-pencil"></span></a> @if ($aurora_user) Admin: {{ $aurora_user->hasRole('admin') ? '✓' : 'x' }} @if (!$aurora_user->hasRole('admin')) {{ Form::open(['route' => array('admin.create', $aurora_user->id)]) }} {{ Form::submit('make admin') }} {{ Form::close() }} @endif @endif <div class="container"> @foreach($user as $key => $field) @if (!in_array($key, ['created_at', 'updated_at', 'campaigns'])) @if (!empty($field)) <dt class="control-label col-sm-2"><strong>{{ $key }}</strong> </dt> <dl> {{ $field }} </dl> @endif @endif @if ($key == 'campaigns') @foreach($field as $campaigns) {{var_dump($campaigns)}} @endforeach @endif @endforeach </div> @stop
@extends('layout.master') @section('main_content') <a href="{{ url('users/' . $user['_id'] . '/edit') }}"> Edit User <span class="glyphicon glyphicon-pencil"></span></a> @if ($aurora_user) Admin: {{ $aurora_user->hasRole('admin') ? '✓' : 'x' }} @if (!$aurora_user->hasRole('admin')) {{ Form::open(['route' => array('admin.create', $aurora_user->id)]) }} {{ Form::submit('make admin') }} {{ Form::close() }} @endif @endif @foreach($user as $key => $field) @if (!in_array($key, ['created_at', 'updated_at', 'campaigns'])) @if (!empty($field)) <dt><strong>{{ $key }}</strong> </dt> <dl> {{ $field }} </dl> @endif @endif @if ($key == 'campaigns') @foreach($field as $campaigns) {{var_dump($campaigns)}} @endforeach @endif @endforeach @stop
Use debug log for logging.
const crypto = require('crypto'); /** * memHandler - In memory upload handler * @param {object} options * @param {string} fieldname * @param {string} filename */ module.exports = function(options, fieldname, filename) { let buffers = []; let fileSize = 0; // eslint-disable-line let hash = crypto.createHash('md5'); const getBuffer = () => Buffer.concat(buffers); const emptyFunc = () => ''; return { dataHandler: function(data) { buffers.push(data); hash.update(data); fileSize += data.length; debugLog(options, `Uploading ${fieldname} -> ${filename}, bytes: ${fileSize}`); }, getBuffer: getBuffer, getFilePath: emptyFunc, getFileSize: function(){ return fileSize; }, getHash: function(){ return hash.digest('hex'); }, complete: getBuffer, cleanup: emptyFunc }; };
const crypto = require('crypto'); /** * memHandler - In memory upload handler * @param {object} options * @param {string} fieldname * @param {string} filename */ module.exports = function(options, fieldname, filename) { let buffers = []; let fileSize = 0; // eslint-disable-line let hash = crypto.createHash('md5'); const getBuffer = () => Buffer.concat(buffers); const emptyFunc = () => ''; return { dataHandler: function(data) { buffers.push(data); hash.update(data); fileSize += data.length; if (options.debug) { return console.log('Uploading %s -> %s, bytes: %d', fieldname, filename, fileSize); // eslint-disable-line } }, getBuffer: getBuffer, getFilePath: emptyFunc, getFileSize: function(){ return fileSize; }, getHash: function(){ return hash.digest('hex'); }, complete: getBuffer, cleanup: emptyFunc }; };
Increase max length of petition answer text
import settings from 'settings'; export default [ { element: 'input', name: 'petitionId', hidden: true, html: { type: 'hidden' } }, { element: 'input', name: 'token', hidden: true, html: { type: 'hidden' } }, { element: 'textarea', name: 'answer.text', label: settings.respondToPetitionFields.response.label, hint: settings.respondToPetitionFields.response.hint, html: { placeholder: settings.respondToPetitionFields.response.placeholder, required: true, minLength: 50, maxLength: 10000 } }, { element: 'input', name: 'answer.name', label: settings.respondToPetitionFields.name.label, hint: settings.respondToPetitionFields.name.hint, html: { type: 'text', placeholder: settings.respondToPetitionFields.name.placeholder, required: true, minLength: 15, maxLength: 80 } } ];
import settings from 'settings'; export default [ { element: 'input', name: 'petitionId', hidden: true, html: { type: 'hidden' } }, { element: 'input', name: 'token', hidden: true, html: { type: 'hidden' } }, { element: 'textarea', name: 'answer.text', label: settings.respondToPetitionFields.response.label, hint: settings.respondToPetitionFields.response.hint, html: { placeholder: settings.respondToPetitionFields.response.placeholder, required: true, minLength: 50, maxLength: 500 } }, { element: 'input', name: 'answer.name', label: settings.respondToPetitionFields.name.label, hint: settings.respondToPetitionFields.name.hint, html: { type: 'text', placeholder: settings.respondToPetitionFields.name.placeholder, required: true, minLength: 15, maxLength: 80 } } ];
Rename Connection transmit function to process for use in IPFGraph
# -*- coding: utf-8 -*- import ioport class Connection(object): """ Connection class for IPFBlock Connection binding OPort and IPort of some IPFBlocks """ def __init__(self, oport, iport): # Check port compatibility and free of input port if ioport.compatible(oport, iport) and iport.is_free(): self._oport = oport self._iport = iport self._oport.increase_binded_count() self._iport.set_binded() else: raise ValueError("Can not create Connection with given ports") def __del__(self): self._oport.decrease_binded_count() self._iport.set_free() def process(self): """ Send value from output port to input port """ self._iport.pass_value(self._oport.get_valure())
# -*- coding: utf-8 -*- import ioport class Connection(object): """ Connection class for IPFBlock Connection binding OPort and IPort of some IPFBlocks """ def __init__(self, oport, iport): # Check port compatibility and free of input port if ioport.compatible(oport, iport) and iport.is_free(): self._oport = oport self._iport = iport self._oport.increase_binded_count() self._iport.set_binded() else: raise ValueError("Can not create Connection with given ports") def __del__(self): self._oport.decrease_binded_count() self._iport.set_free() def transmit(self): """ Send value from output port to input port """ self._iport.pass_value(self._oport.get_valure())