text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
test: Use fixture name to name test
<?php namespace nochso\Phormat\Test; /** * FixtureIterator provides test data from files. * * For files named `*.in.php` will try to use a matching `*.out.php` file for expected output. * If not output file is found, the input is re-used for expected output. */ class FixtureIterator implements \Iterator{ /** * @var string[] */ private $files; /** * @param string $pattern glob() style pattern of input files. */ public function __construct($pattern) { $this->files = glob($pattern); } public function rewind() { return reset($this->files); } public function current() { $inputFile = current($this->files); return $this->readFixture($inputFile); } public function key() { return basename(current($this->files)); } public function next() { return next($this->files); } public function valid() { return key($this->files) !== null; } private function readFixture($inputFile) { $outputFile = str_replace('.in.php', '.out.php', $inputFile); $input = file_get_contents($inputFile); if (!is_file($outputFile)) { $output = $input; } else { $output = file_get_contents($outputFile); } return [$output, $input]; } }
<?php namespace nochso\Phormat\Test; /** * FixtureIterator provides test data from files. * * For files named `*.in.php` will try to use a matching `*.out.php` file for expected output. * If not output file is found, the input is re-used for expected output. */ class FixtureIterator implements \Iterator{ /** * @var string[] */ private $files; /** * @param string $pattern glob() style pattern of input files. */ public function __construct($pattern) { $this->files = glob($pattern); } public function rewind() { return reset($this->files); } public function current() { $inputFile = current($this->files); return $this->readFixture($inputFile); } public function key() { return key($this->files); } public function next() { return next($this->files); } public function valid() { return key($this->files) !== null; } private function readFixture($inputFile) { $outputFile = str_replace('.in.php', '.out.php', $inputFile); $input = file_get_contents($inputFile); if (!is_file($outputFile)) { $output = $input; } else { $output = file_get_contents($outputFile); } return [$output, $input]; } }
Update PyDelphin interface to recent version
from delphin.interfaces import ace from delphin.mrs import simplemrs, dmrx from pydmrs.core import ListDmrs from pydmrs.utils import load_config, get_config_option DEFAULT_CONFIG_FILE = 'default_interface.conf' config = load_config(DEFAULT_CONFIG_FILE) DEFAULT_ERG_FILE = get_config_option(config, 'Grammar', 'ERG') def parse(sentence, cls=ListDmrs, erg_file=DEFAULT_ERG_FILE): results = [] for result in ace.parse(erg_file, sentence).results(): # cmdargs=['-r', 'root_informal'] xmrs = result.mrs() dmrs_xml = dmrx.dumps_one(xmrs)[11:-12] dmrs = cls.loads_xml(dmrs_xml) results.append(dmrs) return results def generate(dmrs, erg_file=DEFAULT_ERG_FILE): dmrs_xml = '<dmrs-list>' + dmrs.dumps_xml(encoding='utf-8') + '</dmrs-list>' xmrs = dmrx.loads_one(dmrs_xml) mrs = simplemrs.dumps_one(xmrs) results = [] for result in ace.generate(erg_file, mrs).results(): sentence = result['surface'] results.append(sentence) return results
from delphin.interfaces import ace from delphin.mrs import simplemrs, dmrx from pydmrs.core import ListDmrs from pydmrs.utils import load_config, get_config_option DEFAULT_CONFIG_FILE = 'default_interface.conf' config = load_config(DEFAULT_CONFIG_FILE) DEFAULT_ERG_FILE = get_config_option(config, 'Grammar', 'ERG') def parse(sentence, cls=ListDmrs, erg_file=DEFAULT_ERG_FILE): results = [] for result in ace.parse(erg_file, sentence)['RESULTS']: # cmdargs=['-r', 'root_informal'] mrs = result['MRS'] xmrs = simplemrs.loads_one(mrs) dmrs_xml = dmrx.dumps_one(xmrs)[11:-12] dmrs = cls.loads_xml(dmrs_xml) results.append(dmrs) return results def generate(dmrs, erg_file=DEFAULT_ERG_FILE): dmrs_xml = '<dmrs-list>' + dmrs.dumps_xml(encoding='utf-8') + '</dmrs-list>' xmrs = dmrx.loads_one(dmrs_xml) mrs = simplemrs.dumps_one(xmrs) results = [] for result in ace.generate(erg_file, mrs)['RESULTS']: sentence = result['SENT'] results.append(sentence) return results
Update: Create worker methods at prototype level This approach is slightly faster since the code is executed only once. Rather constructor code is executed every time a new instance is created. Serious advantage of prototype over constructor is that the former is compatible with class inheritance.
export default class Worker { constructor() { // EventTarget var delegate = document.createDocumentFragment(); [ 'addEventListener', 'dispatchEvent', 'removeEventListener' ].forEach(f => /*this[f]*/ Worker.prototype[f] = (...xs) => delegate[f](...xs)) } postMessage(aMessage, transferList) { let e = new class extends CustomEvent { constructor() { super('message', { bubbles: false, cancelable: true }) } get data() { return aMessage } get ports() { let ret = [] (transferList || []).forEach(transfer => { if (transfer instanceof MessagePort) { ret.push(transfer) } }) return ret.length > 0 ? ret : null } }; if (this.onmessage) { this.onmessage(e); } this.dispatchEvent(e); } }
export default class Worker { constructor() { // EventTarget var delegate = document.createDocumentFragment(); [ 'addEventListener', 'dispatchEvent', 'removeEventListener' ].forEach(f => this[f] = (...xs) => delegate[f](...xs) ) } postMessage(aMessage, transferList) { let e = new class extends CustomEvent { constructor() { super('message', {bubbles: false, cancelable: true}) } get data() { return aMessage } get ports() { let ret = [] (transferList || []).forEach(function(transfer) { if (transfer instanceof MessagePort) { ret.push(transfer) } }) return ret.length > 0 ? ret : null } }; if (this.onmessage) { this.onmessage(e); } this.dispatchEvent(e); } }
Save app preset in config
'use strict'; var BaseGenerator = require('yeoman-generator').Base; module.exports = BaseGenerator.extend({ constructor: function () { BaseGenerator.apply(this, arguments); this.option('preset', {desc: 'App preset: dust | example | handlebars | jade', alias: 'p', defaults: 'handlebars'}); this.argument('appName', {desc: 'App name', required: false, defaults: this.appname}); }, writing: function () { var appName = this.appName, preset = this.options.preset; this.log('App name = ' + appName); this.config.set('preset', preset); this.fs.copy( this.templatePath(preset + '/**/*'), this.destinationRoot() ); this.fs.extendJSON(this.destinationPath('package.json'), {name: appName}); }, install: function () { this.installDependencies(); } });
'use strict'; var BaseGenerator = require('yeoman-generator').Base; module.exports = BaseGenerator.extend({ constructor: function () { BaseGenerator.apply(this, arguments); this.option('preset', {desc: 'App preset: dust | example | handlebars | jade', alias: 'p', defaults: 'handlebars'}); this.argument('appName', {desc: 'App name', required: false, defaults: this.appname}); }, writing: function () { this.log('App name = ' + this.appName); this.fs.copy( this.templatePath(this.options.preset + '/**/*'), this.destinationRoot() ); this.fs.extendJSON(this.destinationPath('package.json'), {name: this.appName}); }, install: function () { this.installDependencies(); } });
Change 500 Internal Server Error to 400 Bad Request
package main import ( "io/ioutil" "strconv" "github.com/gin-gonic/gin" "github.com/mdeheij/gitlegram/gitlab" log "github.com/mdeheij/logwrap" ) func main() { c := NewConfig() //gin.SetMode(gin.ReleaseMode) r := gin.Default() r.POST("/", func(c *gin.Context) { body, ioerr := ioutil.ReadAll(c.Request.Body) if ioerr != nil { c.String(400, "Could not read request body") log.Critical(ioerr) return } //TODO: Request can be ambiguous request, err := gitlab.Parse(string(body)) if err != nil { c.String(400, "Could not parse request body") log.Critical(err) return } c.JSON(200, getMessage(request)) }) address := c.Address + ":" + strconv.FormatInt(c.Port, 10) r.Run(address) }
package main import ( "io/ioutil" "strconv" "github.com/gin-gonic/gin" "github.com/mdeheij/gitlegram/gitlab" log "github.com/mdeheij/logwrap" ) func main() { c := NewConfig() //gin.SetMode(gin.ReleaseMode) r := gin.Default() r.POST("/", func(c *gin.Context) { body, ioerr := ioutil.ReadAll(c.Request.Body) if ioerr != nil { c.String(500, "Could not read request body") log.Critical(ioerr) return } //TODO: Request can be ambiguous request, err := gitlab.Parse(string(body)) if err != nil { c.String(500, "Could not parse request body") log.Critical(err) return } c.JSON(200, getMessage(request)) }) address := c.Address + ":" + strconv.FormatInt(c.Port, 10) r.Run(address) }
Add wait time to ebay pageset Bug: skia:11898 Change-Id: I0bb58f1d8e9c6ad48148d50b840f152fc158f071 Reviewed-on: https://skia-review.googlesource.com/c/skia/+/400538 Reviewed-by: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_ebay_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url, timeout_in_seconds=120) class SkiaEbayDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaEbayDesktopPageSet, self).__init__( archive_data_file='data/skia_ebay_desktop.json') urls_list = [ # go/skia-skps-3-2019 'http://www.ebay.com', ] for url in urls_list: self.AddStory(SkiaDesktopPage(url, self))
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_ebay_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(15) class SkiaEbayDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaEbayDesktopPageSet, self).__init__( archive_data_file='data/skia_ebay_desktop.json') urls_list = [ # go/skia-skps-3-2019 'http://www.ebay.com', ] for url in urls_list: self.AddStory(SkiaDesktopPage(url, self))
Add temporary accessor to make the helloworld application work again with @Visible This accessor will be removed when MVEL processing of @Visible will be fixed.
package info.sitebricks.example.web; import com.google.sitebricks.At; import com.google.sitebricks.Visible; import com.google.sitebricks.http.Get; /** * The home page that our users will see at the top level URI "/". * <p> * This page is created once per request and has "no scope" in Guice * terminology. See the <a href="http://code.google.com/p/google-guice">Guice wiki</a> * for details. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ @At("/") public class HomePage { @Visible String message; @Get void showHome() { // This is where you would normally fetch stuff from a database, for example. message = "Hello from Sitebricks!"; } /** * TODO This getter should be removed when @Visible annotation processing by mvel will be fixed. */ public String getMessage() { return message; } public boolean getShouldShow() { // Always show our message. return true; } }
package info.sitebricks.example.web; import com.google.sitebricks.At; import com.google.sitebricks.Visible; import com.google.sitebricks.http.Get; /** * The home page that our users will see at the top level URI "/". * <p> * This page is created once per request and has "no scope" in Guice * terminology. See the <a href="http://code.google.com/p/google-guice">Guice wiki</a> * for details. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ @At("/") public class HomePage { @Visible String message; @Get void showHome() { // This is where you would normally fetch stuff from a database, for example. message = "Hello from Sitebricks!"; } public boolean getShouldShow() { // Always show our message. return true; } }
Fix FCM URL for stage
/** * @description * This module sets all configuration * * policyCompassConfig is exposed as a global variable in order to use it in * the main app.js file. If there's a way to do the same with dependency * injection, this should be fixed. */ // Configuration for remote services var policyCompassConfig = { 'URL': '/api/v1', 'METRICS_MANAGER_URL': 'https://services-stage.policycompass.eu/api/v1/metricsmanager', 'VISUALIZATIONS_MANAGER_URL': 'https://services-stage.policycompass.eu/api/v1/visualizationsmanager', 'EVENTS_MANAGER_URL': 'https://services-stage.policycompass.eu/api/v1/eventsmanager', 'REFERENCE_POOL_URL': 'https://services-stage.policycompass.eu/api/v1/references', 'FCM_URL': 'https://fcm-stage.policycompass.eu/api/v1/fcmmanager', 'ELASTIC_URL' : 'https://search-stage.policycompass.eu/', 'ELASTIC_INDEX_NAME' : 'policycompass_search', 'ENABLE_ADHOCRACY': true, 'ADHOCRACY_BACKEND_URL': 'https://adhocracy-frontend-stage.policycompass.eu/api', 'ADHOCRACY_FRONTEND_URL': 'https://adhocracy-frontend-stage.policycompass.eu' }; angular.module('pcApp.config', []).constant('API_CONF', policyCompassConfig);
/** * @description * This module sets all configuration * * policyCompassConfig is exposed as a global variable in order to use it in * the main app.js file. If there's a way to do the same with dependency * injection, this should be fixed. */ // Configuration for remote services var policyCompassConfig = { 'URL': '/api/v1', 'METRICS_MANAGER_URL': 'https://services-stage.policycompass.eu/api/v1/metricsmanager', 'VISUALIZATIONS_MANAGER_URL': 'https://services-stage.policycompass.eu/api/v1/visualizationsmanager', 'EVENTS_MANAGER_URL': 'https://services-stage.policycompass.eu/api/v1/eventsmanager', 'REFERENCE_POOL_URL': 'https://services-stage.policycompass.eu/api/v1/references', 'FCM_URL': 'https://alpha.policycompass.eu/api/v1/fcmmanager', 'ELASTIC_URL' : 'https://search-stage.policycompass.eu/', 'ELASTIC_INDEX_NAME' : 'policycompass_search', 'ENABLE_ADHOCRACY': true, 'ADHOCRACY_BACKEND_URL': 'https://adhocracy-frontend-stage.policycompass.eu/api', 'ADHOCRACY_FRONTEND_URL': 'https://adhocracy-frontend-stage.policycompass.eu' }; angular.module('pcApp.config', []).constant('API_CONF', policyCompassConfig);
Work around `AttributeError: 'module' object has no attribute 'BufferedIOBase'` on Python 2.7+, Windows
"""Image Processing SciKit (Toolbox for SciPy)""" import os.path as _osp data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data')) from version import version as __version__ def _setup_test(): import gzip import functools basedir = _osp.dirname(_osp.join(__file__, '../')) args = ['', '--exe', '-w', '%s' % basedir] try: import nose as _nose except ImportError: print("Could not load nose. Unit tests not available.") return None else: return functools.partial(_nose.run, 'scikits.image', argv=args) test = _setup_test() if test is None: del test def get_log(name): """Return a console logger. Output may be sent to the logger using the `debug`, `info`, `warning`, `error` and `critical` methods. Parameters ---------- name : str Name of the log. References ---------- .. [1] Logging facility for Python, http://docs.python.org/library/logging.html """ import logging, sys logging.basicConfig(stream=sys.stdout, level=logging.WARNING) return logging.getLogger(name) from util.dtype import *
"""Image Processing SciKit (Toolbox for SciPy)""" import os.path as _osp data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data')) from version import version as __version__ def _setup_test(): import functools basedir = _osp.dirname(_osp.join(__file__, '../')) args = ['', '--exe', '-w', '%s' % basedir] try: import nose as _nose except ImportError: print("Could not load nose. Unit tests not available.") return None else: return functools.partial(_nose.run, 'scikits.image', argv=args) test = _setup_test() if test is None: del test def get_log(name): """Return a console logger. Output may be sent to the logger using the `debug`, `info`, `warning`, `error` and `critical` methods. Parameters ---------- name : str Name of the log. References ---------- .. [1] Logging facility for Python, http://docs.python.org/library/logging.html """ import logging, sys logging.basicConfig(stream=sys.stdout, level=logging.WARNING) return logging.getLogger(name) from util.dtype import *
Allow override of backend urls from env variables
from flask import Flask from flask import redirect from flask import url_for from kqueen_ui.blueprints.ui.views import ui from werkzeug.contrib.cache import SimpleCache import logging import os logger = logging.getLogger(__name__) cache = SimpleCache() config_file = os.environ.get('KQUEEN_CONFIG_FILE', 'config/dev.py') def create_app(config_file=config_file): app = Flask(__name__, static_folder='./asset/static') app.register_blueprint(ui, url_prefix='/ui') # load configuration if app.config.from_pyfile(config_file): logger.info('Loading configuration from {}'.format(config_file)) else: raise Exception('Config file {} could not be loaded.'.format(config_file)) # allow override of backend urls from env variables kqueen_api_url = os.getenv('KQUEEN_API_URL', app.config['KQUEEN_API_URL']) kqueen_auth_url = os.getenv('KQUEEN_AUTH_URL', app.config['KQUEEN_AUTH_URL']) app.config.update( KQUEEN_API_URL=kqueen_api_url, KQUEEN_AUTH_URL=kqueen_auth_url ) return app app = create_app() app.logger.setLevel(logging.INFO) @app.route('/') def root(): return redirect(url_for('ui.index'), code=302) def run(): logger.debug('kqueen_ui starting') app.run(port=8000)
from flask import Flask from flask import redirect from flask import url_for from kqueen_ui.blueprints.ui.views import ui from werkzeug.contrib.cache import SimpleCache import logging import os logger = logging.getLogger(__name__) cache = SimpleCache() config_file = os.environ.get('KQUEEN_CONFIG_FILE', 'config/dev.py') def create_app(config_file=config_file): app = Flask(__name__, static_folder='./asset/static') app.register_blueprint(ui, url_prefix='/ui') # load configuration if app.config.from_pyfile(config_file): logger.info('Loading configuration from {}'.format(config_file)) else: raise Exception('Config file {} could not be loaded.'.format(config_file)) return app app = create_app() app.logger.setLevel(logging.INFO) @app.route('/') def root(): return redirect(url_for('ui.index'), code=302) def run(): logger.debug('kqueen_ui starting') app.run(port=8000)
Make stable builder pull from 1.10 R=kasperl@google.com BUG= Review URL: https://codereview.chromium.org/1107673002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@294974 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.10', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.9', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Rename the used variable everywhere, and not just in its definition...
define(['jquery'], function ($) { var colors = { log: '#000000', warn: '#cc9900', error: '#cc0000' }; var log = $('#log'); if (!console) { console = {}; } for (var name in colors) { console[name] = (function (original, color) { return function () { original.apply(console, arguments); var line = $('<div>'); log.append(line); for (var i = 0; i < arguments.length; i++) { var section = $('<span>'); section.text(arguments[i]); line.append(section); line.css('color', color); } }; })(console[name] || function() {}, colors[name]); } return console; });
define(['jquery'], function ($) { var colors = { log: '#000000', warn: '#cc9900', error: '#cc0000' }; var log = $('#log'); if (!console) { console = {}; } for (var name in colors) { console[name] = (function (original, color) { return function () { func.apply(console, arguments); var line = $('<div>'); log.append(line); for (var i = 0; i < arguments.length; i++) { var section = $('<span>'); section.text(arguments[i]); line.append(section); line.css('color', color); } }; })(console[name] || function() {}, colors[name]); } return console; });
Include license file in resulting tar.gz I am going to package this module for Fedora. And it is better for Fedora if tar.gz file contains the file with the license (it is better for auditing). Can you please include it with next version?
from setuptools import setup setup( name="ordered-set", version = '1.3.1', maintainer='Luminoso Technologies, Inc.', maintainer_email='rob@luminoso.com', license = "MIT-LICENSE", url = 'http://github.com/LuminosoInsight/ordered-set', platforms = ["any"], description = "A MutableSet that remembers its order, so that every entry has an index.", py_modules=['ordered_set'], package_data={'': ['MIT-LICENSE']}, include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
from setuptools import setup setup( name="ordered-set", version = '1.3.1', maintainer='Luminoso Technologies, Inc.', maintainer_email='rob@luminoso.com', license = "MIT-LICENSE", url = 'http://github.com/LuminosoInsight/ordered-set', platforms = ["any"], description = "A MutableSet that remembers its order, so that every entry has an index.", py_modules=['ordered_set'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
Address when args passed to cli are in quotes puts entire string as first element in []string, so must grab this element and split it on spaces
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" ) const aURL = "http://artii.herokuapp.com" func main() { args := os.Args[1:] if len(args) == 0 { fmt.Printf("Usage:\n") return } switch args[0] { case "fonts": fmt.Printf("%v", fontList()) return } fmt.Println(draw(args)) } func fontList() string { url := aURL + "/fonts_list" resp, err := http.Get(url) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } s := string(body) + "\n" return s } func draw(s []string) string { f := strings.Split(s[0], " ") js := strings.Join(f, "+") url := fmt.Sprintf("%s/make?text=%s", aURL, js) resp, err := http.Get(url) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } a := string(body) return a }
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" ) const aURL = "http://artii.herokuapp.com" func main() { args := os.Args[1:] if len(args) == 0 { fmt.Printf("Usage:\n") return } switch args[0] { case "fonts": fmt.Printf("%v", fontList()) } fmt.Println(draw(args[0])) } func fontList() string { url := aURL + "/fonts_list" resp, err := http.Get(url) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } s := string(body) + "\n" return s } func draw(s string) string { url := fmt.Sprintf("%s/make?text=%s", aURL, s) resp, err := http.Get(url) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } a := string(body) return a }
Add newline to format imports properly.
import os from distutils.core import setup from shortwave import VERSION def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-shortwave', version=VERSION, description='Shortwave command file management for Django apps.', url='https://github.com/benspaulding/django-shortwave/', author='Ben Spaulding', author_email='ben@benspaulding.us', license='BSD', download_url='https://github.com/benspaulding/django-shortwave/tarball/v%s' % VERSION, long_description = read('README.rst'), packages = [ 'shortwave', 'shortwave.tests' ], package_data = { 'shortwave': [ 'fixtures/*', 'locale/*/LC_MESSAGES/*', 'templates/shortwave/*', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], )
import os from distutils.core import setup from shortwave import VERSION def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-shortwave', version=VERSION, description='Shortwave command file management for Django apps.', url='https://github.com/benspaulding/django-shortwave/', author='Ben Spaulding', author_email='ben@benspaulding.us', license='BSD', download_url='https://github.com/benspaulding/django-shortwave/tarball/v%s' % VERSION, long_description = read('README.rst'), packages = [ 'shortwave', 'shortwave.tests' ], package_data = { 'shortwave': [ 'fixtures/*', 'locale/*/LC_MESSAGES/*', 'templates/shortwave/*', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], )
Add on.('close') to clear node status on Deploy
module.exports = function (RED) { var alasql = require('alasql'); function AlasqlNodeIn(config) { RED.nodes.createNode(this, config); var node = this; node.query = config.query; node.on("input", function (msg) { var sql = this.query || 'SELECT * FROM ?'; var bind = Array.isArray(msg.payload) ? msg.payload : [msg.payload]; alasql.promise(sql, [bind]) .then(function (res) { msg.payload = res; node.status({fill: "green", shape: "dot", text: ' Records: ' + msg.payload.length}); node.send(msg); }).catch((err) => { node.error(err, msg); }); }); this.on('close', () => { node.status({}); }); } RED.nodes.registerType("alasql", AlasqlNodeIn); };
module.exports = function (RED) { var alasql = require('alasql'); function AlasqlNodeIn(config) { RED.nodes.createNode(this, config); var node = this; node.query = config.query; node.on("input", function (msg) { var sql = this.query || 'SELECT * FROM ?'; var bind = Array.isArray(msg.payload) ? msg.payload : [msg.payload]; alasql.promise(sql, [bind]) .then(function (res) { msg.payload = res; node.status({fill: "green", shape: "dot", text: ' Records: ' + msg.payload.length}); node.send(msg); }).catch((err) => { node.error(err, msg); }); }); } RED.nodes.registerType("alasql", AlasqlNodeIn); }
Add params to topic partial
package net.ontopia.presto.jaxb; import java.util.Collection; import java.util.Map; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @XmlRootElement @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class TopicPartial { private String format = "topic-partial"; private Map<String, Object> params; private Collection<TopicView> views; public Collection<TopicView> getViews() { return views; } public void setViews(Collection<TopicView> views) { this.views = views; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public Map<String, Object> getParams() { return params; } public void setParams(Map<String, Object> params) { this.params = params; } }
package net.ontopia.presto.jaxb; import java.util.Collection; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @XmlRootElement @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class TopicPartial { private String format = "topic-partial"; private Collection<TopicView> views; public Collection<TopicView> getViews() { return views; } public void setViews(Collection<TopicView> views) { this.views = views; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } }
Add win32 to platform information
""" Return information about the given platform. """ import sys class Platform(object): @staticmethod def is_darwin(name=None): name = name or sys.platform return 'darwin' in name @staticmethod def is_freebsd(name=None): name = name or sys.platform return name.startswith("freebsd") @staticmethod def is_linux(name=None): name = name or sys.platform return 'linux' in name @staticmethod def is_bsd(name=None): """ Return true if this is a BSD like operating system. """ name = name or sys.platform return Platform.is_darwin(name) or Platform.is_freebsd(name) @staticmethod def is_solaris(name=None): name = name or sys.platform return name == "sunos5" @staticmethod def is_unix(name=None): """ Return true if the platform is a unix, False otherwise. """ name = name or sys.platform return (Platform.is_darwin() or Platform.is_linux() or Platform.is_freebsd() ) @staticmethod def is_win32(name=None): name = name or sys.platform return name == "win32"
""" Return information about the given platform. """ import sys class Platform(object): @staticmethod def is_darwin(name=None): name = name or sys.platform return 'darwin' in name @staticmethod def is_freebsd(name=None): name = name or sys.platform return name.startswith("freebsd") @staticmethod def is_linux(name=None): name = name or sys.platform return 'linux' in name @staticmethod def is_bsd(name=None): """ Return true if this is a BSD like operating system. """ name = name or sys.platform return Platform.is_darwin(name) or Platform.is_freebsd(name) @staticmethod def is_solaris(name=None): name = name or sys.platform return name == "sunos5" @staticmethod def is_unix(name=None): """ Return true if the platform is a unix, False otherwise. """ name = name or sys.platform return (Platform.is_darwin() or Platform.is_linux() or Platform.is_freebsd() )
Fix default log level in logging
const winston = require('winston'); module.exports = ({ filename, level, transports: transports = [{ type: 'Console', options: { level: 'debug' } }], }) => { if (filename) { transports.push({ type: 'File', options: { filename, level: 'debug' }, }); } if (level) { for (const transport of transports) { transport.options = transport.options || {}; transport.options.level = level; } } return (category, options) => { const logger = new winston.Logger(options); for (const transport of transports) { logger.add( winston.transports[transport.type], Object.assign({}, transport.options, { label: category }) ); } return logger; }; };
const winston = require('winston'); module.exports = ({ filename, level, transports: transports = [{ level: 'debug', type: 'Console' }], }) => { if (filename) { transports.push({ type: 'File', options: { filename, level: 'debug' }, }); } if (level) { for (const transport of transports) { transport.options = transport.options || {}; transport.options.level = level; } } return (category, options) => { const logger = new winston.Logger(options); for (const transport of transports) { logger.add( winston.transports[transport.type], Object.assign({}, transport.options, { label: category }) ); } return logger; }; };
Fix display of coverage report
var gulp = require('gulp'); var plugins = require('gulp-load-plugins')(); var runSequence = require('run-sequence'); gulp.task('test', function(done) { return runSequence('test-unit', 'test-coverage', 'test-complexity', done); }); gulp.task('test-complexity', function() { return gulp.src(['lib/**/*.js']) .pipe(plugins.complexity({ halstead: [15, 15, 20] })); }); gulp.task('test-unit', function() { return gulp.src(['test/**/*.js', '!test/fixture/*.js']) .pipe(plugins.mocha()); }); gulp.task('test-cover', function() { return gulp.src(['lib/**/*.js']) .pipe(plugins.istanbul()) .pipe(plugins.istanbul.hookRequire()); }); gulp.task('test-coverage', ['test-cover'], function() { return gulp.src(['test/**/*.js', '!test/fixture/*.js']) .pipe(plugins.mocha()) .pipe(plugins.istanbul.writeReports()); });
var gulp = require('gulp'); var plugins = require('gulp-load-plugins')(); var runSequence = require('run-sequence'); gulp.task('test', function(done) { return runSequence('test-unit', 'test-complexity', 'test-coverage', done); }); gulp.task('test-complexity', function() { return gulp.src(['lib/**/*.js']) .pipe(plugins.complexity({ halstead: [15, 15, 20] })); }); gulp.task('test-unit', function() { return gulp.src(['test/**/*.js', '!test/fixture/*.js']) .pipe(plugins.mocha()); }); gulp.task('test-cover', function() { return gulp.src(['lib/**/*.js']) .pipe(plugins.istanbul()) .pipe(plugins.istanbul.hookRequire()); }); gulp.task('test-coverage', ['test-cover'], function() { return gulp.src(['test/**/*.js', '!test/fixture/*.js']) .pipe(plugins.mocha()) .pipe(plugins.istanbul.writeReports()); });
Remove "validation" from RejectionException docstring
#!/usr/bin/env python3 """Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton.""" pass
#!/usr/bin/env python3 """Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton after validation.""" pass
Throw Error instead of string
import VulcanEmail from 'meteor/vulcan:email'; import Handlebars from 'handlebars'; import moment from 'moment'; const postsQuery = ` query PostsSingleQuery($documentId: String){ PostsSingle(documentId: $documentId){ title url pageUrl linkUrl postedAt htmlBody thumbnailUrl user{ pageUrl displayName } } } `; VulcanEmail.addEmails({ newPost: { template: "newPost", path: "/email/new-post/:documentId", subject(data) { if(!data || !data.PostsSingle) throw new Error("Missing post when rendering newPost email"); const post = data.PostsSingle; return post.title; }, query: postsQuery } }) Handlebars.registerHelper('formatPostDate', function(date) { return moment(new Date(date)).format("MMM D, YYYY"); }); VulcanEmail.addTemplates({ wrapper: Assets.getText("server/emails/templates/wrapper.handlebars"), newPost: Assets.getText("server/emails/templates/newPost.handlebars"), });
import VulcanEmail from 'meteor/vulcan:email'; import Handlebars from 'handlebars'; import moment from 'moment'; const postsQuery = ` query PostsSingleQuery($documentId: String){ PostsSingle(documentId: $documentId){ title url pageUrl linkUrl postedAt htmlBody thumbnailUrl user{ pageUrl displayName } } } `; VulcanEmail.addEmails({ newPost: { template: "newPost", path: "/email/new-post/:documentId", subject(data) { if(!data || !data.PostsSingle) throw "Missing post when rendering newPost email"; const post = data.PostsSingle; return post.title; }, query: postsQuery } }) Handlebars.registerHelper('formatPostDate', function(date) { return moment(new Date(date)).format("MMM D, YYYY"); }); VulcanEmail.addTemplates({ wrapper: Assets.getText("server/emails/templates/wrapper.handlebars"), newPost: Assets.getText("server/emails/templates/newPost.handlebars"), });
jQuery: Fix code style, remove JSHint comment.
/** * <%= name %> * * Makes bla bla. * * @version 0.0.0 * @requires jQuery * @author <%= authorName %> * @copyright <%= (new Date).getFullYear() %> <%= authorName %>, <%= authorUrl %> * @license MIT */ /*global define:false*/ ;(function(factory) { // Try to register as an anonymous AMD module if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(jQuery); } }(function($) { 'use strict'; $.fn.<%= method %> = function(options) { options = $.extend({}, $.fn.<%= method %>.defaults, options); return this.each(function() { // var elem = $(this); new <%= cls %>($(this), options); }); }; $.fn.<%= method %>.defaults = { }; function <%= cls %>(container, options) { this.container = container; this.options = options; this.init(); } <%= cls %>.prototype = { init: function() { /* Magic begins here */ } }; }));
/** * <%= name %> * * Makes bla bla. * * @version 0.0.0 * @requires jQuery * @author <%= authorName %> * @copyright <%= (new Date).getFullYear() %> <%= authorName %>, <%= authorUrl %> * @license MIT */ /*jshint browser:true, jquery:true, white:false, smarttabs:true, eqeqeq:true, immed:true, latedef:false, newcap:true, undef:true */ /*global define:false*/ ;(function(factory) { // Try to register as an anonymous AMD module if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(jQuery); } }(function($) { 'use strict'; $.fn.<%= method %> = function(options) { options = $.extend({}, $.fn.<%= method %>.defaults, options); return this.each(function() { // var elem = $(this); new <%= cls %>($(this), options); }); }; $.fn.<%= method %>.defaults = { }; function <%= cls %>(container, options) { this.container = container; this.options = options; this.init(); } <%= cls %>.prototype = { init: function() { /* Magic begins here */ } }; }));
Update example for update to isSameDay()
import React from "react"; import DayPicker from "react-day-picker"; import { dateUtils } from "react-day-picker/utils"; import "react-day-picker/lib/style.css"; export default class SelectableDay extends React.Component { state = { selectedDay: null } handleDayClick(e, day, modifiers) { if (modifiers.indexOf("selected") > -1) { this.setState({ selectedDay: null }) } else { this.setState({ selectedDay: day }); } } render() { const { selectedDay } = this.state; // Add the `selected` modifier to the cell of the clicked day const modifiers = { selected: day => dateUtils.isSameDay(selectedDay, day) }; return ( <div className="SelectableDayExample"> <DayPicker modifiers={ modifiers } onDayClick={ this.handleDayClick.bind(this) } /> <p> Selected: { selectedDay ? selectedDay.toLocaleDateString() : "(none)" } </p> </div> ); } }
import React from "react"; import DayPicker from "react-day-picker"; import { dateUtils } from "react-day-picker/utils"; import "react-day-picker/lib/style.css"; export default class SelectableDay extends React.Component { state = { selectedDay: null } handleDayClick(e, day, modifiers) { if (modifiers.indexOf("selected") > -1) { this.setState({ selectedDay: null }) } else { this.setState({ selectedDay: day }); } } render() { const { selectedDay } = this.state; // Add the `selected` modifier to the cell of the clicked day const modifiers = { selected: day => dateUtils.isSameDay(selectedDay, day) }; return ( <div className="SelectableDayExample"> <DayPicker modifiers={ selectedDay && modifiers } onDayClick={ this.handleDayClick.bind(this) } /> <p> Selected: { selectedDay ? selectedDay.toLocaleDateString() : "(none)" } </p> </div> ); } }
Add cache key in HTML source
from django.core.cache import cache def cache_get_key(*args, **kwargs): """Get the cache key for storage""" import hashlib serialise = [] for arg in args: serialise.append(str(arg)) for key,arg in kwargs.items(): if key == "clear_cache": continue serialise.append(str(key)) serialise.append(str(arg)) key = hashlib.md5("".join(serialise)).hexdigest() return key def cache_for(time): """Decorator for caching functions""" def decorator(fn): def wrapper(*args, **kwargs): key = cache_get_key(fn.__name__, *args, **kwargs) result = cache.get(key) if not result or "clear_cache" in kwargs and kwargs["clear_cache"]: cache.delete(key) result = fn(*args, **kwargs) cache.set(key, result, time) return result + "<!-- cache key: %s -->" % key return wrapper return decorator
from django.core.cache import cache def cache_get_key(*args, **kwargs): """Get the cache key for storage""" import hashlib serialise = [] for arg in args: serialise.append(str(arg)) for key,arg in kwargs.items(): if key == "clear_cache": continue serialise.append(str(key)) serialise.append(str(arg)) key = hashlib.md5("".join(serialise)).hexdigest() return key def cache_for(time): """Decorator for caching functions""" def decorator(fn): def wrapper(*args, **kwargs): key = cache_get_key(fn.__name__, *args, **kwargs) result = cache.get(key) if not result or "clear_cache" in kwargs and kwargs["clear_cache"]: cache.delete(key) result = fn(*args, **kwargs) cache.set(key, result, time) return result return wrapper return decorator
Fix FileNotFoundError on missing local_settings.py This has been broken for a long time... When running LBB without a local_settings.py and without an LBB_ENV environment variable, importing local_settings.py was resulting in a FileNotFoundError.
import imp import os from labonneboite.conf.common import settings_common # Settings # -------- # Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`. # A specific environment (staging, production...) can define its custom settings by: # - creating a specific `settings` file, e.g. `lbb_staging_settings.py` # - defining an environment variable containing the path to this specific `settings` file # # Specific and default settings will be merged, and values found in specific settings will take precedence. # When no specific settings are found, `labonneboite/conf/local_settings.py` is used. # Dynamically import LBB_SETTINGS environment variable as the `settings` # module, or import `local_settings.py` as the `settings` module if it does not # exist. settings = settings_common if settings_common.get_current_env() != settings_common.ENV_TEST: # Don't override settings in tests settings_module = os.path.join(os.path.dirname(__file__), 'local_settings.py') settings_module = os.environ.get('LBB_SETTINGS', settings_module) try: settings = imp.load_source('settings', settings_module) except FileNotFoundError: pass else: # Iterate over each setting defined in the `settings_common` module and add them to the dynamically # imported `settings` module if they don't already exist. for setting in dir(settings_common): if not hasattr(settings, setting): setattr(settings, setting, getattr(settings_common, setting))
import imp import os from labonneboite.conf.common import settings_common # Settings # -------- # Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`. # A specific environment (staging, production...) can define its custom settings by: # - creating a specific `settings` file, e.g. `lbb_staging_settings.py` # - defining an environment variable containing the path to this specific `settings` file # # Specific and default settings will be merged, and values found in specific settings will take precedence. # When no specific settings are found, `labonneboite/conf/local_settings.py` is used. # Dynamically import LBB_SETTINGS environment variable as the `settings` # module, or import `local_settings.py` as the `settings` module if it does not # exist. settings = settings_common if settings_common.get_current_env() != settings_common.ENV_TEST: # Don't override settings in tests settings_module = os.path.join(os.path.dirname(__file__), 'local_settings.py') settings_module = os.environ.get('LBB_SETTINGS', settings_module) settings = imp.load_source('settings', settings_module) # Iterate over each setting defined in the `settings_common` module and add them to the dynamically # imported `settings` module if they don't already exist. for setting in dir(settings_common): if not hasattr(settings, setting): setattr(settings, setting, getattr(settings_common, setting))
Fix codegen template typo for app dll generation
<?php require_once($argv[1]); // type.php require_once($argv[2]); // program.php $file_prefix = $argv[3]; $idl_type = $argv[4]; ?> // apps # include "<?=$file_prefix?>.app.example.h" void dsn_app_registration_<?=$_PROG->name?>() { // register all possible service apps dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_server_app>("server"); dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_client_app>("client"); <?php foreach ($_PROG->services as $svc) { ?> dsn::register_app< <?=$_PROG->get_cpp_namespace().$svc->name?>_perf_test_client_app>("client.perf.<?=$svc->name?>"); <?php } ?> } # ifndef DSN_RUN_USE_SVCHOST int main(int argc, char** argv) { dsn_app_registration_<?=$_PROG->name?>(); // specify what services and tools will run in config file, then run dsn_run(argc, argv, true); return 0; } # else # include <dsn/internal/module_init.cpp.h> MODULE_INIT_BEGIN(<?=$_PROG->name?>) dsn_app_registration_<?=$_PROG->name?>(); MODULE_INIT_END # endif
<?php require_once($argv[1]); // type.php require_once($argv[2]); // program.php $file_prefix = $argv[3]; $idl_type = $argv[4]; ?> // apps # include "<?=$file_prefix?>.app.example.h" void dsn_app_registration_<?=$_PROG->name?>() { // register all possible service apps dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_server_app>("server"); dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_client_app>("client"); <?php foreach ($_PROG->services as $svc) { ?> dsn::register_app< <?=$_PROG->get_cpp_namespace().$svc->name?>_perf_test_client_app>("client.perf.<?=$svc->name?>"); <?php } ?> } # ifndef DSN_RUN_USE_SVCHOST int main(int argc, char** argv) { dsn_app_registration_<?=$_PROG->name?>(); // specify what services and tools will run in config file, then run dsn_run(argc, argv, true); return 0; } # else # include <dsn/internal/module_int.cpp.h> MODULE_INIT_BEGIN dsn_app_registration_<?=$_PROG->name?>(); MODULE_INIT_END # endif
Update plugin to latest YggdrasilCore
package ru.linachan.pushbullet; import ru.linachan.yggdrasil.component.YggdrasilPlugin; import ru.linachan.yggdrasil.notification.YggdrasilNotificationManager; public class PushBulletPlugin extends YggdrasilPlugin { private PushBulletClient client; @Override protected void setUpDependencies() { } @Override protected void onInit() { String apiKey = core.getConfig().getString("push_bullet.api.key", null); client = new PushBulletClient(core, apiKey); client.setUpDevice("Yggdrasil"); PushBulletProvider provider = new PushBulletProvider(); core.getManager(YggdrasilNotificationManager.class).registerProvider(provider); } @Override protected void onShutdown() { } @Override protected boolean executeTests() { return true; } public PushBulletClient getClient() { return client; } }
package ru.linachan.pushbullet; import ru.linachan.yggdrasil.component.YggdrasilPlugin; public class PushBulletPlugin extends YggdrasilPlugin { private PushBulletClient client; @Override protected void setUpDependencies() { } @Override protected void onInit() { String apiKey = core.getConfig("PushBulletAPIKey", null); client = new PushBulletClient(core, apiKey); client.setUpDevice("Yggdrasil"); PushBulletProvider provider = new PushBulletProvider(); core.getNotificationManager().registerProvider(provider); } @Override protected void onShutdown() { } @Override protected boolean executeTests() { return true; } public PushBulletClient getClient() { return client; } }
Use `RuntimeException` instead of `UnexpectedValueException` when zip extension is not enabled
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class ZipDownloader extends FileDownloader { protected function extract($file, $path) { if (!class_exists('ZipArchive')) { throw new \RuntimeException('You need the zip extension enabled to use the ZipDownloader'); } $zipArchive = new \ZipArchive(); if (true !== ($retval = $zipArchive->open($file))) { throw new \UnexpectedValueException($file.' is not a valid zip archive, got error code '.$retval); } $zipArchive->extractTo($path); $zipArchive->close(); } }
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Downloader; use Composer\Package\PackageInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class ZipDownloader extends FileDownloader { protected function extract($file, $path) { if (!class_exists('ZipArchive')) { throw new \UnexpectedValueException('You need the zip extension enabled to use the ZipDownloader'); } $zipArchive = new \ZipArchive(); if (true !== ($retval = $zipArchive->open($file))) { throw new \UnexpectedValueException($file.' is not a valid zip archive, got error code '.$retval); } $zipArchive->extractTo($path); $zipArchive->close(); } }
Remove another “trick babel” hack in analytics Test plan * with or without the “Drop IE 11” commit applied * bin/rspec ./gems/plugins/analytics/spec_canvas/selenium/analytics_spec.rb:250 Should pass Or to test manually: * apply the “drop ie11” commit in canvas-lms * check out this commit in gems/plugins/analytics * go to /courses/x/analytics/users/y * it should load successfully and not die on this error at page load: “Uncaught TypeError: Cannot read property '0' of null” Change-Id: I3b7d098d2b6c1d13f3d623b366d591ac68778e7d Reviewed-on: https://gerrit.instructure.com/204099 Reviewed-by: Steven Burnett <a0b450117c5d20a22d5c4d52bb8ae13adee003d8@instructure.com> QA-Review: Steven Burnett <a0b450117c5d20a22d5c4d52bb8ae13adee003d8@instructure.com> Tested-by: Jenkins Product-Review: Ryan Shaw <ea3cd978650417470535f3a4725b6b5042a6ab59@instructure.com>
import ComboBox from 'compiled/widget/ComboBox' import StudentInCourseRouter from '../StudentInCourse/StudentInCourseRouter' // # // A combobox representing the possible filters for the department view. export default class StudentComboBox extends ComboBox { constructor(model) { // construct combobox super(model.get('course').get('students').models, { value: student => student.get('id'), label: student => student.get('name'), selected: model.get('student').get('id') }) this.model = model this.router = new StudentInCourseRouter(this.model) // connect combobox to model this.on('change', this.push) this.model.on('change:student', this.pull) } // # // Push the current value of the combobox to the URL push = student => this.router.select(student.get('id')) // # // Pull the current value from the model to the combobox pull = () => this.select(this.model.get('student').get('id')) }
import ComboBox from 'compiled/widget/ComboBox' import StudentInCourseRouter from '../StudentInCourse/StudentInCourseRouter' // # // A combobox representing the possible filters for the department view. export default class StudentComboBox extends ComboBox { constructor(model) { { // Hack: trick Babel/TypeScript into allowing this before super. if (false) { super(); } let thisFn = (() => { return this; }).toString(); let thisName = thisFn.match(/_this\d*/)[0]; eval(`${thisName} = this;`); } this.model = model this.router = new StudentInCourseRouter(this.model) // construct combobox super(this.model.get('course').get('students').models, { value: student => student.get('id'), label: student => student.get('name'), selected: this.model.get('student').get('id') }) // connect combobox to model this.on('change', this.push) this.model.on('change:student', this.pull) } // # // Push the current value of the combobox to the URL push = student => this.router.select(student.get('id')) // # // Pull the current value from the model to the combobox pull = () => this.select(this.model.get('student').get('id')) }
Add kwargs to this to make Jenkins shut up about it
from utils.command_system import command from utils import confirm import discord class SuperUser: def __init__(self, amethyst): self.amethyst = amethyst @command() @confirm.instance_owner() async def coreswap(self, ctx, *, path1, path2): """Command to swap your core module. Please note that this cog is in the devleopment folder, meaning that it should NOT be used in your bot until completion. It is far from complete and may contain a lot of bugs, Any bug report regarding any modules from the Development folder will be dismissed.""" if not ctx.args: return await ctx.send('No arguments given.') try: self.amethyst.holder.unload_module(path1) self.amethyst.holder.load_module(path2) await ctx.send('Core swap complete.') except: await ctx.send('Core swap failed!.') def setup(amethyst): return SuperUser(amethyst)
from utils.command_system import command from utils import confirm import discord class SuperUser: def __init__(self, amethyst): self.amethyst = amethyst @command(usage='<path1> <path2>') @confirm.instance_owner() async def coreswap(self, ctx): """Command to swap your core module. Please note that this cog is in the devleopment folder, meaning that it should NOT be used in your bot until completion. It is far from complete and may contain a lot of bugs, Any bug report regarding any modules from the Development folder will be dismissed.""" if not ctx.args: return await ctx.send('No arguments given.') try: self.amethyst.holder.unload_module(path1) self.amethyst.holder.load_module(path2) await ctx.send('Core swap complete.') except: await ctx.send('Core swap failed!.') def setup(amethyst): return SuperUser(amethyst)
Rename tests so that they run.
import pytest import pyrostest class TestSpinUp(pyrostest.RosTest): def test_noop(self): pass @pyrostest.launch_node('pyrostest', 'add_one.py') def test_launches_node(self): pass class TestFailureCases(pyrostest.RosTest): @pytest.mark.xfail(strict=True) @pyrostest.launch_node('this_isnt_a_project', 'add_one.py') def test_no_rospackage(self): pass @pytest.mark.xfail(strict=True) @pyrostest.launch_node('pyrostest', 'this_isnt_a_rosnode.py') def test_no_node(self): pass @pytest.mark.xfail(strict=True) @pyrostest.with_launch_file('pyrostest', 'does_not_exist') def test_no_launch_file(self): pass @pytest.mark.xfail(strict=True) @pyrostest.with_launch_file('not_a_package', 'exists') def test_no_launch_package(self): pass
import pytest import pyrostest class TestSpinUp(pyrostest.RosTest): def noop(self): pass @pyrostest.launch_node('pyrostest', 'add_one.py') def launches_node(self): pass class FailureCases(pyrostest.RosTest): @pytest.mark.xfail(strict=True) @pyrostest.launch_node('this_isnt_a_project', 'add_one.py') def no_rospackage(self): pass @pytest.mark.xfail(strict=True) @pyrostest.launch_node('pyrostest', 'this_isnt_a_rosnode.py') def no_node(self): pass @pytest.mark.xfail(strict=True) @pyrostest.with_launch_file('pyrostest', 'does_not_exist') def no_launch_file(self): pass @pytest.mark.xfail(strict=True) @pyrostest.with_launch_file('not_a_package', 'exists') def no_launch_package(self): pass
Fix trello micro service url
export const dbURI = (() => { if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') { return 'mongodb://localhost/trelloService'; } else { return 'mongodb://trellodb:27017/trelloService'; } })(); export const dbTestURI = (() => { if (process.env.NODE_ENV === 'docker-test') { return 'mongodb://trellodb:27017/trelloService'; } else if (process.env.NODE_ENV === 'test'){ return 'mongodb://localhost/trelloServiceTest'; } })(); export const usersMicroserviceUrl = (() => { if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') { return 'http://localhost:3002/'; } else { return 'http://usersmicroservice:3002/'; } })(); export const port = 3001;
export const dbURI = (() => { if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') { return 'mongodb://localhost/trelloService'; } else { return 'mongodb://trellodb:27017/trelloService'; } })(); export const dbTestURI = (() => { if (process.env.NODE_ENV === 'docker-test') { return 'mongodb://trellodb:27017/trelloService'; } else if (process.env.NODE_ENV === 'test'){ return 'mongodb://localhost/trelloServiceTest'; } })(); export const usersMicroserviceUrl = (() => { if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') { return 'http://localhost:3002/users/'; } else { return 'http://usersmicroservice:3002/'; } })(); export const port = 3001;
Add css and img files to bdist
#!/usr/bin/env python # vim: set sts=4 sw=4 et: try: from setuptools import setup except ImportError: from distutils.core import setup VERSION = "0.0.4" setup (name = "tupelo", description = "Random code around a card game called Tuppi", version = VERSION, author = "Jari Tenhunen", author_email = "jari.tenhunen@iki.fi", license = "BSD", packages = ['tupelo'], scripts = ['scripts/tupelo', 'scripts/tupelo-server'], data_files = [('share/tupelo/www', ['www/index.html', 'www/tupelo.js', 'www/tupelo-main.js', 'www/tupelo.css', 'www/buttons.css']), ('share/tupelo/www/img', ['www/img/bg.png', 'www/img/bg-button.gif'])], platforms="Python 2.5 and later.", test_suite = "nose.collector" )
#!/usr/bin/env python # vim: set sts=4 sw=4 et: try: from setuptools import setup except ImportError: from distutils.core import setup VERSION = "0.0.4" setup (name = "tupelo", description = "Random code around a card game called Tuppi", version = VERSION, author = "Jari Tenhunen", author_email = "jari.tenhunen@iki.fi", license = "BSD", packages = ['tupelo'], scripts = ['scripts/tupelo', 'scripts/tupelo-server'], data_files = [('share/tupelo/www', ['www/index.html', 'www/tupelo.js', 'www/tupelo-main.js'])], platforms="Python 2.5 and later.", test_suite = "nose.collector" )
Update auth details on reauthorization
from tapiriik.services import * from tapiriik.database import db class Service: def FromID(id): if id=="runkeeper": return RunKeeper elif id=="strava": return Strava raise ValueError def List(): return [RunKeeper, Strava] def WebInit(): global UserAuthorizationURL for itm in Service.List(): itm.WebInit() def GetServiceRecordWithAuthDetails(service, authDetails): return db.connections.find_one({"Service": service.ID, "Authorization": authDetails}) def EnsureServiceRecordWithAuth(service, uid, authDetails): serviceRecord = db.connections.find_one({"ExternalID": uid, "Service": service.ID}) if serviceRecord is None: db.connections.insert({"ExternalID": uid, "Service": service.ID, "SynchronizedActivities": [], "Authorization": authDetails}) serviceRecord = db.connections.find_one({"ExternalID": uid, "Service": service.ID}) if serviceRecord["Authorization"] != authDetails: db.connections.update({"ExternalID": uid, "Service": service.ID}, {"$set": {"Authorization": authDetails}}) return serviceRecord
from tapiriik.services import * from tapiriik.database import db class Service: def FromID(id): if id=="runkeeper": return RunKeeper elif id=="strava": return Strava raise ValueError def List(): return [RunKeeper, Strava] def WebInit(): global UserAuthorizationURL for itm in Service.List(): itm.WebInit() def GetServiceRecordWithAuthDetails(service, authDetails): return db.connections.find_one({"Service": service.ID, "Authorization": authDetails}) def EnsureServiceRecordWithAuth(service, uid, authDetails): serviceRecord = db.connections.find_one({"ExternalID": uid, "Service": service.ID}) if serviceRecord is None: db.connections.insert({"ExternalID": uid, "Service": service.ID, "SynchronizedActivities": [], "Authorization": authDetails}) serviceRecord = db.connections.find_one({"ExternalID": uid, "Service": service.ID}) return serviceRecord
Revert "sample data structure for multithread working" This reverts commit 33a475b883c311666078b91ed1dab5870c6d583d.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.peta2kuba.sample_data; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** * * @author skornok */ @Component @Transactional //transactions are handled on facade layer public class SampleDataLoadingFacadeImpl implements SampleDataLoadingFacade { final static Logger log = LoggerFactory.getLogger(SampleDataLoadingFacadeImpl.class); @Override @SuppressWarnings("unused") public void loadData() throws IOException { log.info("Loaded Haunted Houses."); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.peta2kuba.sample_data; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** * * @author skornok */ @Component @Transactional //transactions are handled on facade layer public class SampleDataLoadingFacadeImpl implements SampleDataLoadingFacade { final static Logger log = LoggerFactory.getLogger(SampleDataLoadingFacadeImpl.class); @Override @SuppressWarnings("unused") public void loadData() throws IOException { log.info("Loaded Haunted Houses."); createPeople(); createHouses(); createAbilities(); createHaunters(); } private void createPeople() { } private void createHouses() { } private void createAbilities() { } private void createHaunters() { } }
Disable duplicate celery log messages
from scoring_engine.celery_app import celery_app from billiard.exceptions import SoftTimeLimitExceeded import subprocess from scoring_engine.logger import logger @celery_app.task(name='execute_command', soft_time_limit=30) def execute_command(job): output = "" # Disable duplicate celery log messages if logger.propagate: logger.propagate = False logger.info("Running cmd for " + str(job)) try: cmd_result = subprocess.run( job['command'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) output = cmd_result.stdout.decode("utf-8") job['errored_out'] = False except SoftTimeLimitExceeded: job['errored_out'] = True job['output'] = output return job
from scoring_engine.celery_app import celery_app from billiard.exceptions import SoftTimeLimitExceeded import subprocess from scoring_engine.logger import logger @celery_app.task(name='execute_command', soft_time_limit=30) def execute_command(job): output = "" logger.info("Running cmd for " + str(job)) try: cmd_result = subprocess.run( job['command'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) output = cmd_result.stdout.decode("utf-8") job['errored_out'] = False except SoftTimeLimitExceeded: job['errored_out'] = True job['output'] = output return job
fix(TripSummary): Remove green bar outside of batch itinerary results.
import coreUtils from '@opentripplanner/core-utils' import { ClassicLegIcon } from '@opentripplanner/icons' import React from 'react' import ItinerarySummary from '../../narrative/default/itinerary-summary' const { formatDuration, formatTime } = coreUtils.time const TripSummary = ({ monitoredTrip }) => { const { itinerary } = monitoredTrip const { duration, endTime, startTime } = itinerary // TODO: use the modern itinerary summary built for trip comparison. return ( <div className={`otp option default-itin`} style={{borderTop: '0px', padding: '0px'}}> <div className='header'> <span className='title'>Itinerary</span>{' '} <span className='duration pull-right'>{formatDuration(duration)}</span>{' '} <span className='arrivalTime'>{formatTime(startTime)}—{formatTime(endTime)}</span> <ItinerarySummary itinerary={itinerary} LegIcon={ClassicLegIcon} /> </div> </div> ) } export default TripSummary
import coreUtils from '@opentripplanner/core-utils' import { ClassicLegIcon } from '@opentripplanner/icons' import React from 'react' import ItinerarySummary from '../../narrative/default/itinerary-summary' const { formatDuration, formatTime } = coreUtils.time const TripSummary = ({ monitoredTrip }) => { const { itinerary } = monitoredTrip const { duration, endTime, startTime } = itinerary // TODO: use the modern itinerary summary built for trip comparison. return ( <div className={`otp option default-itin active`} style={{borderTop: '0px', padding: '0px'}}> <div className='header'> <span className='title'>Itinerary</span>{' '} <span className='duration pull-right'>{formatDuration(duration)}</span>{' '} <span className='arrivalTime'>{formatTime(startTime)}—{formatTime(endTime)}</span> <ItinerarySummary itinerary={itinerary} LegIcon={ClassicLegIcon} /> </div> </div> ) } export default TripSummary
Fix mistaken document about token pos
class Token: """ Individual word with lemma, part-of-speech and location in text. :ivar word: Unprocessed word :ivar lemma: Lemmatized word :ivar partofspeech: Part-of-speech of word :ivar startPos: Start position of token in document text (note: not the sentence text) :ivar endPos: End position of token in document text (note: not the sentence text) """ def __init__(self,word,lemma,partofspeech,startPos,endPos): """ Constructor for Token class :param word: Unprocessed word :param lemma: Lemmatized word :param partofspeech: Part-of-speech of word :param startPos: Start position of token in document text (note: not the sentence text) :param endPos: End position of token in document text (note: not the sentence text) :type word: str :type lemma: str :type partofspeech: str :type startPos: int :type endPos: int """ self.word = word self.lemma = lemma self.partofspeech = partofspeech self.startPos = startPos self.endPos = endPos def __str__(self): return self.word def __repr__(self): return self.__str__()
class Token: """ Individual word with lemma, part-of-speech and location in text. :ivar word: Unprocessed word :ivar lemma: Lemmatized word :ivar partofspeech: Part-of-speech of word :ivar startPos: Start position of token in sentence :ivar endPos: End position of token in sentence """ def __init__(self,word,lemma,partofspeech,startPos,endPos): """ Constructor for Token class :param word: Unprocessed word :param lemma: Lemmatized word :param partofspeech: Part-of-speech of word :param startPos: Start position of token in sentence :param endPos: End position of token in sentence :type word: str :type lemma: str :type partofspeech: str :type startPos: int :type endPos: int """ self.word = word self.lemma = lemma self.partofspeech = partofspeech self.startPos = startPos self.endPos = endPos def __str__(self): return self.word def __repr__(self): return self.__str__()
Set content-length in bytes instead of characters
module.exports = function (options) { options = options || {} options.property = options.property || 'body' options.stringify = options.stringify || JSON.stringify return function (req, res, next) { req.removeAllListeners('data') req.removeAllListeners('end') if(req.headers['content-length'] !== undefined){ req.headers['content-length'] = Buffer.byteLength(options.stringify(req[options.property]), 'utf8') } next() process.nextTick(function () { if(req[options.property]) { if('function' === typeof options.modify) req[options.property] = options.modify(req[options.property]) req.emit('data', options.stringify(req[options.property])) } req.emit('end') }) } }
module.exports = function (options) { options = options || {} options.property = options.property || 'body' options.stringify = options.stringify || JSON.stringify return function (req, res, next) { req.removeAllListeners('data') req.removeAllListeners('end') if(req.headers['content-length'] !== undefined){ req.headers['content-length'] = options.stringify(req[options.property]).length } next() process.nextTick(function () { if(req[options.property]) { if('function' === typeof options.modify) req[options.property] = options.modify(req[options.property]) req.emit('data', options.stringify(req[options.property])) } req.emit('end') }) } }
Fix redirection rule inside post comment route.
var path = require('path'); var posts = require('data-post'); var express = require('express'); var app = module.exports = express(); app.set('view engine', 'jade'); app.set('views', path.join(__dirname, 'views')); app.param('slug', function _slug(req, res, next, val) { var regex = /^[\w\-]+$/; var captures; if (captures = regex.exec(String(val))) { req.params.slug = captures[0]; next(); } else { next('route'); } }); app.get('/post/:slug', function index(req, res) { posts.get({ slug: req.params.slug, callback: function render(err, item) { res.render('index', {post: item}); } }); }); app.post('/post/:slug', function posting(req, res) { var comment = req.body; comment.createdAt = new Date(); posts.addComment({ slug: req.params.slug, comments: [comment], callback: function added(err, count) { res.redirect('/post/' + req.params.slug); } }); });
var path = require('path'); var posts = require('data-post'); var express = require('express'); var app = module.exports = express(); app.set('view engine', 'jade'); app.set('views', path.join(__dirname, 'views')); app.param('slug', function _slug(req, res, next, val) { var regex = /^[\w\-]+$/; var captures; if (captures = regex.exec(String(val))) { req.params.slug = captures[0]; next(); } else { next('route'); } }); app.get('/post/:slug', function index(req, res) { posts.get({ slug: req.params.slug, callback: function render(err, item) { res.render('index', {post: item}); } }); }); app.post('/post/:slug', function posting(req, res) { var comment = req.body; comment.createdAt = new Date(); posts.addComment({ slug: req.params.slug, comments: [comment], callback: function added(err, count) { res.redirect('/post/' + slug); } }); });
Add friendly name to email-address
import AWS from 'aws-sdk' import InputValidator from './InputValidator' import EmailFormatter from './EmailFormatter' AWS.config.region = 'us-east-1' exports.handler = function(event, context) { // Validate Inputs let errors = InputValidator.validate(event) if (errors) { context.fail(errors) return } // TODO Add task to SQS and invoke ECS container // Send Email let {emailText, subject} = EmailFormatter.format(event), ses = new AWS.SES() ses.sendEmail({ Source: 'MOOC Fetcher Support <contact@moocfetcher.com>', Destination: { ToAddresses: [event.email] }, Message: { Subject: { Data: subject, Charset: 'UTF-8' }, Body: { Text: { Data: emailText, Charset: 'UTF-8' } } } }, function(err) { if (err) { context.fail(err) return } context.succeed() }) }
import AWS from 'aws-sdk' import InputValidator from './InputValidator' import EmailFormatter from './EmailFormatter' AWS.config.region = 'us-east-1' exports.handler = function(event, context) { // Validate Inputs let errors = InputValidator.validate(event) if (errors) { context.fail(errors) return } // TODO Add task to SQS and invoke ECS container // Send Email let {emailText, subject} = EmailFormatter.format(event), ses = new AWS.SES() ses.sendEmail({ Source: 'contact@moocfetcher.com', Destination: { ToAddresses: [event.email] }, Message: { Subject: { Data: subject, Charset: 'UTF-8' }, Body: { Text: { Data: emailText, Charset: 'UTF-8' } } } }, function(err) { if (err) { context.fail(err) return } context.succeed() }) }
Update git url, formatting nits
Package.describe({ summary: "Ravelry OAuth flow", name: "amschrader:ravelry", git: "https://github.com/amschrader/meteor-ravelry.git", version: "0.1.2" }); Package.onTest(function(api) { api.use('tinytest'); api.use('amschrader:ravelry'); api.addFiles('ravelry-tests.js'); }); Package.onUse(function(api) { api.use('http@1.0.8', ['client', 'server']); api.use('templating@1.0.9', 'client'); api.use('oauth1@1.1.2', ['client', 'server']); api.use('oauth@1.1.2', ['client', 'server']); api.use('random@1.0.1', 'client'); api.use('underscore@1.0.1', 'server'); api.use('service-configuration@1.0.2', ['client', 'server']); api.export && api.export('Ravelry'); api.add_files([ 'ravelry-configure.html', 'ravelry-configure.js' ],'client'); api.addFiles('ravelry-server.js', 'server'); api.addFiles('ravelry-client.js', 'client'); });
Package.describe({ summary: "Ravelry OAuth flow", name: "amschrader:ravelry", git: "git@github.com:amschrader/meteor-ravelry.git", version: "0.1.0" }); Package.onTest(function(api) { api.use('tinytest'); api.use('amschrader:ravelry'); api.addFiles('ravelry-tests.js'); }); Package.on_use(function(api) { api.use('http@1.0.8', ['client', 'server']); api.use('templating@1.0.9', 'client'); api.use('oauth1@1.1.2', ['client', 'server']); api.use('oauth@1.1.2', ['client', 'server']); api.use('random@1.0.1', 'client'); api.use('underscore@1.0.1', 'server'); api.use('service-configuration@1.0.2', ['client', 'server']); api.export && api.export('Ravelry'); api.add_files([ 'ravelry-configure.html', 'ravelry-configure.js' ],'client'); api.add_files('ravelry-server.js', 'server'); api.add_files('ravelry-client.js', 'client'); });
Use read stream to ensure file is greater than 0 bytes
#! /usr/bin/env node "use strict"; var argv = require("optimist").argv; var pjson = require("../package.json"); var defaultConfig = require("./default-config"); var cliUtils = require("./cli").utils; var cliInfo = require("./cli-info").info; /** * Handle Command-line usage */ if (require.main === module) { if (argv.version || argv.v) { return cliInfo.getVersion(pjson); } if (argv._[0] === "init") { return cliInfo.makeConfig(); } var config = cliUtils.getConfig(defaultConfig, argv), filesArg = cliUtils.getFilesArg(argv, config), files = cliUtils.getFiles(filesArg); if (config.exclude) { files = cliUtils.mergeFiles(files, config.exclude); } cliUtils._start(files, config, pjson.version); } /** * Return init method for external use * @param {String|Array} [files] * @param {Object} [userConfig] */ module.exports.init = function (files, userConfig) { var config = defaultConfig; if (userConfig) { config = cliUtils.mergeConfigObjects(defaultConfig, userConfig || {}); if (files && userConfig.exclude) { files = cliUtils.mergeFiles(files, userConfig.exclude); } } return cliUtils._start(files, config, pjson.version); };
#! /usr/bin/env node "use strict"; var argv = require("optimist").argv; var pjson = require("../package.json"); var defaultConfig = require("./default-config"); var cliUtils = require("./cli").utils; var cliInfo = require("./cli-info").info; /** * Handle Command-line usage */ if (require.main === module) { if (argv.version || argv.v) { return cliInfo.getVersion(pjson); } if (argv._[0] === "init") { return cliInfo.makeConfig(); } var config = cliUtils.getConfig(defaultConfig, argv), filesArg = cliUtils.getFilesArg(argv, config), files = cliUtils.getFiles(filesArg); if (config.exclude) { files = cliUtils.mergeFiles(files, config.exclude); } cliUtils._start(files, config, pjson.version); } /** * @param {String|Array} [files] * @param {Object} [userConfig] */ module.exports.init = function (files, userConfig) { var config = defaultConfig; if (userConfig) { config = cliUtils.mergeConfigObjects(defaultConfig, userConfig || {}); if (files && userConfig.exclude) { files = cliUtils.mergeFiles(files, userConfig.exclude); } } return cliUtils._start(files, config, pjson.version); };
[gulp] Make Gulp wait on the Promise returned from `del` This fixes the `lib` build step; running `gulp build` now creates `lib` as expected.
var babel = require('gulp-babel'); var del = require('del'); var flatten = require('gulp-flatten'); var gulp = require('gulp'); var runSequence = require('run-sequence'); var babelOpts = require('./scripts/babel/default-options'); var paths = { src: [ 'src/**/*.js', '!src/**/__tests__/**/*.js', '!src/**/__mocks__/**/*.js' ], lib: 'lib' }; gulp.task('clean', function() { return del([paths.lib]); }); gulp.task('lib', function() { return gulp .src(paths.src) .pipe(babel(babelOpts)) .pipe(flatten()) .pipe(gulp.dest(paths.lib)); }); gulp.task('build', function(cb) { runSequence('clean', ['lib'], cb); }); gulp.task('default', ['build']);
var babel = require('gulp-babel'); var del = require('del'); var flatten = require('gulp-flatten'); var gulp = require('gulp'); var runSequence = require('run-sequence'); var babelOpts = require('./scripts/babel/default-options'); var paths = { src: [ 'src/**/*.js', '!src/**/__tests__/**/*.js', '!src/**/__mocks__/**/*.js' ], lib: 'lib' }; gulp.task('clean', function(cb) { del([paths.lib], cb); }); gulp.task('lib', function() { return gulp .src(paths.src) .pipe(babel(babelOpts)) .pipe(flatten()) .pipe(gulp.dest(paths.lib)); }); gulp.task('build', function(cb) { runSequence('clean', ['lib'], cb); }); gulp.task('default', ['build']);
Add Python 3 to supported languages
#!/usr/bin/env python from setuptools import setup setup( name='Simon', version='0.7.0', description='Simple MongoDB Models', long_description=open('README.rst').read(), author='Andy Dirnberger', author_email='dirn@dirnonline.com', url='https://github.com/dirn/Simon', packages=['simon'], package_data={'': ['LICENSE', 'README.rst']}, include_package_data=True, install_requires=['pymongo>=2.4'], tests_require=['coverage', 'mock', 'nose'], license=open('LICENSE').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
#!/usr/bin/env python from setuptools import setup setup( name='Simon', version='0.7.0', description='Simple MongoDB Models', long_description=open('README.rst').read(), author='Andy Dirnberger', author_email='dirn@dirnonline.com', url='https://github.com/dirn/Simon', packages=['simon'], package_data={'': ['LICENSE', 'README.rst']}, include_package_data=True, install_requires=['pymongo>=2.4'], tests_require=['coverage', 'mock', 'nose'], license=open('LICENSE').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Fix indentation which causes error on restore Fixes error message, that document with a specific number already exists, even if it doesn't.
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, json from frappe.model.document import Document from frappe import _ class DeletedDocument(Document): pass @frappe.whitelist() def restore(name): deleted = frappe.get_doc('Deleted Document', name) doc = frappe.get_doc(json.loads(deleted.data)) try: doc.insert() except frappe.DocstatusTransitionError: frappe.msgprint(_("Cancelled Document restored as Draft")) doc.docstatus = 0 doc.insert() doc.add_comment('Edit', _('restored {0} as {1}').format(deleted.deleted_name, doc.name)) deleted.new_name = doc.name deleted.restored = 1 deleted.db_update() frappe.msgprint(_('Document Restored'))
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, json from frappe.model.document import Document from frappe import _ class DeletedDocument(Document): pass @frappe.whitelist() def restore(name): deleted = frappe.get_doc('Deleted Document', name) doc = frappe.get_doc(json.loads(deleted.data)) try: doc.insert() except frappe.DocstatusTransitionError: frappe.msgprint(_("Cancelled Document restored as Draft")) doc.docstatus = 0 doc.insert() doc.add_comment('Edit', _('restored {0} as {1}').format(deleted.deleted_name, doc.name)) deleted.new_name = doc.name deleted.restored = 1 deleted.db_update() frappe.msgprint(_('Document Restored'))
Fix errrors on Firefox when dismiss toaster
/* global element, by */ 'use strict'; var common = require('../common/common'); var navigation = require('../common/navigation'); var genericForm = require('../generic_form/generic_form'); var goToCloudImageList = function() { navigation.go('main', 'admin'); navigation.go('admin', 'cloud-images'); }; module.exports.goToCloudImageList = goToCloudImageList; var addNewCloudImage = function(name, osType, osArch, osDistribution, osVersion, numCPUs, diskSize, memSize) { goToCloudImageList(); element(by.id('new-cloud-image-button')).click(); genericForm.sendValueToPrimitive('name', name, false, 'input'); genericForm.sendValueToPrimitive('osType', osType, false, 'select'); genericForm.sendValueToPrimitive('osArch', osArch, false, 'select'); genericForm.sendValueToPrimitive('osDistribution', osDistribution, false, 'input'); genericForm.sendValueToPrimitive('osVersion', osVersion, false, 'input'); genericForm.sendValueToPrimitive('numCPUs', numCPUs, false, 'input'); genericForm.sendValueToPrimitive('diskSize', diskSize, false, 'input'); genericForm.sendValueToPrimitive('memSize', memSize, false, 'input'); element(by.binding('GENERIC_FORM.SAVE')).click(); common.dismissAlertIfPresent(); }; module.exports.addNewCloudImage = addNewCloudImage;
/* global element, by */ 'use strict'; var common = require('../common/common'); var navigation = require('../common/navigation'); var genericForm = require('../generic_form/generic_form'); var goToCloudImageList = function() { navigation.go('main', 'admin'); navigation.go('admin', 'cloud-images'); }; module.exports.goToCloudImageList = goToCloudImageList; var addNewCloudImage = function(name, osType, osArch, osDistribution, osVersion, numCPUs, diskSize, memSize) { goToCloudImageList(); element(by.id('new-cloud-image-button')).click(); genericForm.sendValueToPrimitive('name', name, false, 'input'); genericForm.sendValueToPrimitive('osType', osType, false, 'select'); genericForm.sendValueToPrimitive('osArch', osArch, false, 'select'); genericForm.sendValueToPrimitive('osDistribution', osDistribution, false, 'input'); genericForm.sendValueToPrimitive('osVersion', osVersion, false, 'input'); genericForm.sendValueToPrimitive('numCPUs', numCPUs, false, 'input'); genericForm.sendValueToPrimitive('diskSize', diskSize, false, 'input'); genericForm.sendValueToPrimitive('memSize', memSize, false, 'input'); element(by.binding('GENERIC_FORM.SAVE')).click(); common.dismissAlert(); }; module.exports.addNewCloudImage = addNewCloudImage;
Make it compatible with older node.js
module.exports = function (protocol) { protocol = protocol || 'http'; var url = 'http://vicopo.selfbuild.fr/search/'; switch (protocol) { case 'https': url = 'https://www.selfbuild.fr/vicopo/search/'; break; case 'http': break; default: throw new Error(protocol + ' protocol not supported'); } var transport = require(protocol); return function (search, done) { transport.get(url + encodeURIComponent(search), function (res) { var data = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { var result; try { result = JSON.parse(data); } catch(e) { return done(new Error('Cannot parse Vicopo answear:\n' + e + '\n' + data)); } if (result.cities) { done(null, result.cities); } else { done(new Error('The answear should contains a cities list:\n' + data)); } }); }) .on('error', done); }; };
module.exports = function (protocol) { protocol = protocol || 'http'; var url = 'http://vicopo.selfbuild.fr/search/'; switch (protocol) { case 'https': url = 'https://www.selfbuild.fr/vicopo/search/'; break; case 'http': break; default: throw new Error(protocol + ' protocol not supported'); } var transport = require(protocol); return function (search, done) { transport.get(url + encodeURIComponent(search), function (res) { var data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { var result; try { result = JSON.parse(data); } catch(e) { return done(new Error('Cannot parse Vicopo answear:\n' + e + '\n' + data)); } if (result.cities) { done(null, result.cities); } else { done(new Error('The answear should contains a cities list:\n' + data)); } }); }) .on('error', done); }; };
Change ID to String (easier for comparisons)
/* * Copyright 2013 That Amazing Web Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taw.dashtube.model; import com.google.api.client.util.Key; import com.google.api.client.xml.GenericXml; /** * Simple class encapsulating the &lt;Line&gt; element. */ public class Line extends GenericXml { @Key("@ID") public String id; @Key("@Name") public String name; }
/* * Copyright 2013 That Amazing Web Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taw.dashtube.model; import com.google.api.client.util.Key; import com.google.api.client.xml.GenericXml; /** * Simple class encapsulating the &lt;Line&gt; element. */ public class Line extends GenericXml { @Key("@ID") public int id; @Key("@Name") public String name; }
Return a cloned model.attributes by default
Minionette.ModelView = Minionette.View.extend({ // Listen to the default events modelEvents: { 'change': 'render', 'destroy': 'remove' }, // The data that is sent into the template function. // Override this to provide custom data. serializeData: function() { }, // A useful default render method. render: function() { this.trigger('render:before'); // Detach all our subviews, so they don't need to be re-rendered. _.each(this._subViews, function(view) { view.$el.detach(); }); this.$el.html(this.template(this.serializeData())); // Listen for render events to reattach subviews. this.trigger('render'); return this; return _.clone(this.model.attributes); } });
Minionette.ModelView = Minionette.View.extend({ // Listen to the default events modelEvents: { 'change': 'render', 'destroy': 'remove' }, // The data that is sent into the template function. // Override this to provide custom data. serializeData: function() { return this.model.attributes; }, // A useful default render method. render: function() { this.trigger('render:before'); // Detach all our subviews, so they don't need to be re-rendered. _.each(this._subViews, function(view) { view.$el.detach(); }); this.$el.html(this.template(this.serializeData())); // Listen for render events to reattach subviews. this.trigger('render'); return this; } });
Set the Renderer in the View Helper Manager This would have been done in the EngineFactory - however - that creates a circular dependency.
<?php namespace ZfcTwig\Service; use ZfcTwig\View\Renderer; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\View\Resolver\TemplatePathStack; class ViewRendererFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Configuration'); $config = $config['zfctwig']; $pathResolver = $serviceLocator->get('ViewTemplatePathStack'); $pathResolver->setDefaultSuffix($config['suffix']); $resolver = $serviceLocator->get('ViewResolver'); $renderer = new Renderer(); $engine = $serviceLocator->get('TwigEnvironment'); $engine->manager()->setRenderer($renderer); $renderer->setEngine($engine); $renderer->setResolver($resolver); return $renderer; } }
<?php namespace ZfcTwig\Service; use ZfcTwig\View\Renderer; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\View\Resolver\TemplatePathStack; class ViewRendererFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Configuration'); $config = $config['zfctwig']; $pathResolver = $serviceLocator->get('ViewTemplatePathStack'); $pathResolver->setDefaultSuffix($config['suffix']); $resolver = $serviceLocator->get('ViewResolver'); $renderer = new Renderer(); $renderer->setEngine($serviceLocator->get('TwigEnvironment')); $renderer->setResolver($resolver); return $renderer; } }
Add exception for streams forcefully reset
# -*- coding: utf-8 -*- """ hyper/http20/exceptions ~~~~~~~~~~~~~~~~~~~~~~~ This defines exceptions used in the HTTP/2 portion of hyper. """ class HTTP20Error(Exception): """ The base class for all of ``hyper``'s HTTP/2-related exceptions. """ pass class HPACKEncodingError(HTTP20Error): """ An error has been encountered while performing HPACK encoding. """ pass class HPACKDecodingError(HTTP20Error): """ An error has been encountered while performing HPACK decoding. """ pass class ConnectionError(HTTP20Error): """ The remote party signalled an error affecting the entire HTTP/2 connection, and the connection has been closed. """ pass class ProtocolError(HTTP20Error): """ The remote party violated the HTTP/2 protocol. """ pass class StreamResetError(HTTP20Error): """ A stream was forcefully reset by the remote party. """ pass
# -*- coding: utf-8 -*- """ hyper/http20/exceptions ~~~~~~~~~~~~~~~~~~~~~~~ This defines exceptions used in the HTTP/2 portion of hyper. """ class HTTP20Error(Exception): """ The base class for all of ``hyper``'s HTTP/2-related exceptions. """ pass class HPACKEncodingError(HTTP20Error): """ An error has been encountered while performing HPACK encoding. """ pass class HPACKDecodingError(HTTP20Error): """ An error has been encountered while performing HPACK decoding. """ pass class ConnectionError(HTTP20Error): """ The remote party signalled an error affecting the entire HTTP/2 connection, and the connection has been closed. """ pass class ProtocolError(HTTP20Error): """ The remote party violated the HTTP/2 protocol. """ pass
Update gateways to use new sendData method
<?php namespace Omnipay\Mollie\Message; /** * Mollie Abstract Request */ abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest { protected $endpoint = 'https://secure.mollie.nl/xml/ideal'; public function getPartnerId() { return $this->getParameter('partnerId'); } public function setPartnerId($value) { return $this->setParameter('partnerId', $value); } public function getIssuer() { return $this->getParameter('issuer'); } public function setIssuer($value) { return $this->setParameter('issuer', $value); } protected function getBaseData() { $data = array(); if ($this->getTestMode()) { $data['testmode'] = 'true'; } return $data; } public function sendData($data) { $httpResponse = $this->httpClient->post($this->endpoint, null, $data)->send(); return $this->response = new Response($this, $httpResponse->xml()); } }
<?php namespace Omnipay\Mollie\Message; /** * Mollie Abstract Request */ abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest { protected $endpoint = 'https://secure.mollie.nl/xml/ideal'; public function getPartnerId() { return $this->getParameter('partnerId'); } public function setPartnerId($value) { return $this->setParameter('partnerId', $value); } public function getIssuer() { return $this->getParameter('issuer'); } public function setIssuer($value) { return $this->setParameter('issuer', $value); } protected function getBaseData() { $data = array(); if ($this->getTestMode()) { $data['testmode'] = 'true'; } return $data; } public function send() { $httpResponse = $this->httpClient->post($this->endpoint, null, $this->getData())->send(); return $this->response = new Response($this, $httpResponse->xml()); } }
Make instance private, reorder lambda
package io.teiler.api.endpoint; import static spark.Spark.before; import static spark.Spark.get; import static spark.Spark.post; import io.teiler.api.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @Controller public class GroupEndpoint implements Endpoint { private static final Logger LOGGER = LoggerFactory.getLogger(GroupEndpoint.class); @Autowired private GroupService groupService; @Override public void register() { before((req, res) -> LOGGER.debug("API call to '" + req.pathInfo() + "'")); post("/v1/group", (req, res) -> groupService.handlePost(req)); get("/v1/group", (req, res) -> groupService.handleGet(req)); } }
package io.teiler.api.endpoint; import static spark.Spark.before; import static spark.Spark.get; import static spark.Spark.post; import io.teiler.api.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @Controller public class GroupEndpoint implements Endpoint { private static final Logger LOGGER = LoggerFactory.getLogger(GroupEndpoint.class); @Autowired GroupService groupService; @Override public void register() { before((req, res) -> LOGGER.debug("API call to '" + req.pathInfo() + "'")); post("/v1/group", (req, res) -> { return groupService.handlePost(req); }); get("/v1/group", (req, res) -> { return groupService.handleGet(req); }); } }
Make sure the username is lower case when imported from ldap Otherwise the meteor accounts package cannot find the user document which leads to errors when logging in with an username that has upper case letters
let _ = require('underscore'); module.exports = function (ldapSettings, userData) { let searchDn = ldapSettings.searchDn || 'cn'; // userData.mail may be a string with one mail address or an array. // Nevertheless we are only interested in the first mail address here - if there should be more... let tmpEMail = userData.mail; if (Array.isArray(userData.mail)) { tmpEMail = userData.mail[0]; } let tmpEMailArray = [{ address: tmpEMail, verified: true, fromLDAP: true }]; let user = { createdAt: new Date(), emails: tmpEMailArray, username: userData[searchDn].toLowerCase(), profile: _.pick(userData, _.without(ldapSettings.whiteListedFields, 'mail')) }; // copy over the LDAP user's long name from "cn" field to the meteor accounts long name field if (user.profile.cn) { user.profile.name = user.profile.cn; delete user.profile.cn; } if (userData.isInactive) { user.isInactive = true; } return user; };
let _ = require('underscore'); module.exports = function (ldapSettings, userData) { let searchDn = ldapSettings.searchDn || 'cn'; // userData.mail may be a string with one mail address or an array. // Nevertheless we are only interested in the first mail address here - if there should be more... let tmpEMail = userData.mail; if (Array.isArray(userData.mail)) { tmpEMail = userData.mail[0]; } let tmpEMailArray = [{ address: tmpEMail, verified: true, fromLDAP: true }]; let user = { createdAt: new Date(), emails: tmpEMailArray, username: userData[searchDn], profile: _.pick(userData, _.without(ldapSettings.whiteListedFields, 'mail')) }; // copy over the LDAP user's long name from "cn" field to the meteor accounts long name field if (user.profile.cn) { user.profile.name = user.profile.cn; delete user.profile.cn; } if (userData.isInactive) { user.isInactive = true; } return user; };
Make accessKey a zoneData param.
<?php class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract { public function getHtml($zoneData, array $variables) { $zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']); $variables = $this->_variableKeysToUnderscore($variables); $variables['key'] = $zoneData['accessKey']; $html = '<div id="epom-' . $zoneId . '" class="epom-ad" data-zone-id="' . $zoneId . '" data-variables="' . CM_Util::htmlspecialchars(json_encode($variables, JSON_FORCE_OBJECT)) . '"></div>'; return $html; } private function _variableKeysToUnderscore($variables) { foreach ($variables as $key => $value) { unset ($variables[$key]); $underscoreKey = str_replace('-', '_', $key); $variables[$underscoreKey] = $value; } return $variables; } }
<?php class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract { /** * @return string */ private function _getAccessKey() { return self::_getConfig()->accessKey; } public function getHtml($zoneData, array $variables) { $zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']); $variables = $this->_variableKeysToUnderscore($variables); $variables['key'] = $this->_getAccessKey(); $html = '<div id="epom-' . $zoneId . '" class="epom-ad" data-zone-id="' . $zoneId . '" data-variables="' . CM_Util::htmlspecialchars(json_encode($variables, JSON_FORCE_OBJECT)) . '"></div>'; return $html; } private function _variableKeysToUnderscore($variables) { foreach ($variables as $key => $value) { unset ($variables[$key]); $underscoreKey = str_replace('-', '_', $key); $variables[$underscoreKey] = $value; } return $variables; } }
Fix bug when transcriptions are empty
from flask import render_template, jsonify, request from app import app from app import evolver @app.route('/') @app.route('/index') def index(): return render_template('index.html') def format_transcriptions(transcriptions): '''Split the raw string of transcriptions into the correct tuple rules.''' clean_transcriptions = transcriptions.strip().lower() if len(clean_transcriptions) == 0: return [] else: return [(pair.split(':')[0], pair.split(':')[1]) for pair in clean_transcriptions.split('\n')] @app.route('/evolve', methods=['POST']) def evolve(): words = request.form['words'].split() try: transcriptions = format_transcriptions(request.form['transcriptions']) except IndexError: return jsonify({'error': 'Error: Transcription seperator must be a colon'}) try: generations = int(request.form['generations']) except ValueError: return jsonify({'error': 'Error: Generations must be an integer'}) words, rules = evolver.evolve(words, generations, transcriptions) return jsonify({'rules': rules, 'words': words, 'error': 0})
from flask import render_template, jsonify, request from app import app from app import evolver @app.route('/') @app.route('/index') def index(): return render_template('index.html') def format_transcriptions(transcriptions): '''Split the raw string of transcriptions into the correct tuple rules.''' return [(pair.split(':')[0], pair.split(':')[1]) for pair in transcriptions.split('\n')] @app.route('/evolve', methods=['POST']) def evolve(): words = request.form['words'].split() try: transcriptions = format_transcriptions(request.form['transcriptions']) except IndexError: return jsonify({'error': 'Error: Transcription seperator must be a colon'}) try: generations = int(request.form['generations']) except ValueError: return jsonify({'error': 'Error: Generations must be an integer'}) words, rules = evolver.evolve(words, generations, transcriptions) return jsonify({'rules': rules, 'words': words, 'error': 0})
Disable ens for rin and rop since they have a different implementation
import domainSale from '@/assets/images/icons/domain-sale.svg'; import domainSaleHov from '@/assets/images/icons/domain-sale-hov.svg'; import registerDomain from '@/assets/images/icons/domain.svg'; import registerDomainHov from '@/assets/images/icons/domain-hov.svg'; import secureTransaction from '@/assets/images/icons/button-key-hover.svg'; import secureTransactionHov from '@/assets/images/icons/button-key.svg'; import { ETH, GOERLI } from '@/networks/types'; const dapps = { registerDomain: { route: '/interface/dapps/register-domain', icon: registerDomain, iconDisabled: registerDomainHov, title: 'interface.registerEns', desc: 'interface.registerENSDescShort', supportedNetworks: [ETH.name, GOERLI.name] }, domainSale: { route: '/interface/dapps/buy-subdomain', icon: domainSale, iconDisabled: domainSaleHov, title: 'interface.subdomains', desc: 'interface.buySubDomains', supportedNetworks: [ETH.name] }, secureTransaction: { route: '/interface/dapps/secure-transaction', icon: secureTransaction, iconDisabled: secureTransactionHov, title: 'dapps.safesend_title', desc: 'dapps.safesend_desc', supportedNetworks: [ETH.name] } }; export default dapps;
import domainSale from '@/assets/images/icons/domain-sale.svg'; import domainSaleHov from '@/assets/images/icons/domain-sale-hov.svg'; import registerDomain from '@/assets/images/icons/domain.svg'; import registerDomainHov from '@/assets/images/icons/domain-hov.svg'; import secureTransaction from '@/assets/images/icons/button-key-hover.svg'; import secureTransactionHov from '@/assets/images/icons/button-key.svg'; import { ETH, GOERLI, ROP, RIN } from '@/networks/types'; const dapps = { registerDomain: { route: '/interface/dapps/register-domain', icon: registerDomain, iconDisabled: registerDomainHov, title: 'interface.registerEns', desc: 'interface.registerENSDescShort', supportedNetworks: [ETH.name, GOERLI.name, ROP.name, RIN.name] }, domainSale: { route: '/interface/dapps/buy-subdomain', icon: domainSale, iconDisabled: domainSaleHov, title: 'interface.subdomains', desc: 'interface.buySubDomains', supportedNetworks: [ETH.name] }, secureTransaction: { route: '/interface/dapps/secure-transaction', icon: secureTransaction, iconDisabled: secureTransactionHov, title: 'dapps.safesend_title', desc: 'dapps.safesend_desc', supportedNetworks: [ETH.name] } }; export default dapps;
Fix the marker bouncing function.
function initMap() { var map; var $business_object; var biz_loc_collection; var i; $business_object = $('#businesses').data('url'); biz_loc_collection = []; for (i = 0; i < $business_object.length; ++i) { biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}); } map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 47.6062, lng: -122.3321}, // center: should be the lat and long of leading biz zoom: 12 }); biz_loc_collection.forEach(addMarker); function addMarker(business){ var marker; marker = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, position: business }); marker.addListener('click', toggleBounce); } function toggleBounce() { var marker; marker = this; if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); setTimeout(function(){ marker.setAnimation(null); }, 750); } } }
function initMap() { var map; var $business_object; var biz_loc_collection; var i; $business_object = $('#businesses').data('url'); biz_loc_collection = []; for (i = 0; i < $business_object.length; ++i) { biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}); } map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 47.6062, lng: -122.3321}, // center: should be the lat and long of leading biz zoom: 12 }); for (i = 0; i < biz_loc_collection.length; ++i) { marker = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, position: biz_loc_collection[i] }); marker.addListener('click', toggleBounce); } function toggleBounce() { if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); } } }
Use 'future_or_past' for the Meetup API scroll parameter. Hopefully this will fix the issue of the blank Meetup section after the meetup begins.
(function($) { "use strict"; // Start of use strict var meetupEventsUrl = "https://api.meetup.com/Phoenix-Unreal-Engine-Developers/events?scroll=future_or_past&photo-host=public&page=1&sig_id=55074012&status=past%2Cupcoming&sig=b751e22a582e2309e5b03a0cd1a80466ef7e4fc3"; function populateMap(data) { var API_KEY = 'AIzaSyCJZJPBFj_dGqWruxfkQFEEis8jTf0eVNE'; var LOCATION = data.venue.address_1 + "," + data.venue.city + " " + data.venue.state; $('#meetup-map')[0].src = "https://www.google.com/maps/embed/v1/place?key="+API_KEY+"&q="+encodeURIComponent(LOCATION); $('#meetup-date').html(moment(data.time).calendar()); $('#meetup-venue').html(data.venue.name); $('#meetup-title').html(data.name); $('#meetup-link')[0].href = data.link; $('#meetup-details').html(data.description); } $.ajax({ dataType: 'jsonp', method: 'get', url: meetupEventsUrl, success: function(result) { populateMap(result.data['0']); } }); })(jQuery);
(function($) { "use strict"; // Start of use strict var meetupEventsUrl = "https://api.meetup.com/Phoenix-Unreal-Engine-Developers/events?scroll=next_upcoming&photo-host=public&page=1&sig_id=198889890&status=past%2Cupcoming&sig=fba37148ddce35c43bfcbed2979dbaa5804a5d9f"; function populateMap(data) { var API_KEY = 'AIzaSyCJZJPBFj_dGqWruxfkQFEEis8jTf0eVNE'; var LOCATION = data.venue.address_1 + "," + data.venue.city + " " + data.venue.state; $('#meetup-map')[0].src = "https://www.google.com/maps/embed/v1/place?key="+API_KEY+"&q="+encodeURIComponent(LOCATION); $('#meetup-date').html(moment(data.time).calendar()); $('#meetup-venue').html(data.venue.name); $('#meetup-title').html(data.name); $('#meetup-link')[0].href = data.link; $('#meetup-details').html(data.description); } $.ajax({ dataType: 'jsonp', method: 'get', url: meetupEventsUrl, success: function(result) { populateMap(result.data['0']); } }); })(jQuery);
Make sure the demo project is in the pythonpath
#!/usr/bin/env python import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) sys.path.insert(0, demo_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys from pathlib import Path if __name__ == "__main__": # We add ourselves into the python path, so we can find # the package later. demo_root =os.path.dirname(os.path.abspath(__file__)) crud_install = os.path.dirname(os.path.dirname(demo_root)) sys.path.insert(0, crud_install) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
Add some methods to the container for migration
package info.u_team.u_team_test.init; import info.u_team.u_team_core.containertype.UContainerType; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.container.*; import net.minecraft.inventory.container.ContainerType; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.registries.*; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestContainers { public static final DeferredRegister<ContainerType<?>> CONTAINER_TYPES = DeferredRegister.create(ForgeRegistries.CONTAINERS, TestMod.MODID); public static final ContainerType<BasicTileEntityContainer> BASIC = new UContainerType<>("basic", BasicTileEntityContainer::new); public static final ContainerType<BasicEnergyCreatorContainer> BASIC_ENERGY_CREATOR = new UContainerType<>("energy_creator", BasicEnergyCreatorContainer::new); public static final ContainerType<BasicFluidInventoryContainer> BASIC_FLUID_INVENTORY = new UContainerType<>("fluid_inventory", BasicFluidInventoryContainer::new); public static void register(IEventBus bus) { CONTAINER_TYPES.register(bus); } }
package info.u_team.u_team_test.init; import info.u_team.u_team_core.containertype.UContainerType; import info.u_team.u_team_core.util.registry.BaseRegistryUtil; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.container.*; import net.minecraft.inventory.container.ContainerType; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestContainers { public static final ContainerType<BasicTileEntityContainer> BASIC = new UContainerType<>("basic", BasicTileEntityContainer::new); public static final ContainerType<BasicEnergyCreatorContainer> BASIC_ENERGY_CREATOR = new UContainerType<>("energy_creator", BasicEnergyCreatorContainer::new); public static final ContainerType<BasicFluidInventoryContainer> BASIC_FLUID_INVENTORY = new UContainerType<>("fluid_inventory", BasicFluidInventoryContainer::new); @SubscribeEvent public static void register(Register<ContainerType<?>> event) { BaseRegistryUtil.getAllGenericRegistryEntriesAndApplyNames(TestMod.MODID, ContainerType.class).forEach(event.getRegistry()::register); } }
Add url callback on custom login
#!/usr/bin/env python # -*- coding: utf-8 -*- from bottle.ext import auth from utils import conf try: auth_import = conf('auth')['engine'].split('.')[-1] auth_from = u".".join(conf('auth')['engine'].split('.')[:-1]) auth_engine = getattr(__import__(auth_from, fromlist=[auth_import]), auth_import) except: print 'Set valid auth engine' exit(0) callback = u"{}://{}".format( conf('openmining')['protocol'], conf('openmining')['domain']) if conf('openmining')['domain_port'] not in ['80', '443']: callback = "{}:{}".format(callback, conf('openmining')['domain_port']) if auth_import == 'Google': engine = auth_engine( conf('auth')['key'], conf('auth')['secret'], callback) elif auth_import == 'Facebook': # Not working requered parans engine = auth_engine() elif auth_import == 'Twitter': # Not working requered parans engine = auth_engine() else: engine = auth_engine(callback_url=callback) auth = auth.AuthPlugin(engine)
#!/usr/bin/env python # -*- coding: utf-8 -*- from bottle.ext import auth from utils import conf try: auth_import = conf('auth')['engine'].split('.')[-1] auth_from = u".".join(conf('auth')['engine'].split('.')[:-1]) auth_engine = getattr(__import__(auth_from, fromlist=[auth_import]), auth_import) except: print 'Set valid auth engine' exit(0) callback = u"{}://{}".format( conf('openmining')['protocol'], conf('openmining')['domain']) if conf('openmining')['domain_port'] not in ['80', '443']: callback = "{}:{}".format(callback, conf('openmining')['domain_port']) if auth_import == 'Google': engine = auth_engine( conf('auth')['key'], conf('auth')['secret'], callback) elif auth_import == 'Facebook': # Not working requered parans engine = auth_engine() elif auth_import == 'Twitter': # Not working requered parans engine = auth_engine() else: engine = auth_engine() auth = auth.AuthPlugin(engine)
Fix start/watch issues for server
'use strict'; var argv = require('yargs').argv; var path = require('path'); module.exports = function(gulp, plugins, config) { return function() { function getSources(root, filter) { if (root instanceof Array) { return root.map(function(item) { return item + filter; }) } return root + filter }; function watch(source) { gulp.watch(getSources(source + "/**/", "*.*"), [ 'build-internal-scripts-server', 'build-server-server' ]); }; if (!argv.production) { if (config.source instanceof Array) { config.source.forEach(function(item) { watch(item); }); } else { watch(config.source); } } }; };
'use strict'; var argv = require('yargs').argv; var path = require('path'); module.exports = function(gulp, plugins, config) { return function() { function getSources(root, filter) { if (root instanceof Array) { return root.map(function(item) { return item + filter; }) } return root + filter }; function watch(source) { gulp.watch(getSources(source + "/**/*.*"), ['build-server-server']); }; if (!argv.production) { if (config.source instanceof Array) { config.source.forEach(function(item) { watch(item); }); } else { watch(config.source); } } }; };
Add log and remove isProduction
// Description: // for initialize // "use strict"; const config = require("config"); const Raven = require('raven'); // TODO wrapper function sentryIsSet() { return config.sentry !== null; } module.exports = function(robot) { robot.logger.info(`node env: ${process.env.NODE_ENV}`); robot.logger.info(`server port: ${process.env.PORT}`); if (sentryIsSet()) { Raven.config(config.sentry).install(); robot.logger.info(`sentry installed`); } robot.error((err, res) => { robot.logger.error(`Error: ${err}`); robot.logger.error(`res: ${res}`); res && res.reply(err); if (sentryIsSet()) { Raven.captureException(err); } }); };
// Description: // for initialize // "use strict"; const config = require("config"); const Raven = require('raven'); // TODO wrapper function isProduction() { return process.env.NODE_ENV === 'production'; } function sentryIsSet() { return config.sentry !== null; } module.exports = function(robot) { robot.logger.info(`node env: ${process.env.NODE_ENV}`); robot.logger.info(`server port: ${process.env.PORT}`); if (sentryIsSet()) { Raven.config(config.sentry).install(); } robot.error((err, res) => { robot.logger.error(`Error: ${err}`); robot.logger.error(`res: ${res}`); res && res.reply(err); if (sentryIsSet()) { Raven.captureException(err); } }); };
Remove unused github api instance
require('dotenv').config({silent: true}); const process = require('process'); const http = require('http'); const createHandler = require('github-webhook-handler'); const Configuration = require('./lib/configuration'); const Dispatcher = require('./lib/dispatcher'); const installations = require('./lib/installations'); const PORT = process.env.PORT || 3000; const webhook = createHandler({path: '/', secret: process.env.WEBHOOK_SECRET || 'development'}); // Cache installations installations.load(); // Listen for new installations installations.listen(webhook); http.createServer((req, res) => { webhook(req, res, err => { if (err) { console.log('ERROR', err); res.statusCode = 500; res.end('Something has gone terribly wrong.'); } else { res.statusCode = 404; res.end('no such location'); } }); }).listen(PORT); webhook.on('*', event => { if (event.payload.repository) { const installation = installations.for(event.payload.repository.owner.login); installations.authAs(installation).then(github => { const dispatcher = new Dispatcher(github, event); return Configuration.load(github, event.payload.repository).then(config => { dispatcher.call(config); }); }); } }); console.log('Listening on http://localhost:' + PORT);
require('dotenv').config({silent: true}); const process = require('process'); const http = require('http'); const createHandler = require('github-webhook-handler'); const GitHubApi = require('github'); const Configuration = require('./lib/configuration'); const Dispatcher = require('./lib/dispatcher'); const installations = require('./lib/installations'); const PORT = process.env.PORT || 3000; const webhook = createHandler({path: '/', secret: process.env.WEBHOOK_SECRET || 'development'}); // Cache installations installations.load(); // Listen for new installations installations.listen(webhook); const github = new GitHubApi({ debug: true }); github.authenticate({ type: 'oauth', token: process.env.GITHUB_TOKEN }); http.createServer((req, res) => { webhook(req, res, err => { if (err) { console.log('ERROR', err); res.statusCode = 500; res.end('Something has gone terribly wrong.'); } else { res.statusCode = 404; res.end('no such location'); } }); }).listen(PORT); webhook.on('*', event => { if (event.payload.repository) { const installation = installations.for(event.payload.repository.owner.login); installations.authAs(installation).then(github => { const dispatcher = new Dispatcher(github, event); return Configuration.load(github, event.payload.repository).then(config => { dispatcher.call(config); }); }); } }); console.log('Listening on http://localhost:' + PORT);
Allow other middleware by calling `cb()`
'use strict'; var assign = require('object-assign'); var chalk = require('chalk'); var ProgressBar = require('progress'); /** * Progress bar download plugin * * @param {Object} res * @api public */ module.exports = function (opts) { return function (res, file, cb) { opts = opts || { info: 'cyan' }; var msg = chalk[opts.info](' downloading') + ' : ' + file.url; var info = chalk[opts.info](' progress') + ' : [:bar] :percent :etas'; var len = parseInt(res.headers['content-length'], 10); var bar = new ProgressBar(info, assign({ complete: '=', incomplete: ' ', width: 20, total: len }, opts)); console.log(msg); res.on('data', function (data) { bar.tick(data.length); }); res.on('end', function () { console.log('\n'); cb(); }); }; };
'use strict'; var assign = require('object-assign'); var chalk = require('chalk'); var ProgressBar = require('progress'); /** * Progress bar download plugin * * @param {Object} res * @api public */ module.exports = function (opts) { return function (res, file) { opts = opts || { info: 'cyan' }; var msg = chalk[opts.info](' downloading') + ' : ' + file.url; var info = chalk[opts.info](' progress') + ' : [:bar] :percent :etas'; var len = parseInt(res.headers['content-length'], 10); var bar = new ProgressBar(info, assign({ complete: '=', incomplete: ' ', width: 20, total: len }, opts)); console.log(msg); res.on('data', function (data) { bar.tick(data.length); }); res.on('end', function () { console.log('\n'); }); }; };
Fix typo on output name, add module concat plugin.
const path = require('path') const webpack = require('webpack') module.exports = { context: __dirname, entry: './src/index.js', devtool: 'source-map', output: { library: 'es2015-starter', libraryTarget: 'umd', path: path.resolve('dist'), filename: 'es2015-starter.js', }, resolve: { extensions: ['.js'], modules: [ path.resolve('node_modules'), path.resolve('src'), ], }, plugins: [ new webpack.optimize.ModuleConcatenationPlugin(), ], module: { loaders: [ { use: ['babel-loader'], test: /\.js$/, exclude: [path.resolve('node_modules')], }, { use: 'file-loader', test: /.*/, exclude: [/\.js$/], }, ], }, watchOptions: { ignored: /node_modules/, }, devServer: { port: 3030, contentBase: path.resolve('src'), stats: 'errors-only', overlay: { warnings: true, errors: true, }, }, }
const path = require('path') module.exports = { context: __dirname, entry: './src/index.js', devtool: 'source-map', output: { library: 'es2016-starter', libraryTarget: 'umd', path: path.resolve('dist'), filename: 'es2015-starter.js', }, resolve: { extensions: ['.js'], modules: [ path.resolve('node_modules'), path.resolve('src'), ], }, module: { loaders: [ { use: ['babel-loader'], test: /\.js$/, exclude: [path.resolve('node_modules')], }, { use: 'file-loader', test: /.*/, exclude: [/\.js$/], }, ], }, watchOptions: { ignored: /node_modules/, }, devServer: { port: 3030, contentBase: path.resolve('src'), stats: 'errors-only', overlay: { warnings: true, errors: true, }, }, }
Use the update function's time argument in the spinning example and cleanup code.
var Gesso = require('gesso'); var fillRotatedRect = require('./helpers').fillRotatedRect; // Create the game object var game = new Gesso(); // We'll use closures for game variables var angle = 0; // This gets called every frame. // Update your game state here. game.update(function (t) { // Calculate one rotation per second, in radians angle = (2 * Math.PI / 60) * t; }); // This gets called at least once per frame. You can call // Gesso.renderTo(target) to render the game to another canvas. game.render(function (ctx) { // Clear the canvas ctx.clearRect(0, 0, game.width, game.height); // Draw a red box, rotating four times per second ctx.fillStyle = '#f34'; fillRotatedRect(ctx, 50, 100, 200, 20, angle); // Draw a green box, fully rotating every two seconds ctx.fillStyle = '#cf8'; fillRotatedRect(ctx, 400, 50, 200, 150, -angle / 8); // Draw a blue box, fully rotating two times per second ctx.fillStyle = '#3cf'; fillRotatedRect(ctx, 200, 250, 200, 200, angle * 0.5); }); // Run the game game.run();
var Gesso = require('gesso'); var fillRotatedRect = require('./helpers').fillRotatedRect; // Create the game object var game = new Gesso(); // We'll use closures for game variables var seconds = 0; // This gets called every frame. Update your game state here. game.update(function () { // Calculate the time passed, based on 60 frames per second seconds += 1 / 60; }); // This gets called at least once per frame. You can call // Gesso.renderTo(target) to render the game to another canvas. game.render(function (ctx) { // Calculate one rotation per second var angle = seconds * (Math.PI / 2); // Clear the canvas ctx.clearRect(0, 0, game.width, game.height); // Draw a red box, rotating four times per second ctx.fillStyle = '#f34'; fillRotatedRect(ctx, 50, 100, 200, 20, angle * 4); // Draw a green box, fully rotating every two seconds ctx.fillStyle = '#cf8'; fillRotatedRect(ctx, 400, 50, 200, 150, -angle / 2); // Draw a blue box, fully rotating two times per second ctx.fillStyle = '#3cf'; fillRotatedRect(ctx, 200, 250, 200, 200, angle * 2); }); // Run the game game.run();
Remove "x-powered-by" header (for security)
/** server The backbone of the server module. In development, this runs proxied through BrowserSync server. @param {Object} options Options passed on to "globals" @param {Function} next Called when server successfully initialized **/ var reorg = require("reorg"); module.exports = reorg(function(options, next) { // Globals require("./globals")(options); var server = global.shipp.framework({ strict: true }), middleware = require("./middleware"), Utils = require("./utils"); // Remove powered-by header for security server.disable("x-powered-by"); [ // User-defined middleware middleware("beforeAll"), // Common middleware: logging, favicons, cookie parsing, sessions and body parsing require("./common")(), // User-defined middleware middleware("beforeRoutes"), // Static and compiled routes require("./routes")(), // Data-server require("./data-server")(), // User-defined middleware middleware("afterRoutes") ].forEach(function(library) { Utils.useMiddleware(server, library); }); // Error handling: please see errors middleware for explanation of structure require("./errors")(server, middleware("errorHandler")); // Find open port and set up graceful shutdown require("./lifecycle")(server, next); }, "object", ["function", function() {}]);
/** server The backbone of the server module. In development, this runs proxied through BrowserSync server. @param {Object} options Options passed on to "globals" @param {Function} next Called when server successfully initialized **/ var reorg = require("reorg"); module.exports = reorg(function(options, next) { // Globals require("./globals")(options); var server = global.shipp.framework({ strict: true }), middleware = require("./middleware"), Utils = require("./utils"); [ // User-defined middleware middleware("beforeAll"), // Common middleware: logging, favicons, cookie parsing, sessions and body parsing require("./common")(), // User-defined middleware middleware("beforeRoutes"), // Static and compiled routes require("./routes")(), // Data-server require("./data-server")(), // User-defined middleware middleware("afterRoutes") ].forEach(function(library) { Utils.useMiddleware(server, library); }); // Error handling: please see errors middleware for explanation of structure require("./errors")(server, middleware("errorHandler")); // Find open port and set up graceful shutdown require("./lifecycle")(server, next); }, "object", ["function", function() {}]);
Remove markup-accepting signature of Document
'use strict'; var util = require('util'); var Node = require('./node'); var Element = require('./nodes/element'); var makeElement = require('./nodes/make-element'); function Document(options) { Node.call(this, { tagName: 'html', nodeType: 9, parseOptions: options }); this.documentElement = new Element({ tagName: 'html', ownerDocument: this, parseOptions: options }); this.defaultView = options && options.defaultView || null; this.childNodes = [this.documentElement]; } util.inherits(Document, Element); Document.prototype.write = function(content) { this.documentElement.innerHTML = content; }; Document.prototype.createDocumentFragment = function() { return new Node({ nodeType: 11, ownerDocument: this }); }; Document.prototype.createElement = function(nodeName) { return makeElement({ nodeName: nodeName, ownerDocument: this }); }; Document.prototype.createTextNode = function(data) { if (arguments.length === 0) { throw new Error('Document#createTextNode: not enough arguments.'); } return new Node({ nodeType: 3, ownerDocument: this, data: data }); }; module.exports = Document;
'use strict'; var util = require('util'); var Node = require('./node'); var Element = require('./nodes/element'); var makeElement = require('./nodes/make-element'); function Document(markup, options) { if (typeof markup !== 'string') { options = markup; markup = null; } Node.call(this, { tagName: 'html', nodeType: 9, parseOptions: options }); this.documentElement = new Element({ tagName: 'html', ownerDocument: this, parseOptions: options }); this.defaultView = options && options.defaultView || null; this.childNodes = [this.documentElement]; if (markup) { this.documentElement.innerHTML = markup; } } util.inherits(Document, Element); Document.prototype.write = function(content) { this.documentElement.innerHTML = content; }; Document.prototype.createDocumentFragment = function() { return new Node({ nodeType: 11, ownerDocument: this }); }; Document.prototype.createElement = function(nodeName) { return makeElement({ nodeName: nodeName, ownerDocument: this }); }; Document.prototype.createTextNode = function(data) { if (arguments.length === 0) { throw new Error('Document#createTextNode: not enough arguments.'); } return new Node({ nodeType: 3, ownerDocument: this, data: data }); }; module.exports = Document;
Add top offset to prevent top bar from cropping the top stack
'use strict' const fg = require('d3-fg') const render = require('nanohtml') const morphdom = require('morphdom') const debounce = require('debounce') const createActions = require('./actions') const createState = require('./state') const graph = require('./cmp/graph')(render) const ui = require('./cmp/ui')(render) module.exports = function (trees, opts) { opts = opts || {} const { kernelTracing } = opts const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init']) const chart = graph() const tree = trees.unmerged // default view const categorizer = !kernelTracing && graph.v8cats const flamegraph = fg({ categorizer, tree, exclude: Array.from(exclude), element: chart, topOffset: 55 }) const { colors } = flamegraph window.addEventListener('resize', debounce(() => { const width = document.body.clientWidth * 0.89 flamegraph.width(width).update() chart.querySelector('svg').setAttribute('width', width) }, 150)) const state = createState({colors, trees, exclude, kernelTracing, title: opts.title}) const actions = createActions({flamegraph, state}, (state) => { morphdom(iface, ui({state, actions})) }) const iface = ui({state, actions}) document.body.appendChild(chart) document.body.appendChild(iface) }
'use strict' const fg = require('d3-fg') const render = require('nanohtml') const morphdom = require('morphdom') const debounce = require('debounce') const createActions = require('./actions') const createState = require('./state') const graph = require('./cmp/graph')(render) const ui = require('./cmp/ui')(render) module.exports = function (trees, opts) { opts = opts || {} const { kernelTracing } = opts const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init']) const chart = graph() const tree = trees.unmerged // default view const categorizer = !kernelTracing && graph.v8cats const flamegraph = fg({ categorizer, tree, exclude: Array.from(exclude), element: chart }) const { colors } = flamegraph window.addEventListener('resize', debounce(() => { const width = document.body.clientWidth * 0.89 flamegraph.width(width).update() chart.querySelector('svg').setAttribute('width', width) }, 150)) const state = createState({colors, trees, exclude, kernelTracing, title: opts.title}) const actions = createActions({flamegraph, state}, (state) => { morphdom(iface, ui({state, actions})) }) const iface = ui({state, actions}) document.body.appendChild(chart) document.body.appendChild(iface) }
Undo accidental version bump caused by Makefile
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='Flask-RESTful', version='0.1.7', url='https://www.github.com/twilio/flask-restful/', author='Kyle Conroy', author_email='kyle@twilio.com', description='Simple framework for creating REST APIs', packages=find_packages(), zip_safe=False, include_package_data=True, platforms='any', test_suite = 'nose.collector', setup_requires=[ 'nose>=1.1.2', 'mock>=0.8', ], install_requires=[ 'Flask>=0.8', 'pycrypto>=2.6', ] )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='Flask-RESTful', version='0.1.8', url='https://www.github.com/twilio/flask-restful/', author='Kyle Conroy', author_email='kyle@twilio.com', description='Simple framework for creating REST APIs', packages=find_packages(), zip_safe=False, include_package_data=True, platforms='any', test_suite = 'nose.collector', setup_requires=[ 'nose>=1.1.2', 'mock>=0.8', ], install_requires=[ 'Flask>=0.8', 'pycrypto>=2.6', ] )
Add correct syntax for environment variable
import csv import re import os from elasticsearch import Elasticsearch es = Elasticsearch({'host': os.environ['ELASTICSEARCH_URL']}) with open('data/ParcelCentroids.csv', 'r') as csvfile: print "open file" csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',') current_row = 0 for row in csv_reader: current_row += 1 if current_row == 1: csv_reader.fieldnames = row['undefined-fieldnames'] continue address = row if re.match('\d+', address['PVANUM']): es.index(index='addresses', doc_type='address', id=address['PVANUM'], body={'PVANUM': address['PVANUM'], 'NUM1': address['NUM1'], 'NAME': address['NAME'], 'TYPE': address['TYPE'], 'ADDRESS': address['ADDRESS'], 'UNIT': address['UNIT'], 'X': address['X'], 'Y': address['Y']}) csvfile.close()
import csv import re from elasticsearch import Elasticsearch es = Elasticsearch({'host': ELASTICSEARCH_URL}) with open('data/ParcelCentroids.csv', 'r') as csvfile: print "open file" csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',') current_row = 0 for row in csv_reader: current_row += 1 if current_row == 1: csv_reader.fieldnames = row['undefined-fieldnames'] continue address = row if re.match('\d+', address['PVANUM']): es.index(index='addresses', doc_type='address', id=address['PVANUM'], body={'PVANUM': address['PVANUM'], 'NUM1': address['NUM1'], 'NAME': address['NAME'], 'TYPE': address['TYPE'], 'ADDRESS': address['ADDRESS'], 'UNIT': address['UNIT'], 'X': address['X'], 'Y': address['Y']}) csvfile.close()
Send button disabled as long as there is no message
import React from 'react' import PropTypes from 'prop-types' /* Component with a state */ export default class AddChatMessage extends React.Component { constructor(props) { super(props) this.state = {message: ''} } onChangeMessage = (e) => { this.setState({message: e.target.value}) } onSendCick = () => { this.props.onClick({message: this.state.message}) this.setState({message:''}) this.textInput.focus() } handleKeyPress = (e) => { if (e.key === 'Enter'){ e.preventDefault() this.onSendCick() return false } } render() { return ( <div> <textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/> <button onClick={this.onSendCick} disabled={(this.state.message.trim()=='')}>Send</button> </div> ) } } AddChatMessage.propTypes = { onClick: PropTypes.func }
import React from 'react' import PropTypes from 'prop-types' /* Component with a state */ export default class AddChatMessage extends React.Component { constructor(props) { super(props) this.state = {message: ''} } onChangeMessage = (e) => { this.setState({message: e.target.value}) } onSendCick = () => { this.props.onClick({message: this.state.message}) this.setState({message:''}) this.textInput.focus() } handleKeyPress = (e) => { if (e.key === 'Enter'){ e.preventDefault() this.onSendCick() return false } } render() { return ( <div> <textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/> <button onClick={this.onSendCick}>Send</button> </div> ) } } AddChatMessage.propTypes = { onClick: PropTypes.func }
Remove duplicated slash in virus_scan
from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse from django.core.signing import TimestampSigner class BaseEngine: def __init__(self): self.signer = TimestampSigner() def get_webhook_url(self): return "{}://{}{}?token={}".format( "https", get_current_site(None).domain, reverse("virus_scan:webhook"), self.signer.sign(self.name), ) def send_scan(self, this_file, filename): raise NotImplementedError( "Provide 'send' in {name}".format(name=self.__class__.__name__) ) def receive_scan(self, engine_id): raise NotImplementedError( "Provide 'receive_scan' in {name}".format(name=self.__class__.__name__) )
from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse from django.core.signing import TimestampSigner class BaseEngine: def __init__(self): self.signer = TimestampSigner() def get_webhook_url(self): return "{}://{}/{}?token={}".format( "https", get_current_site(None).domain, reverse("virus_scan:webhook"), self.signer.sign(self.name), ) def send_scan(self, this_file, filename): raise NotImplementedError( "Provide 'send' in {name}".format(name=self.__class__.__name__) ) def receive_scan(self, engine_id): raise NotImplementedError( "Provide 'receive_scan' in {name}".format(name=self.__class__.__name__) )
Check if participant exists when tracking pixel is requested
<?php namespace Intracto\SecretSantaBundle\Controller; use Intracto\SecretSantaBundle\Response\TransparentPixelResponse; use Intracto\SecretSantaBundle\Entity\Participant; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpKernel\Event\KernelEvent; use Symfony\Component\HttpKernel\KernelEvents; class TrackingController extends Controller { /** * @Route("email/{participantId}.gif", name="mailopen_tracker") */ public function trackEmailAction($participantId) { $dispatcher = $this->get('event_dispatcher'); $dispatcher->addListener(KernelEvents::TERMINATE, function (KernelEvent $event) use ($participantId) { /** @var Participant $participant */ $participant = $this->get('intracto_secret_santa.repository.participant')->find($participantId); if ($participant != null) { $participant->setOpenEmailDate(new \DateTime()); $this->get('doctrine.orm.default_entity_manager')->flush($participant); } } ); return new TransparentPixelResponse(); } }
<?php namespace Intracto\SecretSantaBundle\Controller; use Intracto\SecretSantaBundle\Response\TransparentPixelResponse; use Intracto\SecretSantaBundle\Entity\Participant; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpKernel\Event\KernelEvent; use Symfony\Component\HttpKernel\KernelEvents; class TrackingController extends Controller { /** * @Route("email/{participantId}.gif", name="mailopen_tracker") */ public function trackEmailAction($participantId) { $dispatcher = $this->get('event_dispatcher'); $dispatcher->addListener(KernelEvents::TERMINATE, function (KernelEvent $event) use ($participantId) { /**@var Participant $participant*/ $participant = $this->get('intracto_secret_santa.repository.participant')->find($participantId); $participant->setOpenEmailDate(new \DateTime()); $this->get('doctrine.orm.default_entity_manager')->flush($participant); } ); return new TransparentPixelResponse(); } }
Revert "For removing the FlagShip section in the shipping settings tab, avoid hardcoding the FlagShip shipping method id." This reverts commit 1ca4ad0917decb824fc7ea3dc7cb1d27b5612738.
<?php namespace FS\Components\Event\Listener; use FS\Injection\I; use FS\Components\AbstractComponent; use FS\Context\ApplicationListenerInterface; use FS\Components\Event\NativeHookInterface; use FS\Context\ConfigurableApplicationContextInterface as Context; use FS\Context\ApplicationEventInterface as Event; use FS\Components\Event\ApplicationEvent; class GetSectionsShipping extends AbstractComponent implements ApplicationListenerInterface, NativeHookInterface { public function getSupportedEvent() { return ApplicationEvent::GET_SECTIONS_SHIPPING; } public function onApplicationEvent(Event $event, Context $context) { $sections = $event->getInput('sections'); unset($sections['flagship_shipping_method']); return $sections; } public function publishNativeHook(Context $context) { \add_filter('woocommerce_get_sections_shipping', function ($sections) use ($context) { $event = new ApplicationEvent(ApplicationEvent::GET_SECTIONS_SHIPPING); $event->setInputs(array( 'sections' => $sections, )); return $context->publishEvent($event); }, 10, 1); } public function getNativeHookType() { return self::TYPE_FILTER; } }
<?php namespace FS\Components\Event\Listener; use FS\Components\AbstractComponent; use FS\Context\ApplicationListenerInterface; use FS\Components\Event\NativeHookInterface; use FS\Context\ConfigurableApplicationContextInterface as Context; use FS\Context\ApplicationEventInterface as Event; use FS\Components\Event\ApplicationEvent; class GetSectionsShipping extends AbstractComponent implements ApplicationListenerInterface, NativeHookInterface { public function getSupportedEvent() { return ApplicationEvent::GET_SECTIONS_SHIPPING; } public function onApplicationEvent(Event $event, Context $context) { //Since on woocommerce3.0.x, settings are for each shipping zone, the global settings for FlagShip method will not be displayed. $sections = $event->getInput('sections'); unset($sections[$context->setting('FLAGSHIP_SHIPPING_PLUGIN_ID')]); return $sections; } public function publishNativeHook(Context $context) { \add_filter('woocommerce_get_sections_shipping', function ($sections) use ($context) { $event = new ApplicationEvent(ApplicationEvent::GET_SECTIONS_SHIPPING); $event->setInputs(array( 'sections' => $sections, )); return $context->publishEvent($event); }, 10, 1); } public function getNativeHookType() { return self::TYPE_FILTER; } }
Move component actions to the bottom of the file
import Ember from 'ember'; const { computed, defineProperty } = Ember; export default Ember.Component.extend({ classNames: ['f-default__row'], model: null, type: 'text', placeholder: '', value: null, valuePath: '', validation: null, isTyping: false, notValidating: computed.not('validation.isValidating'), didValidate: computed.oneWay('targetObject.didValidate'), hasContent: computed.notEmpty('value'), isValid: computed.oneWay('validation.isValid'), isInvalid: computed.oneWay('validation.isInvalid'), showMessage: computed('validation.isDirty', 'didValidate', 'isInvalid', function() { return (this.get('validation.isDirty') || this.get('didValidate') && this.get('isInvalid')); }), init() { var valuePath = this.get('valuePath'); // eslint-disable-line this._super(...arguments); // eslint-disable-line prefer-rest-params defineProperty(this, 'validation', computed.oneWay(`model.validations.attrs.${valuePath}`)); defineProperty(this, 'value', computed.alias(`model.${valuePath}`)); }, actions: { validateField() { this.get('model').validate({ on: this.get('valuePath') }); } } });
import Ember from 'ember'; const { computed, defineProperty } = Ember; export default Ember.Component.extend({ classNames: ['f-default__row'], model: null, type: 'text', placeholder: '', value: null, valuePath: '', validation: null, isTyping: false, init() { var valuePath = this.get('valuePath'); // eslint-disable-line this._super(...arguments); // eslint-disable-line prefer-rest-params defineProperty(this, 'validation', computed.oneWay(`model.validations.attrs.${valuePath}`)); defineProperty(this, 'value', computed.alias(`model.${valuePath}`)); }, actions: { validateField() { this.get('model').validate({ on: this.get('valuePath') }); } }, notValidating: computed.not('validation.isValidating'), didValidate: computed.oneWay('targetObject.didValidate'), hasContent: computed.notEmpty('value'), isValid: computed.oneWay('validation.isValid'), isInvalid: computed.oneWay('validation.isInvalid'), showMessage: computed('validation.isDirty', 'didValidate', 'isInvalid', function() { return (this.get('validation.isDirty') || this.get('didValidate') && this.get('isInvalid')); }) });
Add useful constructor to range filter
<?php /** * Range Filter * * @uses Elastica_Filter_Abstract * @category Xodoa * @package Elastica * @author Nicolas Ruflin <spam@ruflin.com> * @link http://www.elasticsearch.org/guide/reference/query-dsl/range-filter.html */ class Elastica_Filter_Range extends Elastica_Filter_Abstract { protected $_fields = array(); /** * @param string $fieldName Field name * @param array $args Field arguments * @return Elastica_Filter_Range */ public function __construct($fieldName = false, array $args = array()) { if ($fieldName) { $this->addField($fieldName, $args); } } /** * Ads a field with arguments to the range query * * @param string $fieldName Field name * @param array $args Field arguments * @return Elastica_Filter_Range */ public function addField($fieldName, array $args) { $this->_fields[$fieldName] = $args; return $this; } /** * Convers object to array * * @see Elastica_Filter_Abstract::toArray() * @return array Filter array */ public function toArray() { $this->setParams($this->_fields); return parent::toArray(); } }
<?php /** * Range Filter * * @uses Elastica_Filter_Abstract * @category Xodoa * @package Elastica * @author Nicolas Ruflin <spam@ruflin.com> * @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/range_query/ */ class Elastica_Filter_Range extends Elastica_Filter_Abstract { protected $_fields = array(); /** * Ads a field with arguments to the range query * * @param string $fieldName Field name * @param array $args Field arguments * @return Elastica_Filter_Range */ public function addField($fieldName, array $args) { $this->_fields[$fieldName] = $args; return $this; } /** * Convers object to array * * @see Elastica_Filter_Abstract::toArray() * @return array Filter array */ public function toArray() { $this->setParams($this->_fields); return parent::toArray(); } }
Send "no such channel" message on NAMES with a nonexistent channel
from twisted.words.protocols import irc from txircd.modbase import Command class NamesCommand(Command): def onUse(self, user, data): for chan in data["targetchan"]: user.report_names(chan) def processParams(self, user, params): if user.registered > 0: user.sendMessage(irc.ERR_NOTREGISTERED, "NAMES", ":You have not registered") return {} if params: channels = params[0].split(",") else: channels = user.channels.keys() chan_param = [] for chan in channels: if chan in self.ircd.channels: chan_param.append(self.ircd.channels[chan]) else: user.sendMessage(irc.ERR_NOSUCHNICK, chan, ":No such nick/channel") return { "user": user, "targetchan": chan_param } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "NAMES": NamesCommand() } } def cleanup(self): del self.ircd.commands["NAMES"]
from twisted.words.protocols import irc from txircd.modbase import Command class NamesCommand(Command): def onUse(self, user, data): for chan in data["targetchan"]: user.report_names(chan) def processParams(self, user, params): if user.registered > 0: user.sendMessage(irc.ERR_NOTREGISTERED, "NAMES", ":You have not registered") return {} if params: channels = filter(lambda x: x in user.channels and x in self.ircd.channels, params[0].split(",")) else: channels = user.channels.keys() chan_param = [] for chan in channels: if chan in self.ircd.channels: chan_param.append(self.ircd.channels[chan]) return { "user": user, "targetchan": chan_param } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "NAMES": NamesCommand() } } def cleanup(self): del self.ircd.commands["NAMES"]
Fix migration 211 to handle lack of data.
""" All the forum canned responses are stored in KB articles. There is a category for them now. Luckily they follow a simple pattern of slugs, so they are easy to find. This could have been an SQL migration, but I'm lazy and prefer Python. """ from django.conf import settings from wiki.models import Document from wiki.config import CANNED_RESPONSES_CATEGORY to_move = list(Document.objects.filter(slug__startswith='forum-response-', locale=settings.WIKI_DEFAULT_LANGUAGE)) try: to_move.append(Document.objects.get(slug='common-forum-responses', locale=settings.WIKI_DEFAULT_LANGUAGE)) except Document.DoesNotExist: pass print 'Recategorizing %d common response articles.' % len(to_move) for doc in to_move: doc.category = CANNED_RESPONSES_CATEGORY doc.is_localizable = True doc.save()
""" All the forum canned responses are stored in KB articles. There is a category for them now. Luckily they follow a simple pattern of slugs, so they are easy to find. This could have been an SQL migration, but I'm lazy and prefer Python. """ from django.conf import settings from wiki.models import Document from wiki.config import CANNED_RESPONSES_CATEGORY to_move = list(Document.objects.filter(slug__startswith='forum-response-', locale=settings.WIKI_DEFAULT_LANGUAGE)) to_move.append(Document.objects.get(slug='common-forum-responses', locale=settings.WIKI_DEFAULT_LANGUAGE)) print 'Recategorizing %d common response articles.' % len(to_move) for doc in to_move: doc.category = CANNED_RESPONSES_CATEGORY doc.is_localizable = True doc.save()
Update AWS::FMS::Policy per 2020-06-18 changes
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSProperty, AWSObject, Tags from .validators import json_checker, boolean class IEMap(AWSProperty): props = { 'ACCOUNT': ([basestring], False), 'ORGUNIT': ([basestring], False), } class Policy(AWSObject): resource_type = "AWS::FMS::Policy" props = { 'DeleteAllPolicyResources': (boolean, False), 'ExcludeMap': (IEMap, False), 'ExcludeResourceTags': (boolean, True), 'IncludeMap': (IEMap, False), 'PolicyName': (basestring, True), 'RemediationEnabled': (boolean, True), 'ResourceTags': (Tags, False), 'ResourceType': (basestring, True), 'ResourceTypeList': ([basestring], True), 'SecurityServicePolicyData': (json_checker, True), 'Tags': (Tags, False), } class NotificationChannel(AWSObject): resource_type = "AWS::FMS::NotificationChannel" props = { 'SnsRoleName': (basestring, True), 'SnsTopicArn': (basestring, True), }
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSProperty, AWSObject, Tags from .validators import json_checker, boolean class IEMap(AWSProperty): props = { 'ACCOUNT': ([basestring], False), } class Policy(AWSObject): resource_type = "AWS::FMS::Policy" props = { 'DeleteAllPolicyResources': (boolean, False), 'ExcludeMap': (IEMap, False), 'ExcludeResourceTags': (boolean, True), 'IncludeMap': (IEMap, False), 'PolicyName': (basestring, True), 'RemediationEnabled': (boolean, True), 'ResourceTags': (Tags, False), 'ResourceType': (basestring, True), 'ResourceTypeList': ([basestring], True), 'SecurityServicePolicyData': (json_checker, True), 'Tags': (Tags, False), } class NotificationChannel(AWSObject): resource_type = "AWS::FMS::NotificationChannel" props = { 'SnsRoleName': (basestring, True), 'SnsTopicArn': (basestring, True), }
Allow modify experiment status via REST API.
from django.contrib.auth.models import User, Group from rest_framework import serializers from damis.models import Dataset, Algorithm, Experiment class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class DatasetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dataset fields = ('title', 'licence', 'description', 'author', 'created', 'file', 'file_format') class AlgorithmSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Algorithm fields = ('title', 'user', 'file', 'executable_file', 'created', 'updated') class ExperimentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Experiment fields = ('title', 'start', 'finish', 'user', 'status')
from django.contrib.auth.models import User, Group from rest_framework import serializers from damis.models import Dataset, Algorithm, Experiment class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class DatasetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dataset fields = ('title', 'licence', 'description', 'author', 'created', 'file', 'file_format') class AlgorithmSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Algorithm fields = ('title', 'user', 'file', 'executable_file', 'created', 'updated') class ExperimentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Experiment fields = ('title', 'start', 'finish', 'user')
Use STATIC_DRAW as default WebGL buffer usage
/** * @module ol/webgl/Buffer */ import _ol_webgl_ from '../webgl.js'; /** * @enum {number} */ const BufferUsage = { STATIC_DRAW: _ol_webgl_.STATIC_DRAW, STREAM_DRAW: _ol_webgl_.STREAM_DRAW, DYNAMIC_DRAW: _ol_webgl_.DYNAMIC_DRAW }; /** * @constructor * @param {Array.<number>=} opt_arr Array. * @param {number=} opt_usage Usage. * @struct */ const WebGLBuffer = function(opt_arr, opt_usage) { /** * @private * @type {Array.<number>} */ this.arr_ = opt_arr !== undefined ? opt_arr : []; /** * @private * @type {number} */ this.usage_ = opt_usage !== undefined ? opt_usage : BufferUsage.STATIC_DRAW; }; /** * @return {Array.<number>} Array. */ WebGLBuffer.prototype.getArray = function() { return this.arr_; }; /** * @return {number} Usage. */ WebGLBuffer.prototype.getUsage = function() { return this.usage_; }; export default WebGLBuffer;
/** * @module ol/webgl/Buffer */ import _ol_webgl_ from '../webgl.js'; /** * @enum {number} */ const BufferUsage = { STATIC_DRAW: _ol_webgl_.STATIC_DRAW, STREAM_DRAW: _ol_webgl_.STREAM_DRAW, DYNAMIC_DRAW: _ol_webgl_.DYNAMIC_DRAW }; /** * @constructor * @param {Array.<number>=} opt_arr Array. * @param {number=} opt_usage Usage. * @struct */ const WebGLBuffer = function(opt_arr, opt_usage) { /** * @private * @type {Array.<number>} */ this.arr_ = opt_arr !== undefined ? opt_arr : []; /** * @private * @type {number} */ this.usage_ = opt_usage !== undefined ? opt_usage : BufferUsage; }; /** * @return {Array.<number>} Array. */ WebGLBuffer.prototype.getArray = function() { return this.arr_; }; /** * @return {number} Usage. */ WebGLBuffer.prototype.getUsage = function() { return this.usage_; }; export default WebGLBuffer;
Use split_up in both places
#! /usr/bin/env python import os.path import time from time import strftime import os import sys import shutil FILE = 'todo.md' def date_to_append(): return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE))) def rename_file(the_file): base = os.path.basename(the_file) split_up = os.path.splitext(base) file_name = split_up[0] file_extension = split_up[1] new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension) os.rename(the_file, new_file_name) def move_old_todo(): for filename in os.listdir("."): if filename.startswith('todo'): shutil.move(filename, 'Archive') def create_new_todo(): open(FILE, 'w') rename_file(FILE) move_old_todo() create_new_todo()
#! /usr/bin/env python import os.path import time from time import strftime import os import sys import shutil FILE = 'todo.md' def date_to_append(): return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE))) def rename_file(the_file): base = os.path.basename(the_file) split_up = os.path.splitext(base) file_name = os.path.splitext(base)[0] file_extension = split_up[1] new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension) os.rename(the_file, new_file_name) def move_old_todo(): for filename in os.listdir("."): if filename.startswith('todo'): shutil.move(filename, 'Archive') def create_new_todo(): open(FILE, 'w') rename_file(FILE) move_old_todo() create_new_todo()
Remove duplicate declaration of componentWillUnmount Remove duplicate declaration of componentWillUnmount and move `this._isMounted = true` inside componentDidMount
/* @flow */ import React, {Component} from 'react'; import StyleKeeper from '../style-keeper'; export default class StyleSheet extends Component { static contextTypes = { _radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper) }; constructor() { super(...arguments); this.state = this._getCSSState(); this._onChange = this._onChange.bind(this); } componentDidMount() { this._isMounted = true; this._subscription = this.context._radiumStyleKeeper.subscribe( this._onChange ); this._onChange(); } componentWillUnmount() { this._isMounted = false; if (this._subscription) { this._subscription.remove(); } } _getCSSState(): {css: string} { return {css: this.context._radiumStyleKeeper.getCSS()}; } _onChange() { setTimeout(() => { this._isMounted && this.setState(this._getCSSState()); }, 0); } render(): ReactElement { return ( <style dangerouslySetInnerHTML={{__html: this.state.css}} /> ); } }
/* @flow */ import React, {Component} from 'react'; import StyleKeeper from '../style-keeper'; export default class StyleSheet extends Component { static contextTypes = { _radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper) }; constructor() { super(...arguments); this.state = this._getCSSState(); this._onChange = this._onChange.bind(this); } componentDidMount() { this._subscription = this.context._radiumStyleKeeper.subscribe( this._onChange ); this._onChange(); } componentWillUnmount() { this._isMounted = true; if (this._subscription) { this._subscription.remove(); } } componentWillUnmount() { this._isMounted = false; } _getCSSState(): {css: string} { return {css: this.context._radiumStyleKeeper.getCSS()}; } _onChange() { setTimeout(() => { this._isMounted && this.setState(this._getCSSState()); }, 0); } render(): ReactElement { return ( <style dangerouslySetInnerHTML={{__html: this.state.css}} /> ); } }
Add suffixes to all gifs
import os def remove_image_from_csvs(image): for csv in os.listdir("."): if csv[-4:] != ".csv": continue with open(csv, "r") as h: lines = h.readlines() modified = False for x in range(len(lines)): if image in lines[x]: lines[x] = lines[x].replace(image, image+".gif") modified = True print(lines[x]) if not modified: continue with open(csv, "w") as h: h.write("".join(lines)) images = os.listdir("static") for image in images: if image == ".gitkeep": continue path = os.path.join("static", image) size = os.path.getsize(path) if "." in image: continue print(image) remove_image_from_csvs(image) os.rename(path, path+".gif")
import os def remove_image_from_csvs(image): for csv in os.listdir("."): if csv[-4:] != ".csv": continue with open(csv, "r") as h: lines = h.readlines() modified = False for x in range(len(lines)): if image in lines[x]: del lines[x] modified = True print(lines[x]) if not modified: continue with open(csv, "w") as h: h.write("".join(lines)) images = os.listdir("static") for image in images: if image == ".gitkeep": continue path = os.path.join("static", image) size = os.path.getsize(path) if size != 0: continue print(image) remove_image_from_csvs(image) os.remove(path)
Use Laravel base controller in example
<?php // Add the ServiceProvider // Create the oauth-providers config file // Create a route: Route::get('login/{provider}', ['uses' => 'SocialController@login']); // Create a controller: use CodeZero\OAuth\Contracts\Authenticator; use Illuminate\Routing\Controller; class SocialController extends Controller { public function __construct() { $this->middleware('guest'); } public function login($provider, Authenticator $auth) { $details = $auth->request($provider); if ($details) { var_dump($details->getEmail()); var_dump($details->getFirstName()); var_dump($details->getLastName()); } else { echo 'User canceled!'; } die(); return redirect()->intended('/'); } }
<?php // Add the ServiceProvider // Create the oauth-providers config file // Create a route: Route::get('login/{provider}', ['uses' => 'SocialController@login']); // Create a controller: use CodeZero\OAuth\Contracts\Authenticator; class SocialController extends Controller { public function __construct() { $this->middleware('guest'); } public function login($provider, Authenticator $auth) { $details = $auth->request($provider); if ($details) { var_dump($details->getEmail()); var_dump($details->getFirstName()); var_dump($details->getLastName()); } else { echo 'User canceled!'; } die(); return redirect()->intended('/'); } }
Update imports to use json extensions in fixtures.
/** * Tag Manager datastore fixtures. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import ContainersAMPOnly from './get-containers--amp.json'; import ContainersWebOnly from './get-containers--web.json'; export { default as accounts } from './accounts.json'; export { default as createContainer } from './create-container.json'; export { default as liveContainerVersion } from './live-container-version.json'; export const getContainers = { amp: ContainersAMPOnly, web: ContainersWebOnly, all: [ ...ContainersAMPOnly, ...ContainersWebOnly, ], };
/** * Tag Manager datastore fixtures. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import ContainersAMPOnly from './get-containers--amp'; import ContainersWebOnly from './get-containers--web'; export { default as accounts } from './accounts'; export { default as createContainer } from './create-container'; export { default as liveContainerVersion } from './live-container-version.json'; export const getContainers = { amp: ContainersAMPOnly, web: ContainersWebOnly, all: [ ...ContainersAMPOnly, ...ContainersWebOnly, ], };
Fix exception with adding paths that don't exist.
<?php namespace ZfcTwig\Service; use Zend\ServiceManager\FactoryInterface; use Twig_Loader_Filesystem; use Zend\ServiceManager\ServiceLocatorInterface; class TwigDefaultLoaderFactory implements FactoryInterface { /** * Create service * * @param ServiceLocatorInterface $serviceLocator * @return mixed */ public function createService(ServiceLocatorInterface $serviceLocator) { /** @var $templateStack \Zend\View\Resolver\TemplatePathStack */ $templateStack = $serviceLocator->get('ViewTemplatePathStack'); $loader = new Twig_Loader_Filesystem('module/Application/view'); foreach($templateStack->getPaths() as $path) { if (file_exists($path)) { $loader->addPath($path); } } return $loader; } }
<?php namespace ZfcTwig\Service; use Zend\ServiceManager\FactoryInterface; use Twig_Loader_Filesystem; use Zend\ServiceManager\ServiceLocatorInterface; class TwigDefaultLoaderFactory implements FactoryInterface { /** * Create service * * @param ServiceLocatorInterface $serviceLocator * @return mixed */ public function createService(ServiceLocatorInterface $serviceLocator) { /** @var $templateStack \Zend\View\Resolver\TemplatePathStack */ $templateStack = $serviceLocator->get('ViewTemplatePathStack'); $loader = new Twig_Loader_Filesystem('module/Application/view'); foreach($templateStack->getPaths() as $path) { $loader->addPath($path); } return $loader; } }
Resolve ONLY file:// deps relative to package root, everything else CWD
"use strict" var fs = require("fs") var path = require("path") var dz = require("dezalgo") var npa = require("npm-package-arg") module.exports = function (spec, where, cb) { if (where instanceof Function) cb = where, where = null if (where == null) where = "." cb = dz(cb) try { var dep = npa(spec) } catch (e) { return cb(e) } var specpath = dep.type == "local" ? path.resolve(where, dep.spec) : path.resolve(spec) fs.stat(specpath, function (er, s) { if (er) return finalize() if (!s.isDirectory()) return finalize("local") fs.stat(path.join(specpath, "package.json"), function (er) { finalize(er ? null : "directory") }) }) function finalize(type) { if (type != null) dep.type = type if (dep.type == "local" || dep.type == "directory") dep.spec = specpath cb(null, dep) } }
"use strict" var fs = require("fs") var path = require("path") var dz = require("dezalgo") var npa = require("npm-package-arg") module.exports = function (spec, where, cb) { if (where instanceof Function) cb = where, where = null if (where == null) where = "." cb = dz(cb) try { var dep = npa(spec) } catch (e) { return cb(e) } var specpath = path.resolve(where, dep.type == "local" ? dep.spec : spec) fs.stat(specpath, function (er, s) { if (er) return finalize() if (!s.isDirectory()) return finalize("local") fs.stat(path.join(specpath, "package.json"), function (er) { finalize(er ? null : "directory") }) }) function finalize(type) { if (type != null) dep.type = type if (dep.type == "local" || dep.type == "directory") dep.spec = specpath cb(null, dep) } }
Add Subscriber dependency to droninit
package org.inaetics.dronessimulator.drone.droneinit; import org.apache.felix.dm.DependencyActivatorBase; import org.apache.felix.dm.DependencyManager; import org.inaetics.dronessimulator.discovery.api.Discoverer; import org.inaetics.dronessimulator.pubsub.api.subscriber.Subscriber; import org.osgi.framework.BundleContext; public class Activator extends DependencyActivatorBase { @Override public void init(BundleContext bundleContext, DependencyManager dependencyManager) throws Exception { dependencyManager.add(createComponent() .setInterface(DroneInit.class.getName(), null) .setImplementation(DroneInit.class) .add(createServiceDependency() .setService(Subscriber.class) .setRequired(true) ) .add(createServiceDependency() .setService(Discoverer.class) .setRequired(true) ) .setCallbacks("init", "start", "stop", "destroy") ); } }
package org.inaetics.dronessimulator.drone.droneinit; import org.apache.felix.dm.DependencyActivatorBase; import org.apache.felix.dm.DependencyManager; import org.inaetics.dronessimulator.discovery.api.Discoverer; import org.osgi.framework.BundleContext; public class Activator extends DependencyActivatorBase { @Override public void init(BundleContext bundleContext, DependencyManager dependencyManager) throws Exception { dependencyManager.add(createComponent() .setInterface(DroneInit.class.getName(), null) .setImplementation(DroneInit.class) .add(createServiceDependency() .setService(Discoverer.class) .setRequired(true) ) .setCallbacks("init", "start", "stop", "destroy") ); } }
Use IOException instead of Throwable for not successful http status
package de.fau.amos.virtualledger.android.api.shared; import android.util.Log; import java.io.IOException; import io.reactivex.subjects.PublishSubject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RetrofitCallback<T> implements Callback<T> { private static final String TAG = RetrofitCallback.class.getSimpleName(); private final PublishSubject<T> observable; public RetrofitCallback(final PublishSubject<T> observable) { this.observable = observable; } @Override public void onResponse(final Call<T> call, final Response<T> response) { // got response from server final String requestString = "Request " + call.request().method() + " " + call.request().url() + " "; if (response.isSuccessful()) { final T result = response.body(); Log.v(TAG, requestString + "was successful: " + response.code()); observable.onNext(result); } else { Log.e(TAG, requestString + "was not successful! ERROR " + response.code()); observable.onError(new IOException(requestString + " was not successful!")); } } @Override public void onFailure(final Call<T> call, final Throwable t) { // response of server failed Log.e(TAG, "No connection to server!"); observable.onError(t); } }
package de.fau.amos.virtualledger.android.api.shared; import android.util.Log; import io.reactivex.subjects.PublishSubject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RetrofitCallback<T> implements Callback<T> { private static final String TAG = RetrofitCallback.class.getSimpleName(); private final PublishSubject<T> observable; public RetrofitCallback(final PublishSubject<T> observable) { this.observable = observable; } @Override public void onResponse(final Call<T> call, final Response<T> response) { // got response from server final String requestString = "Request " + call.request().method() + " " + call.request().url() + " "; if (response.isSuccessful()) { final T result = response.body(); Log.v(TAG, requestString + "was successful: " + response.code()); observable.onNext(result); } else { Log.e(TAG, requestString + "was not successful! ERROR " + response.code()); observable.onError(new Throwable(requestString + " was not successful!")); } } @Override public void onFailure(final Call<T> call, final Throwable t) { // response of server failed Log.e(TAG, "No connection to server!"); observable.onError(t); } }
Add function method that gives the resource location of the registry name. Can be used for sound events etc
package info.u_team.u_team_core.util.registry; import java.util.*; import java.util.function.*; import net.minecraft.util.ResourceLocation; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.*; public class CommonDeferredRegister<R extends IForgeRegistryEntry<R>> implements Iterable<RegistryObject<R>> { public static <C extends IForgeRegistryEntry<C>> CommonDeferredRegister<C> create(IForgeRegistry<C> registry, String modid) { return new CommonDeferredRegister<C>(registry, modid); } private final String modid; private final DeferredRegister<R> register; public CommonDeferredRegister(IForgeRegistry<R> registry, String modid) { this.modid = modid; register = DeferredRegister.create(registry, modid); } public <E extends R> RegistryObject<E> register(String name, Function<ResourceLocation, ? extends E> function) { return register(name, () -> function.apply(new ResourceLocation(modid, name))); } public <E extends R> RegistryObject<E> register(String name, Supplier<? extends E> supplier) { return register.register(name, supplier); } public void register(IEventBus bus) { register.register(bus); } public Collection<RegistryObject<R>> getEntries() { return register.getEntries(); } @Override public Iterator<RegistryObject<R>> iterator() { return register.getEntries().iterator(); } }
package info.u_team.u_team_core.util.registry; import java.util.*; import java.util.function.Supplier; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.*; public class CommonDeferredRegister<R extends IForgeRegistryEntry<R>> implements Iterable<RegistryObject<R>> { public static <C extends IForgeRegistryEntry<C>> CommonDeferredRegister<C> create(IForgeRegistry<C> registry, String modid) { return new CommonDeferredRegister<C>(registry, modid); } private final String modid; private final DeferredRegister<R> register; public CommonDeferredRegister(IForgeRegistry<R> registry, String modid) { this.modid = modid; register = DeferredRegister.create(registry, modid); } public <E extends R> RegistryObject<E> register(String name, Supplier<? extends E> supplier) { return register.register(name, supplier); } public void register(IEventBus bus) { register.register(bus); } public Collection<RegistryObject<R>> getEntries() { return register.getEntries(); } @Override public Iterator<RegistryObject<R>> iterator() { return register.getEntries().iterator(); } }
Fix redis initialization in tests
# -*- coding: utf-8 -*- from flask import Flask from flask_split import split from flask_split.core import _get_redis_connection class TestCase(object): def setup_method(self, method): self.app = Flask(__name__) self.app.debug = True self.app.secret_key = 'very secret' self.app.register_blueprint(split) self._ctx = self.make_test_request_context() self._ctx.push() self.redis = _get_redis_connection() self.redis.flushall() self.client = self.app.test_client() def teardown_method(self, method): self._ctx.pop() def make_test_request_context(self): return self.app.test_request_context() def assert_redirects(response, location): """ Checks if response is an HTTP redirect to the given location. :param response: Flask response :param location: relative URL (i.e. without **http://localhost**) """ assert response.status_code in (301, 302) assert response.location == 'http://localhost' + location
# -*- coding: utf-8 -*- from flask import Flask from flask_split import split from redis import Redis class TestCase(object): def setup_method(self, method): self.redis = Redis() self.redis.flushall() self.app = Flask(__name__) self.app.debug = True self.app.secret_key = 'very secret' self.app.register_blueprint(split) self._ctx = self.make_test_request_context() self._ctx.push() self.client = self.app.test_client() def teardown_method(self, method): self._ctx.pop() def make_test_request_context(self): return self.app.test_request_context() def assert_redirects(response, location): """ Checks if response is an HTTP redirect to the given location. :param response: Flask response :param location: relative URL (i.e. without **http://localhost**) """ assert response.status_code in (301, 302) assert response.location == 'http://localhost' + location
Unify component name and filename.
import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import InputContainer from '../Input/InputContainer'; import { inputChanged } from './PlatbyActions'; import { formatValue, inputOptions, inputValid, isInputEnabled, isInputVisible } from './platbyReducer'; const mapStateToProps = (state, ownProps) => { const form = state.registrator.prihlasky.platby; const { name } = ownProps; const [, subName] = name.split('.'); const rawValue = form[subName]; return { form, rawValue, formatValue, inputChanged, inputOptions, inputValid, isInputEnabled, isInputVisible, ...ownProps }; }; const NovaPlatbaInputContainer = connect(mapStateToProps, {})(InputContainer); NovaPlatbaInputContainer.propTypes = { name: PropTypes.string.isRequired }; export default NovaPlatbaInputContainer;
import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import InputContainer from '../Input/InputContainer'; import { inputChanged } from './PlatbyActions'; import { formatValue, inputOptions, inputValid, isInputEnabled, isInputVisible } from './platbyReducer'; const mapStateToProps = (state, ownProps) => { const form = state.registrator.prihlasky.platby; const { name } = ownProps; const [, subName] = name.split('.'); const rawValue = form[subName]; return { form, rawValue, formatValue, inputChanged, inputOptions, inputValid, isInputEnabled, isInputVisible, ...ownProps }; }; const PlatbyInputContainer = connect(mapStateToProps, {})(InputContainer); PlatbyInputContainer.propTypes = { name: PropTypes.string.isRequired }; export default PlatbyInputContainer;
Update json.loads line for python 3.5 Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'". Fixed it by decoding downloaded json to utf-8
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data.decode('utf-8')) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
Fix tear down click handler problem in tests It's not obvious what "the way" to teardown window event handlers is in Ember. The datacenter-picker is permanently in the app during usage, but in tests I'm assuming it gets added and removed lots. So when you run the tests, as the tests aren't run in an isolated runner the QUnit test runner ends up with a click handler on it, So if you click on the test runner one of the tests will fail. The failure is related to there not being an element with a `.contains` method. So this checks that the element is truthy first, i.e. it exists. If it doesn't it just bails out.
import Mixin from '@ember/object/mixin'; import { next } from '@ember/runloop'; import { get } from '@ember/object'; const isOutside = function(element, e) { if (element) { const isRemoved = !e.target || !document.contains(e.target); const isInside = element === e.target || element.contains(e.target); return !isRemoved && !isInside; } else { return false; } }; const handler = function(e) { const el = get(this, 'element'); if (isOutside(el, e)) { this.onblur(e); } }; export default Mixin.create({ init: function() { this._super(...arguments); this.handler = handler.bind(this); }, onchange: function() {}, onblur: function() {}, didInsertElement: function() { this._super(...arguments); next(this, () => { document.addEventListener('click', this.handler); }); }, willDestroyElement: function() { this._super(...arguments); document.removeEventListener('click', this.handler); }, });
import Mixin from '@ember/object/mixin'; import { next } from '@ember/runloop'; import { get } from '@ember/object'; const isOutside = function(element, e) { const isRemoved = !e.target || !document.contains(e.target); const isInside = element === e.target || element.contains(e.target); return !isRemoved && !isInside; }; const handler = function(e) { const el = get(this, 'element'); if (isOutside(el, e)) { this.onblur(e); } }; export default Mixin.create({ init: function() { this._super(...arguments); this.handler = handler.bind(this); }, onchange: function() {}, onblur: function() {}, didInsertElement: function() { this._super(...arguments); next(this, () => { document.addEventListener('click', this.handler); }); }, willDestroyElement: function() { this._super(...arguments); document.removeEventListener('click', this.handler); }, });