text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix URL of healthcheck endpoint
package com.surfsoftconsulting.clipper.racetracker.controller; /* * Copyright 2017 Phil Haigh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.web.bind.annotation.RequestMethod.GET; @RestController public class HealthCheckController { @RequestMapping(method=GET, path="/healthcheck") public void healthCheck() {} }
package com.surfsoftconsulting.clipper.racetracker.controller; /* * Copyright 2017 Phil Haigh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.web.bind.annotation.RequestMethod.GET; @RestController public class HealthCheckController { @RequestMapping(method=GET, path="/") public void healthCheck() {} }
Prepare version numbers for upcoming beta
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.08.06-RC"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ "" }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.06.06"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ "2022-07-31" }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
Add more Python 3 classifiers
#!/usr/bin/env python # coding: utf-8 """A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='david.michael.tucker@gmail.com', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Development Status :: 4 - Beta', ], )
#!/usr/bin/env python # coding: utf-8 """A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='david.michael.tucker@gmail.com', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Development Status :: 4 - Beta', ], )
Fix iframe info receiver using wrong url
'use strict'; var inherits = require('inherits') , EventEmitter = require('events').EventEmitter , JSON3 = require('json3') , XHRLocalObject = require('./transport/sender/xhr-local') , InfoAjax = require('./info-ajax') ; function InfoReceiverIframe(transUrl) { var self = this; EventEmitter.call(this); this.ir = new InfoAjax(transUrl, XHRLocalObject); this.ir.once('finish', function(info, rtt) { self.ir = null; self.emit('message', JSON3.stringify([info, rtt])); }); } inherits(InfoReceiverIframe, EventEmitter); InfoReceiverIframe.transportName = 'iframe-info-receiver'; InfoReceiverIframe.prototype.close = function() { if (this.ir) { this.ir.close(); this.ir = null; } this.removeAllListeners(); }; module.exports = InfoReceiverIframe;
'use strict'; var inherits = require('inherits') , EventEmitter = require('events').EventEmitter , JSON3 = require('json3') , XHRLocalObject = require('./transport/sender/xhr-local') , InfoAjax = require('./info-ajax') ; function InfoReceiverIframe(transUrl, baseUrl) { var self = this; EventEmitter.call(this); this.ir = new InfoAjax(baseUrl, XHRLocalObject); this.ir.once('finish', function(info, rtt) { self.ir = null; self.emit('message', JSON3.stringify([info, rtt])); }); } inherits(InfoReceiverIframe, EventEmitter); InfoReceiverIframe.transportName = 'iframe-info-receiver'; InfoReceiverIframe.prototype.close = function() { if (this.ir) { this.ir.close(); this.ir = null; } this.removeAllListeners(); }; module.exports = InfoReceiverIframe;
Add version constraint for xamfoo:reactive-obj
Package.describe({ name: 'blazer:react', version: '0.1.1', summary: "Blaze add-on: Create stateful components with methods and mixins like in Facebook's React", git: 'https://github.com/xamfoo/blazer-react', documentation: 'README.md' }); Package.onUse(function(api) { configure(api); }); Package.onTest(function(api) { configure(api); api.use('tinytest'); }); function configure (api) { api.versionsFrom('1.0.4.1'); api.use([ 'blaze', 'reactive-dict', 'tracker', 'check', 'underscore', 'templating' ], 'client'); api.use('xamfoo:reactive-obj@0.4.0', 'client', {weak: true}); api.addFiles([ 'lib/blazer.js', 'lib/component.js', 'lib/component_static.js', 'lib/helpers.js', ], 'client'); api.export('Blazer', 'client'); }
Package.describe({ name: 'blazer:react', version: '0.1.1', summary: "Blaze add-on: Create stateful components with methods and mixins like in Facebook's React", git: 'https://github.com/xamfoo/blazer-react', documentation: 'README.md' }); Package.onUse(function(api) { configure(api); }); Package.onTest(function(api) { configure(api); api.use('tinytest'); }); function configure (api) { api.versionsFrom('1.0.4.1'); api.use([ 'blaze', 'reactive-dict', 'tracker', 'check', 'underscore', 'templating' ], 'client'); api.use('xamfoo:reactive-obj', 'client', {weak: true}); api.addFiles([ 'lib/blazer.js', 'lib/component.js', 'lib/component_static.js', 'lib/helpers.js', ], 'client'); api.export('Blazer', 'client'); }
Add spaces to leaderboard names
require('./style.scss'); var $ = require("jquery"); var Game = require("./game"); var Menu = require("./menu"); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var menu = new Menu(); function setupPregameDisplay() { menu.setup(); $("#restartButton").on("click", gameLoop); } function setupGameDisplay() { menu.prepareForGame(); } function setupPostgameDisplay(score) { $("#restartButton").show(); menu.scoreBoard.getLeaderName(score); } function gameLoop() { var game = new Game(canvas, context); setupGameDisplay(); game.setup(); requestAnimationFrame(function gamePlay() { if (game.inProgress()) { game.gameLoop(); setTimeout(function(){ requestAnimationFrame(gamePlay); }, game.speed * 50); } else { game.render.displayGameOver(); setupPostgameDisplay(game.score); } }); } setupPregameDisplay(); window.addEventListener("keydown", function(e) { if([37, 38, 39, 40].indexOf(e.keyCode) > -1) { e.preventDefault(); } }, false);
require('./style.scss'); var $ = require("jquery"); var Game = require("./game"); var Menu = require("./menu"); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var menu = new Menu(); function setupPregameDisplay() { menu.setup(); $("#restartButton").on("click", gameLoop); } function setupGameDisplay() { menu.prepareForGame(); } function setupPostgameDisplay(score) { $("#restartButton").show(); menu.scoreBoard.getLeaderName(score); } function gameLoop() { var game = new Game(canvas, context); setupGameDisplay(); game.setup(); requestAnimationFrame(function gamePlay() { if (game.inProgress()) { game.gameLoop(); setTimeout(function(){ requestAnimationFrame(gamePlay); }, game.speed * 50); } else { game.render.displayGameOver(); setupPostgameDisplay(game.score); } }); } setupPregameDisplay(); window.addEventListener("keydown", function(e) { if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) { e.preventDefault(); } }, false);
Allow space before custom command name
'use strict'; const { hears } = require('telegraf'); const R = require('ramda'); // DB const { getCommand } = require('../../stores/command'); const capitalize = R.replace(/^./, R.toUpper); const getRepliedToId = R.path([ 'reply_to_message', 'message_id' ]); const typeToMethod = type => type === 'text' ? 'replyWithHTML' : `replyWith${capitalize(type)}`; const runCustomCmdHandler = async (ctx, next) => { const { message, state } = ctx; const { isAdmin, isMaster } = state; const commandName = ctx.match[1].toLowerCase(); const command = await getCommand({ isActive: true, name: commandName }); if (!command) { return next(); } const { caption, content, type } = command; const role = command.role.toLowerCase(); if ( role === 'master' && !isMaster || role === 'admins' && !isAdmin ) { return next(); } const reply_to_message_id = getRepliedToId(message); const options = { caption, disable_web_page_preview: true, reply_to_message_id, }; return ctx[typeToMethod(type)](content, options); }; module.exports = hears(/^! ?(\w+)/, runCustomCmdHandler);
'use strict'; const { hears } = require('telegraf'); const R = require('ramda'); // DB const { getCommand } = require('../../stores/command'); const capitalize = R.replace(/^./, R.toUpper); const getRepliedToId = R.path([ 'reply_to_message', 'message_id' ]); const typeToMethod = type => type === 'text' ? 'replyWithHTML' : `replyWith${capitalize(type)}`; const runCustomCmdHandler = async (ctx, next) => { const { message, state } = ctx; const { isAdmin, isMaster } = state; const commandName = ctx.match[1].toLowerCase(); const command = await getCommand({ isActive: true, name: commandName }); if (!command) { return next(); } const { caption, content, type } = command; const role = command.role.toLowerCase(); if ( role === 'master' && !isMaster || role === 'admins' && !isAdmin ) { return next(); } const reply_to_message_id = getRepliedToId(message); const options = { caption, disable_web_page_preview: true, reply_to_message_id, }; return ctx[typeToMethod(type)](content, options); }; module.exports = hears(/^!(\w+)/, runCustomCmdHandler);
Add default country to wpa supplicant
package config // Default Configurator constants that are describe a specific configuration option const ( Locale = "Locale" Keymap = "Keymap" Wifi = "Wifi" Interface = "Interface" DNS = "DNS" SSH = "SSH" Camera = "Camera" MountDir = "/tmp/isaax-sd/" Language = "LANGUAGE=%s\n" LocaleAll = "LC_ALL=%s\n" LocaleLang = "LANG=%s\n" DefaultLocale = "en_US.UTF-8" IsaaxConfDir = "/etc/" TmpDir = "/tmp/" InterfaceWLAN string = "auto wlan0\n" + "iface wlan0 inet static\n" + "address %s\n" + "netmask %s\n" + "gateway %s\n" + "dns-nameservers %s\n" InterfaceETH string = "auto eth0\n" + "iface eth0 inet static\n" + "address %s\n" + "netmask %s\n" + "gateway %s\n" + "dns-nameservers %s\n" + "\n" + "iface default inet dhcp\n" WPAconf = `ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev country=us update_config=1 network={ ssid=\"%s\" psk=\"%s\" } ` )
package config // Default Configurator constants that are describe a specific configuration option const ( Locale = "Locale" Keymap = "Keymap" Wifi = "Wifi" Interface = "Interface" DNS = "DNS" SSH = "SSH" Camera = "Camera" MountDir = "/tmp/isaax-sd/" Language = "LANGUAGE=%s\n" LocaleAll = "LC_ALL=%s\n" LocaleLang = "LANG=%s\n" DefaultLocale = "en_US.UTF-8" IsaaxConfDir = "/etc/" TmpDir = "/tmp/" InterfaceWLAN string = "auto wlan0\n" + "iface wlan0 inet static\n" + "address %s\n" + "netmask %s\n" + "gateway %s\n" + "dns-nameservers %s\n" InterfaceETH string = "auto eth0\n" + "iface eth0 inet static\n" + "address %s\n" + "netmask %s\n" + "gateway %s\n" + "dns-nameservers %s\n" + "\n" + "iface default inet dhcp\n" WPAconf = `ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev update_config=1 network={ ssid=\"%s\" psk=\"%s\" } ` )
Add Read single Product method to Angular Controller.
'use strict'; angular.module('products').controller('ProductsController', ['$scope', '$stateParams', '$location', 'Products', function($scope, $stateParams, $location, Products) { // List Products $scope.find = function() { $scope.products = Products.query(); }; // CREATE new Product $scope.create = function() { // Create new Product object var product = new Products ({ category: this.category, name: this.name, quantityPerUnit: this.quantityPerUnit, unitPrice: this.unitPrice, unitsInStock: this.unitsInStock, unitsOnOrder: this.unitsOnOrder }); // Redirect after save product.$save(function(response) { $location.path('products/' + response._id); // Clear form fields $scope.name = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // READ single Product $scope.findOne = function() { $scope.product = Products.get({ productId: $stateParams.productId }); }; } ]);
'use strict'; angular.module('products').controller('ProductsController', ['$scope', '$stateParams', '$location', 'Products', function($scope, $stateParams, $location, Products) { // List Categories $scope.find = function() { $scope.products = Products.query(); }; // CREATE new Category $scope.create = function() { // Create new Product object var product = new Products ({ category: this.category, name: this.name, quantityPerUnit: this.quantityPerUnit, unitPrice: this.unitPrice, unitsInStock: this.unitsInStock, unitsOnOrder: this.unitsOnOrder }); // Redirect after save product.$save(function(response) { $location.path('products/' + response._id); // Clear form fields $scope.name = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; } ]);
Revert "Function is used statically, changed function definition to fix error" This reverts commit d4bfa121e6a028f0a8d239e8a4806e44b553e737.
<?php class Kwf_View_Helper_FileSize { public function fileSize($filesize) { if (!is_int($filesize) && file_exists($filesize)) { $filesize = filesize($filesize); } $shortcuts = array("Bytes", "KB", "MB", "GB", "TB", "PB"); $i = 0; while ($filesize > 1024 && isset($shortcuts[$i+1])) { $filesize = $filesize / 1024; $i++; } if ($filesize < 10) { $ret = number_format($filesize, 1, ",", "."); } else { $ret = number_format($filesize, 0, ",", "."); } $ret .= ' '.$shortcuts[$i]; return $ret; } }
<?php class Kwf_View_Helper_FileSize { public static function fileSize($filesize) { if (!is_int($filesize) && file_exists($filesize)) { $filesize = filesize($filesize); } $shortcuts = array("Bytes", "KB", "MB", "GB", "TB", "PB"); $i = 0; while ($filesize > 1024 && isset($shortcuts[$i+1])) { $filesize = $filesize / 1024; $i++; } if ($filesize < 10) { $ret = number_format($filesize, 1, ",", "."); } else { $ret = number_format($filesize, 0, ",", "."); } $ret .= ' '.$shortcuts[$i]; return $ret; } }
Define mock @profile decorator in builtins.
# -*- coding: utf-8 -*- # flake8: noqa """ phy is an open source electrophysiological data analysis package in Python for neuronal recordings made with high-density multielectrode arrays containing up to thousands of channels. """ #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ # Define a mock @profile decorator to avoid NameErrors when profiling. import sys if sys.version_info[0] == 3: import builtins else: import __builtin__ as builtins builtins.__dict__['profile'] = lambda func: func import os.path as op from pkg_resources import get_distribution, DistributionNotFound from .utils.logging import _default_logger, set_level from .utils.datasets import download_test_data from .utils.dock import enable_qt, qt_app #------------------------------------------------------------------------------ # Global variables and functions #------------------------------------------------------------------------------ __author__ = 'Kwik team' __email__ = 'cyrille.rossant at gmail.com' __version__ = '0.1.0.dev0' __all__ = ['debug', 'set_level'] # Set up the default logger. _default_logger() def debug(enable=True): """Enable debug logging mode.""" if enable: set_level('debug') else: set_level('info')
# -*- coding: utf-8 -*- # flake8: noqa """ phy is an open source electrophysiological data analysis package in Python for neuronal recordings made with high-density multielectrode arrays containing up to thousands of channels. """ #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import os.path as op from pkg_resources import get_distribution, DistributionNotFound from .utils.logging import _default_logger, set_level from .utils.datasets import download_test_data from .utils.dock import enable_qt, qt_app #------------------------------------------------------------------------------ # Global variables and functions #------------------------------------------------------------------------------ __author__ = 'Kwik team' __email__ = 'cyrille.rossant at gmail.com' __version__ = '0.1.0.dev0' __all__ = ['debug', 'set_level'] # Set up the default logger. _default_logger() def debug(enable=True): """Enable debug logging mode.""" if enable: set_level('debug') else: set_level('info')
Disable preloader so the site isn't blanked out with js disabled
//<![CDATA[ $(window).load(function() { // makes sure the whole site is loaded // $('#status').fadeOut(); // will first fade out the loading animation // $('#preloader').delay(150).fadeOut('fast'); // will fade out the white DIV that covers the website. $('body').delay(100).css({'overflow':'visible'}); }) //]]> !function ($) { $(function(){ window.prettyPrint && prettyPrint() }) }(window.jQuery) (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-X', 'auto'); ga('send', 'pageview');
//<![CDATA[ $(window).load(function() { // makes sure the whole site is loaded $('#status').fadeOut(); // will first fade out the loading animation $('#preloader').delay(150).fadeOut('fast'); // will fade out the white DIV that covers the website. $('body').delay(100).css({'overflow':'visible'}); }) //]]> !function ($) { $(function(){ window.prettyPrint && prettyPrint() }) }(window.jQuery) (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-X', 'auto'); ga('send', 'pageview');
Replace type filtering method with a name based assign() method
<?php namespace Bolt\Api; class Connections extends \Bolt\Base { public $sources; public function __construct($connections = null) { if ($connections !== null) { if (is_array($connections)) { foreach ($connections as $connection) { $this->add($connection); } } else { $this->add($connections); } } } public function add($connection) { $this->sources[] = $connection; } public function assign($name, $index) { $this->$name = &$this->sources[$index]; } private function filter($className) { $results = array(); foreach ($this->sources as $source) { if ($source->className() == $className) { $results[] = $source; } } return $results; } } ?>
<?php namespace Bolt\Api; class Connections extends \Bolt\Base { public $sources; public function __construct($connections = null) { if ($connections !== null) { if (is_array($connections)) { foreach ($connections as $connection) { $this->add($connection); } } else { $this->add($connections); } } } public function add($connection) { $this->sources[] = $connection; } public function dbo() { return $this->filter("Bolt\Dbo"); } public function eso() { return $this->filter("Bolt\Eso"); } private function filter($className) { $results = array(); foreach ($this->sources as $source) { if ($source->className() == $className) { $results[] = $source; } } return $results; } } ?>
Update existing native rounding post processor Reviewed By: oprisnik Differential Revision: D9607950 fbshipit-source-id: 080aa9cd339761a48e534c2fd4d3677005063e78
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.postprocessors; import android.graphics.Bitmap; import com.facebook.cache.common.CacheKey; import com.facebook.cache.common.SimpleCacheKey; import com.facebook.imagepipeline.nativecode.NativeRoundingFilter; import com.facebook.imagepipeline.request.BasePostprocessor; import javax.annotation.Nullable; /** Postprocessor that rounds a given image as a circle. */ public class RoundAsCirclePostprocessor extends BasePostprocessor { private static final boolean ENABLE_ANTI_ALIASING = true; private @Nullable CacheKey mCacheKey; private final boolean mEnableAntiAliasing; public RoundAsCirclePostprocessor() { this(ENABLE_ANTI_ALIASING); } public RoundAsCirclePostprocessor(boolean enableAntiAliasing) { mEnableAntiAliasing = enableAntiAliasing; } @Override public void process(Bitmap bitmap) { NativeRoundingFilter.toCircle(bitmap, mEnableAntiAliasing); } @Nullable @Override public CacheKey getPostprocessorCacheKey() { if (mCacheKey == null) { if (mEnableAntiAliasing) { mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor#AntiAliased"); } else { mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor"); } } return mCacheKey; } }
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.postprocessors; import android.graphics.Bitmap; import com.facebook.cache.common.CacheKey; import com.facebook.cache.common.SimpleCacheKey; import com.facebook.imagepipeline.nativecode.NativeRoundingFilter; import com.facebook.imagepipeline.request.BasePostprocessor; import javax.annotation.Nullable; /** Postprocessor that rounds a given image as a circle. */ public class RoundAsCirclePostprocessor extends BasePostprocessor { private @Nullable CacheKey mCacheKey; @Override public void process(Bitmap bitmap) { NativeRoundingFilter.toCircle(bitmap); } @Nullable @Override public CacheKey getPostprocessorCacheKey() { if (mCacheKey == null) { mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor"); } return mCacheKey; } }
Make test output more verbose so we can figure out what is hanging
from bongo.settings.prod import * # The same settings as production, but no database password. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bongo_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', }, } INSTALLED_APPS += ( 'django_nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = ['--with-fixture-bundling', '--nologcapture', '--verbosity=2'] NOSE_TESTMATCH = '(?:^|[b_./-])[Tt]ests'
from bongo.settings.prod import * # The same settings as production, but no database password. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bongo_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', }, } INSTALLED_APPS += ( 'django_nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = ['--with-fixture-bundling', '--nologcapture'] NOSE_TESTMATCH = '(?:^|[b_./-])[Tt]ests'
Change connect command to 439
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('439') def handle_notice(bot, message): """ Use the notice message to identify and register to the server. """ if not bot.identified: bot.send('USER MotoBot localhost localhost MotoBot') bot.send('NICK ' + bot.nick) sleep(2) if bot.nickserv_password is not None: bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password) sleep(2) for channel in bot.channels: bot.send('JOIN ' + channel) bot.identified = True @hook('INVITE') def handle_invite(bot, message): """ Join a channel when invited. """ bot.join(message.params[-1]) @hook('ERROR') def handle_error(bot, message): """ Handle an error message from the server. """ bot.connected = bot.identified = False
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('NOTICE') def handle_notice(bot, message): """ Use the notice message to identify and register to the server. """ if not bot.identified: bot.send('USER MotoBot localhost localhost MotoBot') bot.send('NICK ' + bot.nick) sleep(2) if bot.nickserv_password is not None: bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password) sleep(2) for channel in bot.channels: bot.send('JOIN ' + channel) bot.identified = True @hook('INVITE') def handle_invite(bot, message): """ Join a channel when invited. """ bot.join(message.params[-1]) @hook('ERROR') def handle_error(bot, message): """ Handle an error message from the server. """ bot.connected = bot.identified = False
Fix listeners getting registered too many times on card scan
var cardio = require('com.pointsource.card.io'); function handleScan(e) { console.log('scan event', e); var cardNumber = e.cardNumber; var cardType = e.cardType; var cardholderName = e.cardholderName; var cvv = e.cvv; var expiryMonth = e.expiryMonth; var expiryYear = e.expiryYear; var postalCode = e.postalCode; removeListeners(); } function handleCancel(e) { console.log("Canceled scan"); removeListeners(); } function removeListeners() { cardio.removeEventListener("scan", handleScan); cardio.removeEventListener("cancel", handleCancel); } function openCardIO() { cardio.addEventListener("scan", handleScan); cardio.addEventListener("cancel", handleCancel); console.log("Opening Card.io"); cardio.scanCard({ languageOrLocale: "fr", collectPostalCode: true, collectCardholderName: true, guideColor: "yellow", navigationBarTintColor: "green", restrictPostalCodeToNumericOnly: true }); }
var cardio = require('com.pointsource.card.io'); function openCardIO() { console.log("Opening Card.io"); cardio.addEventListener("scan", function(e) { console.log('scan event', e); var cardNumber = e.cardNumber; var cardType = e.cardType; var cardholderName = e.cardholderName; var cvv = e.cvv; var expiryMonth = e.expiryMonth; var expiryYear = e.expiryYear; var postalCode = e.postalCode; }); cardio.addEventListener("cancel", function(err, res) { console.log("Canceled scan"); }); cardio.scanCard({ languageOrLocale: "fr", collectPostalCode: true, collectCardholderName: true, guideColor: "yellow", navigationBarTintColor: "green", restrictPostalCodeToNumericOnly: true }); }
Configure store creation to incorporate ReduxRouter
import { createStore, applyMiddleware, compose } from 'redux'; import { reduxReactRouter } from 'redux-router'; import thunk from 'redux-thunk'; import createHistory from 'history/lib/createBrowserHistory'; import routes from '../routes'; import createLogger from 'redux-logger'; import rootReducer from '../reducers'; const finalCreateStore = compose( applyMiddleware(thunk), applyMiddleware(createLogger()), reduxReactRouter({ routes, createHistory }) )(createStore); export default function configureStore(initialState) { const store = finalCreateStore(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers'); store.replaceReducer(nextRootReducer); }); } return store; }
import { createStore, applyMiddleware } from 'redux'; import { reduxReactRouter } from 'redux-router'; import createHistory from 'history/lib/createBrowserHistory'; import routes from '../routes'; import thunkMiddleware from 'redux-thunk'; import createLogger from 'redux-logger'; import rootReducer from '../reducers'; const createStoreWithMiddleware = applyMiddleware( thunkMiddleware, reduxReactRouter({ routes, createHistory }), createLogger() )(createStore); export default function configureStore(initialState) { const store = createStoreWithMiddleware(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers'); store.replaceReducer(nextRootReducer); }); } return store; }
Use Throwable instead of Exception
package com.ternaryop.utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class DialogUtils { public static void showErrorDialog(Context context, Throwable t) { showErrorDialog(context, "Error", t); } public static void showErrorDialog(Context context, String title, Throwable t) { showSimpleMessageDialog(context, title, t.getLocalizedMessage()); } public static void showErrorDialog(Context context, int resId, Throwable t) { showSimpleMessageDialog(context, context.getString(resId), t.getLocalizedMessage()); } public static void showSimpleMessageDialog(Context context, int resId, String message) { showSimpleMessageDialog(context, context.getString(resId), message); } public static void showSimpleMessageDialog(Context context, String title, String message) { new AlertDialog.Builder(context) .setCancelable(false) // This blocks the 'BACK' button .setTitle(title) .setMessage(message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .show(); } }
package com.ternaryop.utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class DialogUtils { public static void showErrorDialog(Context context, Exception e) { showErrorDialog(context, "Error", e); } public static void showErrorDialog(Context context, String title, Exception e) { showSimpleMessageDialog(context, title, e.getLocalizedMessage()); } public static void showErrorDialog(Context context, int resId, Exception e) { showSimpleMessageDialog(context, context.getString(resId), e.getLocalizedMessage()); } public static void showSimpleMessageDialog(Context context, int resId, String message) { showSimpleMessageDialog(context, context.getString(resId), message); } public static void showSimpleMessageDialog(Context context, String title, String message) { new AlertDialog.Builder(context) .setCancelable(false) // This blocks the 'BACK' button .setTitle(title) .setMessage(message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .show(); } }
Remove unused <T> generic type from method signature git-svn-id: d9b8539636d91aff9cd33ed5cd52a0cf73394897@1236307 13f79535-47bb-0310-9956-ffa450edef68
// Copyright 2009, 2011, 2012 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.ioc.services; import org.apache.tapestry5.ioc.MethodAdviceReceiver; import org.slf4j.Logger; /** * A service used in conjunction with a service advisor method to add logging advice to a service. * * @since 5.1.0.0 * @see org.apache.tapestry5.ioc.annotations.Advise */ public interface LoggingAdvisor { /** * Adds logging advice to all methods of the object. * * @param logger * log used for debug level logging messages by the interceptor * @param methodAdviceReceiver */ void addLoggingAdvice(Logger logger, MethodAdviceReceiver methodAdviceReceiver); }
// Copyright 2009, 2011 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.ioc.services; import org.apache.tapestry5.ioc.MethodAdviceReceiver; import org.slf4j.Logger; /** * A service used in conjunction with a service advisor method to add logging advice to a service. * * @since 5.1.0.0 */ public interface LoggingAdvisor { /** * Adds logging advice to all methods of the object. * * @param logger * log used for debug level logging messages by the interceptor * @param methodAdviceReceiver */ <T> void addLoggingAdvice(Logger logger, MethodAdviceReceiver methodAdviceReceiver); }
Use the right graph factory
package com.github.ferstl.depgraph; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import com.github.ferstl.depgraph.dot.DotBuilder; @Mojo( name = "graph", aggregator = false, defaultPhase = LifecyclePhase.NONE, requiresDependencyCollection = ResolutionScope.TEST, requiresDirectInvocation = true, threadSafe = true) public class DepGraphMojo extends AbstractDepGraphMojo { @Override protected GraphFactory createGraphFactory( DependencyGraphBuilder dependencyGraphBuilder, ArtifactFilter artifactFilter) { DotBuilder dotBuilder = new DotBuilder(NodeRenderers.VERSIONLESS_ID, NodeRenderers.ARTIFACT_ID_LABEL); return new SimpleDotGraphFactory(dependencyGraphBuilder, artifactFilter, dotBuilder); } }
package com.github.ferstl.depgraph; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import com.github.ferstl.depgraph.dot.DotBuilder; @Mojo( name = "graph", aggregator = false, defaultPhase = LifecyclePhase.NONE, requiresDependencyCollection = ResolutionScope.TEST, requiresDirectInvocation = true, threadSafe = true) public class DepGraphMojo extends AbstractDepGraphMojo { @Override protected GraphFactory createGraphFactory( DependencyGraphBuilder dependencyGraphBuilder, ArtifactFilter artifactFilter) { DotBuilder dotBuilder = new DotBuilder(NodeRenderers.VERSIONLESS_ID, NodeRenderers.ARTIFACT_ID_LABEL); return new AggregatingDotGraphFactory(dependencyGraphBuilder, artifactFilter, dotBuilder); } }
Write comments in n-ary operator
package edu.washington.escience.myria.operator; import java.util.Objects; import com.google.common.base.Preconditions; import edu.washington.escience.myria.Schema; /** * * @author dominik * */ public abstract class NAryOperator extends Operator { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * The children of the n-ary operator. * */ protected Operator[] children; /** * Default, empty constructor. */ public NAryOperator() { super(); } @Override public Operator[] getChildren() { return children; } @Override public void setChildren(final Operator[] children) { Objects.requireNonNull(children); Preconditions.checkArgument(children.length > 0); this.children = children; } @Override public Schema getSchema() { return children[0].getSchema(); } /** * @return number of children */ protected int numChildren() { return children.length; } }
package edu.washington.escience.myria.operator; import java.util.Objects; import com.google.common.base.Preconditions; import edu.washington.escience.myria.Schema; public abstract class NAryOperator extends Operator { /** * The children of the n-ary operator. * */ protected Operator[] children; public NAryOperator() { super(); } @Override public Operator[] getChildren() { return children; } @Override public void setChildren(final Operator[] children) { Objects.requireNonNull(children); Preconditions.checkArgument(children.length > 0); this.children = children; } @Override public Schema getSchema() { return children[0].getSchema(); } /** * @return number of children */ protected int numChildren() { return children.length; } }
Remove comment from zabbix integration
from dbaas_dbmonitor.provider import DBMonitorProvider from dbaas_zabbix.provider import ZabbixProvider import logging LOG = logging.getLogger(__name__) class MonitoringManager(): @classmethod def create_monitoring(cls, databaseinfra): try: LOG.info("Creating monitoring...") ZabbixProvider().create_monitoring(dbinfra=databaseinfra) return DBMonitorProvider().create_dbmonitor_monitoring(databaseinfra) except Exception, e: LOG.warn("Exception: %s" % e) return None @classmethod def remove_monitoring(cls, databaseinfra): try: LOG.info("Removing monitoring...") ZabbixProvider().destroy_monitoring(dbinfra=databaseinfra) return DBMonitorProvider().remove_dbmonitor_monitoring(databaseinfra) except Exception, e: LOG.warn("Exception: %s" % e) return None
from dbaas_dbmonitor.provider import DBMonitorProvider from dbaas_zabbix.provider import ZabbixProvider import logging LOG = logging.getLogger(__name__) class MonitoringManager(): @classmethod def create_monitoring(cls, databaseinfra): try: LOG.info("Creating monitoring...") #ZabbixProvider().create_monitoring(dbinfra=databaseinfra) return DBMonitorProvider().create_dbmonitor_monitoring(databaseinfra) except Exception, e: LOG.warn("Exception: %s" % e) return None @classmethod def remove_monitoring(cls, databaseinfra): try: LOG.info("Removing monitoring...") #ZabbixProvider().destroy_monitoring(dbinfra=databaseinfra) return DBMonitorProvider().remove_dbmonitor_monitoring(databaseinfra) except Exception, e: LOG.warn("Exception: %s" % e) return None
[wiki:DbFinderPlugin] Allow for easier testing with sf 1.1
<?php // Autofind the first available app environment $sf_root_dir = realpath(dirname(__FILE__).'/../../../'); $apps_dir = glob($sf_root_dir.'/apps/*', GLOB_ONLYDIR); $app = substr($apps_dir[0], strrpos($apps_dir[0], DIRECTORY_SEPARATOR) + 1, strlen($apps_dir[0])); if (!$app) { throw new Exception('No app has been detected in this project'); } // -- path to the symfony project where the plugin resides $sf_path = dirname(__FILE__).'/../../..'; // bootstrap include($sf_path . '/test/bootstrap/functional.php'); // create a new test browser $browser = new sfTestBrowser(); $browser->initialize(); // initialize database manager if(method_exists('sfDatabaseManager', 'loadConfiguration')) { // symfony 1.1 style new sfDatabaseManager($configuration); } else { // symfony 1.0 style $databaseManager = new sfDatabaseManager(); $databaseManager->initialize(); }
<?php // Autofind the first available app environment $sf_root_dir = realpath(dirname(__FILE__).'/../../../'); $apps_dir = glob($sf_root_dir.'/apps/*', GLOB_ONLYDIR); $app = substr($apps_dir[0], strrpos($apps_dir[0], DIRECTORY_SEPARATOR) + 1, strlen($apps_dir[0])); if (!$app) { throw new Exception('No app has been detected in this project'); } // -- path to the symfony project where the plugin resides $sf_path = dirname(__FILE__).'/../../..'; // bootstrap include($sf_path . '/test/bootstrap/functional.php'); // create a new test browser $browser = new sfTestBrowser(); $browser->initialize(); // initialize database manager $databaseManager = new sfDatabaseManager(); $databaseManager->initialize();
Remove trailing line break from C4 UCI instance
from __future__ import division, print_function, unicode_literals from capstone.game import Connect4 as C4 def load_instance(instance): ''' Loads a position from the UCI Connect 4 database: https://archive.ics.uci.edu/ml/machine-learning-databases/connect-4/connect-4.names Returns a tuple with an instance of a Connect4 game with that position, and the outcome for the first player under perfect play. ''' instance = instance.rstrip() tokens = instance.split(',') cells = tokens[:-1] outcome = tokens[-1] cell_map = {'x': 'X', 'o': 'O', 'b': '-'} board = [[' '] * C4.COLS for row in range(C4.ROWS)] for ix, cell in enumerate(cells): row = C4.ROWS - (ix % C4.ROWS) - 1 col = ix // C4.ROWS board[row][col] = cell_map[cell] return C4(board), outcome
from __future__ import division, print_function, unicode_literals from capstone.game import Connect4 as C4 def load_instance(instance): ''' Loads a position from the UCI Connect 4 database: https://archive.ics.uci.edu/ml/machine-learning-databases/connect-4/connect-4.names Returns a tuple with an instance of a Connect4 game with that position, and the outcome for the first player under perfect play. ''' tokens = instance.split(',') cells = tokens[:-1] outcome = tokens[-1] cell_map = {'x': 'X', 'o': 'O', 'b': '-'} board = [[' '] * C4.COLS for row in range(C4.ROWS)] for ix, cell in enumerate(cells): row = C4.ROWS - (ix % C4.ROWS) - 1 col = ix // C4.ROWS board[row][col] = cell_map[cell] return C4(board), outcome
Rename method to be more logical
from .base import Base class List(Base): def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def get_object_name(self): return self.object_type.__name__.lower() + 's' def __iter__(self): for item in self['_embedded'][self.get_object_name()]: yield self.object_type(item) @property def count(self): if 'count' not in self: return None return int(self['count']) def get_offset(self): if 'offset' not in self: return None return self['offset']
from .base import Base class List(Base): def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def get_resource_name(self): return self.object_type.__name__.lower() + 's' def __iter__(self): for item in self['_embedded'][self.get_resource_name()]: yield self.object_type(item) @property def count(self): if 'count' not in self: return None return int(self['count']) def get_offset(self): if 'offset' not in self: return None return self['offset']
Add final save to batch lookup
import csv from indra.literature import pubmed_client, crossref_client doi_cache = {} with open('doi_cache.txt') as f: csvreader = csv.reader(f, delimiter='\t') for row in csvreader: doi_cache[row[0]] = row[1] with open('missing_dois.txt') as f: missing_dois = [line.strip('\n') for line in f.readlines()] def save(doi_cache, counter): with open('doi_cache_%.5d.txt' % counter, 'w') as f: print "Writing to doi cache" csvwriter = csv.writer(f, delimiter='\t') for k, v in doi_cache.iteritems(): csvwriter.writerow((k, v)) for counter, ref in enumerate(missing_dois): if doi_cache.get(ref): print "Already got", ref continue title = pubmed_client.get_title(ref) if not title: print "No title, skipping", ref continue doi = crossref_client.doi_query(title) doi_cache[ref] = doi print "%d: %s --> %s" % (counter, ref, doi) if counter % 100 == 0: save(doi_cache, counter) save(doi_cache, counter)
import csv from indra.literature import pubmed_client, crossref_client doi_cache = {} with open('doi_cache.txt') as f: csvreader = csv.reader(f, delimiter='\t') for row in csvreader: doi_cache[row[0]] = row[1] with open('missing_dois.txt') as f: missing_dois = [line.strip('\n') for line in f.readlines()] for counter, ref in enumerate(missing_dois): if doi_cache.get(ref): print "Already got", ref continue title = pubmed_client.get_title(ref) if not title: print "No title, skipping", ref continue doi = crossref_client.doi_query(title) doi_cache[ref] = doi print "%d: %s --> %s" % (counter, ref, doi) if counter % 100 == 0: with open('doi_cache_%.5d.txt' % counter, 'w') as f: print "Writing to doi cache" csvwriter = csv.writer(f, delimiter='\t') for k, v in doi_cache.iteritems(): csvwriter.writerow((k, v))
Use the correct excel path.
""" This module is a general example using test data showing usage of sparks, excel and the studbook structure. """ import os from GTT import SPARKS from GTT import excel as ew from GTT import studBookStruct TEST_DIR = os.path.dirname(__file__) TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData') # my_sparks_reader = SPARKS.SPARKSReader("test/testData/test_sparks_data.dbf") moves_data = os.path.join(TEST_DATA_DIR, 'test_moves_data.dbf') my_sparks_reader = SPARKS.SPARKSReader(moves_data) excel_write = os.path.join(TEST_DATA_DIR, 'test_excel_write.xlsx') my_excel_writer = ew.ExcelWriter(excel_write) my_studbook = studBookStruct.Studbook() my_studbook.add_header(my_sparks_reader.get_header_as_list()) my_studbook.add_records_from_list(my_sparks_reader.get_records_as_list()) my_excel_writer.write_studbook(my_studbook) my_excel_writer.close()
""" This module is a general example using test data showing usage of sparks, excel and the studbook structure. """ import os from GTT import SPARKS from GTT import excel as ew from GTT import studBookStruct TEST_DIR = os.path.dirname(__file__) TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData') # my_sparks_reader = SPARKS.SPARKSReader("test/testData/test_sparks_data.dbf") moves_data = os.path.join(TEST_DATA_DIR, 'test_moves_data.dbf') my_sparks_reader = SPARKS.SPARKSReader(moves_data) my_excel_writer = ew.ExcelWriter("test/testData/test_excel_write.xlsx") my_studbook = studBookStruct.Studbook() my_studbook.add_header(my_sparks_reader.get_header_as_list()) my_studbook.add_records_from_list(my_sparks_reader.get_records_as_list()) my_excel_writer.write_studbook(my_studbook) my_excel_writer.close()
Fix file chunk size off-by-one error
module.exports = class RarFileChunk { constructor(fileMedia, startOffset, endOffset) { this.fileMedia = fileMedia; this.startOffset = startOffset; this.endOffset = endOffset; } paddEnd(endPadding) { return new RarFileChunk( this.fileMedia, this.startOffset, this.endOffset - endPadding ); } paddStart(startPadding) { return new RarFileChunk( this.fileMedia, this.startOffset + startPadding, this.endOffset ); } get length() { return Math.max(0, this.endOffset - this.startOffset + 1); } getStream() { return this.fileMedia.createReadStream({ start: this.startOffset, end: this.endOffset, }); } };
module.exports = class RarFileChunk { constructor(fileMedia, startOffset, endOffset) { this.fileMedia = fileMedia; this.startOffset = startOffset; this.endOffset = endOffset; } paddEnd(endPadding) { return new RarFileChunk( this.fileMedia, this.startOffset, this.endOffset - endPadding ); } paddStart(startPadding) { return new RarFileChunk( this.fileMedia, this.startOffset + startPadding, this.endOffset ); } get length() { return Math.abs(this.endOffset - this.startOffset); } getStream() { return this.fileMedia.createReadStream({ start: this.startOffset, end: this.endOffset, }); } };
Bring the directory near to the modules definition
'use strict'; /** * Run the modules with the libraries and the services * @example let config = { libraries: { library: require('library') }, directory: __dirname + '/', modules: [ [require('bundle'), [ ['modules/module', {}] ]], ['modules/module', {}] ] }; require('dragonnodejs')(config); */ module.exports = (config, services) => { services = services || {}; for (let module of config.modules) { if (typeof module[0] === 'string') { module[0] = require(config.directory + module[0]); } module[0](module[1], config.libraries, services); } };
'use strict'; /** * Run the modules with the libraries and the services * @example let config = { directory: __dirname + '/', libraries: { library: require('library') }, modules: [ [require('bundle'), [ ['modules/module', {}] ]], ['modules/module', {}] ] }; require('dragonnodejs')(config); */ module.exports = (config, services) => { services = services || {}; for (let module of config.modules) { if (typeof module[0] === 'string') { module[0] = require(config.directory + module[0]); } module[0](module[1], config.libraries, services); } };
Add per-word replace probability, max outputs.
import piglatin import random from interfaces.SentenceOperation import SentenceOperation from tasks.TaskTypes import TaskType class PigLatin(SentenceOperation): tasks = [ TaskType.TEXT_CLASSIFICATION, TaskType.TEXT_TO_TEXT_GENERATION, TaskType.TEXT_TAGGING, ] languages = ["en"] def __init__(self, seed=0, max_outputs=1, replace_prob=1.0): super().__init__(seed, max_outputs=max_outputs) self.replace_prob = replace_prob def generate(self, sentence: str): piglatin_sentences = [] for _ in range(self.max_outputs): piglatin_sentence = [] for word in sentence.lower().split(): if random.random() < self.replace_prob: new_word = piglatin.translate(word) else: new_word = word piglatin_sentence.append(new_word.replace('-', '')) piglatin_sentence = ' '.join(piglatin_sentence) piglatin_sentences.append(piglatin_sentence) return piglatin_sentences
import piglatin from interfaces.SentenceOperation import SentenceOperation from tasks.TaskTypes import TaskType class PigLatin(SentenceOperation): tasks = [ TaskType.TEXT_CLASSIFICATION, TaskType.TEXT_TO_TEXT_GENERATION, TaskType.TEXT_TAGGING, ] languages = ["en"] def __init__(self, seed=0, max_outputs=1): super().__init__(seed, max_outputs=max_outputs) def generate(self, sentence: str): output_sentence = piglatin.translate(sentence.lower()) piglatin_sentence = [] for word in output_sentence.split(): piglatin_sentence.append(word.replace('-', '')) piglatin_sentence = ' '.join(piglatin_sentence) return [piglatin_sentence]
Use correct settings when registering the Builder with Laravel.
<?php namespace Staf\Generator; use Illuminate\Support\ServiceProvider; class GeneratorServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // Setup the config file for publishing. $this->publishes([__DIR__ . '/config.php' => config_path('generator.php')], 'config'); // Add the default console command if ($this->app->runningInConsole()) { $this->commands([PublishCommand::class]); } } /** * Register any application services. * * @return void */ public function register() { $this->app->bind(Builder::class, function ($app) { return new Builder([ 'source_path' => $app['config']['generator']['source_path'], 'target_path' => $app['config']['generator']['target_path'], 'cache_path' => $app['config']['generator']['cache_path'], ]); }); } }
<?php namespace Staf\Generator; use Illuminate\Support\ServiceProvider; class GeneratorServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // Setup the config file for publishing. $this->publishes([__DIR__ . '/config.php' => config_path('generator.php')], 'config'); // Add the default console command if ($this->app->runningInConsole()) { $this->commands([PublishCommand::class]); } } /** * Register any application services. * * @return void */ public function register() { $this->app->bind(Builder::class, function ($app) { return new Builder([ 'source_path' => $app['config']['generator']['source_path'], 'target_path' => $app['config']['generator']['source_path'], 'cache_path' => $app['config']['generator']['source_path'], ]); }); } }
Fix playlist link when user does not have custom path close #56
/*jslint nomen: true, plusplus: true, es5: true, regexp: true */ /*global GS, GSX, GSXUtil, console, $, _ */ var GSXmodules = window.GSXmodules = window.GSXmodules || []; GSXmodules.push({ name: 'Sidebar', init: function () { 'use strict'; _.extend(GS.Views.Sidebar.prototype, { render: _.compose(function () { var item = '<li class="nav-item"><a href="' + this.user.toUrl() + '/playlists" class="nav-link playlists"><i class="icon icon-playlist"></i><span data-translate-text="PLAYLISTS" class="label">Playlists</span></a></li>'; this.$('.nav-link.favorites').parent().after(item); }, GS.Views.Sidebar.prototype.render) }); } });
/*jslint nomen: true, plusplus: true, es5: true, regexp: true */ /*global GS, GSX, GSXUtil, console, $, _ */ var GSXmodules = window.GSXmodules = window.GSXmodules || []; GSXmodules.push({ name: 'Sidebar', init: function () { 'use strict'; _.extend(GS.Views.Sidebar.prototype, { render: _.compose(function () { var item = '<li class="nav-item"><a href="#!/' + this.user.get('PathName') + '/playlists" class="nav-link playlists"><i class="icon icon-playlist"></i><span data-translate-text="PLAYLISTS" class="label">Playlists</span></a></li>'; this.$('.nav-link.favorites').parent().after(item); }, GS.Views.Sidebar.prototype.render) }); } });
:shirt: Resolve 'unnecessary escape character' violations Resolves the following linter violations: lib/toggle-markdown-task.js:43:31: Unnecessary escape character: \-. lib/toggle-markdown-task.js:43:33: Unnecessary escape character: \*. lib/toggle-markdown-task.js:43:36: Unnecessary escape character: \ . lib/toggle-markdown-task.js:43:43: Unnecessary escape character: \ .
const {CompositeDisposable} = require('atom') module.exports = ({ subscriptions: null, activate (state) { this.subscriptions = new CompositeDisposable() this.subscriptions.add(atom.commands.add('atom-text-editor', {'toggle-markdown-task:toggle': () => this.toggle()}) ) }, deactivate () { this.subscriptions.dispose() }, toggle () { const editor = atom.workspace.getActiveTextEditor() if (editor) { editor.transact(() => { editor.getSelections().forEach((selection) => toggleSelection(selection)) }) } } }) function toggleSelection (selection) { const originalRange = selection.getBufferRange() const [startingRow, endingRow] = selection.getBufferRowRange() for (let row = startingRow; row <= endingRow; row++) { selection.cursor.setBufferPosition([row, 0]) selection.selectToEndOfLine() const toggledTask = toggleTask(selection.getText()) selection.insertText(toggledTask) } selection.setBufferRange(originalRange) } function toggleTask (taskText) { const regex = new RegExp(/([-*] )(\[[ x]\])/) return taskText.replace(regex, (_, taskPrefix, taskStatus) => { return (taskStatus === '[ ]') ? `${taskPrefix}[x]` : `${taskPrefix}[ ]` }) }
const {CompositeDisposable} = require('atom') module.exports = ({ subscriptions: null, activate (state) { this.subscriptions = new CompositeDisposable() this.subscriptions.add(atom.commands.add('atom-text-editor', {'toggle-markdown-task:toggle': () => this.toggle()}) ) }, deactivate () { this.subscriptions.dispose() }, toggle () { const editor = atom.workspace.getActiveTextEditor() if (editor) { editor.transact(() => { editor.getSelections().forEach((selection) => toggleSelection(selection)) }) } } }) function toggleSelection (selection) { const originalRange = selection.getBufferRange() const [startingRow, endingRow] = selection.getBufferRowRange() for (let row = startingRow; row <= endingRow; row++) { selection.cursor.setBufferPosition([row, 0]) selection.selectToEndOfLine() const toggledTask = toggleTask(selection.getText()) selection.insertText(toggledTask) } selection.setBufferRange(originalRange) } function toggleTask (taskText) { const regex = new RegExp(/([\-\*]\ )(\[[\ x]\])/) return taskText.replace(regex, (_, taskPrefix, taskStatus) => { return (taskStatus === '[ ]') ? `${taskPrefix}[x]` : `${taskPrefix}[ ]` }) }
Add environment variable for password.
package org.kelley; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Created by tkelley on 1/17/2016. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${ENV_APP_PASSWORD}") private String password; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("kelley").password(password).roles("USER"); } }
package org.kelley; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Created by tkelley on 1/17/2016. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("kelley").password("scrappy").roles("USER"); } }
Handle when /grid ends with a period, since Twitter let apgwoz link to it that way
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), url(r'^grid\.$', 'django.views.generic.simple.redirect_to', {'url': r'/grid'}), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
Use a dict representation of the GET QueryDict
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.dict() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.copy() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
Change default deadline notify setting to true
package com.phicdy.totoanticipation.model.storage; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.phicdy.totoanticipation.model.Game; import com.phicdy.totoanticipation.model.Toto; import java.util.ArrayList; import java.util.Date; import java.util.List; public class SettingStorageImpl implements SettingStorage { private SharedPreferences preferences; private static final String KEY_PREF = "keyPrefSetting"; private static final String KEY_NOTIFY_DEADLINE = "keyNotifyDeadline"; public SettingStorageImpl(@NonNull Context context) { preferences = context.getSharedPreferences(KEY_PREF, Context.MODE_PRIVATE); } @Override public boolean isDeadlineNotify() { return preferences.getBoolean(KEY_NOTIFY_DEADLINE, true); } @Override public void setDeadlineNotify(boolean isEnabled) { preferences.edit().putBoolean(KEY_NOTIFY_DEADLINE, isEnabled).apply(); } }
package com.phicdy.totoanticipation.model.storage; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.phicdy.totoanticipation.model.Game; import com.phicdy.totoanticipation.model.Toto; import java.util.ArrayList; import java.util.Date; import java.util.List; public class SettingStorageImpl implements SettingStorage { private SharedPreferences preferences; private static final String KEY_PREF = "keyPrefSetting"; private static final String KEY_NOTIFY_DEADLINE = "keyNotifyDeadline"; public SettingStorageImpl(@NonNull Context context) { preferences = context.getSharedPreferences(KEY_PREF, Context.MODE_PRIVATE); } @Override public boolean isDeadlineNotify() { return preferences.getBoolean(KEY_NOTIFY_DEADLINE, false); } @Override public void setDeadlineNotify(boolean isEnabled) { preferences.edit().putBoolean(KEY_NOTIFY_DEADLINE, isEnabled).apply(); } }
Fix warning with list iteration
import React from "react" import { connect } from "react-redux" //import { fetchLinks } from "../actions/linkActions" @connect((store) => { return { user: 'Celso', myList: ['fee', 'fi', 'fo', 'fum'], message: ''//, //links: store.links.links }; }) export default class Layout extends React.Component { // fetchLinks() { // this.props.dispatch(fetchLinks()) // } handleMsgChange() { console.log('clicked') } handleClick() { console.log('clicked') } render() { const { user, message, myList } = this.props; const list = myList.map((message) => { return ( <li key={message}>{message}</li> ) }); return (<div className="container"> <h1>Cosecha SMS</h1> <input type="text" value={message} onChange={this.handleMsgChange.bind(this)} placeholder="Message" /> <button onClick={this.handleClick.bind(this)} >Send</button> <ul>{list}</ul> </div>) } }
import React from "react" import { connect } from "react-redux" //import { fetchLinks } from "../actions/linkActions" @connect((store) => { return { user: 'Celso', myList: ['fee', 'fi', 'fo', 'fum'], message: ''//, //links: store.links.links }; }) export default class Layout extends React.Component { // fetchLinks() { // this.props.dispatch(fetchLinks()) // } handleMsgChange() { console.log('clicked') } handleClick() { console.log('clicked') } render() { const { user, message, myList } = this.props; const list = myList.map((message) => { return ( <li>message</li> ) }); return (<div> <h1>Cosecha SMS</h1> <input type="text" value={message} onChange={this.handleMsgChange.bind(this)} placeholder="Message" /> <button onClick={this.handleClick.bind(this)} >Send</button> <ul>{list}</ul> </div>) } }
Make titles and hotbars more visible
package tc.oc.commons.bukkit.chat; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.entity.Player; import tc.oc.commons.core.chat.Components; import tc.oc.commons.core.stream.Collectors; import java.util.stream.Stream; public class LegacyPlayerAudience extends PlayerAudience { private BaseComponent recentHotbarMessage; public LegacyPlayerAudience(Player player) { super(player); } @Override public void sendHotbarMessage(BaseComponent message) { // Do not spam hot bar messages, as the protocol converts // them to regular chat messages. if(!Components.equals(message, recentHotbarMessage)) { emphasize(message); recentHotbarMessage = message; } } @Override public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) { emphasize(Components.join(Components.space(), Stream.of(title, subtitle).filter(msg -> msg != null).collect(Collectors.toImmutableList()))); } protected void emphasize(BaseComponent message) { sendMessage(Components.blank()); sendMessage(message); sendMessage(Components.blank()); } }
package tc.oc.commons.bukkit.chat; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.entity.Player; import tc.oc.commons.core.chat.Component; import tc.oc.commons.core.chat.Components; public class LegacyPlayerAudience extends PlayerAudience { private BaseComponent recentHotbarMessage; public LegacyPlayerAudience(Player player) { super(player); } @Override public void sendHotbarMessage(BaseComponent message) { // Do not spam hot bar messages, as the protocol converts // them to regular chat messages. if(!Components.equals(message, recentHotbarMessage)) { super.sendHotbarMessage(message); recentHotbarMessage = message; } } @Override public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) { super.sendMessage(new Component(title).extra(" ").extra(subtitle)); } }
Fix for handling of zero-length declaration blocks
/*! Parker v0.0.0 - MIT license */ 'use strict'; var _ = require('underscore'); function CssRule(raw) { this.raw = raw; } CssRule.prototype.getSelectors = function () { return getSelectors(getSelectorBlock(this.raw)); }; CssRule.prototype.getDeclarations = function () { return getDeclarations(getDeclarationBlock(this.raw)); }; var getSelectorBlock = function (rule) { var pattern = /([\w,\.#\-\[\]\"=\s:>\*\(\)]+)[\s]?\{/g, results = pattern.exec(rule); return results[1]; }; var getSelectors = function (selectorBlock) { var untrimmedSelectors = selectorBlock.split(','), trimmedSelectors = untrimmedSelectors.map(function (untrimmed) { return untrimmed.trim(); }); return trimmedSelectors; }; var getDeclarationBlock = function (rule) { var pattern = /\{(.+)\}/g, results = pattern.exec(rule); if (_.isNull(results)) { return ''; } return results[1]; }; var getDeclarations = function (declarationBlock) { var untrimmedDeclarations = _.compact(declarationBlock.trim().split(';')), trimmedDeclarations = untrimmedDeclarations.map(function (untrimmed) { return untrimmed.trim(); }); return trimmedDeclarations; }; module.exports = CssRule;
/*! Parker v0.0.0 - MIT license */ 'use strict'; var _ = require('underscore'); function CssRule(raw) { this.raw = raw; } CssRule.prototype.getSelectors = function () { return getSelectors(getSelectorBlock(this.raw)); }; CssRule.prototype.getDeclarations = function () { return getDeclarations(getDeclarationBlock(this.raw)); }; var getSelectorBlock = function (rule) { var pattern = /([\w,\.#\-\[\]\"=\s:>\*\(\)]+)[\s]?\{/g, results = pattern.exec(rule); return results[1]; }; var getSelectors = function (selectorBlock) { var untrimmedSelectors = selectorBlock.split(','), trimmedSelectors = untrimmedSelectors.map(function (untrimmed) { return untrimmed.trim(); }); return trimmedSelectors; }; var getDeclarationBlock = function (rule) { var pattern = /\{(.+)\}/g; return pattern.exec(rule)[1]; }; var getDeclarations = function (declarationBlock) { var untrimmedDeclarations = _.compact(declarationBlock.trim().split(';')), trimmedDeclarations = untrimmedDeclarations.map(function (untrimmed) { return untrimmed.trim(); }); return trimmedDeclarations; }; module.exports = CssRule;
Remove "express." from errorHandler line
// Module dependencies. var express = require('express'); var ArticleProvider = require('./articleprovider-memory').ArticleProvider; var app = express(); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var errorHandler = require('errorhandler'); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(bodyParser.json()); app.use(methodOverride()); app.use(require('stylus').middleware({ src: __dirname + '/public' })); /*app.configure('production', function(){ app.use(express.errorHandler()); });*/ var articleProvider= new ArticleProvider(); app.get('/', function(req, res){ articleProvider.findAll(function(error, docs){ res.send(docs); }); }) app.use(express.static(__dirname + '/public')); app.use(errorHandler({ dumpExceptions: true, showStack: true })); app.listen(3000);
// Module dependencies. var express = require('express'); var ArticleProvider = require('./articleprovider-memory').ArticleProvider; var app = express(); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var errorHandler = require('errorhandler'); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(bodyParser.json()); app.use(methodOverride()); app.use(require('stylus').middleware({ src: __dirname + '/public' })); /*app.configure('production', function(){ app.use(express.errorHandler()); });*/ var articleProvider= new ArticleProvider(); app.get('/', function(req, res){ articleProvider.findAll(function(error, docs){ res.send(docs); }); }) app.use(express.static(__dirname + '/public')); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); app.listen(3000);
Delete to the root now deletes all todos on db.
var express = require('express'); var cors = require('cors'); var bodyParser = require('body-parser'); var Pool = require('pg').Pool; var pool = new Pool({ database: 'todo', max: 10, idelTimeoutMillis: 1000 }); var app = express(); app.use(cors()); app.use(bodyParser.json()); app.get('/', function(req, res, next) { console.log('GET / called'); pool.query( 'select * from todo', function(err, result) { res.json(result.rows); }); }); app.post('/', function(req, res, next) { console.log('POST / called'); pool.query( 'insert into todo(title) values($1)', [req.body.title], function(err, result) { res.json(req.body); }); }); app.delete('/', function(req, res, next) { console.log('DELETE / called'); pool.query('delete from todo', function(err, result) { res.json([]); }); }); app.post('/setup/db', function(req, res, next) { console.log('POST /setup/db'); pool.query('drop table todo'); pool.query('create table todo (id serial, title varchar(100))'); res.json({success: 'db setup succesfully'}); }); app.listen(3000, function() { console.log('app listening on port 3000'); });
var express = require('express'); var cors = require('cors'); var bodyParser = require('body-parser'); var Pool = require('pg').Pool; var pool = new Pool({ database: 'todo', max: 10, idelTimeoutMillis: 1000 }); var app = express(); app.use(cors()); app.use(bodyParser.json()); app.get('/', function(req, res, next) { console.log('GET / called'); pool.query( 'select * from todo', function(err, result) { res.json(result.rows); }); }); app.post('/', function(req, res, next) { console.log('POST / called'); pool.query( 'insert into todo(title) values($1)', [req.body.title], function(err, result) { res.json(req.body); }); }); app.delete('/', function(req, res, next) { console.log('DELETE / called'); res.json([]); }); app.post('/setup/db', function(req, res, next) { console.log('POST /setup/db'); pool.query('drop table todo'); pool.query('create table todo (id serial, title varchar(100))'); res.json({success: 'db setup succesfully'}); }); app.listen(3000, function() { console.log('app listening on port 3000'); });
Fix a bug involving how mock_state is set
import random from ...mock.mock_abstract_device import MockAbstractDevice from ..tc335 import TC335 """ Mock Lakeshore 335 Temperature Controller """ class MockTC335(MockAbstractDevice, TC335): """ Mock interface for Lakeshore 335 Temperature Controller. """ def __init__(self, *args, **kwargs): self.mocking = TC335 MockAbstractDevice.__init__(self, *args, **kwargs) self.mock_state = {} self.mock_state['readingstatus'] = 0 self.mock_state['read_only'] = ['temperature'] def _reset(self): pass def write(self, message, result=None, done=False): if not done: cmd, args, query = self._split_message(message) if cmd[0] == 'rdgst' and query: result = self.mock_state['readingstatus'] done = True elif cmd[0] == 'krdg' and query: result = random.randint(5,100) done = True MockAbstractDevice.write(self, message, result, done) name = '335 Temperature Controller' implementation = MockTC335
import random from ...mock.mock_abstract_device import MockAbstractDevice from ..tc335 import TC335 """ Mock Lakeshore 335 Temperature Controller """ class MockTC335(MockAbstractDevice, TC335): """ Mock interface for Lakeshore 335 Temperature Controller. """ def __init__(self, *args, **kwargs): self.mocking = TC335 self.mock_state = {} self.mock_state['readingstatus'] = 0 self.mock_state['read_only'] = ['temperature'] MockAbstractDevice.__init__(self, *args, **kwargs) def _reset(self): pass def write(self, message, result=None, done=False): if not done: cmd, args, query = self._split_message(message) if cmd[0] == 'rdgst' and query: result = self.mock_state['readingstatus'] done = True elif cmd[0] == 'krdg' and query: result = random.randint(5,100) done = True MockAbstractDevice.write(self, message, result, done) name = '335 Temperature Controller' implementation = MockTC335
Fix variable and return value
from __future__ import absolute_import from celery import shared_task from twisted.internet import reactor from scrapy.crawler import Crawler from scrapy import log, signals from scrapy.utils.project import get_project_settings import os from raw.scraper.spiders.legco_library import LibraryAgendaSpider from raw.scraper.spiders.members import LibraryMemberSpider @shared_task def run_scraper(): output_name = 'foo.jl' spider = LibraryAgendaSpider() settings = get_project_settings() output_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name) settings.overrides['FEED_URI'] = output_path crawler = Crawler(settings) crawler.signals.connect(reactor.stop, signal=signals.spider_closed) crawler.configure() crawler.crawl(spider) crawler.start() log.start(loglevel=log.INFO, logstdout=True) reactor.run() return output_path
from __future__ import absolute_import from celery import shared_task from twisted.internet import reactor from scrapy.crawler import Crawler from scrapy import log, signals from scrapy.utils.project import get_project_settings import os from raw.scraper.spiders.legco_library import LibraryAgendaSpider from raw.scraper.spiders.members import LibraryMemberSpider @shared_task def run_scraper(): output_name = 'foo.jl' spider = LibraryAgendaSpider() settings = get_project_settings() url_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name) settings.overrides['FEED_URI'] = url_path crawler = Crawler(settings) crawler.signals.connect(reactor.stop, signal=signals.spider_closed) crawler.configure() crawler.crawl(spider) crawler.start() log.start(loglevel=log.INFO, logstdout=True) reactor.run() return output_name
Rename origin -> sourceNodes, u -> node
// This is an ES6 module. // This exported function provides a constructor for graph instances. // Usage `var graph = Graph();` or (optionally) `var graph = new Graph();` export function Graph(){ // The adjacency list of the graph. // Keys are node ids. // Values are arrays of adjacent node ids. var edges = {}; // Gets or creates the adjacent node list for node u. function adjacent(u){ return edges[u] || (edges[u] = []); } return { adjacent: adjacent, addEdge: function (u, v){ adjacent(u).push(v); }, // Depth First Search algorithm, inspired by // Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 604 DFS: function (sourceNodes){ var visited = {}; var nodes = []; sourceNodes.forEach(function DFSVisit(node){ if(!visited[node]){ visited[node] = true; adjacent(node).forEach(DFSVisit); nodes.push(node); } }); return nodes; } }; }
// This is an ES6 module. export function Graph(){ // Keys are node ids. // Values are arrays of adjacent node ids. var edges = {}; // Gets or creates the adjacent node list for node u. function adjacent(u){ return edges[u] || (edges[u] = []); } return { adjacent: adjacent, addEdge: function (u, v){ adjacent(u).push(v); }, // Depth First Search algorithm, inspired by // Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 604 DFS: function (originNodes){ var visited = {}; var nodes = []; originNodes.forEach(function DFSVisit(u){ if(!visited[u]){ visited[u] = true; adjacent(u).forEach(DFSVisit); nodes.push(u); } }); return nodes; } }; }
Undo premature fix for dependency
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Google OpenID auth has been turned off, so any associations that users had to their Google accounts via Google OpenID are now useless. Just remove them. """ from django.db import migrations def no_op(apps, schema_editor): pass def remove_old_google_openid_auths(apps, schema_editor): UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth') db_alias = schema_editor.connection.alias UserSocialAuth.objects.using(db_alias).filter(provider='google').delete() class Migration(migrations.Migration): dependencies = [ ('pycon', '0001_initial'), ] operations = [ migrations.RunPython(remove_old_google_openid_auths, no_op), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Google OpenID auth has been turned off, so any associations that users had to their Google accounts via Google OpenID are now useless. Just remove them. """ from django.db import migrations def no_op(apps, schema_editor): pass def remove_old_google_openid_auths(apps, schema_editor): UserSocialAuth = apps.get_model('social_auth', 'UserSocialAuth') db_alias = schema_editor.connection.alias UserSocialAuth.objects.using(db_alias).filter(provider='google').delete() class Migration(migrations.Migration): dependencies = [ ('pycon', '0001_initial'), ('social_auth', '0001_initial'), ] operations = [ migrations.RunPython(remove_old_google_openid_auths, no_op), ]
Add get merged count method.
""" serializers.py - (C) Copyright - 2017 This software is copyrighted to contributors listed in CONTRIBUTIONS.md. SPDX-License-Identifier: MIT Author(s) of this file: J. Harding Serializer for issue stats of a GitHub repo. """ from rest_framework import serializers as s from ..models import GhIssueEvent from repo_health.index.mixins import CountForPastYearMixin class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin): _label_names = None issues_count = s.SerializerMethodField() issues_closed_last_year = s.SerializerMethodField() issues_opened_last_year = s.SerializerMethodField() merged_count = s.SerializerMethodField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) repo = args[0] self._label_names = repo.labels.values_list('name', flat=True) def get_issues_count(self, repo): return repo.issues_count def get_issues_closed_last_year(self, repo): return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct()) def get_issues_opened_last_year(self, repo): return self.get_count_list_for_year(repo.issues) def get_merged_count(self, repo): return repo.issues.filter(events__action=GhIssueEvent.MERGED_ACTION).count()
""" serializers.py - (C) Copyright - 2017 This software is copyrighted to contributors listed in CONTRIBUTIONS.md. SPDX-License-Identifier: MIT Author(s) of this file: J. Harding Serializer for issue stats of a GitHub repo. """ from rest_framework import serializers as s from ..models import GhIssueEvent from repo_health.index.mixins import CountForPastYearMixin class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin): _label_names = None issues_count = s.SerializerMethodField() issues_closed_last_year = s.SerializerMethodField() issues_opened_last_year = s.SerializerMethodField() merged_count = s.SerializerMethodField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) repo = args[0] self._label_names = repo.labels.values_list('name', flat=True) def get_issues_count(self, repo): return repo.issues_count def get_issues_closed_last_year(self, repo): return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct()) def get_issues_opened_last_year(self, repo): return self.get_count_list_for_year(repo.issues)
Set required python ver to 3.5
from os import path from pip.download import PipSession from pip.req import parse_requirements from graphene_permissions import __version__ from setuptools import setup here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() install_requirements = parse_requirements('requirements/requirements.txt', session=PipSession()) setup( name='graphene-permissions', packages=('graphene_permissions',), license='MIT', version=__version__, author='redzej', description='Simple graphene-django permission system', long_description=long_description, url='https://github.com/redzej/graphene-permissions', download_url='https://github.com/redzej/graphene-permissions/archive/1.0.0.tar.gz', install_requires=[str(ir.req) for ir in install_requirements], keywords='graphene django permissions permission system', python_requires='>=3.5', classifiers=( 'Development Status :: 5 - Production', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 2.0', 'Topic :: Internet :: WWW/HTTP', 'Intended Audience :: Developers', ), )
from os import path from pip.download import PipSession from pip.req import parse_requirements from graphene_permissions import __version__ from setuptools import setup here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() install_requirements = parse_requirements('requirements/requirements.txt', session=PipSession()) setup( name='graphene-permissions', packages=('graphene_permissions',), license='MIT', version=__version__, author='redzej', description='Simple graphene-django permission system', long_description=long_description, url='https://github.com/redzej/graphene-permissions', download_url='https://github.com/redzej/graphene-permissions', install_requires=[str(ir.req) for ir in install_requirements], keywords='graphene django permissions permission system', python_requires='>=3.4', classifiers=( 'Development Status :: 5 - Production', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 2.0', 'Topic :: Internet :: WWW/HTTP', 'Intended Audience :: Developers', ), )
Comment post endpoint return a ksopn, fix issue saving comments add post id and convert it to int
from flask import jsonify from flask_classy import FlaskView from flask_user import current_user, login_required from ..models import CommentModel, PostModel from ..forms import CommentForm class Comment(FlaskView): def get(self): pass def all(self, post_id): comment = CommentModel() comment.query.add_filter('post_id', '=', int(post_id)) return jsonify(comment.fetch()) @login_required def post(self, post_id): form = CommentForm() if form.validate_on_submit(): post = PostModel().get(post_id) post = PostModel(**post) comment = CommentModel(user=current_user.username, post_id=int(post_id), **form.data) comment.put() post.add_comment(comment.id) return jsonify(comment.data) return "form.errors"
from flask import jsonify from flask_classy import FlaskView from flask_user import current_user, login_required from ..models import CommentModel, PostModel from ..forms import CommentForm class Comment(FlaskView): def get(self): pass def all(self, post_id): comment = CommentModel() comment.query.add_filter('post_id', '=', int(post_id)) return jsonify(comment.fetch()) @login_required def post(self, post_id): form = CommentForm() if form.validate_on_submit(): post = PostModel().get(post_id) post = PostModel(**post) comment = CommentModel(user=current_user.username, **form.data) comment.put() post.add_comment(comment.id) return "ALEYUYA" return "form.errors"
Add new line for LR_PASS;
package lv.ctco.cukesrest.loadrunner; import java.util.*; public class LoadRunnerAction { private List<LoadRunnerTransaction> transactions = new ArrayList<LoadRunnerTransaction>(); public List<LoadRunnerTransaction> getTransactions() { return transactions; } public void setTransactions(List<LoadRunnerTransaction> transactions) { this.transactions = transactions; } public void addTransaction(LoadRunnerTransaction trx) { transactions.add(trx); } public String format() { StringBuilder result = new StringBuilder().append("Action() {\n" + "int HttpRetCode;\n" + "int transactionStatus;\n" + "int actionStatus = LR_PASS;\n" + "lr_continue_on_error(1);\n"); for (LoadRunnerTransaction transaction : transactions) { result.append(transaction.format()); } return result.append("lr_exit(LR_EXIT_ACTION_AND_CONTINUE , actionStatus);\n" + "return 0;\n}\n\n").toString(); } }
package lv.ctco.cukesrest.loadrunner; import java.util.*; public class LoadRunnerAction { private List<LoadRunnerTransaction> transactions = new ArrayList<LoadRunnerTransaction>(); public List<LoadRunnerTransaction> getTransactions() { return transactions; } public void setTransactions(List<LoadRunnerTransaction> transactions) { this.transactions = transactions; } public void addTransaction(LoadRunnerTransaction trx) { transactions.add(trx); } public String format() { StringBuilder result = new StringBuilder().append("Action() {\n" + "int HttpRetCode;\n" + "int transactionStatus;\n" + "int actionStatus = LR_PASS;" + "lr_continue_on_error(1);\n"); for (LoadRunnerTransaction transaction : transactions) { result.append(transaction.format()); } return result.append("lr_exit(LR_EXIT_ACTION_AND_CONTINUE , actionStatus);\n" + "return 0;\n}\n\n").toString(); } }
Comment out t_shadow, t_stats, and t_circuitbreaker, at Flynn's behest
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_cors import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting import t_loadbalancer import t_lua_scripts import t_mappingtests import t_optiontests import t_plain import t_ratelimit import t_redirect #import t_shadow #import t_stats import t_tcpmapping import t_tls import t_tracing import t_retrypolicy import t_consul #import t_circuitbreaker import t_knative import t_envoy_logs import t_ingress # pytest will find this because Runner is a toplevel callable object in a file # that pytest is willing to look inside. # # Also note: # - Runner(cls) will look for variants of _every subclass_ of cls. # - Any class you pass to Runner needs to be standalone (it must have its # own manifests and be able to set up its own world). main = Runner(AmbassadorTest)
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_cors import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting import t_loadbalancer import t_lua_scripts import t_mappingtests import t_optiontests import t_plain import t_ratelimit import t_redirect import t_shadow import t_stats import t_tcpmapping import t_tls import t_tracing import t_retrypolicy import t_consul import t_circuitbreaker import t_knative import t_envoy_logs import t_ingress # pytest will find this because Runner is a toplevel callable object in a file # that pytest is willing to look inside. # # Also note: # - Runner(cls) will look for variants of _every subclass_ of cls. # - Any class you pass to Runner needs to be standalone (it must have its # own manifests and be able to set up its own world). main = Runner(AmbassadorTest)
:chart_with_upwards_trend: UPDATE JSON AT 五 2月 17 15:43:00 CST 2017
var CronJob = require('cron').CronJob; var exec = require('child_process').exec; var buildAwesome = 'npm run awesome'; var buildAllRepo = 'npm run build'; var pushToGithub = 'npm run push'; console.log('Do The Crob Job! Awesome :)'); new CronJob('* * */6 * * *', function () { try { exec(buildAwesome, finishAwesome); } catch (e) { console.error(e); } }, false, 'Asia/Taipei'); new CronJob('00 40 15 * * *', function () { try { exec(buildAllRepo, finishBuild); } catch (e) { console.error(e); } }, true, 'Asia/Taipei'); new CronJob('00 43 15 * * *', function () { try { exec(pushToGithub, function (err, stdout, stderr) { if (err) { console.log(stderr); } else { console.log(stdout); } }); } catch (e) { console.error(e); } }, false, 'Asia/Taipei'); function finishAwesome(err, stdout, stderr) { if (err) { console.log(stderr); } else { console.log(stdout); } } function finishBuild(err, stdout, stderr) { if (err) { console.log(stderr); } else { console.log(stdout); } }
var CronJob = require('cron').CronJob; var exec = require('child_process').exec; var buildAwesome = 'npm run awesome'; var buildAllRepo = 'npm run build'; var pushToGithub = 'npm run push'; console.log('Do The Crob Job! Awesome :)'); new CronJob('* * */6 * * *', function () { try { exec(buildAwesome, finishAwesome); } catch (e) { console.error(e); } }, false, 'Asia/Taipei'); new CronJob('00 20 15 * * *', function () { try { exec(buildAllRepo, finishBuild); } catch (e) { console.error(e); } }, true, 'Asia/Taipei'); new CronJob('00 25 15 * * *', function () { try { exec(pushToGithub, function (err, stdout, stderr) { if (err) { console.log(stderr); } else { console.log(stdout); } }); } catch (e) { console.error(e); } }, false, 'Asia/Taipei'); function finishAwesome(err, stdout, stderr) { if (err) { console.log(stderr); } else { console.log(stdout); } } function finishBuild(err, stdout, stderr) { if (err) { console.log(stderr); } else { console.log(stdout); } }
Remove the noise default broken image
import os from fabric.api import local, settings, abort, run, cd, env, put, sudo from fabric.contrib.console import confirm import time DEPLOY_WAIT_TIME = 15 timestamp="release-%s" % int(time.time() * 1000) env.user = 'deploy' # Special group with limited sudo env.hosts = ['104.236.224.252'] code_dir = '/home/liza/scribeAPI' def deploy(): deploy_app() def deploy_app(): with cd(code_dir): run('git pull origin master') run('rake project:load["label_this","workflows","content"]') stop_host() time.sleep(DEPLOY_WAIT_TIME) # Wait for the process to die start_host() print "Done deploying" def stop_host(): sudo('service unicorn_labelthis stop', shell=False) def start_host(): sudo('service unicorn_labelthis start', shell=False)
import os from fabric.api import local, settings, abort, run, cd, env, put, sudo from fabric.contrib.console import confirm import time DEPLOY_WAIT_TIME = 15 timestamp="release-%s" % int(time.time() * 1000) env.user = 'deploy' # Special group with limited sudo env.hosts = ['104.236.224.252'] code_dir = '/home/liza/scribeAPI' def deploy(): deploy_app() def deploy_app(): with cd(code_dir): run('git pull origin master') run('rake project:load["label_this","workflows","content"]') stop_host() time.sleep(DEPLOY_WAIT_TIME) # Wait for the process to die start_shot() print "Done deploying" def stop_host(): sudo('service unicorn_labelthis stop', shell=False) def start_host(): sudo('service unicorn_labelthis start', shell=False)
Make toDate test less dependent on local time
import momentTimezone from 'moment-timezone'; import { HOUR_IN_PIXELS } from '../src/Constants'; import toDate from '../src/toDate'; it('sets the right hour', () => { const expected = momentTimezone.tz('2017-05-01T07:33:11.722Z', 'Europe/Stockholm') .hours(4).minutes(0).seconds(0) .milliseconds(0) .toDate(); expect(toDate(expected, HOUR_IN_PIXELS * 4, 'Europe/Stockholm')).toEqual(expected); }); it('sets the right minute', () => { const expected = momentTimezone.tz('2017-05-01T07:33:11.722Z', 'Europe/Stockholm') .hours(23).minutes(15).seconds(0) .milliseconds(0) .toDate(); expect(toDate(expected, (HOUR_IN_PIXELS * 23) + (HOUR_IN_PIXELS / 4), 'Europe/Stockholm')) .toEqual(expected); }); it('rounds up', () => { const expected = momentTimezone.tz('2017-05-01T07:33:11.722Z', 'Europe/Stockholm') .hours(23).minutes(15).seconds(0) .milliseconds(0) .toDate(); expect(toDate(expected, (HOUR_IN_PIXELS * 23) + ((HOUR_IN_PIXELS / 4) - 0.1343), 'Europe/Stockholm')) .toEqual(expected); });
import { HOUR_IN_PIXELS } from '../src/Constants'; import toDate from '../src/toDate'; it('sets the right hour', () => { const expected = new Date(); expected.setHours(4, 0, 0, 0); expect(toDate(new Date(), HOUR_IN_PIXELS * 4, 'Europe/Stockholm')).toEqual(expected); }); it('sets the right minute', () => { const expected = new Date(); expected.setHours(23, 15, 0, 0); expect(toDate(new Date(), (HOUR_IN_PIXELS * 23) + (HOUR_IN_PIXELS / 4), 'Europe/Stockholm')) .toEqual(expected); }); it('rounds up', () => { const expected = new Date(); expected.setHours(23, 15, 0, 0); expect(toDate(new Date(), (HOUR_IN_PIXELS * 23) + ((HOUR_IN_PIXELS / 4) - 0.1343), 'Europe/Stockholm')) .toEqual(expected); });
Fix failing test caused by new toolchain The challenge with floating point values in tests is that the value can change slightly based on the order of operations, which can legally be affected by optimizations. The results aren't visible (often just 1 ULP), but the tests validate exact bit patterns. This test would be more robust if it did a comparison with the target image and allowed some small amount of variability. Currently it computes a SHA checksum of the framebuffer. Updated the checksum for the new toolchain.
#!/usr/bin/env python3 # # Copyright 2011-2015 Jeff Bush # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys sys.path.insert(0, '../..') import test_harness test_harness.register_render_test('render_texture', ['main.cpp'], 'feb853e1a54d4ba2ce394142ea6119d5e401a60b', targets=['emulator']) test_harness.execute_tests()
#!/usr/bin/env python3 # # Copyright 2011-2015 Jeff Bush # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys sys.path.insert(0, '../..') import test_harness test_harness.register_render_test('render_texture', ['main.cpp'], '2ec4cc681873bc5978617e347d46f3b38230a3a0', targets=['emulator']) test_harness.execute_tests()
Add removed APP_PATH setup in micro project.
<?php defined('APP_PATH') || define('APP_PATH', realpath('.')); return new \Phalcon\Config([ 'database' => [ 'adapter' => 'Mysql', 'host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'test', 'charset' => 'utf8', ], 'application' => [ 'modelsDir' => APP_PATH . '/models/', 'migrationsDir' => APP_PATH . '/migrations/', 'viewsDir' => APP_PATH . '/views/', 'baseUri' => '/@@name@@/', ] ]);
<?php return new \Phalcon\Config([ 'database' => [ 'adapter' => 'Mysql', 'host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'test', 'charset' => 'utf8', ], 'application' => [ 'modelsDir' => APP_PATH . '/models/', 'migrationsDir' => APP_PATH . '/migrations/', 'viewsDir' => APP_PATH . '/views/', 'baseUri' => '/@@name@@/', ] ]);
Add ability to add dependencies in extractor
var path = require('path'); var _readFile = require('../utils/readFile'); function resolve(filepath) { return path.resolve(this.source.absolutePath, filepath); } function addDependency(filepath) { this.module.fileDependencies.push(filepath); } function readFile(filepath) { return _readFile(filepath, this.fs); } /** * @param {Source} source * @param {Function} extractor * @param {Object} options * @param {Compilation} compilation * @returns {Promise} */ function extractDocs(source, extractor, options, compilation) { var context = { source: source, compilation: compilation, compiler: compilation.compiler, fs: compilation.compiler.inputFileSystem, module: compilation.modules.filter(function (module) { return module.resource == source.absolutePath })[0], resolve: resolve, addDependency: addDependency, readFile: readFile }; return extractor.call(context, source.content, options); } module.exports = extractDocs;
var path = require('path'); var _readFile = require('../utils/readFile'); function resolve(filepath) { return path.resolve(this.source.absolutePath, filepath); } function addDependency(filepath) { this.compilation.fileDependencies.push(filepath); } function readFile(filepath) { return _readFile(filepath, this.fs); } /** * @param {Source} source * @param {Function} extractor * @param {Object} options * @param {Compilation} compilation * @returns {Promise} */ function extractDocs(source, extractor, options, compilation) { var context = { source: source, compilation: compilation, compiler: compilation.compiler, fs: compilation.compiler.inputFileSystem, resolve: resolve, addDependency: addDependency, readFile: readFile }; return extractor.call(context, source.content, options); } module.exports = extractDocs;
Remove useless offset propety from addItem initialState
import { SET_ITEM_NAME, SET_ITEM_CATEGORY, RESET_ADD_ITEM_FORM, } from '../constants/ActionTypes'; const initialState = { name: null, categoryId: null, }; export default (state = initialState, action) => { switch (action.type) { case SET_ITEM_NAME: return { ...state, name: action.name }; case SET_ITEM_CATEGORY: return { ...state, categoryId: action.categoryId }; case RESET_ADD_ITEM_FORM: return { ...initialState }; default: return state; } };
import { SET_ITEM_NAME, SET_ITEM_CATEGORY, RESET_ADD_ITEM_FORM, } from '../constants/ActionTypes'; const initialState = { offset: null, name: null, categoryId: null, }; export default (state = initialState, action) => { switch (action.type) { case SET_ITEM_NAME: return { ...state, name: action.name }; case SET_ITEM_CATEGORY: return { ...state, categoryId: action.categoryId }; case RESET_ADD_ITEM_FORM: return { ...initialState }; default: return state; } };
Update Client Version to 3.2
from setuptools import setup setup( name="teamscale-client", version="3.2.0", author="Thomas Kinnen - CQSE GmbH", author_email="kinnen@cqse.eu", description=("A simple service client to interact with Teamscale's REST API."), license="Apache", keywords="rest api teamscale", url="https://github.com/cqse/teamscale-client-python", packages=['teamscale_client'], long_description="A simple service client to interact with Teamscale's REST API.", classifiers=[ "Topic :: Utilities", ], install_requires=[ 'simplejson', 'requests>=2.0', 'jsonpickle' ], tests_require=[ 'pytest', 'responses' ], setup_requires=["pytest-runner"] )
from setuptools import setup setup( name="teamscale-client", version="3.1.1", author="Thomas Kinnen - CQSE GmbH", author_email="kinnen@cqse.eu", description=("A simple service client to interact with Teamscale's REST API."), license="Apache", keywords="rest api teamscale", url="https://github.com/cqse/teamscale-client-python", packages=['teamscale_client'], long_description="A simple service client to interact with Teamscale's REST API.", classifiers=[ "Topic :: Utilities", ], install_requires=[ 'simplejson', 'requests>=2.0', 'jsonpickle' ], tests_require=[ 'pytest', 'responses' ], setup_requires=["pytest-runner"] )
Handle directory creation when it is not present
package fortiss.gui.listeners.helper; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import fortiss.gui.DesignerPanel; import memap.helper.DirectoryConfiguration; public class WindowSnipper { public WindowSnipper() { } public void createTopologySnip() { Dimension d = DesignerPanel.pl_ems.getSize(); BufferedImage image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); DesignerPanel.pl_ems.print(g2d); g2d.dispose(); try { String location = System.getProperty("user.dir") + File.separator + DirectoryConfiguration.mainDir + File.separator + "topology.jpg"; File file = new File(location); if (!file.exists()) { try { file.getParentFile().mkdirs(); file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } ImageIO.write(image, "jpg", file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package fortiss.gui.listeners.helper; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import fortiss.gui.DesignerPanel; import memap.helper.DirectoryConfiguration; public class WindowSnipper { public WindowSnipper() { } public void createTopologySnip() { Dimension d = DesignerPanel.pl_ems.getSize(); BufferedImage image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); DesignerPanel.pl_ems.print(g2d); g2d.dispose(); try { String location = System.getProperty("user.dir") + File.separator + DirectoryConfiguration.mainDir + File.separator + "topology.jpg"; ImageIO.write(image, "jpg", new File(location)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Fix path for handlebars helpers
var path = require("path"); // Export function to create new config (builder is passed in from outside) module.exports = function(builder) { var bootstrapLess = require.resolve("bootstrap/less/bootstrap.less"); return builder.merge({ template: require.resolve("./handlebars/template.hbs"), partials: path.resolve(__dirname,"handlebars"), helpers: require("./handlebars/helpers.js"), less: { main: [ bootstrapLess, require.resolve("./less/main.less") ], paths: [ path.dirname(bootstrapLess) ] }, /** * A preprocessor that may return a modified json before entering the rendering process. * Access the inherited preprocessor is possible via <code>this.previous(json)</code> * @param obj the input object * @return a modified object or a promise for a modified object. */ preprocessor: function(obj) { return obj; } }) }; // Add "package" to be used by bootprint-doc-generator module.exports.package = require("./package");
var path = require("path"); // Export function to create new config (builder is passed in from outside) module.exports = function(builder) { var bootstrapLess = require.resolve("bootstrap/less/bootstrap.less"); return builder.merge({ template: require.resolve("./handlebars/template.hbs"), partials: path.resolve(__dirname,"handlebars"), helpers: require("./src/handlebars-helper.js"), less: { main: [ bootstrapLess, require.resolve("./less/main.less") ], paths: [ path.dirname(bootstrapLess) ] }, /** * A preprocessor that may return a modified json before entering the rendering process. * Access the inherited preprocessor is possible via <code>this.previous(json)</code> * @param obj the input object * @return a modified object or a promise for a modified object. */ preprocessor: function(obj) { return obj; } }) }; // Add "package" to be used by bootprint-doc-generator module.exports.package = require("./package");
Add threejs library as one of the usable module for compatibility.
/** * Provides a global namespace for the Zinc javascript library and some default parameters for it. * * @namespace * @author Alan Wu */ var Zinc = function() { this.Revision = 29; this.defaultMaterialColor = 0xFFFFFF; this.defaultOpacity = 1.0; this.Geometry = require('./geometry').Geometry; this.Glyph = require('./glyph').Glyph; this.Glyphset = require('./glyphset').Glyphset; this.Renderer = require('./renderer').Renderer; this.Scene = require('./scene').Scene; this.GeometryCSG = require('./geometryCSG').GeometryCSG; this.Viewport = require('./controls').Viewport; this.CameraControls = require('./controls').CameraControls; this.SmoothCameraTransition = require('./controls').SmoothCameraTransition; this.RayCaster = require('./controls').RayCaster; this.CameraAutoTumble = require('./controls').CameraAutoTumble; this.loadExternalFile = require('./utilities').loadExternalFile; this.loadExternalFiles = require('./utilities').loadExternalFiles; this.StereoEffect = require('./controls').StereoEffect; this.THREE = require('three'); } module.exports = new Zinc();
/** * Provides a global namespace for the Zinc javascript library and some default parameters for it. * * @namespace * @author Alan Wu */ var Zinc = function() { this.Revision = 29; this.defaultMaterialColor = 0xFFFFFF; this.defaultOpacity = 1.0; this.Geometry = require('./geometry').Geometry; this.Glyph = require('./glyph').Glyph; this.Glyphset = require('./glyphset').Glyphset; this.Renderer = require('./renderer').Renderer; this.Scene = require('./scene').Scene; this.GeometryCSG = require('./geometryCSG').GeometryCSG; this.Viewport = require('./controls').Viewport; this.CameraControls = require('./controls').CameraControls; this.SmoothCameraTransition = require('./controls').SmoothCameraTransition; this.RayCaster = require('./controls').RayCaster; this.CameraAutoTumble = require('./controls').CameraAutoTumble; this.loadExternalFile = require('./utilities').loadExternalFile; this.loadExternalFiles = require('./utilities').loadExternalFiles; this.StereoEffect = require('./controls').StereoEffect; } module.exports = new Zinc();
Add indexes to user schema
var mongoose = require('mongoose'), urlFormatter = require('../../app/models/url_formatter.server.model'), Schema = mongoose.Schema; var UserSchema = new Schema({ firstName: String, lastName: String, email: { type: String, index: true }, username: { type: String, trim: true, unique: true }, password: String, created: { type: Date, default: Date.now }, website: { type: String, set: urlFormatter.addHttpIfNotPresent, get: urlFormatter.addHttpIfNotPresent } }); UserSchema.virtual('fullName').get(function() { return this.firstName + ' ' + this.lastName; }); UserSchema.set('toJSON', { getters: true , virtuals: true }); mongoose.model('User', UserSchema);
var mongoose = require('mongoose'), urlFormatter = require('../../app/models/url_formatter.server.model'), Schema = mongoose.Schema; var UserSchema = new Schema({ firstName: String, lastName: String, email: String, username: { type: String, trim: true }, password: String, created: { type: Date, default: Date.now }, website: { type: String, set: urlFormatter.addHttpIfNotPresent, get: urlFormatter.addHttpIfNotPresent } }); UserSchema.virtual('fullName').get(function() { return this.firstName + ' ' + this.lastName; }); UserSchema.set('toJSON', { getters: true , virtuals: true }); mongoose.model('User', UserSchema);
Fix bug with getting ec2 connection instead of source image
package chroot import ( "fmt" "github.com/mitchellh/goamz/ec2" "github.com/mitchellh/multistep" "github.com/mitchellh/packer/packer" ) // StepCheckRootDevice makes sure the root device on the AMI is EBS-backed. type StepCheckRootDevice struct{} func (s *StepCheckRootDevice) Run(state multistep.StateBag) multistep.StepAction { image := state.Get("source_image").(*ec2.Image) ui := state.Get("ui").(packer.Ui) ui.Say("Checking the root device on source AMI...") // It must be EBS-backed otherwise the build won't work if image.RootDeviceType != "ebs" { err := fmt.Errorf("The root device of the source AMI must be EBS-backed.") state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } return multistep.ActionContinue } func (s *StepCheckRootDevice) Cleanup(multistep.StateBag) {}
package chroot import ( "fmt" "github.com/mitchellh/goamz/ec2" "github.com/mitchellh/multistep" "github.com/mitchellh/packer/packer" ) // StepCheckRootDevice makes sure the root device on the AMI is EBS-backed. type StepCheckRootDevice struct{} func (s *StepCheckRootDevice) Run(state multistep.StateBag) multistep.StepAction { image := state.Get("ec2").(*ec2.Image) ui := state.Get("ui").(packer.Ui) ui.Say("Checking the root device on source AMI...") // It must be EBS-backed otherwise the build won't work if image.RootDeviceType != "ebs" { err := fmt.Errorf("The root device of the source AMI must be EBS-backed.") state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } return multistep.ActionContinue } func (s *StepCheckRootDevice) Cleanup(multistep.StateBag) {}
Make version hack more reliable
import importlib.metadata from typing import Any, Optional, Protocol, cast class BasePath(Protocol): """A protocol that various path objects conform. This exists because importlib.metadata uses both ``pathlib.Path`` and ``zipfile.Path``, and we need a common base for type hints (Union does not work well since ``zipfile.Path`` is too new for our linter setup). This does not mean to be exhaustive, but only contains things that present in both classes *that we need*. """ name: str @property def parent(self) -> "BasePath": raise NotImplementedError() def get_info_location(d: importlib.metadata.Distribution) -> Optional[BasePath]: """Find the path to the distribution's metadata directory. HACK: This relies on importlib.metadata's private ``_path`` attribute. Not all distributions exist on disk, so importlib.metadata is correct to not expose the attribute as public. But pip's code base is old and not as clean, so we do this to avoid having to rewrite too many things. Hopefully we can eliminate this some day. """ return getattr(d, "_path", None) def get_dist_name(dist: importlib.metadata.Distribution) -> str: """Get the distribution's project name. The ``name`` attribute is only available in Python 3.10 or later. We are targeting exactly that, but Mypy does not know this. """ return cast(Any, dist).name
import importlib.metadata from typing import Optional, Protocol class BasePath(Protocol): """A protocol that various path objects conform. This exists because importlib.metadata uses both ``pathlib.Path`` and ``zipfile.Path``, and we need a common base for type hints (Union does not work well since ``zipfile.Path`` is too new for our linter setup). This does not mean to be exhaustive, but only contains things that present in both classes *that we need*. """ name: str @property def parent(self) -> "BasePath": raise NotImplementedError() def get_info_location(d: importlib.metadata.Distribution) -> Optional[BasePath]: """Find the path to the distribution's metadata directory. HACK: This relies on importlib.metadata's private ``_path`` attribute. Not all distributions exist on disk, so importlib.metadata is correct to not expose the attribute as public. But pip's code base is old and not as clean, so we do this to avoid having to rewrite too many things. Hopefully we can eliminate this some day. """ return getattr(d, "_path", None) def get_dist_name(dist: importlib.metadata.Distribution) -> str: """Get the distribution's project name. The ``name`` attribute is only available in Python 3.10 or later. We are targeting exactly that, but Mypy does not know this. """ return dist.name # type: ignore[attr-defined]
Use html tech from bemhtml library
var PATH = require('path'), pjoin = PATH.join, presolve = PATH.resolve.bind(null, __dirname), PRJ_ROOT = presolve('../../'), PRJ_TECHS = presolve('../techs/'); exports.getTechs = function() { return { 'bemjson.js' : '', 'bemdecl.js' : 'bemdecl.js', 'deps.js' : 'deps.js', 'js' : 'js-i', 'css' : 'css', 'ie.css' : 'ie.css', 'ie6.css' : 'ie6.css', 'ie7.css' : 'ie7.css', 'ie8.css' : 'ie8.css', 'ie9.css' : 'ie9.css', 'bemhtml' : pjoin(PRJ_ROOT, 'bemhtml/.bem/techs/bemhtml.js'), 'html' : pjoin(PRJ_ROOT, 'bemhtml/.bem/techs/html.js') }; }; // Do not create any techs files during bundle creation by default exports.defaultTechs = [];
var PATH = require('path'), pjoin = PATH.join, presolve = PATH.resolve.bind(null, __dirname), PRJ_ROOT = presolve('../../'), PRJ_TECHS = presolve('../techs/'), BEMBL_TECHS = pjoin(PRJ_ROOT, 'bem-bl/blocks-common/i-bem/bem/techs'); exports.getTechs = function() { return { 'bemjson.js' : '', 'bemdecl.js' : 'bemdecl.js', 'deps.js' : 'deps.js', 'js' : 'js-i', 'css' : 'css', 'ie.css' : 'ie.css', 'ie6.css' : 'ie6.css', 'ie7.css' : 'ie7.css', 'ie8.css' : 'ie8.css', 'ie9.css' : 'ie9.css', 'bemhtml' : pjoin(PRJ_ROOT, 'bemhtml/.bem/techs/bemhtml.js'), 'html' : pjoin(BEMBL_TECHS, 'html.js') }; }; // Do not create any techs files during bundle creation by default exports.defaultTechs = [];
feat(bot): Implement switching to webhooks in production
"use strict"; const http = require('http'); const mongoose = require('mongoose'); const requireAll = require('require-all'); const TelegramBot = require('node-telegram-bot-api'); const GitHubNotifications = require('./services/GitHubNotifications'); const User = require('./models/User'); const BOT_COMMANDS = requireAll({dirname: `${__dirname}/commands`}); const TELEGRAM_BOT_TOKEN = process.env['TELEGRAM_BOT_TOKEN']; if (!TELEGRAM_BOT_TOKEN) throw new Error('You must provide telegram bot token'); const telegramBotConfig = process.env.NODE_ENV === 'production' ? {webHook: true} : {polling: true}; const bot = new TelegramBot(TELEGRAM_BOT_TOKEN, telegramBotConfig); Object.keys(BOT_COMMANDS).forEach(command => BOT_COMMANDS[command](bot)); mongoose.connect(process.env['MONGODB_URI']); User.find({}, (error, users) => { if (error) throw new Error(error); users.forEach(user => { new GitHubNotifications(user.username, user.token).on('notification', data => { bot.sendMessage(user.telegramId, `You have unread notification - ${data}`); }); }); }); http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Bot is working\n'); }).listen(process.env['PORT']);
"use strict"; const http = require('http'); const mongoose = require('mongoose'); const requireAll = require('require-all'); const TelegramBot = require('node-telegram-bot-api'); const GitHubNotifications = require('./common/GitHubNotifications'); const User = require('./models/User'); const BOT_COMMANDS = requireAll({dirname: `${__dirname}/commands`}); const TELEGRAM_BOT_TOKEN = process.env['TELEGRAM_BOT_TOKEN']; if (!TELEGRAM_BOT_TOKEN) throw new Error('You must provide telegram bot token'); const bot = new TelegramBot(TELEGRAM_BOT_TOKEN, {polling: true}); Object.keys(BOT_COMMANDS).forEach(command => BOT_COMMANDS[command](bot)); mongoose.connect(process.env['MONGODB_URI']); User.find({}, (error, users) => { if (error) throw new Error(error); users.forEach(user => { new GitHubNotifications(user.username, user.token).on('notification', data => { bot.sendMessage(user.telegramId, `You have unread notification - ${data}`); }); }); }); http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Bot is working\n'); }).listen(process.env['PORT']);
Use let instead of const
/* * This script will automaticly look at the closest entity. * It checks for a near entity every tick. */ const mineflayer = require('mineflayer') if (process.argv.length < 4 || process.argv.length > 6) { console.log('Usage : node echo.js <host> <port> [<name>] [<password>]') process.exit(1) } const bot = mineflayer.createBot({ host: process.argv[2], port: parseInt(process.argv[3]), username: process.argv[4] ? process.argv[4] : 'looker', password: process.argv[5] }) bot.once('spawn', function () { setInterval(() => { var entity = nearestEntity() if (entity) { if (entity.type === 'player') { bot.lookAt(entity.position.offset(0, 1.6, 0)) } else if (entity.type === 'mob') { bot.lookAt(entity.position) } } }, 50) }) function nearestEntity (type) { let id, entity, dist let best = null let bestDistance = null for (id in bot.entities) { entity = bot.entities[id] if (type && entity.type !== type) continue if (entity === bot.entity) continue dist = bot.entity.position.distanceTo(entity.position) if (!best || dist < bestDistance) { best = entity bestDistance = dist } } return best }
/* * This script will automaticly look at the closest entity. * It checks for a near entity every tick. */ const mineflayer = require('mineflayer') if (process.argv.length < 4 || process.argv.length > 6) { console.log('Usage : node echo.js <host> <port> [<name>] [<password>]') process.exit(1) } const bot = mineflayer.createBot({ host: process.argv[2], port: parseInt(process.argv[3]), username: process.argv[4] ? process.argv[4] : 'looker', password: process.argv[5] }) bot.once('spawn', function () { setInterval(() => { var entity = nearestEntity() if (entity) { if (entity.type === 'player') { bot.lookAt(entity.position.offset(0, 1.6, 0)) } else if (entity.type === 'mob') { bot.lookAt(entity.position) } } }, 50) }) function nearestEntity (type) { let id, entity, dist const best = null const bestDistance = null for (id in bot.entities) { entity = bot.entities[id] if (type && entity.type !== type) continue if (entity === bot.entity) continue dist = bot.entity.position.distanceTo(entity.position) if (!best || dist < bestDistance) { best = entity bestDistance = dist } } return best }
[Genomics]: Make it easier to run the SAM indexer on a single file.
package com.github.sparkcaller.preprocessing; import htsjdk.samtools.BAMIndexer; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.Function2; import java.io.File; public class BamIndexer implements Function<File, File> { // Create an index (.bai) file for the given BAM file. public static void indexBam(File bamFile) throws Exception { final SamReader bamReader = SamReaderFactory.makeDefault() .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS) .open(bamFile); BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai")); } @Override public File call(File inputBAM) throws Exception { BamIndexer.indexBam(inputBAM); return inputBAM; } }
package com.github.sparkcaller.preprocessing; import htsjdk.samtools.BAMIndexer; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import org.apache.spark.api.java.function.Function; import java.io.File; public class BamIndexer implements Function<File, File> { // Create an index (.bai) file for the given BAM file. public File call(File bamFile) throws Exception { final SamReader bamReader = SamReaderFactory.makeDefault() .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS) .open(bamFile); BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai")); return bamFile; } }
Remove useless blank line after the namespace declaration
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace DoctrineORMModuleTest\Assets; class RepositoryClass extends \Doctrine\ORM\EntityRepository { }
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace DoctrineORMModuleTest\Assets; class RepositoryClass extends \Doctrine\ORM\EntityRepository { }
Set is_found in AppleFrameworks constructor Set is_found in AppleFrameworks constructor, rather than overriding the found() method, as other superclass methods may access is_found.
# Copyright 2013-2017 The Meson development team # 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. # This file contains the detection logic for external dependencies that are # platform-specific (generally speaking). from .. import mesonlib from .base import ExternalDependency, DependencyException class AppleFrameworks(ExternalDependency): def __init__(self, env, kwargs): super().__init__('appleframeworks', env, None, kwargs) modules = kwargs.get('modules', []) if isinstance(modules, str): modules = [modules] if not modules: raise DependencyException("AppleFrameworks dependency requires at least one module.") self.frameworks = modules # FIXME: Use self.clib_compiler to check if the frameworks are available for f in self.frameworks: self.link_args += ['-framework', f] self.is_found = mesonlib.is_osx() def get_version(self): return 'unknown'
# Copyright 2013-2017 The Meson development team # 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. # This file contains the detection logic for external dependencies that are # platform-specific (generally speaking). from .. import mesonlib from .base import ExternalDependency, DependencyException class AppleFrameworks(ExternalDependency): def __init__(self, env, kwargs): super().__init__('appleframeworks', env, None, kwargs) modules = kwargs.get('modules', []) if isinstance(modules, str): modules = [modules] if not modules: raise DependencyException("AppleFrameworks dependency requires at least one module.") self.frameworks = modules # FIXME: Use self.clib_compiler to check if the frameworks are available for f in self.frameworks: self.link_args += ['-framework', f] def found(self): return mesonlib.is_osx() def get_version(self): return 'unknown'
Add Knockout to font loader
var urls = [ 'http://s.npr.org/templates/css/fonts/GothamSSm.css', 'http://s.npr.org/templates/css/fonts/Gotham.css', 'http://s.npr.org/templates/css/fonts/Knockout.css' ]; if (window.location.protocol == "https:") { urls = [ 'https://secure.npr.org/templates/css/fonts/GothamSSm.css', 'https://secure.npr.org/templates/css/fonts/Gotham.css', 'https://secure.npr.org/templates/css/fonts/Knockout.css' ]; } WebFont.load({ custom: { families: [ 'Gotham SSm:n4,n7', 'Gotham:n4,n7', 'Knockout 31 4r:n4' ], urls: urls }, timeout: 10000 });
var urls = [ 'http://s.npr.org/templates/css/fonts/GothamSSm.css', 'http://s.npr.org/templates/css/fonts/Gotham.css' ]; if (window.location.protocol == "https:") { urls = [ 'https://secure.npr.org/templates/css/fonts/GothamSSm.css', 'https://secure.npr.org/templates/css/fonts/Gotham.css' ]; } WebFont.load({ custom: { families: [ 'Gotham SSm:n4,n7', 'Gotham:n4,n7' ], urls: urls }, timeout: 10000 });
Allow exception to be thrown in `elixir` helper
<?php if (! function_exists('public_path')) { /** * Get the path to the public folder. * * @param string $path * @return string */ function public_path($path = '') { return 'source'.($path ? DIRECTORY_SEPARATOR.$path : $path); } } if (! function_exists('elixir')) { /** * Get the path to a versioned Elixir file. * * @param string $file * @param string $buildDirectory * @return string * * @throws \InvalidArgumentException */ function elixir($file, $buildDirectory = 'build') { static $manifest; static $manifestPath; if (is_null($manifest) || $manifestPath !== $buildDirectory) { $manifest = json_decode(file_get_contents(public_path($buildDirectory.'/rev-manifest.json')), true); $manifestPath = $buildDirectory; } if (isset($manifest[$file])) { return '/'.trim($buildDirectory.'/'.$manifest[$file], '/'); } throw new InvalidArgumentException("File {$file} not defined in asset manifest."); } }
<?php if (! function_exists('public_path')) { /** * Get the path to the public folder. * * @param string $path * @return string */ function public_path($path = '') { return 'source'.($path ? DIRECTORY_SEPARATOR.$path : $path); } } if (! function_exists('elixir')) { /** * Get the path to a versioned Elixir file. * * @param string $file * @param string $buildDirectory * @return string * * @throws \InvalidArgumentException */ function elixir($file, $buildDirectory = 'build') { static $manifest; static $manifestPath; if (is_null($manifest) || $manifestPath !== $buildDirectory) { $manifest = json_decode(file_get_contents(public_path($buildDirectory.'/rev-manifest.json')), true); $manifestPath = $buildDirectory; } if (isset($manifest[$file])) { return '/'.trim($buildDirectory.'/'.$manifest[$file], '/'); } return $file; throw new InvalidArgumentException("File {$file} not defined in asset manifest."); } }
Use latest petitions on HP instead...
import React from 'react'; import TeaserGrid from 'components/TeaserGrid'; import Container from 'components/Container'; import BlockContainer from 'components/BlockContainer'; import Section from 'components/Section'; import Heading2 from 'components/Heading2'; import styles from './homepage-petitions.scss'; import Link from 'components/Link'; const HomepagePetitions = ({ groupedPetitions, title, text, linkText }) => ( <section> <Section> <Container> <BlockContainer> <div className={styles.head}> <div className={styles.left}> <Heading2 text={title} /> <span className={styles.text}>{text}</span> </div> <Link href='/petitions'>{linkText}</Link> </div> </BlockContainer> <TeaserGrid petitions={groupedPetitions.latest.data} isLoading={groupedPetitions.latest.isLoading} /> </Container> </Section> </section> ); export default HomepagePetitions;
import React from 'react'; import TeaserGrid from 'components/TeaserGrid'; import Container from 'components/Container'; import BlockContainer from 'components/BlockContainer'; import Section from 'components/Section'; import Heading2 from 'components/Heading2'; import styles from './homepage-petitions.scss'; import Link from 'components/Link'; const HomepagePetitions = ({ groupedPetitions, title, text, linkText }) => ( <section> <Section> <Container> <BlockContainer> <div className={styles.head}> <div className={styles.left}> <Heading2 text={title} /> <span className={styles.text}>{text}</span> </div> <Link href='/petitions'>{linkText}</Link> </div> </BlockContainer> <TeaserGrid petitions={groupedPetitions.trending.data} isLoading={groupedPetitions.trending.isLoading} /> </Container> </Section> </section> ); export default HomepagePetitions;
Change extension path in registerBackendControllers()
<?php namespace Bolt\Extension\Bolt\Importwxr; use Bolt\Extension\Bolt\Importwxr\Controller\ImportController; use Bolt\Extension\SimpleExtension; use Bolt\Menu\MenuEntry; /** * Importwxr extension class. * * @author Your Name <you@example.com> */ class ImportwxrExtension extends SimpleExtension { protected function registerMenuEntries() { $menu = new MenuEntry('importwxr-menu', 'importWXR'); $menu->setLabel('Import WXR') ->setIcon('fa:gear') ->setPermission('settings') ; return [ $menu, ]; } protected function registerBackendControllers() { return [ '/extensions/importWXR' => new ImportController($this->getContainer(), $this->getConfig()), ]; } /** * {@inheritdoc} */ protected function getDefaultConfig() { return [ 'allowed_tags' => ['div', 'p', 'br', 's', 'u', 'strong', 'em', 'i', 'b', 'blockquote', 'a', 'img'], 'allowed_attributes' => ['id', 'class', 'name', 'value', 'href', 'src', 'alt', 'title'] ]; } }
<?php namespace Bolt\Extension\Bolt\Importwxr; use Bolt\Extension\Bolt\Importwxr\Controller\ImportController; use Bolt\Extension\SimpleExtension; use Bolt\Menu\MenuEntry; /** * Importwxr extension class. * * @author Your Name <you@example.com> */ class ImportwxrExtension extends SimpleExtension { protected function registerMenuEntries() { $menu = new MenuEntry('importwxr-menu', 'importWXR'); $menu->setLabel('Import WXR') ->setIcon('fa:gear') ->setPermission('settings') ; return [ $menu, ]; } protected function registerBackendControllers() { return [ '/extend/importWXR' => new ImportController($this->getContainer(), $this->getConfig()), ]; } /** * {@inheritdoc} */ protected function getDefaultConfig() { return [ 'allowed_tags' => ['div', 'p', 'br', 's', 'u', 'strong', 'em', 'i', 'b', 'blockquote', 'a', 'img'], 'allowed_attributes' => ['id', 'class', 'name', 'value', 'href', 'src', 'alt', 'title'] ]; } }
Update message for missing ResponsiveMiddleware
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "You must enable the 'ResponsiveMiddleware'. Edit your " "MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "responsive context_processors requires the responsive middleware to " "be installed. Edit your MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
Clarify static method description for sharing
package org.mozilla.webmaker.util; import android.app.Activity; import android.content.Intent; import org.mozilla.webmaker.R; public class Share { /** * Launches a share intent. * * @param url URL to be appended to the share body * @param activity Base activity */ public static void launchShareIntent(final String url, final Activity activity) { final Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); final String shareSubject = activity.getString(R.string.share_subject); final String shareBody = activity.getString(R.string.share_body).concat(" " + url); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject); shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody); activity.startActivity(Intent.createChooser(shareIntent, "Share")); } }
package org.mozilla.webmaker.util; import android.app.Activity; import android.content.Intent; import org.mozilla.webmaker.R; public class Share { /** * Launches a share intent using a specified subject and body. * * @param url URL to be appended to the share body * @param activity Base activity */ public static void launchShareIntent(final String url, final Activity activity) { final Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); final String shareSubject = activity.getString(R.string.share_subject); final String shareBody = activity.getString(R.string.share_body).concat(" " + url); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject); shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody); activity.startActivity(Intent.createChooser(shareIntent, "Share")); } }
Drop use of 'oslo' namespace package The Oslo libraries have moved all of their code out of the 'oslo' namespace package into per-library packages. The namespace package was retained during kilo for backwards compatibility, but will be removed by the liberty-2 milestone. This change removes the use of the namespace package, replacing it with the new package names. The patches in the libraries will be put on hold until application patches have landed, or L2, whichever comes first. At that point, new versions of the libraries without namespace packages will be released as a major version update. Please merge this patch, or an equivalent, before L2 to avoid problems with those library releases. Blueprint: remove-namespace-packages https://blueprints.launchpad.net/oslo-incubator/+spec/remove-namespace-packages Change-Id: Id54b2381f00d9905c4bb07821f54c5aaaa48d970
# Copyright 2014 Red Hat, Inc # All Rights .Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_i18n import * # noqa _translators = TranslatorFactory(domain='zaqarclient') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
# Copyright 2014 Red Hat, Inc # All Rights .Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.i18n import * # noqa _translators = TranslatorFactory(domain='zaqarclient') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
Fix typo in Pushbullet user section title
package fr.jcgay.jenkins.plugins.pushbullet; import hudson.Extension; import hudson.model.User; import hudson.model.UserProperty; import hudson.model.UserPropertyDescriptor; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; public class PushbulletUser extends UserProperty { private final Secret apiToken; @DataBoundConstructor public PushbulletUser(String apiToken) { this.apiToken = Secret.fromString(apiToken); } public String getApiToken() { return apiToken.getEncryptedValue(); } public Secret getSecretApiToken() { return apiToken; } @Extension public static final class DescriptorImpl extends UserPropertyDescriptor { public String getDisplayName() { return "Pushbullet"; } @Override public UserProperty newInstance(User user) { return new PushbulletUser(null); } } }
package fr.jcgay.jenkins.plugins.pushbullet; import hudson.Extension; import hudson.model.User; import hudson.model.UserProperty; import hudson.model.UserPropertyDescriptor; import hudson.util.Secret; import org.kohsuke.stapler.DataBoundConstructor; public class PushbulletUser extends UserProperty { private final Secret apiToken; @DataBoundConstructor public PushbulletUser(String apiToken) { this.apiToken = Secret.fromString(apiToken); } public String getApiToken() { return apiToken.getEncryptedValue(); } public Secret getSecretApiToken() { return apiToken; } @Extension public static final class DescriptorImpl extends UserPropertyDescriptor { public String getDisplayName() { return "Pusbullet"; } @Override public UserProperty newInstance(User user) { return new PushbulletUser(null); } } }
Tweak documentation for market listener in order book reconstruction
package org.jvirtanen.parity.top; /** * The interface for outbound events from the order book reconstruction. */ public interface MarketListener { /** * An event indicating that the best bid and offer (BBO) has changed. * * @param instrument the instrument * @param bidPrice the bid price or zero if there are no bids * @param bidSize the bid size or zero if there are no bids * @param askPrice the ask price or zero if there are no asks * @param askSize the ask size or zero if there are no asks */ void bbo(long instrument, long bidPrice, long bidSize, long askPrice, long askSize); /** * An event indicating that a trade has taken place. * * @param instrument the instrument * @param side the side of the resting order * @param price the trade price * @param size the trade size */ void trade(long instrument, Side side, long price, long size); }
package org.jvirtanen.parity.top; /** * <code>MarketListener</code> is the interface for outbound events from the * order book reconstruction. */ public interface MarketListener { /** * An event indicating that the best bid and offer (BBO) has changed. * * @param instrument the instrument * @param bidPrice the bid price or zero if there are no bids * @param bidSize the bid size or zero if there are no bids * @param askPrice the ask price or zero if there are no asks * @param askSize the ask size or zero if there are no asks */ void bbo(long instrument, long bidPrice, long bidSize, long askPrice, long askSize); /** * An event indicating that a trade has taken place. * * @param instrument the instrument * @param side the side of the resting order * @param price the trade price * @param size the trade size */ void trade(long instrument, Side side, long price, long size); }
Fix Dominator memory leak with explicit sub.connection.Close() call.
package herd import ( "github.com/Symantec/Dominator/dom/mdb" ) func (herd *Herd) mdbUpdate(mdb *mdb.Mdb) { herd.subsByIndex = nil if herd.subsByName == nil { herd.subsByName = make(map[string]*Sub) } for _, sub := range herd.subsByName { sub.hostname = "" } for _, machine := range mdb.Machines { sub := herd.subsByName[machine.Hostname] if sub == nil { sub = new(Sub) herd.subsByName[machine.Hostname] = sub } sub.hostname = machine.Hostname sub.requiredImage = machine.RequiredImage sub.plannedImage = machine.PlannedImage } subsToDelete := make([]string, 0) for hostname, sub := range herd.subsByName { if sub.hostname == "" { subsToDelete = append(subsToDelete, hostname) if sub.connection != nil { // Destroying a Client doesn't free up all the memory, so call // the Close() method to free up the memory. sub.connection.Close() } } } for _, hostname := range subsToDelete { delete(herd.subsByName, hostname) } herd.subsByIndex = make([]*Sub, 0, len(herd.subsByName)) for _, sub := range herd.subsByName { herd.subsByIndex = append(herd.subsByIndex, sub) } }
package herd import ( "github.com/Symantec/Dominator/dom/mdb" ) func (herd *Herd) mdbUpdate(mdb *mdb.Mdb) { herd.subsByIndex = nil if herd.subsByName == nil { herd.subsByName = make(map[string]*Sub) } for _, sub := range herd.subsByName { sub.hostname = "" } for _, machine := range mdb.Machines { sub := herd.subsByName[machine.Hostname] if sub == nil { sub = new(Sub) herd.subsByName[machine.Hostname] = sub } sub.hostname = machine.Hostname sub.requiredImage = machine.RequiredImage sub.plannedImage = machine.PlannedImage } subsToDelete := make([]string, 0) for hostname, sub := range herd.subsByName { if sub.hostname == "" { subsToDelete = append(subsToDelete, hostname) } } for _, hostname := range subsToDelete { delete(herd.subsByName, hostname) } herd.subsByIndex = make([]*Sub, 0, len(herd.subsByName)) for _, sub := range herd.subsByName { herd.subsByIndex = append(herd.subsByIndex, sub) } }
Fix random x axis ball speed
import Item, { MovingDirection, ItemType } from './Item' import Ball from './Ball' import ItemLoader from '../Loader/ItemLoader' import Helper from '../Utility/Utility' export default class Platform extends Item { constructor(width, height, color) { super( [500 - (width / 2), 500 - height - 10], [width, height], color, ItemType.PLATFORM, ) } unbindBall() { for (let i = 0; i < this.boundItems.length; i += 1) { if (this.boundItems[i] instanceof Ball) { const prevBoundPosition = this.boundItems[i].getPosition() const prevColor = this.boundItems[i].getColor() const prevWidth = this.boundItems[i].getWidth() this.detachItem(this.boundItems[i]) const detachedBall = new Ball(prevWidth, prevColor, prevBoundPosition) const xDirections = [MovingDirection.LEFT, MovingDirection.RIGHT] const randomXDirection = xDirections[Math.floor(Math.random() * xDirections.length)] const randomSpeed = () => Helper.randomIntFromInterval(1, 8) detachedBall.setSpeed([randomSpeed(), randomSpeed()]) detachedBall.setDirection([randomXDirection, MovingDirection.UP]) ItemLoader.addItem(detachedBall) ItemLoader.addMovingItem(detachedBall) } } } }
import Item, { MovingDirection, ItemType } from './Item' import Ball from './Ball' import ItemLoader from '../Loader/ItemLoader' import Helper from '../Utility/Utility' export default class Platform extends Item { constructor(width, height, color) { super( [500 - (width / 2), 500 - height - 10], [width, height], color, ItemType.PLATFORM, ) } unbindBall() { for (let i = 0; i < this.boundItems.length; i += 1) { if (this.boundItems[i] instanceof Ball) { const prevBoundPosition = this.boundItems[i].getPosition() const prevColor = this.boundItems[i].getColor() const prevWidth = this.boundItems[i].getWidth() this.detachItem(this.boundItems[i]) const detachedBall = new Ball(prevWidth, prevColor, prevBoundPosition) const xDirections = [MovingDirection.LEFT, MovingDirection.RIGHT] const randomXDirection = xDirections[Math.floor(Math.random() * xDirections.length)] const randomSpeed = () => Helper.randomIntFromInterval(1, 8) detachedBall.setSpeed([0, randomSpeed()]) detachedBall.setDirection([randomXDirection, MovingDirection.UP]) ItemLoader.addItem(detachedBall) ItemLoader.addMovingItem(detachedBall) } } } }
Handle unparseable log lines properly
#!/usr/bin/env node "use strict"; var bunyan = require("bunyan"); var ss = require("stream-splitter"); var lineFormat = /(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2}) /; var tagFormat = /([\w.]+): /; var logName = process.argv[2] || "etcd"; var log = bunyan.createLogger({name: logName}); var stream = process.stdin.pipe(ss("\n")); stream.encoding = "utf8"; stream.on("token", function(line) { var preambleMatch = lineFormat.exec(line); if (preambleMatch === null) { log.info({type: "misc"}, line); return; } line = line.substring(preambleMatch[0].length); var date = new Date(preambleMatch[1], preambleMatch[2], preambleMatch[3], preambleMatch[4], preambleMatch[5], preambleMatch[6]); var tagMatch = tagFormat.exec(line); var tag = tagMatch ? tagMatch[1] : undefined; if (tagMatch) { line = line.substring(tagMatch[0].length); } log.info({time: date, type: tag}, line); });
#!/usr/bin/env node "use strict"; var bunyan = require("bunyan"); var ss = require("stream-splitter"); var lineFormat = /(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2}) /; var tagFormat = /([\w.]+): /; var logName = process.argv[2] || "etcd"; var log = bunyan.createLogger({name: logName}); var stream = process.stdin.pipe(ss("\n")); stream.encoding = "utf8"; stream.on("token", function(line) { var preambleMatch = lineFormat.exec(line); line = line.substring(preambleMatch[0].length); var date = new Date(preambleMatch[1], preambleMatch[2], preambleMatch[3], preambleMatch[4], preambleMatch[5], preambleMatch[6]); var tagMatch = tagFormat.exec(line); var tag = tagMatch ? tagMatch[1] : undefined; if (tagMatch) { line = line.substring(tagMatch[0].length); } log.info({time: date, type: tag}, line); });
Add declare_strict_types rule for php-cs-fixer
<?php $finder = (new PhpCsFixer\Finder()) ->in(__DIR__); return (new PhpCsFixer\Config()) ->setRiskyAllowed(true) ->setRules([ '@Symfony' => true, '@Symfony:risky' => true, 'array_syntax' => [ 'syntax' => 'short', ], 'concat_space' => [ 'spacing' => 'one', ], 'declare_strict_types' => true, 'global_namespace_import' => [ 'import_classes' => true, 'import_constants' => null, 'import_functions' => true, ], 'native_constant_invocation' => [ 'fix_built_in' => false, ], 'ordered_imports' => [ 'imports_order' => [ 'class', 'function', 'const', ], ], 'single_line_throw' => false, ]) ->setFinder($finder);
<?php $finder = (new PhpCsFixer\Finder()) ->in(__DIR__); return (new PhpCsFixer\Config()) ->setRiskyAllowed(true) ->setRules([ '@Symfony' => true, '@Symfony:risky' => true, 'array_syntax' => [ 'syntax' => 'short', ], 'concat_space' => [ 'spacing' => 'one', ], 'global_namespace_import' => [ 'import_classes' => true, 'import_constants' => null, 'import_functions' => true, ], 'native_constant_invocation' => [ 'fix_built_in' => false, ], 'ordered_imports' => [ 'imports_order' => [ 'class', 'function', 'const', ], ], 'single_line_throw' => false, ]) ->setFinder($finder);
Make the jplock/zookeeper tag explicit (3.4.6 instead of 'latest')
package com.containersol.minimesos.mesos; import com.containersol.minimesos.MesosCluster; import com.containersol.minimesos.container.AbstractContainer; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.model.ExposedPort; /** * Base zookeeper class */ public class ZooKeeper extends AbstractContainer { public static final String MESOS_LOCAL_IMAGE = "jplock/zookeeper"; public static final String REGISTRY_TAG = "3.4.6"; public static final int DEFAULT_ZOOKEEPER_PORT = 2181; protected ZooKeeper(DockerClient dockerClient) { super(dockerClient); } @Override protected void pullImage() { pullImage(MESOS_LOCAL_IMAGE, REGISTRY_TAG); } @Override protected CreateContainerCmd dockerCommand() { return dockerClient.createContainerCmd(MESOS_LOCAL_IMAGE + ":" + REGISTRY_TAG) .withName("minimesos-zookeeper-" + MesosCluster.getClusterId() + "-" + getRandomId()) .withExposedPorts(new ExposedPort(DEFAULT_ZOOKEEPER_PORT), new ExposedPort(2888), new ExposedPort(3888)); } public static String formatZKAddress(String ipAddress) { return "zk://" + ipAddress + ":" + DEFAULT_ZOOKEEPER_PORT; } }
package com.containersol.minimesos.mesos; import com.containersol.minimesos.MesosCluster; import com.containersol.minimesos.container.AbstractContainer; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.model.ExposedPort; /** * Base zookeeper class */ public class ZooKeeper extends AbstractContainer { public static final String MESOS_LOCAL_IMAGE = "jplock/zookeeper"; public static final String REGISTRY_TAG = "latest"; public static final int DEFAULT_ZOOKEEPER_PORT = 2181; protected ZooKeeper(DockerClient dockerClient) { super(dockerClient); } @Override protected void pullImage() { pullImage(MESOS_LOCAL_IMAGE, REGISTRY_TAG); } @Override protected CreateContainerCmd dockerCommand() { return dockerClient.createContainerCmd(MESOS_LOCAL_IMAGE + ":" + REGISTRY_TAG) .withName("minimesos-zookeeper-" + MesosCluster.getClusterId() + "-" + getRandomId()) .withExposedPorts(new ExposedPort(DEFAULT_ZOOKEEPER_PORT), new ExposedPort(2888), new ExposedPort(3888)); } public static String formatZKAddress(String ipAddress) { return "zk://" + ipAddress + ":" + DEFAULT_ZOOKEEPER_PORT; } }
Fix jumping on ref removing.
import { Component } from 'substance' /* Simplistic back-matter displaying references and appendixes */ export default class BackComponent extends Component { render($$) { const node = this.props.node let el = $$('div').addClass('sc-back') .attr('data-id', node.id) // NOTE: Bibliography depends on entityDb and referenceManager in the context. let refList = node.find('ref-list') if (refList) { el.append( $$(this.getComponent('ref-list'), { node: refList }).ref('ref-list') ) } let fnGroup = node.find('fn-group') if (fnGroup) { el.append( $$(this.getComponent('fn-group'), { node: fnGroup }) ) } return el } }
import { Component } from 'substance' /* Simplistic back-matter displaying references and appendixes */ export default class BackComponent extends Component { render($$) { const node = this.props.node let el = $$('div').addClass('sc-back') .attr('data-id', node.id) // NOTE: Bibliography depends on entityDb and referenceManager in the context. let refList = node.find('ref-list') if (refList) { el.append( $$(this.getComponent('ref-list'), { node: refList }) ) } let fnGroup = node.find('fn-group') if (fnGroup) { el.append( $$(this.getComponent('fn-group'), { node: fnGroup }) ) } return el } }
Reduce size of testings images by default to speed up tests
import StringIO import PIL import pytest from django.core.files.uploadedfile import InMemoryUploadedFile class Image: def __init__(self): self.dimensions = (10, 10) self.color = 'blue' self.name = 'image.jpg' @property def django_file(self): # Create a new Django file-like object to be used in models as ImageField using # InMemoryUploadedFile. If you look at the source in Django, a # SimpleUploadedFile is essentially instantiated similarly to what is shown here return InMemoryUploadedFile(self.image_file, None, self.name, 'image/jpeg', self.image_file.len, None) @property def image_file(self): # Create a file-like object to write thumb data (thumb data previously created # using PIL, and stored in variable 'thumb') image_io = StringIO.StringIO() self.pil_image.save(image_io, format='JPEG') image_io.seek(0) return image_io @property def pil_image(self): return PIL.Image.new('RGB', self.dimensions, self.color) @pytest.fixture() def image(): return Image()
import StringIO import PIL import pytest from django.core.files.uploadedfile import InMemoryUploadedFile class Image: def __init__(self): self.dimensions = (100, 100) self.color = 'blue' self.name = 'image.jpg' @property def django_file(self): # Create a new Django file-like object to be used in models as ImageField using # InMemoryUploadedFile. If you look at the source in Django, a # SimpleUploadedFile is essentially instantiated similarly to what is shown here return InMemoryUploadedFile(self.image_file, None, self.name, 'image/jpeg', self.image_file.len, None) @property def image_file(self): # Create a file-like object to write thumb data (thumb data previously created # using PIL, and stored in variable 'thumb') image_io = StringIO.StringIO() self.pil_image.save(image_io, format='JPEG') image_io.seek(0) return image_io @property def pil_image(self): return PIL.Image.new('RGB', self.dimensions, self.color) @pytest.fixture() def image(): return Image()
Add render template with js instructions
// http://mochajs.org/ // @see http://chaijs.com/api/bdd/ describe('View', function() { var App; var View; var testView; beforeEach(function() { App = window.App; View = App.View; }); afterEach(function() { testView = undefined; App = null; View = null; }); it('should set template', function() { testView = new View('<div><%= name %></div>'); expect(typeof testView.template).to.equal('function'); }); it('should render simple template', function() { testView = new View('<div><%= name %></div>'); var testData = { name: 'test' }; var result = testView.render(testData); var reference = '<div>test</div>'; expect(result).to.equal(reference); }); it('should set tempalte (with JS code) ', function () { testView = new View ('<div><% dataItems.forEach(function(item) { %> <%= item %> <% }); %> <div>'); var testData = {dataItems: [{ item: 'testItem0'}, { item: 'testItem1'}]}; var result = testView.render(testData); var reference = '<div>testItem0<div><div>testItem1<div>'; expect(result).to.equal(reference); }); });
// http://mochajs.org/ // @see http://chaijs.com/api/bdd/ describe('View', function() { var App; var View; var testView; beforeEach(function() { App = window.App; View = App.View; }); afterEach(function() { testView = undefined; App = null; View = null; }); it('should set template', function() { testView = new View('<div><%= name %></div>'); expect(typeof testView.template).to.equal('function'); }); it('should render simple template', function() { testView = new View('<div><%= name %></div>'); var testData = { name: 'test' }; var result = testView.render(testData); var reference = '<div>test</div>'; expect(result).to.equal(reference); }); });
Update test for actually checking existence of nodes before creating.
from nose.tools import eq_, ok_ from tornado.httpclient import HTTPRequest import json from astral.api.tests import BaseTest from astral.models.node import Node from astral.models.tests.factories import NodeFactory class NodesHandlerTest(BaseTest): def test_get_nodes(self): [NodeFactory() for _ in range(3)] response = self.fetch('/nodes') eq_(response.code, 200) result = json.loads(response.body) ok_('nodes' in result) for node in result['nodes']: ok_(Node.get_by(uuid=node['uuid'])) def test_register_node(self): data = {'uuid': "a-unique-id", 'port': 8001} eq_(Node.get_by(uuid=data['uuid']), None) self.http_client.fetch(HTTPRequest( self.get_url('/nodes'), 'POST', body=json.dumps(data)), self.stop) response = self.wait() eq_(response.code, 200) ok_(Node.get_by(uuid=data['uuid']))
from nose.tools import eq_, ok_ from tornado.httpclient import HTTPRequest import json from astral.api.tests import BaseTest from astral.models.node import Node from astral.models.tests.factories import NodeFactory class NodesHandlerTest(BaseTest): def test_get_nodes(self): [NodeFactory() for _ in range(3)] response = self.fetch('/nodes') eq_(response.code, 200) result = json.loads(response.body) ok_('nodes' in result) for node in result['nodes']: ok_(Node.get_by(uuid=node['uuid'])) def test_register_node(self): data = {'uuid': "a-unique-id", 'port': 8000} eq_(Node.get_by(uuid=data['uuid']), None) self.http_client.fetch(HTTPRequest( self.get_url('/nodes'), 'POST', body=json.dumps(data)), self.stop) response = self.wait() eq_(response.code, 200) ok_(Node.get_by(uuid=data['uuid']))
Clean up code a bit.
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name PlacedItem * * @class The PlacedItem class is the base for any items that have a matrix * associated with them, describing their placement in the project, such as * {@link Raster} and {@link PlacedSymbol}. * * @extends Item */ var PlacedItem = this.PlacedItem = Item.extend(/** @lends PlacedItem# */{ // PlacedItem uses strokeBounds for bounds _boundsGetter: { getBounds: 'getStrokeBounds' }, _hitTest: function(point, options, matrix) { var result = this._symbol._definition._hitTest(point, options, matrix); // TODO: When the symbol's definition is a path, should hitResult // contain information like HitResult#curve? if (result) result.item = this; return result; } });
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name PlacedItem * * @class The PlacedItem class is the base for any items that have a matrix * associated with them, describing their placement in the project, such as * {@link Raster} and {@link PlacedSymbol}. * * @extends Item */ var PlacedItem = this.PlacedItem = Item.extend(/** @lends PlacedItem# */{ // PlacedItem uses strokeBounds for bounds _boundsGetter: { getBounds: 'getStrokeBounds' }, _hitTest: function(point, options, matrix) { var hitResult = this._symbol._definition._hitTest(point, options, matrix); // TODO: When the symbol's definition is a path, should hitResult contain // information like HitResult#curve? if (hitResult) hitResult.item = this; return hitResult; } });
Fix test that missed a re-factor
package com.example; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @DirtiesContext // tag::wiremock_test[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockForDocsMockServerApplicationTests { @Autowired private RestTemplate restTemplate; @Autowired private Service service; @Test public void contextLoads() throws Exception { // will read stubs from default /resources/stubs location MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) .baseUrl("http://example.org").stubs("resource"); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } } // end::wiremock_test[]
package com.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.WireMockExpectations; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @DirtiesContext //tag::wiremock_test[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment=WebEnvironment.NONE) public class WiremockForDocsMockServerApplicationTests { @Autowired private RestTemplate restTemplate; @Autowired private Service service; @Test public void contextLoads() throws Exception { // will read stubs from default /resources/stubs location MockRestServiceServer server = WireMockExpectations.with(this.restTemplate) .baseUrl("http://example.org") .expect("resource"); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } } //end::wiremock_test[]
[fix] Make moment global for debugging.
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Config from "./config.js"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static get Config() { return Config; } static get DText() { return DText; } static get Tag() { return Tag; } static get UI() { return UI; } static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } static initialize() { EX.config = new Config(); EX.config.enableHeader && UI.Header.initialize(); EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } } window.EX = EX; window.moment = moment; jQuery(function () { try { EX.initialize(); } catch(e) { $("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`); throw e; } });
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Config from "./config.js"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static get Config() { return Config; } static get DText() { return DText; } static get Tag() { return Tag; } static get UI() { return UI; } static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } static initialize() { EX.config = new Config(); EX.config.enableHeader && UI.Header.initialize(); EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } } window.EX = EX; jQuery(function () { try { EX.initialize(); } catch(e) { $("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`); throw e; } });
Correct typo for view utilities
<?php /* |------------------------------------------------------ | Return the Closure to calculate the remaining tickets |------------------------------------------------------ */ return function(PDO $db_conn) { $totalTickets = require __DIR__.'/check_total_tickets.php'; try { $soldTickets = (int) $db_conn->query('SELECT SUM(quantity) FROM sold_tickets')->fetchColumn(); $db_conn->prepare('DELETE FROM ticket_purchase_sessions WHERE start_time < ?') ->execute([time() - config('app.booking_timeout')]); $stmt = $db_conn->prepare('SELECT SUM(quantity) FROM ticket_purchase_sessions WHERE session_id <> ?'); $stmt->execute([session_id()]); $heldTickets = (int) $stmt->fetchColumn(); } catch (PDOException $e) { die("Database Query Error: " . $e->getMessage()); } return $totalTickets - $soldTickets - $heldTickets; };
<?php /* |------------------------------------------------------ | Return the Closure to calculate the remaining tickets |------------------------------------------------------ */ return function(PDO $db_conn) { $totalTicekts = require __DIR__.'/check_total_tickets.php'; try { $soldTickets = (int) $db_conn->query('SELECT SUM(quantity) FROM sold_tickets')->fetchColumn(); $db_conn->prepare('DELETE FROM ticket_purchase_sessions WHERE start_time < ?') ->execute([time() - config('app.booking_timeout')]); $stmt = $db_conn->prepare('SELECT SUM(quantity) FROM ticket_purchase_sessions WHERE session_id <> ?'); $stmt->execute([session_id()]); $heldTickets = (int) $stmt->fetchColumn(); } catch (PDOException $e) { die("Database Query Error: " . $e->getMessage()); } return $totalTickets - $soldTickets - $heldTickets; };
Fix charset and lang for serving static page
<?php header("Content-Type: text/html; charset=UTF-8"); require("time.php"); ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title><?php echo $pageMeta["title"]?></title> <meta charset="utf-8"> <link rel="stylesheet" href="/wp-content/themes/quis/css/quis.css" type="text/css" /> <link rel="alternate" type="application/rss+xml" title="quis.cc RSS feed" href="/feed/" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui"> <meta name="description" content="<?php echo $pageMeta["description"]?>" /> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <header> <h1> <a title="Home page" href="/">quis.cc is Chris Hill-Scott's photo blog</a> </h1> </header> <div id="photos">
<?php header("Content-Type: text/html; charset=UTF-8"); require("time.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <title><?php echo $pageMeta["title"]?></title> <link rel="stylesheet" href="/wp-content/themes/quis/css/quis.css" type="text/css" /> <link rel="alternate" type="application/rss+xml" title="quis.cc RSS feed" href="/feed/" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui"> <meta name="description" content="<?php echo $pageMeta["description"]?>" /> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <header> <h1> <a title="Home page" href="/">quis.cc is Chris Hill-Scott's photo blog</a> </h1> </header> <div id="photos">
Allow dots in module names.
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView from cbv.views import KlassDetailView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name='base.html'), name='home'), url(r'^admin/', include(admin.site.urls)), url(r'class/(?P<package>[a-zA-Z_-]+)/(?P<version>[^/]+)/(?P<module>[\.A-Za-z_-]+)/(?P<klass>[A-Za-z_-]*)', KlassDetailView.as_view()), ) urlpatterns += staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView from cbv.views import KlassDetailView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name='base.html'), name='home'), url(r'^admin/', include(admin.site.urls)), url(r'class/(?P<package>[a-zA-Z_-]+)/(?P<version>[^/]+)/(?P<module>[A-Za-z_-]+)/(?P<klass>[A-Za-z_-]*)', KlassDetailView.as_view()), ) urlpatterns += staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Fix issue where the tabs object throws an error if no sub_tabs exist at all
<?php namespace Jadu\Pulsar\Twig\Extension; class TabsExtension extends \Twig_Extension { public function getName() { return 'tabs_extension'; } public function getFunctions() { return array( new \Twig_SimpleFunction('get_active_tab', array($this, 'getActiveParentTabID')) ); } public function getActiveParentTabID($tabs = null, $active_parent_tab_id = null) { if ($tabs === null) { return false; } // $tabs passed through Twig is an array rather than a json string if (is_array($tabs)) { $tabs = json_encode($tabs); } $ob = json_decode($tabs); // If we don't have valid json, abandon ship if ($ob === null) { return false; } // Loop through the tab items foreach ($ob as $item) { // If we have subnavigation if (isset($item->sub_tabs) && $item->sub_tabs != null) { // Loop through its sub tabs foreach($item->sub_tabs as $sub_tab) { if ($sub_tab->id === $active_parent_tab_id) { return $item->id; } } } } return false; } }
<?php namespace Jadu\Pulsar\Twig\Extension; class TabsExtension extends \Twig_Extension { public function getName() { return 'tabs_extension'; } public function getFunctions() { return array( new \Twig_SimpleFunction('get_active_tab', array($this, 'getActiveParentTabID')) ); } public function getActiveParentTabID($tabs = null, $active_parent_tab_id = null) { if ($tabs === null) { return false; } // $tabs passed through Twig is an array rather than a json string if (is_array($tabs)) { $tabs = json_encode($tabs); } $ob = json_decode($tabs); // If we don't have valid json, abandon ship if ($ob === null) { return false; } // Loop through the tab items foreach ($ob as $item) { // If we have subnavigation if ($item->sub_tabs != null) { // Loop through its sub tabs foreach($item->sub_tabs as $sub_tab) { if ($sub_tab->id === $active_parent_tab_id) { return $item->id; } } } } return false; } }
Switch default URL back to Jesse
'use strict'; const webpack = require('webpack'); const path = require('path'); var CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: [ 'webpack-dev-server/client?https://0.0.0.0:8080', './src/index.js' ], output: { path: path.resolve(__dirname, 'build'), filename: 'project.bundle.js' }, devtool: "source-map", devServer: { contentBase: './build', hot: true, host: process.env.IP, port: process.env.PORT, "public": "bestburger2-feine.c9users.io", // "public": "bestburger-phaser2-feyrkh.c9users.io", historyApiFallback: true }, plugins: [ // new CopyWebpackPlugin([ // {from: 'assets', to: 'build/assets/'} // ]) ] };
'use strict'; const webpack = require('webpack'); const path = require('path'); var CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: [ 'webpack-dev-server/client?https://0.0.0.0:8080', './src/index.js' ], output: { path: path.resolve(__dirname, 'build'), filename: 'project.bundle.js' }, devtool: "source-map", devServer: { contentBase: './build', hot: true, host: process.env.IP, port: process.env.PORT, // "public": "bestburger2-feine.c9users.io", "public": "bestburger-phaser2-feyrkh.c9users.io", historyApiFallback: true }, plugins: [ // new CopyWebpackPlugin([ // {from: 'assets', to: 'build/assets/'} // ]) ] };
Remove type hints, rename $config => $configs
<?php require __DIR__.'/../vendor/autoload.php'; class HelloController { public function worldAction($request) { return "Hallo welt, got swag yo!\n"; } } $container = Yolo\createContainer( [ 'debug' => true, ], [ new Yolo\DependencyInjection\MonologExtension(), new Yolo\DependencyInjection\ServiceControllerExtension(), new Yolo\DependencyInjection\CallableExtension( 'controller', function ($configs, $container) { $container->register('hello.controller', 'HelloController'); } ), ] ); $app = new Yolo\Application($container); $app->get('/', 'hello.controller:worldAction'); $app->run();
<?php require __DIR__.'/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\DependencyInjection\ContainerBuilder; class HelloController { public function worldAction(Request $request) { return new Response("Hallo welt, got swag yo!\n"); } } $container = Yolo\createContainer( [ 'debug' => true, ], [ new Yolo\DependencyInjection\MonologExtension(), new Yolo\DependencyInjection\ServiceControllerExtension(), new Yolo\DependencyInjection\CallableExtension( 'controller', function (array $config, ContainerBuilder $container) { $container->register('hello.controller', 'HelloController'); } ), ] ); $app = new Yolo\Application($container); $app->get('/', 'hello.controller:worldAction'); $app->run();
Contacts: Add id to vars with id in them
<?php /** * Copyright (c) 2011-2012 Thomas Tanghus <thomas@tanghus.net> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ require_once ("../../lib/base.php"); OC_Util::checkLoggedIn(); OC_Util::checkAppEnabled('contacts'); $bookid = isset($_GET['bookid']) ? $_GET['bookid'] : NULL; $contactid = isset($_GET['contactid']) ? $_GET['contactid'] : NULL; $nl = "\n"; if(isset($bookid)){ $addressbook = OC_Contacts_App::getAddressbook($bookid); $cardobjects = OC_Contacts_VCard::all($bookid); header('Content-Type: text/directory'); header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $addressbook['displayname']) . '.vcf'); foreach($cardobjects as $card) { echo $card['carddata'] . $nl; } }elseif(isset($contactid)){ $data = OC_Contacts_App::getContactObject($contactid); header('Content-Type: text/directory'); header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $data['fullname']) . '.vcf'); echo $data['carddata']; } ?>
<?php /** * Copyright (c) 2011-2012 Thomas Tanghus <thomas@tanghus.net> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ require_once ("../../lib/base.php"); OC_Util::checkLoggedIn(); OC_Util::checkAppEnabled('contacts'); $book = isset($_GET['bookid']) ? $_GET['bookid'] : NULL; $contact = isset($_GET['contactid']) ? $_GET['contactid'] : NULL; $nl = "\n"; if(isset($book)){ $addressbook = OC_Contacts_App::getAddressbook($book); $cardobjects = OC_Contacts_VCard::all($book); header('Content-Type: text/directory'); header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $addressbook['displayname']) . '.vcf'); foreach($cardobjects as $card) { echo $card['carddata'] . $nl; } }elseif(isset($contact)){ $data = OC_Contacts_App::getContactObject($contact); header('Content-Type: text/directory'); header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $data['fullname']) . '.vcf'); echo $data['carddata']; } ?>