text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Stop testing spec on failure
var Jasmine = require("jasmine"); var jasmine = new Jasmine(); var config = { spec_dir: "", spec_files: ["tests/**/*.js", "app/**/tests/index.js", "app/**/tests.js"], helpers: [], stopSpecOnExpectationFailure: true, random: false }; // Pass in a custom test glob for running only specific tests if (process.env.TEST) { config.spec_files = [ process.env.TEST + "**/tests/index.js", process.env.TEST + "**/tests.js" ]; console.log("Running tests from", config.spec_files); } jasmine.loadConfig(config); global.createUser = require("./helpers/createUser"); global.createBlog = require("./helpers/createBlog"); global.removeBlog = require("./helpers/removeBlog"); global.removeUser = require("./helpers/removeUser"); jasmine.execute();
var Jasmine = require("jasmine"); var jasmine = new Jasmine(); var config = { spec_dir: "", spec_files: ["tests/**/*.js", "app/**/tests/index.js", "app/**/tests.js"], helpers: [], stopSpecOnExpectationFailure: false, random: false }; // Pass in a custom test glob for running only specific tests if (process.env.TEST) { config.spec_files = [ process.env.TEST + "**/tests/index.js", process.env.TEST + "**/tests.js" ]; console.log("Running tests from", config.spec_files); } jasmine.loadConfig(config); global.createUser = require("./helpers/createUser"); global.createBlog = require("./helpers/createBlog"); global.removeBlog = require("./helpers/removeBlog"); global.removeUser = require("./helpers/removeUser"); jasmine.execute();
Fix build: Set correct error name
export class CompositionError extends Error { constructor(classInstance, message, component) { super(`@${classInstance}: ${message}`); const stackArray = this.stack.split('\n'); stackArray.splice(1, 2); this.stack = stackArray.join('\n'); if (!process) console.error('Component:', component); this.name = 'CompositionError'; } } export class DependencyError extends Error { constructor(classInstance, message, activeModule, dependencyModule = false) { super(`@${classInstance}: ${message}`); const stackArray = this.stack.split('\n'); stackArray.splice(1, 2); this.stack = stackArray.join('\n'); if (!process) console.error('Active module:', activeModule); if (!process && dependencyModule) console.error('Dependency published by module:', dependencyModule); this.name = 'DependencyError'; } } export class ManagerError extends Error { constructor(classInstance, message, component, activeModule = false) { super(`@${classInstance}: ${message}`); const stackArray = this.stack.split('\n'); stackArray.splice(1, 2); this.stack = stackArray.join('\n'); if (!process) console.error('Component:', dependencyModule); if (!process && activeModule) console.error('Active module:', activeModule); this.name = 'ManagerError'; } }
export class CompositionError extends Error { constructor(classInstance, message, component) { super(`@${classInstance}: ${message}`); const stackArray = this.stack.split('\n'); stackArray.splice(1, 2); this.stack = stackArray.join('\n'); if (!process) console.error('Component:', component); this.name = 'CompositionError'; } } export class DependencyError extends Error { constructor(classInstance, message, activeModule, dependencyModule = false) { super(`@${classInstance}: ${message}`); const stackArray = this.stack.split('\n'); stackArray.splice(1, 2); this.stack = stackArray.join('\n'); if (!process) console.error('Active module:', activeModule); if (!process && dependencyModule) console.error('Dependency published by module:', dependencyModule); this.name = 'DependencyError'; } } export class ManagerError extends Error { constructor(classInstance, message, component, activeModule = false) { super(`@${classInstance}: ${message}`); const stackArray = this.stack.split('\n'); stackArray.splice(1, 2); this.stack = stackArray.join('\n'); if (!process) console.error('Component:', dependencyModule); if (!process && activeModule) console.error('Active module:', activeModule); this.name = 'DependencyError'; } }
Check for EBADF in write-to-closed fd test case
from filedes.test.base import BaseFDTestCase from filedes import FD import os import errno class TestFDIO(BaseFDTestCase): def testReadWrite(self): r, w = os.pipe() self.assertEquals(FD(w).write("OK"), 2) self.assertEquals(FD(r).read(2), "OK") FD(r).close() FD(w).close() def testWriteAfterClose(self): r, w = os.pipe() fw = FD(w) fw.close() try: with self.assertRaises(OSError) as ar: fw.write("oops") self.assertEquals(ar.exception.errno, errno.EBADF) finally: FD(r).close() def testNonblocking(self): r, w = os.pipe() fr = FD(r) try: fr.set_nonblocking() with self.assertRaises(OSError) as ar: fr.read(1) self.assertEquals(ar.exception.errno, errno.EAGAIN) finally: fr.close() FD(w).close()
from filedes.test.base import BaseFDTestCase from filedes import FD import os import errno class TestFDIO(BaseFDTestCase): def testReadWrite(self): r, w = os.pipe() self.assertEquals(FD(w).write("OK"), 2) self.assertEquals(FD(r).read(2), "OK") FD(r).close() FD(w).close() def testWriteAfterClose(self): r, w = os.pipe() fw = FD(w) fw.close() with self.assertRaises(OSError): fw.write("oops") FD(r).close() def testNonblocking(self): r, w = os.pipe() fr = FD(r) try: fr.set_nonblocking() with self.assertRaises(OSError) as ar: fr.read(1) self.assertEquals(ar.exception.errno, errno.EAGAIN) finally: fr.close() FD(w).close()
Add unit tests to ecmaVersion 7 and 8
'use strict' var parsers = [ { name: 'acorn', options: { locations: true, onComment: [] }, parser: require('acorn') }, { name: 'espree', options: { ecmaVersion: 6, loc: true }, parser: require('espree') }, { name: 'espree', options: { ecmaVersion: 7, loc: true }, parser: require('espree') }, { name: 'espree', options: { ecmaVersion: 8, loc: true }, parser: require('espree') }, { name: 'esprima', options: { loc: true }, parser: require('esprima') } ] module.exports.forEach = function forEachParser (tests) { for (var i = 0; i < parsers.length; i++) { var parserName = parsers[i].name var parser = parsers[i].parser var options = parsers[i].options suite('using the ' + parserName + ' parser:', function () { tests(parserName, parser, options) }) } }
'use strict' var parsers = [ { name: 'acorn', options: { locations: true, onComment: [] }, parser: require('acorn') }, { name: 'espree', options: { ecmaVersion: 6, loc: true }, parser: require('espree') }, { name: 'esprima', options: { loc: true }, parser: require('esprima') } ] module.exports.forEach = function forEachParser (tests) { for (var i = 0; i < parsers.length; i++) { var parserName = parsers[i].name var parser = parsers[i].parser var options = parsers[i].options suite('using the ' + parserName + ' parser:', function () { tests(parserName, parser, options) }) } }
Store in the current state, not the previous one
# -- # Copyright (c) 2008-2020 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. # -- """If the ``activated`` parameter of the ``[redirect_after_post]`` section is `on`` (the default), conform to the PRG__ pattern __ http://en.wikipedia.org/wiki/Post/Redirect/GetPRG """ from nagare.services import plugin class PRGService(plugin.Plugin): LOAD_PRIORITY = 120 @staticmethod def handle_request(chain, request, response, session_id, state_id, **params): if (request.method == 'POST') and not request.is_xhr: response = request.create_redirect_response( response=response, _s=session_id, _c='%05d' % state_id, ) else: response = chain.next( request=request, response=response, session_id=session_id, state_id=state_id, **params ) return response
# -- # Copyright (c) 2008-2020 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. # -- """If the ``activated`` parameter of the ``[redirect_after_post]`` section is `on`` (the default), conform to the PRG__ pattern __ http://en.wikipedia.org/wiki/Post/Redirect/GetPRG """ from nagare.services import plugin class PRGService(plugin.Plugin): LOAD_PRIORITY = 120 @staticmethod def handle_request(chain, request, response, session_id, previous_state_id, **params): if (request.method == 'POST') and not request.is_xhr: response = request.create_redirect_response( response=response, _s=session_id, _c='%05d' % previous_state_id ) response.use_same_state = True else: response = chain.next( request=request, response=response, session_id=session_id, previous_state_id=previous_state_id, **params ) return response
Add filename in attrs if fails to load it. Filename in attrs helps to debug.
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import logging from os.path import basename from cotede.qc import ProfileQC from . import fCNV from .exceptions import CNVError class fProfileQC(ProfileQC): """ Apply ProfileQC from CoTeDe straight from a file. """ def __init__(self, inputfile, cfg=None, saveauxiliary=True, verbose=True, logger=None): """ """ self.logger = logging.getLogger(logger or 'seabird.qc.fProfileQC') self.name = 'fProfileQC' try: # Not the best way, but will work for now. I should pass # the reference for the logger being used. profile = fCNV(inputfile, logger=None) except CNVError as e: self.attributes['filename'] = basename(inputfile) logging.error(e.msg) raise super(fProfileQC, self).__init__(profile, cfg=cfg, saveauxiliary=saveauxiliary, verbose=verbose, logger=logger)
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import logging from cotede.qc import ProfileQC from . import fCNV from .exceptions import CNVError class fProfileQC(ProfileQC): """ Apply ProfileQC from CoTeDe straight from a file. """ def __init__(self, inputfile, cfg=None, saveauxiliary=True, verbose=True, logger=None): """ """ self.logger = logging.getLogger(logger or 'seabird.qc.fProfileQC') self.name = 'fProfileQC' try: # Not the best way, but will work for now. I should pass # the reference for the logger being used. profile = fCNV(inputfile, logger=None) except CNVError as e: #self.attributes['filename'] = basename(inputfile) logging.error(e.msg) raise super(fProfileQC, self).__init__(profile, cfg=cfg, saveauxiliary=saveauxiliary, verbose=verbose, logger=logger)
Set pygments style to monokai.
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'Donne Martin' SITENAME = 'Donne Martin' SITEURL = '' PATH = 'content' TIMEZONE = 'America/New_York' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None HIDE_SIDEBAR = True PYGMENTS_STYLE = 'monokai' # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) STATIC_PATHS = [ 'images', 'extra/favicon.ico' ] EXTRA_PATH_METADATA = { 'extra/favicon.ico': {'path': 'favicon.ico'} } DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True # THEME = 'pelican-bootstrap3' # BOOTSTRAP_THEME = 'readable' THEME = 'startbootstrap-agency' BOOTSTRAP_THEME = ''
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'Donne Martin' SITENAME = 'Donne Martin' SITEURL = '' PATH = 'content' TIMEZONE = 'America/New_York' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None HIDE_SIDEBAR = True # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) STATIC_PATHS = [ 'images', 'extra/favicon.ico' ] EXTRA_PATH_METADATA = { 'extra/favicon.ico': {'path': 'favicon.ico'} } DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True # THEME = 'pelican-bootstrap3' # BOOTSTRAP_THEME = 'readable' THEME = 'startbootstrap-agency' BOOTSTRAP_THEME = ''
Add a prefix to the statsd key We have loads of stats at the top leve of our statsd stats in graphite. It makes looking for things that aren't created by backdrop really hard.
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv( "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX")))
Adjust braces to match Magento conventions
<?php /** * Solr response * * @category Asm * @package Asm_Solr * @author Ingo Renner <ingo@infielddesign.com> */ class Asm_Solr_Model_Solr_Response { /** * @var Apache_Solr_Response */ protected $rawResponse; /** * Constructor * */ public function __construct(array $responseParameters = array()) { $this->rawResponse = $responseParameters['rawResponse']; } /** * Gets the number of results found * * @return integer Number of results found */ public function getNumberOfResults() { return $this->rawResponse->response->numFound; } /** * Gets the result documents * * @return Apache_Solr_Document[] Array of Apache_Solr_Document */ public function getDocuments() { return $this->rawResponse->response->docs; } /** * Gets the field facets * * @return Asm_Solr_Model_Solr_Facet_Facet[] Array of Asm_Solr_Model_Solr_Facet_Facet */ public function getFacetFields() { } /* TODO add range and query facet support public function getFacetRanges() { } public function getFacetQueries() { } */ }
<?php /** * Solr response * * @category Asm * @package Asm_Solr * @author Ingo Renner <ingo@infielddesign.com> */ class Asm_Solr_Model_Solr_Response { /** * @var Apache_Solr_Response */ protected $rawResponse; /** * Constructor * */ public function __construct(array $responseParameters = array()) { $this->rawResponse = $responseParameters['rawResponse']; } /** * Gets the number of results found * * @return integer Number of results found */ public function getNumberOfResults() { return $this->rawResponse->response->numFound; } /** * Gets the result documents * * @return Apache_Solr_Document[] Array of Apache_Solr_Document */ public function getDocuments() { return $this->rawResponse->response->docs; } /** * Gets the field facets * * @return Asm_Solr_Model_Solr_Facet_Facet[] Array of Asm_Solr_Model_Solr_Facet_Facet */ public function getFacetFields() { } /* TODO add range and query facet support public function getFacetRanges() { } public function getFacetQueries() { } */ }
Add future to install requirements.
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path import pubcode here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='PubCode', version=pubcode.__version__, description='A simple module for creating barcodes.', long_description=long_description, url='https://github.com/Venti-/pubcode', author='Ari Koivula', author_email='ari@koivu.la', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Multimedia :: Graphics', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], install_requires=[ "future", # For Python3 like builtins in Python2. ], packages=find_packages(exclude=['tests']), )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path import pubcode here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='PubCode', version=pubcode.__version__, description='A simple module for creating barcodes.', long_description=long_description, url='https://github.com/Venti-/pubcode', author='Ari Koivula', author_email='ari@koivu.la', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Multimedia :: Graphics', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], packages=find_packages(exclude=['tests']), )
Make Essence autoloader not attempt to load non-Essence classes. Here we make sure that the Essence autoloader only attempts to load classes that begin with Essence\...
<?php /** * @author Félix Girault <felix.girault@gmail.com> * @license FreeBSD License (http://opensource.org/licenses/BSD-2-Clause) */ namespace Essence\Utility; /** * A simple PSR-0 compliant class loader. * * @package Essence.Utility */ class Autoload { /** * Sets autoload up on the given path. * * @param string $basePath Base include path for all class files. */ public static function setup( $basePath ) { $basePath = rtrim( $basePath, DIRECTORY_SEPARATOR ); spl_autoload_register( function( $className ) use ( $basePath ) { if (strpos($className, 'Essence\\') === false) { return; } $path = $basePath . DIRECTORY_SEPARATOR . str_replace( '\\', DIRECTORY_SEPARATOR, $className ) . '.php'; if ( file_exists( $path )) { require_once $path; } }); } }
<?php /** * @author Félix Girault <felix.girault@gmail.com> * @license FreeBSD License (http://opensource.org/licenses/BSD-2-Clause) */ namespace Essence\Utility; /** * A simple PSR-0 compliant class loader. * * @package Essence.Utility */ class Autoload { /** * Sets autoload up on the given path. * * @param string $basePath Base include path for all class files. */ public static function setup( $basePath ) { $basePath = rtrim( $basePath, DIRECTORY_SEPARATOR ); spl_autoload_register( function( $className ) use ( $basePath ) { $path = $basePath . DIRECTORY_SEPARATOR . str_replace( '\\', DIRECTORY_SEPARATOR, $className ) . '.php'; if ( file_exists( $path )) { require_once $path; } }); } }
Fix CSS Modules ident name for production build (from Sai Kishore Komanduri)
var cssnext = require('postcss-cssnext'); var postcssFocus = require('postcss-focus'); var postcssReporter = require('postcss-reporter'); var cssModulesIdentName = '[name]__[local]__[hash:base64:5]'; if (process.env.NODE_ENV === 'production') { cssModulesIdentName = '[hash:base64]'; } module.exports = { output: { publicPath: '/', libraryTarget: 'commonjs2', }, resolve: { extensions: ['', '.js', '.jsx'], modules: [ 'client', 'node_modules', ], }, module: { loaders: [ { test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader?localIdentName=' + cssModulesIdentName + '&modules&importLoaders=1&sourceMap!postcss-loader', }, { test: /\.jpe?g$|\.gif$|\.png$|\.svg$/i, loader: 'url-loader?limit=10000', }, ], }, postcss: () => [ postcssFocus(), cssnext({ browsers: ['last 2 versions', 'IE > 10'], }), postcssReporter({ clearMessages: true, }), ], };
var cssnext = require('postcss-cssnext'); var postcssFocus = require('postcss-focus'); var postcssReporter = require('postcss-reporter'); module.exports = { output: { publicPath: '/', libraryTarget: 'commonjs2', }, resolve: { extensions: ['', '.js', '.jsx'], modules: [ 'client', 'node_modules', ], }, module: { loaders: [ { test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader', }, { test: /\.jpe?g$|\.gif$|\.png$|\.svg$/i, loader: 'url-loader?limit=10000', }, ], }, postcss: () => [ postcssFocus(), cssnext({ browsers: ['last 2 versions', 'IE > 10'], }), postcssReporter({ clearMessages: true, }), ], };
Fix double encoding that would bork Bertly redirect
'use strict'; const request = require('superagent'); const config = require('../../config/lib/bertly'); /** * executePost - sends the POST request to the Bertly service * * @param {Object} data * @return {Promise} */ async function executePost(data) { return request .post(config.baseUri) .type('form') .set(config.apiKeyHeader, config.apiKey) .send(data) .then(res => res.body); } /** * createRedirect - Receives an URL. It is URI encoded and sent * as the value of the url= property to Bertly. * * @see https://github.com/DoSomething/bertly#create-redirect * @param {string} url * @return {Promise} */ async function createRedirect(url) { return executePost({ url }); } module.exports = { createRedirect, };
'use strict'; const request = require('superagent'); const querystring = require('querystring'); const config = require('../../config/lib/bertly'); /** * executePost - sends the POST request to the Bertly service * * @param {Object} data * @return {Promise} */ async function executePost(data) { return request .post(config.baseUri) .type('form') .set(config.apiKeyHeader, config.apiKey) .send(data) .then(res => res.body); } /** * createRedirect - Receives an URL. It is URI encoded and sent * as the value of the url= property to Bertly. * * @see https://github.com/DoSomething/bertly#create-redirect * @param {string} url * @return {Promise} */ async function createRedirect(url) { const encodedUrl = querystring.escape(url); return executePost({ url: encodedUrl }); } module.exports = { createRedirect, };
Fix the cloud type warning on build
import React from 'react' import { Provider } from 'rebass' import { Head } from 'react-static' import Nav from '../components/Nav' import Bubbles from '../components/Bubbles' import Stripe from '../components/Stripe' import Features from '../components/Features' import Superpower from '../components/Superpower' import Collage from '../components/Collage' import Mosaic from '../components/Mosaic' import Start from '../components/Start' import Footer from '../components/Footer' import theme from '../theme' export default () => ( <Provider theme={theme}> <Head><title>Hack Club</title></Head> <Nav style={{ position: 'absolute', top: 0 }} cloud="true" /> <Bubbles /> <Stripe /> <Features /> <Superpower /> <Collage /> <Mosaic /> <Start /> <Footer /> </Provider> )
import React from 'react' import { Provider } from 'rebass' import { Head } from 'react-static' import Nav from '../components/Nav' import Bubbles from '../components/Bubbles' import Stripe from '../components/Stripe' import Features from '../components/Features' import Superpower from '../components/Superpower' import Collage from '../components/Collage' import Mosaic from '../components/Mosaic' import Start from '../components/Start' import Footer from '../components/Footer' import theme from '../theme' export default () => ( <Provider theme={theme}> <Head><title>Hack Club</title></Head> <Nav style={{ position: 'absolute', top: 0 }} cloud /> <Bubbles /> <Stripe /> <Features /> <Superpower /> <Collage /> <Mosaic /> <Start /> <Footer /> </Provider> )
Revert "Adding request context for proper url generation." This reverts commit 3fa12f6b36f7d1d0dd23cf28e79b7c54f1589fbc.
from todo import app from flask import jsonify, request, url_for from flask import json from todo.database import db_session from todo.models import Entry @app.route("/", methods=["GET", "POST", "DELETE"]) def index(): if request.method == "POST": request_json = request.get_json() entry = Entry(request_json["title"]) db_session.add(entry) db_session.commit() return jsonify(construct_dict(entry)) else: if request.method == "DELETE": Entry.query.delete() db_session.commit() response = [] for entry in Entry.query.all(): response.append(construct_dict(entry)) return json.dumps(response) @app.route("/<int:entry_id>") def entry(entry_id): return jsonify(construct_dict(Entry.query.filter(Entry.id == entry_id).first())) def construct_dict(entry): return dict(title=entry.title, completed=entry.completed, url=url_for("entry", entry_id=entry.id)) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
from todo import app from flask import jsonify, request, url_for from flask import json from todo.database import db_session from todo.models import Entry @app.route("/", methods=["GET", "POST", "DELETE"]) def index(): if request.method == "POST": request_json = request.get_json() entry = Entry(request_json["title"]) db_session.add(entry) db_session.commit() return jsonify(construct_dict(entry, request)) else: if request.method == "DELETE": Entry.query.delete() db_session.commit() response = [] for entry in Entry.query.all(): response.append(construct_dict(entry, request)) return json.dumps(response) @app.route("/<int:entry_id>") def entry(entry_id): return jsonify(construct_dict(Entry.query.filter(Entry.id == entry_id).first(), request)) def construct_dict(entry, request): with request: return dict(title=entry.title, completed=entry.completed, url=url_for("entry", entry_id=entry.id)) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
Make it possible to extend from `Error` in Babel 6.
function ExtendBuiltin(klass) { function ExtendableBuiltin() { klass.apply(this, arguments); } ExtendableBuiltin.prototype = Object.create(klass.prototype); ExtendableBuiltin.prototype.constructor = ExtendableBuiltin; return ExtendableBuiltin; } /** * A simple Error type to represent an error that occured while loading a * resource. * * @class LoadError * @extends Error */ export default class LoadError extends ExtendBuiltin(Error) { /** * Constructs a new LoadError with a supplied error message and an instance * of the AssetLoader service to use when retrying a load. * * @param {String} message * @param {AssetLoader} assetLoader */ constructor(message, assetLoader) { super(...arguments); this.name = 'LoadError'; this.message = message; this.loader = assetLoader; } /** * An abstract hook to define in a sub-class that specifies how to retry * loading the errored resource. */ retryLoad() { throw new Error(`You must define a behavior for 'retryLoad' in a subclass.`); } /** * Invokes a specified method on the AssetLoader service and caches the * result. Should be used in implementations of the retryLoad hook. * * @protected */ _invokeAndCache(method, ...args) { return this._retry || (this._retry = this.loader[method](...args)); } }
/** * A simple Error type to represent an error that occured while loading a * resource. * * @class LoadError * @extends Error */ export default class LoadError extends Error { /** * Constructs a new LoadError with a supplied error message and an instance * of the AssetLoader service to use when retrying a load. * * @param {String} message * @param {AssetLoader} assetLoader */ constructor(message, assetLoader) { super(...arguments); this.name = 'LoadError'; this.message = message; this.loader = assetLoader; } /** * An abstract hook to define in a sub-class that specifies how to retry * loading the errored resource. */ retryLoad() { throw new Error(`You must define a behavior for 'retryLoad' in a subclass.`); } /** * Invokes a specified method on the AssetLoader service and caches the * result. Should be used in implementations of the retryLoad hook. * * @protected */ _invokeAndCache(method, ...args) { return this._retry || (this._retry = this.loader[method](...args)); } }
Fix `exitstatus` sometimes not provided
from urllib.request import urlopen, URLError def pytest_terminal_summary(terminalreporter, exitstatus=None): # pylint: disable=unused-argument _add_patterns() if exitstatus == 0: _pattern('pytest-success') else: _pattern('pytest-failure') def _add_patterns(): _blink('pattern/add?pname=pytest-success&pattern=0.5,%2300ff00,0.5,%23000000,0.5') _blink('pattern/add?pname=pytest-failure&pattern=1,%23ff0000,0.3,1,%23ff0000,0.3,2,%23000000,0.1,0,%23ff0000,0.3,2,%23ff0000,0.3,1,%23000000,0.1,0') def _pattern(name): _blink('pattern/play?pname={}'.format(name)) def _blink(command): try: urlopen('http://localhost:8934/blink1/{}'.format(command)) except URLError as e: pass
from urllib.request import urlopen, URLError def pytest_terminal_summary(terminalreporter, exitstatus): # pylint: disable=unused-argument _add_patterns() if exitstatus == 0: _pattern('pytest-success') else: _pattern('pytest-failure') def _add_patterns(): _blink('pattern/add?pname=pytest-success&pattern=0.5,%2300ff00,0.5,%23000000,0.5') _blink('pattern/add?pname=pytest-failure&pattern=1,%23ff0000,0.3,1,%23ff0000,0.3,2,%23000000,0.1,0,%23ff0000,0.3,2,%23ff0000,0.3,1,%23000000,0.1,0') def _pattern(name): _blink('pattern/play?pname={}'.format(name)) def _blink(command): try: urlopen('http://localhost:8934/blink1/{}'.format(command)) except URLError as e: pass
Create container for both car make and model pickers
import React from 'react-native'; const { Image, TouchableOpacity, StyleSheet, Text, View, } = React; import globalStyles from '../styles/SearchGlobalStyles.js'; import CarMakePicker from './CarMakePicker.js'; import CarModelPicker from './CarModelPicker.js'; const CarMakePickerContainer = (props) => ({ render(){ return ( <View style={globalStyles.container}> <Text style={globalStyles.label}>Chose your car</Text> <View style={globalStyles.innerBox}> <CarMakePicker label='Make' /> <CarModelPicker label='Model' /> </View> </View> ); }, handleStartChange(value) { // this.props.onChange('priceRange', [value, this.props.value[1]]); }, handleEndChange(value) { // this.props.onChange('priceRange', [this.props.value[0], value]); } }); const styles = StyleSheet.create({ divider: { height: 20, width: 1, backgroundColor: '#ccc' }, }); export default CarMakePickerContainer;
import React from 'react-native'; const { Image, TouchableOpacity, StyleSheet, Text, View, } = React; import globalVariables from '../styles/globalVariables.js'; import CarMakePickers from './CarMakePickers.js'; import CarModelPickers from './CarModelPickers.js'; const CarMakePickerContainer(props) => ({ render(){ return ( <View style={globalStyles.container}> <Text style={globalStyles.label}>Chose your car</Text> <View style={globalStyles.innerBox}> <CarMakePickers label='Make' onChange={this.handleStartChange} value={this.props.value[0]} /> <CarModelPickers label='Model' onChange={this.handleEndChange} value={this.props.value[1]} /> </View> </View> ); }, handleStartChange(value) { // this.props.onChange('priceRange', [value, this.props.value[1]]); }, handleEndChange(value) { // this.props.onChange('priceRange', [this.props.value[0], value]); } }) export default CarMakePickerContainer;
TASK: Replace RouteComponent::class matchResults with ServerRequestAttributes::ROUTING_RESULTS
<?php namespace Neos\Flow\Mvc; use Neos\Flow\Annotations as Flow; use Neos\Flow\Http\Component\ComponentContext; use Neos\Flow\Http\Component\ComponentInterface; use Neos\Flow\Http\ServerRequestAttributes; use Neos\Flow\Security\Context; /** * */ class PrepareMvcRequestComponent implements ComponentInterface { /** * @Flow\Inject(lazy=false) * @var Context */ protected $securityContext; /** * @Flow\Inject * @var ActionRequestFactory */ protected $actionRequestFactory; /** * @inheritDoc */ public function handle(ComponentContext $componentContext) { $httpRequest = $componentContext->getHttpRequest(); $routingMatchResults = $httpRequest->getAttribute(ServerRequestAttributes::ROUTING_RESULTS) ?? []; $actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults); $this->securityContext->setRequest($actionRequest); $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest); } }
<?php namespace Neos\Flow\Mvc; use Neos\Flow\Annotations as Flow; use Neos\Flow\Http\Component\ComponentContext; use Neos\Flow\Http\Component\ComponentInterface; use Neos\Flow\Mvc\Routing\RoutingComponent; use Neos\Flow\Security\Context; /** * */ class PrepareMvcRequestComponent implements ComponentInterface { /** * @Flow\Inject(lazy=false) * @var Context */ protected $securityContext; /** * @Flow\Inject * @var ActionRequestFactory */ protected $actionRequestFactory; /** * @inheritDoc */ public function handle(ComponentContext $componentContext) { $httpRequest = $componentContext->getHttpRequest(); $routingMatchResults = $componentContext->getParameter(RoutingComponent::class, 'matchResults'); $actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults ?? []); $this->securityContext->setRequest($actionRequest); $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest); } }
Update build steps to only correct core-css version
import autoprefixer from 'autoprefixer' import postcss from 'rollup-plugin-postcss' import serve from 'rollup-plugin-serve' import header from 'postcss-header' import path from 'path' import fs from 'fs' import { version } from './package.json' if (!process.env.ROLLUP_WATCH) { const readme = String(fs.readFileSync(path.join('lib', 'readme.md'))) const versioned = readme.replace(/core-css\/major\/\d+/, `core-css/major/${version.match(/\d+/)}`) fs.writeFileSync(path.join('lib', 'readme.md'), versioned) } export default [{ input: 'lib/core-css.js', output: { file: 'lib/core-css.min.js', format: 'cjs' }, plugins: [ postcss({ minimize: { reduceIdents: { keyframes: false } }, sourceMap: !process.env.ROLLUP_WATCH, plugins: [ autoprefixer({ browsers: ['last 1 version', '> .1%', 'ie 9-11'] }), header({ header: `/*! @nrk/core-css v${version} - Copyright (c) 2018-${new Date().getFullYear()} NRK */` }) ], extract: true }), !process.env.ROLLUP_WATCH || serve('lib') ] }]
import autoprefixer from 'autoprefixer' import postcss from 'rollup-plugin-postcss' import serve from 'rollup-plugin-serve' import header from 'postcss-header' import path from 'path' import fs from 'fs' import { version } from './package.json' if (!process.env.ROLLUP_WATCH) { const readme = String(fs.readFileSync(path.join('lib', 'readme.md'))) const versioned = readme.replace(/\/major\/\d+/, `/major/${version.match(/\d+/)}`) fs.writeFileSync(path.join('lib', 'readme.md'), versioned) } export default [{ input: 'lib/core-css.js', output: { file: 'lib/core-css.min.js', format: 'cjs' }, plugins: [ postcss({ minimize: { reduceIdents: { keyframes: false } }, sourceMap: !process.env.ROLLUP_WATCH, plugins: [ autoprefixer({ browsers: ['last 1 version', '> .1%', 'ie 9-11'] }), header({ header: `/*! @nrk/core-css v${version} - Copyright (c) 2018-${new Date().getFullYear()} NRK */` }) ], extract: true }), !process.env.ROLLUP_WATCH || serve('lib') ] }]
Change id to String type to avoid data duplication.
package cl.fatman.capital.fund; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.time.LocalDate; @Entity @Table(name = "foment_unit") public class FomentUnit { @Id private String id; private double value; @Column(unique = true) private LocalDate date; public FomentUnit() { super(); } public FomentUnit(double value, LocalDate date) { super(); this.id = date.toString(); this.value = value; this.date = date; } public String getId() { return id; } public void setId(String id) { this.id = id; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } }
package cl.fatman.capital.fund; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import java.time.LocalDate; @Entity @Table(name = "foment_unit") public class FomentUnit { @Id @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") private int id; private double value; @Column(unique = true) private LocalDate date; public FomentUnit() { super(); } public FomentUnit(double value, LocalDate date) { super(); this.value = value; this.date = date; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } }
Refactor jasmin config to es6
/*global jasmine*/ const Jasmine = require('jasmine'), SpecReporter = require('jasmine-spec-reporter'), jrunner = new Jasmine(); let filter; process.argv.slice(2).forEach(option => { 'use strict'; if (option === 'full') { jasmine.getEnv().clearReporters(); jasmine.getEnv().addReporter(new SpecReporter({ displayStacktrace: 'all' })); } if (option === 'ci') { jasmine.getEnv().clearReporters(); jasmine.getEnv().addReporter(new SpecReporter({ displayStacktrace: 'all', displaySpecDuration: true, displaySuiteNumber: true, colors: false, prefixes: { success: '[pass] ', failure: '[fail] ', pending: '[skip] ' } })); } if (option.match('^filter=')) { filter = option.match('^filter=(.*)')[1]; } }); jrunner.loadConfigFile(); // load jasmine.json configuration jrunner.execute(undefined, filter);
/*global jasmine, require, process*/ var Jasmine = require('jasmine'), SpecReporter = require('jasmine-spec-reporter'), jrunner = new Jasmine(), filter; process.argv.slice(2).forEach(function (option) { 'use strict'; if (option === 'full') { jasmine.getEnv().clearReporters(); jasmine.getEnv().addReporter(new SpecReporter({ displayStacktrace: 'all' })); } if (option === 'ci') { jasmine.getEnv().clearReporters(); jasmine.getEnv().addReporter(new SpecReporter({ displayStacktrace: 'all', displaySpecDuration: true, displaySuiteNumber: true, colors: false, prefixes: { success: '[pass] ', failure: '[fail] ', pending: '[skip] ' } })); } if (option.match('^filter=')) { filter = option.match('^filter=(.*)')[1]; } }); jrunner.loadConfigFile(); // load jasmine.json configuration jrunner.execute(undefined, filter);
[AC-7049] Add tests for the functionality added
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals from django.test import TestCase from accelerator.tests.factories import ProgramCycleFactory class TestProgramCycle(TestCase): def test_display_name_no_short_name(self): cycle = ProgramCycleFactory(short_name=None) assert cycle.name in str(cycle) # def test_program_cycle_has_default_application_type(self): # cycle = ProgramCycleFactory() # if (cycle.applications_open and # not cycle.default_application_type): # self.assertRaises("Open applications must have" # "a default application type.") # def test_program_cycle_cannot_remove_default_application_type(self): # cycle = ProgramCycleFactory() # if (cycle.applications_open and # not cycle.default_application_type # and cycle.programs.exists()): # self.assertRaises("Default application type can’t be removed" # "from the cycle until the program cycle is" # "disassociated with all programs")
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals from django.test import TestCase from accelerator.tests.factories import ProgramCycleFactory class TestProgramCycle(TestCase): def test_display_name_no_short_name(self): cycle = ProgramCycleFactory(short_name=None) assert cycle.name in str(cycle) def test_program_cycle_with_open_applications_has_default_application_type(self): cycle = ProgramCycleFactory() if (cycle.applications_open and not cycle.default_application_type): self.assertRaises("Open applications must have a default application type.") def test_program_cycle_with_open_applications_has_default_application_type_and_associated_programs(self): cycle = ProgramCycleFactory() if (cycle.applications_open and not cycle.default_application_type and cycle.programs.exists()): self.assertRaises("Default application type can’t be removed" "from the cycle until the program cycle is" "disassociated with all programs")
Convert string double-quotes to single-quotes
'use strict'; var peg = require('pegjs'); class PegJsPlugin { constructor(config) { this.config = config.plugins.pegjs; // The output of the below peg.generate() function must be a string, not an // object this.config.output = 'source'; } compile(file) { var parser; try { parser = peg.generate(file.data, this.config); } catch(error) { if (error instanceof peg.parser.SyntaxError) { error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`; } return Promise.reject(error); } return Promise.resolve({data: parser}); } } // brunchPlugin must be set to true for all Brunch plugins PegJsPlugin.prototype.brunchPlugin = true; // The type of file to generate PegJsPlugin.prototype.type = 'javascript'; // The extension for files to process PegJsPlugin.prototype.extension = 'pegjs'; module.exports = PegJsPlugin;
'use strict'; var peg = require('pegjs'); class PegJsPlugin { constructor(config) { this.config = config.plugins.pegjs; // The output of the below peg.generate() function must be a string, not an // object this.config.output = 'source'; } compile(file) { var parser; try { parser = peg.generate(file.data, this.config); } catch(error) { if (error instanceof peg.parser.SyntaxError) { error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`; } return Promise.reject(error); } return Promise.resolve({data: parser}); } } // brunchPlugin must be set to true for all Brunch plugins PegJsPlugin.prototype.brunchPlugin = true; // The type of file to generate PegJsPlugin.prototype.type = "javascript"; // The extension for files to process PegJsPlugin.prototype.extension = "pegjs"; module.exports = PegJsPlugin;
Make sure the new url filename is lower case Apparently doc.qt.io does case insensitive file matching, doc-snapshot.qt.io doesn't.
// Copyright (c) 2015 Narwhal Software s.r.l. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. // Global accessor that the popup uses. var pattern = /^(https?:\/\/)((doc-snapshots.qt.io)|(doc.qt.io))\/([^\/]+)\/(.*)/ chrome.runtime.onInstalled.addListener(function() { chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { chrome.declarativeContent.onPageChanged.addRules([ { conditions: [ new chrome.declarativeContent.PageStateMatcher({ pageUrl: { urlMatches: '^https?://((doc-snapshots.qt.io)|(doc.qt.io))/(qt)?[-0-9.]+/(.+)$' }, }) ], actions: [ new chrome.declarativeContent.ShowPageAction() ] } ]); }); }); chrome.pageAction.onClicked.addListener(function(tab) { var match = pattern.exec(tab.url); var newUrl = match[1] + "doc-snapshots.qt.io/qt5-dev/" + match[6].toLowerCase(); chrome.tabs.update(tab.id, {url: newUrl}); });
// Copyright (c) 2015 Narwhal Software s.r.l. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. // Global accessor that the popup uses. var pattern = /^(https?:\/\/)((doc-snapshots.qt.io)|(doc.qt.io))\/([^\/]+)\/(.*)/ chrome.runtime.onInstalled.addListener(function() { chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { chrome.declarativeContent.onPageChanged.addRules([ { conditions: [ new chrome.declarativeContent.PageStateMatcher({ pageUrl: { urlMatches: '^https?://((doc-snapshots.qt.io)|(doc.qt.io))/(qt)?[-0-9.]+/(.+)$' }, }) ], actions: [ new chrome.declarativeContent.ShowPageAction() ] } ]); }); }); chrome.pageAction.onClicked.addListener(function(tab) { var match = pattern.exec(tab.url); var newUrl = match[1] + "doc-snapshots.qt.io/qt5-dev/" + match[6]; chrome.tabs.update(tab.id, {url: newUrl}); });
Use query rather than params to read GET params
var express = require('express'); var fs = require('fs'); var app = express(); var storagePath = "./toilet_status.txt"; // TODO: permission denied in /data app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); app.get('/update', function(req, res) { console.log(new Date().toString(), "Received update:", req.query.status); fs.writeFileSync(storagePath, JSON.stringify({ status: req.query.status })); res.json({ success: true }); }); app.get('/status', function(req, res) { try { var data = fs.readFileSync(storagePath); res.json(JSON.parse(data)); } catch(e) { res.json({ status: "no data yet" }); } }); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); });
var express = require('express'); var fs = require('fs'); var app = express(); var storagePath = "./toilet_status.txt"; app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); app.get('/update', function(req, res) { console.log(new Date().toString(), "Received update:", req.params.status); fs.writeFileSync(storagePath, JSON.stringify({ status: req.params.status })); res.json({ success: true }); }); app.get('/status', function(req, res) { try { var data = fs.readFileSync(storagePath); res.json(JSON.parse(data)); } catch(e) { res.json({ status: "no data yet" }); } }); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); });
Add PyYAML to ``ssl`` extras_require
import sys try: import setuptools except ImportError: from distribute_setup import use_setuptools use_setuptools() import setuptools from pip import req from setuptools.command import test REQ = set([dep.name for dep in req.parse_requirements('requirements/base.txt')]) TREQ = set([dep.name or dep.url for dep in req.parse_requirements('requirements/tests.txt')]) - REQ try: import importlib except ImportError: REQ.add('importlib') class PyTest(test.test): def finalize_options(self): test.test.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) setuptools.setup(setup_requires=('d2to1',), install_requires=REQ, tests_require=TREQ, extras_require={'ssl': ('pycrypto', 'PyYAML')}, cmdclass={'test': PyTest}, d2to1=True)
import sys try: import setuptools except ImportError: from distribute_setup import use_setuptools use_setuptools() import setuptools from pip import req from setuptools.command import test REQ = set([dep.name for dep in req.parse_requirements('requirements/base.txt')]) TREQ = set([dep.name or dep.url for dep in req.parse_requirements('requirements/tests.txt')]) - REQ try: import importlib except ImportError: REQ.add('importlib') class PyTest(test.test): def finalize_options(self): test.test.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) setuptools.setup(setup_requires=('d2to1',), install_requires=REQ, tests_require=TREQ, extras_require={'ssl': ('pycrypto',)}, cmdclass={'test': PyTest}, d2to1=True)
WORK WORK CARRY MOVE MOVEx2+Bracket fixings
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
Add support for drawing the interpreted segments into a data collector. git-svn-id: a0d2519504059b70a86a1ce51b726c2279190bad@24833 6e01202a-0783-4428-890a-84243c50cc2b
package org.concord.datagraph.analysis; import java.awt.Component; import java.util.ArrayList; import org.concord.data.state.OTDataStore; import org.concord.datagraph.analysis.rubric.GraphRubric; import org.concord.datagraph.analysis.rubric.ResultSet; import org.concord.datagraph.state.OTDataCollector; import org.concord.datagraph.state.OTDataGraphable; import org.concord.framework.otrunk.OTObjectList; import org.concord.graph.util.state.OTHideableAnnotation; public interface GraphAnalyzer { public Graph getSegments(OTDataStore dataStore, int xChannel, int yChannel, double tolerance) throws IndexOutOfBoundsException; public GraphRubric buildRubric(OTObjectList rubric); public ResultSet compareGraphs(GraphRubric expected, Graph received); public String getHtmlReasons(ResultSet results); public void displayHtmlReasonsPopup(Component parent, ResultSet results); public ArrayList<OTHideableAnnotation> annotateResults(OTDataCollector dataCollector, ResultSet scoreResults); public OTDataGraphable drawSegmentResults(OTDataCollector dataCollector, Graph graph); }
package org.concord.datagraph.analysis; import java.awt.Component; import java.util.ArrayList; import org.concord.data.state.OTDataStore; import org.concord.datagraph.analysis.rubric.GraphRubric; import org.concord.datagraph.analysis.rubric.ResultSet; import org.concord.datagraph.state.OTDataCollector; import org.concord.framework.otrunk.OTObjectList; import org.concord.graph.util.state.OTHideableAnnotation; public interface GraphAnalyzer { public Graph getSegments(OTDataStore dataStore, int xChannel, int yChannel, double tolerance) throws IndexOutOfBoundsException; public GraphRubric buildRubric(OTObjectList rubric); public ResultSet compareGraphs(GraphRubric expected, Graph received); public String getHtmlReasons(ResultSet results); public void displayHtmlReasonsPopup(Component parent, ResultSet results); public ArrayList<OTHideableAnnotation> annotateResults(OTDataCollector studentObject, ResultSet scoreResults); }
Fix keys case into details panel
'use strict'; let blessed = require('blessed'); let _ = require('lodash'); let config = require('../../config/config'); module.exports = function () { let hostDetailsPanel = blessed.list({ top: 5, bottom: 5, left: '30%', tags: true, border: {type: 'line'}, keys: true, scrollable: true, style: config.styles.main }); hostDetailsPanel.updateItems = function (host) { let items = []; _.forEach(host, function (val, key) { if (_.isArray(val)) val = val.join(', '); key = key[0].toUpperCase() + key.slice(1); let content = '{bold}' + key + '{/bold} : ' + val + '\n'; items.push(content); }); this.setItems(items); }; return hostDetailsPanel; };
'use strict'; let blessed = require('blessed'); let _ = require('lodash'); let config = require('../../config/config'); module.exports = function () { let hostDetailsPanel = blessed.list({ top: 5, bottom: 5, left: '30%', tags: true, border: {type: 'line'}, keys: true, scrollable: true, style: config.styles.main }); hostDetailsPanel.updateItems = function (host) { let items = []; _.forEach(host, function (val, key) { if (_.isArray(val)) val = val.join(', '); let content = '{bold}' + key + '{/bold} : ' + val + '\n'; items.push(content); }); this.setItems(items); }; return hostDetailsPanel; };
Fix an issue with children missing
var isFunction = require('lodash.isfunction'); var joi = require('joi'); var pc = require('pascal-case'); /* Public */ function attach(schema) { var attachments = {}; schema && schema._inner && schema._inner.children && schema._inner.children.forEach(function (child) { attachments[pc(child.key)] = { get: function () { return child.schema; } }; }); return Object.defineProperties(schema, attachments); } function spec(type, params) { var after, spec; if (arguments.length === 1) { params = type; type = params.type; delete params.type; } if (isFunction(params.after)) { after = params.after; delete params.after; } spec = joi[type](); Object.keys(params).forEach(function (key) { spec = Array.isArray(params[key]) ? spec[key].apply(spec, params[key]) : spec[key](params[key]); }); if (after) { after(spec); } return spec; } /* Exports */ module.exports.attach = attach; module.exports.spec = spec;
var isFunction = require('lodash.isfunction'); var joi = require('joi'); var pc = require('pascal-case'); /* Public */ function attach(schema) { var attachments = {}; schema && schema._inner && schema._inner.children.forEach(function (child) { attachments[pc(child.key)] = { get: function () { return child.schema; } }; }); return Object.defineProperties(schema, attachments); } function spec(type, params) { var after, spec; if (arguments.length === 1) { params = type; type = params.type; delete params.type; } if (isFunction(params.after)) { after = params.after; delete params.after; } spec = joi[type](); Object.keys(params).forEach(function (key) { spec = Array.isArray(params[key]) ? spec[key].apply(spec, params[key]) : spec[key](params[key]); }); if (after) { after(spec); } return spec; } /* Exports */ module.exports.attach = attach; module.exports.spec = spec;
Fix onupdate not using current time
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from datetime import datetime from api.models import JSONSerializer from api import db from api.visits.models import Visit class Location(db.Model, JSONSerializer): __tablename__ = 'locations' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False, unique=True) occupied = db.Column(db.Boolean, nullable=False, default=False) changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now) average_duration = db.Column(db.Integer, default=0) token = db.relationship('Token', backref='locations', uselist=False) def __init__(self, name): self.name = name def __repr__(self): return '<Location {}>'.format(self.name) def calculate_average(self): visits = Visit.query.with_entities(Visit.duration).all() # Flatten list visits = list(sum(visits, ())) self.average_duration = sum(visits) / len(visits)
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from datetime import datetime from api.models import JSONSerializer from api import db from api.visits.models import Visit class Location(db.Model, JSONSerializer): __tablename__ = 'locations' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False, unique=True) occupied = db.Column(db.Boolean, nullable=False, default=False) changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now()) average_duration = db.Column(db.Integer, default=0) token = db.relationship('Token', backref='locations', uselist=False) def __init__(self, name): self.name = name def __repr__(self): return '<Location {}>'.format(self.name) def calculate_average(self): visits = Visit.query.with_entities(Visit.duration).all() # Flatten list visits = list(sum(visits, ())) self.average_duration = sum(visits) / len(visits)
Update color example to work the way it should.
package main import ( "log" "time" "github.com/briandowns/spinner" ) func main() { s := spinner.New(spinner.CharSets[0], 100*time.Millisecond) s.Prefix = "Colors: " if err := s.Color("yellow"); err != nil { log.Fatalln(err) } s.Start() time.Sleep(4 * time.Second) if err := s.Color("red"); err != nil { log.Fatalln(err) } s.UpdateCharSet(spinner.CharSets[20]) s.Reverse() s.Restart() time.Sleep(4 * time.Second) if err := s.Color("blue"); err != nil { log.Fatalln(err) } s.UpdateCharSet(spinner.CharSets[3]) s.Restart() time.Sleep(4 * time.Second) if err := s.Color("cyan"); err != nil { log.Fatalln(err) } s.UpdateCharSet(spinner.CharSets[28]) s.Reverse() s.Restart() time.Sleep(4 * time.Second) if err := s.Color("green"); err != nil { log.Fatalln(err) } s.UpdateCharSet(spinner.CharSets[25]) s.Restart() time.Sleep(4 * time.Second) s.Stop() }
package main import ( "log" "time" "github.com/briandowns/spinner" ) func main() { s := spinner.New(spinner.CharSets[0], 100*time.Millisecond) s.Prefix = "Colors: " if err := s.Color("yellow"); err != nil { log.Fatalln(err) } s.Start() time.Sleep(4 * time.Second) s.Color("red") s.UpdateCharSet(spinner.CharSets[20]) s.Reverse() s.Restart() time.Sleep(4 * time.Second) s.Color("blue") s.UpdateCharSet(spinner.CharSets[3]) s.Restart() time.Sleep(4 * time.Second) s.Color("cyan") s.UpdateCharSet(spinner.CharSets[28]) s.Reverse() s.Restart() time.Sleep(4 * time.Second) s.Color("green") s.UpdateCharSet(spinner.CharSets[25]) s.Restart() time.Sleep(4 * time.Second) s.Stop() }
Update to the about dialog text
import React from 'react'; const AboutDialog = ({ closeDialog }) => ( <div> <button className="dialog-close" onClick={closeDialog}> <i className="icon-close" /> </button> <p> This is a Mine Sweeper game built with React and Redux. <br /> <br /> You can play it in the same way as the original Mine Sweeper. </p> <ul> <li>Left Click to open a tile</li> <li>Right Click to &quot;flag&quot; a tile</li> <li>You&apos;ll lose if you open a mine</li> <li>You&apos;ll win if you open all mine-free tiles</li> </ul> <p className="about-footer"> Good luck ! <br /> <br /> <a target="_blank" href="https://twitter.com/hihuz" rel="noopener noreferrer">@hihuz</a> </p> </div> ); export default AboutDialog;
import React from 'react'; const AboutDialog = ({ closeDialog }) => ( <div> <button className="dialog-close" onClick={closeDialog}> <i className="icon-close" /> </button> <p> This is a MineSweeper game implemented with React and Redux. <br /> <br /> You can play it in the same way as the original MineSweeper. </p> <ul> <li>Left Click to open a tile</li> <li>Right Click to &quot;flag&quot; a tile</li> <li>You&apos;ll lose if you open a mine</li> <li>You&apos;ll win if you open all mine-free tiles</li> </ul> <p className="about-footer"> Good luck ! <br /> <br /> <a target="_blank" href="https://twitter.com/hihuz" rel="noopener noreferrer">@hihuz</a> </p> </div> ); export default AboutDialog;
Truncate the file before writing more data.
#! /usr/bin/env python3 import sys import json import argparse def format_json(fp): try: data = json.load(fp) except ValueError: sys.stderr.write("In file: {}\n".format(fp.name)) raise # Jump back to the beginning of the file before overwriting it. fp.seek(0) fp.truncate(0) json.dump(data, fp, ensure_ascii=False, indent=4, separators=(',', ': '), sort_keys=True) fp.write('\n') # add a trailing newline. fp.close() if __name__ == '__main__': parser = argparse.ArgumentParser( description='Format JSON files in place.' ) parser.add_argument( 'files', type=argparse.FileType('r+'), help='JSON filepaths', nargs='+' ) args = parser.parse_args() for json_file in args.files: format_json(json_file)
#! /usr/bin/env python3 import sys import json import argparse def format_json(fp): try: data = json.load(fp) except ValueError: sys.stderr.write("In file: {}\n".format(fp.name)) raise # Jump back to the beginning of the file before overwriting it. fp.seek(0) json.dump(data, fp, ensure_ascii=False, indent=4, separators=(',', ': '), sort_keys=True) fp.write('\n') # add a trailing newline. fp.close() if __name__ == '__main__': parser = argparse.ArgumentParser( description='Format JSON files in place.' ) parser.add_argument( 'files', type=argparse.FileType('r+'), help='JSON filepaths', nargs='+' ) args = parser.parse_args() for json_file in args.files: format_json(json_file)
Enable the Norwegian kindergartens again (not yet visible due to lack of data in the right repo)
/** * Different datasets the tool can use * * The first-level keys are country names, in English, * as they will appear in the app * * The second level names are database identifiers. * These ids are used in the url, so should be as short as possible * * The name of a database will be visible in the app, and may be localised * The url can be a relative url, or an absolute one (starting with http:) * Relative URLs make testing on a local server easier. */ var datasets = { "Belgium": { "BE_dl": { "url": "datasets/belgium-haltes-de-lijn/", "name": "Haltes De Lijn", }, }, "Italy": { "IT_fuel": { "url": "datasets/Italia-stazioni-di-servizo/", "name": "Stazioni di servizo", } }, "Norway" : { "NO_kg": { "url": "datasets/norge-barnehagefakta/", "name": "Barnehagefakta", } } };
/** * Different datasets the tool can use * * The first-level keys are country names, in English, * as they will appear in the app * * The second level names are database identifiers. * These ids are used in the url, so should be as short as possible * * The name of a database will be visible in the app, and may be localised * The url can be a relative url, or an absolute one (starting with http:) * Relative URLs make testing on a local server easier. */ var datasets = { "Belgium": { "BE_dl": { "url": "datasets/belgium-haltes-de-lijn/", "name": "Haltes De Lijn", }, }, "Italy": { "IT_fuel": { "url": "datasets/Italia-stazioni-di-servizo/", "name": "Stazioni di servizo", } }, /* "Norway" : { "NO_kg": { "url": "http://obtitus.github.io/barnehagefakta_osm_data/POI-Importer-data/dataset.json", "name": "Barnehagefakta fra Utdanningsdirektoratet", } }*/ };
Change mecanism to retrive LAN IP
<?php function getLanIpAddr() { $lanIpAddr = null; exec("arp -a", $output); if (is_array($output)) { preg_match('/\((.*)\)/', $output[0], $ipInfos); $lanIpAddr = $ipInfos[1]; // var_dump($lanIpAddr); // exit; } return $lanIpAddr; } define('ROOT_DIR', __DIR__); define('IP_ADDR', getLanIpAddr()); if (is_dir(ROOT_DIR . '/LOCALHOSTR')) { define('APP_FOLDER', 'LOCALHOSTR'); } else { define('APP_FOLDER', '.'); } define('LOCALHOSTR', realpath(ROOT_DIR . '/' . APP_FOLDER)); require LOCALHOSTR . '/core/HostR.php'; require LOCALHOSTR . '/core/HostRAPI.php'; $hostR = new HostR(LOCALHOSTR . '/config.json'); if ($hostR->isService('phpinfos')) { phpinfo(); } else if ($hostR->isService()) { $hostRAPI = new HostRAPI($hostR); return $hostRAPI->getResponse(); } else { $hostR->render(LOCALHOSTR . '/templates/index.phtml'); } exit;
<?php function getLanIpAddr() { $lanIpAddr = null; exec("ifconfig en1 inet", $output); foreach ($output as $value) { if (strpos($value, 'inet') !== false) { preg_match('/[(0-9.)]+/', $value, $matches); $lanIpAddr = count($matches) ? $matches[0] : null; } } return $lanIpAddr; } define('ROOT_DIR', __DIR__); define('IP_ADDR', getLanIpAddr()); if (is_dir(ROOT_DIR . '/LOCALHOSTR')) { define('APP_FOLDER', 'LOCALHOSTR'); } else { define('APP_FOLDER', '.'); } define('LOCALHOSTR', realpath(ROOT_DIR . '/' . APP_FOLDER)); require LOCALHOSTR . '/core/HostR.php'; require LOCALHOSTR . '/core/HostRAPI.php'; $hostR = new HostR(LOCALHOSTR . '/config.json'); if ($hostR->isService('phpinfos')) { phpinfo(); } else if ($hostR->isService()) { $hostRAPI = new HostRAPI($hostR); return $hostRAPI->getResponse(); } else { $hostR->render(LOCALHOSTR . '/templates/index.phtml'); } exit;
Fix for current environment display
'use strict'; const Prismic = require('./prismic'); const Predicates = require('prismic.io').Predicates; const _ = require('lodash'); const getQuotes = (api) => api .form('everything') .ref(Prismic.getEnvironment(api)) .query(Predicates.at('document.type', 'quotes')) .submit() .then((quotes) => { return _.map(quotes.results, (result) => { return _.map(result.data, (datum) => { return datum.value[0].text; }); }); }); const homeHandler = (request, reply) => { Prismic.getAPI().then((api) => { const isProductionEnvironment = Prismic.getEnvironment(api) === api.master(); getQuotes(api).then((quotes) => { reply.view('quotes', { quotes: quotes, environment: isProductionEnvironment ? 'Production' : 'Staging' }); }); }); }; module.exports = { method: 'GET', path: '/', handler: homeHandler };
'use strict'; const Prismic = require('./prismic'); const Predicates = require('prismic.io').Predicates; const _ = require('lodash'); const getQuotes = (api) => api .form('everything') .ref(Prismic.getEnvironment(api)) .query(Predicates.at('document.type', 'quotes')) .submit() .then((quotes) => { return _.map(quotes.results, (result) => { return _.map(result.data, (datum) => { return datum.value[0].text; }); }); }); const homeHandler = (request, reply) => { Prismic.getAPI().then((api) => { const stagingReleaseRef = api.ref(process.env.PRISMIC_IO_STAGING_RELEASE_NAME); getQuotes(api).then((quotes) => { reply.view('quotes', { quotes: quotes, environment: stagingReleaseRef ? 'Staging' : 'Production' }); }); }); }; module.exports = { method: 'GET', path: '/', handler: homeHandler };
Add 'qscintilla' to the program requirements
from setuptools import setup requirements = [ 'pyqt5', 'qscintilla' ] test_requirements = [ 'pytest', 'pytest-cov', 'pytest-faulthandler', 'pytest-mock', 'pytest-qt', 'pytest-xvfb', ] setup( name='EasyEdit', version='0.0.1', description="A PyQt5 cross-platform text editor", author="Matthew S. Klosak", author_email='msklosak@gmail.com', url='https://github.com/msklosak/EasyEdit', packages=['easyedit', 'tests'], entry_points={ 'console_scripts': [ 'EasyEdit=easyedit.editor:main' ] }, install_requires=requirements, zip_safe=False, keywords='EasyEdit', classifiers=[ 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements )
from setuptools import setup requirements = [ 'pyqt5' ] test_requirements = [ 'pytest', 'pytest-cov', 'pytest-faulthandler', 'pytest-mock', 'pytest-qt', 'pytest-xvfb', ] setup( name='EasyEdit', version='0.0.1', description="A PyQt5 cross-platform text editor", author="Matthew S. Klosak", author_email='msklosak@gmail.com', url='https://github.com/msklosak/EasyEdit', packages=['easyedit', 'tests'], entry_points={ 'console_scripts': [ 'EasyEdit=easyedit.editor:main' ] }, install_requires=requirements, zip_safe=False, keywords='EasyEdit', classifiers=[ 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements )
Remove trailing whitespace on component integration test
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %> import hbs from 'htmlbars-inline-precompile';<% } %> moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', { <% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'], unit: true<% } %> }); test('it renders', function(assert) { <% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... });" + EOL + EOL + this.render(hbs`{{<%= componentPathName %>}}`); assert.equal(this.$().text().trim(), ''); // Template block usage:" + EOL + this.render(hbs` {{#<%= componentPathName %>}} template block text {{/<%= componentPathName %>}} `); assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %> // Creates the component instance /*let component =*/ this.subject(); // Renders the component to the page this.render(); assert.equal(this.$().text().trim(), '');<% } %> });
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %> import hbs from 'htmlbars-inline-precompile';<% } %> moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', { <% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'], unit: true<% } %> }); test('it renders', function(assert) { <% if (testType === 'integration' ) { %> // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... });" + EOL + EOL + this.render(hbs`{{<%= componentPathName %>}}`); assert.equal(this.$().text().trim(), ''); // Template block usage:" + EOL + this.render(hbs` {{#<%= componentPathName %>}} template block text {{/<%= componentPathName %>}} `); assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %> // Creates the component instance /*let component =*/ this.subject(); // Renders the component to the page this.render(); assert.equal(this.$().text().trim(), '');<% } %> });
Fix help information not showing up
import commander from 'commander'; import containerInit from './init'; import fs from 'fs'; import path from 'path'; commander .command('serve') .alias('s') .description('serve ap-npm') .option('--config', "config file to use") .action(function(config) { let container; if (fs.existsSync(config)) { console.log("using config: " + config + '\n'); container = containerInit(config); } else if (typeof config === 'string') { if (fs.existsSync(path.join(__dirname, '../', config))) { let configLocation = path.join(__dirname, '../', config); console.log("using config: " + configLocation + '\n'); container = containerInit(configLocation); } } else { console.log("using default config\n"); container = containerInit("../config.json"); } let command = container.get('command-serve'); command.run(); }); commander.parse(process.argv); if (!process.argv.slice(2).length) { commander.outputHelp(); }
import commander from 'commander'; import containerInit from './init'; import fs from 'fs'; import path from 'path'; commander .command('serve') .alias('s') .description('serve ap-npm') .option('--config', "config file to use") .action(function(config) { let container; if (fs.existsSync(config)) { console.log("using config: " + config + '\n'); container = containerInit(config); } else if (typeof config === 'string') { if (fs.existsSync(path.join(__dirname, '../', config))) { let configLocation = path.join(__dirname, '../', config); console.log("using config: " + configLocation + '\n'); container = containerInit(configLocation); } } else { console.log("using default config\n"); container = containerInit("../config.json"); } let command = container.get('command-serve'); command.run(); }); commander.parse(process.argv); if (!process.argv.length) { commander.outputHelp(); }
Add a new column: moves per attack.
@section('title') Melee - Cataclysm: Dark Days Ahead @endsection @section('content') <h1>Melee</h1> <p> Items with bashing+cutting damage higher than 10 and to-hit bonus higher than -2 </p> <table class="table table-bordered table-hover tablesorter"> <thead> <tr> <th></th> <th>Name</th> <th>Material</th> <th><span title="Volume">V</span></th> <th><span title="Weight">W</span></th> <th><span title="Moves per attack">M/A</span></th> <th><span title="Bashing+Cutting">Dmg</span></th> <th><span title="To-Hit">H</span></th> </tr> </thead> @foreach($items as $item) <tr> <td>{{ $item->symbol }}</td> <td><a href="{{route('item.view', $item->id)}}">{{ $item->name }}</a></td> <td>{{ $item->materials }}</td> <td>{{ $item->volume }}</td> <td>{{ $item->weight }}</td> <td>{{ $item->movesPerAttack }}</td> <td>{{ $item->bashing+$item->cutting }}</td> <td>{{ $item->to_hit }}</td> </tr> </tr> @endforeach </table> <script> $(function() { $(".tablesorter").tablesorter({ sortList: [[7,1]] }); }); </script> @endsection
@section('title') Melee - Cataclysm: Dark Days Ahead @endsection @section('content') <h1>Melee</h1> <p> Items with bashing+cutting damage higher than 10 and to-hit bonus higher than -2 </p> <table class="table table-bordered table-hover tablesorter"> <thead> <tr> <th></th> <th>Name</th> <th>Material</th> <th><span title="Volume">V</span></th> <th><span title="Weight">W</span></th> <th><span title="Bashing+Cutting">Dmg</span></th> <th><span title="To-Hit">H</span></th> </tr> </thead> @foreach($items as $item) <tr> <td>{{ $item->symbol }}</td> <td><a href="{{route('item.view', $item->id)}}">{{ $item->name }}</a></td> <td>{{ $item->materials }}</td> <td>{{ $item->volume }}</td> <td>{{ $item->weight }}</td> <td>{{ $item->bashing+$item->cutting }}</td> <td>{{ $item->to_hit }}</td> </tr> </tr> @endforeach </table> <script> $(function() { $(".tablesorter").tablesorter({ sortList: [[7,1]] }); }); </script> @endsection
Fix ZeroLazyVariable size returned by white noise kernel
import torch from . import Kernel from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable class WhiteNoiseKernel(Kernel): def __init__(self, variances): super(WhiteNoiseKernel, self).__init__() self.register_buffer("variances", variances) def forward(self, x1, x2): if self.training: return DiagLazyVariable(self.variances.unsqueeze(0)) elif x1.size(-2) == x2.size(-2) and x1.size(-2) == self.variances.size(-1) and torch.equal(x1, x2): return DiagLazyVariable(self.variances.unsqueeze(0)) else: return ZeroLazyVariable(x1.size(-3), x1.size(-2), x2.size(-2), device=x1.device)
import torch from . import Kernel from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable class WhiteNoiseKernel(Kernel): def __init__(self, variances): super(WhiteNoiseKernel, self).__init__() self.register_buffer("variances", variances) def forward(self, x1, x2): if self.training: return DiagLazyVariable(self.variances.unsqueeze(0)) elif x1.size(-2) == x2.size(-2) and x1.size(-2) == self.variances.size(-1) and torch.equal(x1, x2): return DiagLazyVariable(self.variances.unsqueeze(0)) else: return ZeroLazyVariable(x1.size(-3), x1.size(-2), x1.size(-1), device=x1.device)
Add install-time error message for Python 3.1 and earlier.
from __future__ import print_function import sys from setuptools import setup if sys.version_info < (3, 2): print('ERROR: jump-consistent-hash requires Python version 3.2 or newer.', file=sys.stderr) sys.exit(1) setup(name='jump_consistent_hash', version='1.0.0', description='Implementation of the Jump Consistent Hash algorithm', author='Peter Renström', license='MIT', url='https://github.com/renstrom/python-jump-consistent-hash', packages=['jump'], test_suite='tests', keywords=[ 'jump hash', 'jumphash', 'consistent hash', 'hash algorithm', 'hash' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4' ])
from setuptools import setup setup(name='jump_consistent_hash', version='1.0.0', description='Implementation of the Jump Consistent Hash algorithm', author='Peter Renström', license='MIT', url='https://github.com/renstrom/python-jump-consistent-hash', packages=['jump'], test_suite='tests', keywords=[ 'jump hash', 'jumphash', 'consistent hash', 'hash algorithm', 'hash' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4' ])
Add --list option to typical The option, when enabled, will print all available recipes from the current working directory. It will not run any recipes.
#! /usr/bin/env node const program = require('commander') const colors = require('colors') const configResolver = require('./src/configResolver') const configWriter = require('./src/configWriter') const interpolationResolver = require('./src/interpolationResolver') let configElement = '_default' // Set up and parse program arguments. // We only really care about the first positional argument // giving use the correct config to use program .arguments('[configElement]') .action(_configElement => { configElement = _configElement }) .option('-s, --scan', 'Automatically detect interpolatinos from content') .option('-l, --list', 'List available typical recipes recipes') .parse(process.argv) // Merge regular config file and folder config let config = Object.assign( {}, configResolver.resolve(), configResolver.resolveFolderConfig() ) // If list is true, we simply list the available recipes if (program.list) { console.log(colors.green('Available typical recipes:')) Object.keys(config).forEach(element => { console.log(colors.gray(' + ' + element.toString())) }) process.exit(1) } // Does it exist? if (!config[configElement]) { console.error('Found no recipe named \'' + configElement + '\' in resolved config') process.exit(1) } let resolvedElement = config[configElement] if (program.scan) { interpolationResolver.scan(resolvedElement, (result) => { resolvedElement.__interpolations__ = (resolvedElement.__interpolations__ || []).concat(result) configWriter.write(resolvedElement) }) } else { configWriter.write(resolvedElement) }
#! /usr/bin/env node let program = require('commander') let configResolver = require('./src/configResolver') let configWriter = require('./src/configWriter') let interpolationResolver = require('./src/interpolationResolver') let configElement = '_default' // Set up and parse program arguments. // We only really care about the first positional argument // giving use the correct config to use program .arguments('[configElement]') .action(_configElement => { configElement = _configElement }) .option('-s, --scan', 'Automatically detect interpolatinos from content') .parse(process.argv) // Merge regular config file and folder config let config = Object.assign( {}, configResolver.resolve(), configResolver.resolveFolderConfig() ) // Does it exist? if (!config[configElement]) { console.error('Found no recipe named \'' + configElement + '\' in resolved config') process.exit(1) } let resolvedElement = config[configElement] if (program.scan) { interpolationResolver.scan(resolvedElement, (result) => { resolvedElement.__interpolations__ = (resolvedElement.__interpolations__ || []).concat(result) configWriter.write(resolvedElement) }) } else { configWriter.write(resolvedElement) }
Remove vet check for desktop notifications in AppTokenUtil.
const AppTokenUtil = { getAppTokensBasedOnQuery: getAppTokensBasedOnQuery }; function getAppTokensBasedOnQuery(query, desktopAppId) { let userDisabledMap = new Map(); let userIdsSet = new Set(); let appTokens = Push.appTokens.find(query).fetch(); if (!appTokens.length) { return []; } if (desktopAppId) { return appTokens; } appTokens.forEach(function (appToken) { if (appToken.userId) { userIdsSet.add(appToken.userId); } }); let vet = GlobalVets.findOne({appIdentifier: appTokens[0].appName}); if (!vet) { return []; } let users = Meteor.users.find({_id: {$in: [...userIdsSet]}}).fetch(); users.forEach(user => { let isUserDisabled = user.accountDisabledPerVet && user.accountDisabledPerVet[vet._id]; userDisabledMap.set(user._id, isUserDisabled); }); return appTokens.filter(appToken => { return !(appToken.userId && userDisabledMap.get(appToken.userId)); }); } export {AppTokenUtil};
const AppTokenUtil = { getAppTokensBasedOnQuery: getAppTokensBasedOnQuery }; function getAppTokensBasedOnQuery(query, desktopAppId) { let userDisabledMap = new Map(); let userIdsSet = new Set(); let appTokens = Push.appTokens.find(query).fetch(); if (!appTokens.length) { return []; } appTokens.forEach(function (appToken) { if (appToken.userId) { userIdsSet.add(appToken.userId); } }); let vet = GlobalVets.findOne({appIdentifier: appTokens[0].appName}); if (!vet && desktopAppId) { vet = GlobalVets.findOne({_id: desktopAppId}); } if (!vet) { console.log(`Couldn't find vet for id ${desktopAppId} or app identifier ${appTokens[0].appName}`); return false; } let users = Meteor.users.find({_id: {$in: [...userIdsSet]}}).fetch(); users.forEach(user => { let isUserDisabled = user.accountDisabledPerVet && user.accountDisabledPerVet[vet._id]; userDisabledMap.set(user._id, isUserDisabled); }); return appTokens.filter(appToken => { return !(appToken.userId && userDisabledMap.get(appToken.userId)); }); } export {AppTokenUtil};
Add route to login users
'use strict'; var path = process.cwd(); var Graphriend = require(path + '/app/controllers/Graphriend.server.js'); var sess; module.exports = function (app) { function isLoggedIn (req, res, next) { sess = req.session; if (sess.user) { return next(); } else { res.redirect('/'); } } var graPhriend = new Graphriend(); var user = { isLogged: false, name: 'Jinme', username: 'mirabalj' } app.route('/') .get(function (req, res) { res.render('main', { user: user, page: 'index' }); }); app.post('/api/signup', graPhriend.signUp); app.post('/api/login', graPhriend.logIn); /* Example Authenticated verify app.route('/profile') .get(isLoggedIn, function (req, res) { res.render('main', { user: sess.user, page: 'profile' }); }); */ /* Example REST api app.route('/friends') .get(isLoggedIn, graPhriend.getFriend) .post(isLoggedIn, graPhriend.addFriend) .delete(isLoggedIn, graPhriend.delFriend); */ };
'use strict'; var path = process.cwd(); var Graphriend = require(path + '/app/controllers/Graphriend.server.js'); var sess; module.exports = function (app) { function isLoggedIn (req, res, next) { sess = req.session; if (sess.user) { return next(); } else { res.redirect('/'); } } var graPhriend = new Graphriend(); var user = { isLogged: false, name: 'Jinme', username: 'mirabalj' } app.route('/') .get(function (req, res) { res.render('main', { user: user, page: 'index' }); }); app.post('/api/signup', graPhriend.signUp); /* Example Authenticated verify app.route('/profile') .get(isLoggedIn, function (req, res) { res.render('main', { user: sess.user, page: 'profile' }); }); */ /* Example REST api app.route('/friends') .get(isLoggedIn, graPhriend.getFriend) .post(isLoggedIn, graPhriend.addFriend) .delete(isLoggedIn, graPhriend.delFriend); */ };
PhpDoc: Add missing types & correct incorrect types
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Component\Rule\Repository; use Doctrine\ORM\EntityRepository; use Elcodi\Component\Rule\Entity\Interfaces\RuleInterface; /** * Class RuleRepository */ class RuleRepository extends EntityRepository { /** * Return a rule by name * * @param string $name * * @return null|RuleInterface */ public function findOneByName($name) { return parent::findOneBy(['name' => $name]); } }
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Component\Rule\Repository; use Doctrine\ORM\EntityRepository; use Elcodi\Component\Rule\Entity\Interfaces\RuleInterface; /** * Class RuleRepository */ class RuleRepository extends EntityRepository { /** * Return a rule by name * * @param $name * * @return null|RuleInterface */ public function findOneByName($name) { return parent::findOneBy(['name' => $name]); } }
Speed up vision collector loop
package com.gmail.jakekinsella.background; import com.gmail.jakekinsella.communicator.Communicator; import com.gmail.jakekinsella.map.Map; import com.gmail.jakekinsella.robot.RobotControl; /** * Created by jakekinsella on 12/20/16. */ public class VisionCollector implements Runnable { private Map map; private Communicator communicator; private RobotControl robotControl; public VisionCollector(Map map, Communicator communicator, RobotControl robotControl) { this.map = map; this.communicator = communicator; this.robotControl = robotControl; } @Override public void run() { while (true) { this.map.inputVisionData(this.communicator.getVisionUpdate(), robotControl); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.gmail.jakekinsella.background; import com.gmail.jakekinsella.communicator.Communicator; import com.gmail.jakekinsella.map.Map; import com.gmail.jakekinsella.robot.RobotControl; /** * Created by jakekinsella on 12/20/16. */ public class VisionCollector implements Runnable { private Map map; private Communicator communicator; private RobotControl robotControl; public VisionCollector(Map map, Communicator communicator, RobotControl robotControl) { this.map = map; this.communicator = communicator; this.robotControl = robotControl; } @Override public void run() { while (true) { this.map.inputVisionData(this.communicator.getVisionUpdate(), robotControl); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Add import-time check for pygame (since we can't install automatically)
try: import pygame except ImportError: print 'Failed to import pygame' print '-----------------------' print '' print 'tingbot-python requires pygame. Please download and install pygame 1.9.1' print 'or later from http://www.pygame.org/download.shtml' print '' print "If you're using a virtualenv, you should make the virtualenv with the " print "--system-site-packages flag so the system-wide installation is still " print "accessible." print '' print '-----------------------' print '' raise from . import platform_specific, input from .graphics import screen, Surface, Image from .run_loop import main_run_loop, every from .input import touch from .button import press from .web import webhook platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) main_run_loop.add_after_action_callback(screen.update_if_needed) main_run_loop.add_wait_callback(input.poll) # in case screen updates happen in input.poll... main_run_loop.add_wait_callback(screen.update_if_needed) main_run_loop.run() __all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook'] __author__ = 'Joe Rickerby' __email__ = 'joerick@mac.com' __version__ = '0.3'
from . import platform_specific, input from .graphics import screen, Surface, Image from .run_loop import main_run_loop, every from .input import touch from .button import press from .web import webhook platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) main_run_loop.add_after_action_callback(screen.update_if_needed) main_run_loop.add_wait_callback(input.poll) # in case screen updates happen in input.poll... main_run_loop.add_wait_callback(screen.update_if_needed) main_run_loop.run() __all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook'] __author__ = 'Joe Rickerby' __email__ = 'joerick@mac.com' __version__ = '0.3'
Use getenv instead of environment dict
############################################################################### # This is a very strange handler setup, but this is how it's documented. # See https://github.com/DataDog/datadogpy#quick-start-guide ############################################################################### import os from datadog import initialize traptor_type = os.getenv('TRAPTOR_TYPE', 'track') traptor_id = os.getenv('TRAPTOR_ID', '0') DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { 'statsd_host': os.getenv('STATSD_HOST_IP', '127.0.0.1') } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
############################################################################### # This is a very strange handler setup, but this is how it's documented. # See https://github.com/DataDog/datadogpy#quick-start-guide ############################################################################### import os from datadog import initialize traptor_type = os.environ['TRAPTOR_TYPE'] traptor_id = os.environ['TRAPTOR_ID'] DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { 'statsd_host': os.environ['STATSD_HOST_IP'], } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
Fix to load MySql Class
<?php namespace Spika\Provider; use Spika\Db\CouchDb; use Spika\Db\MySql; use Silex\Application; use Silex\ServiceProviderInterface; class SpikaDbServiceProvider implements ServiceProviderInterface { public function register(Application $app) { /* $app['spikadb'] = $app->share(function () use ($app) { return new CouchDb( $app['couchdb.couchDBURL'], $app['logger'] ); }); */ $app['spikadb'] = $app->share(function () use ($app) { return new MySQL( $app['couchdb.couchDBURL'], $app['logger'], $app['db'] ); }); } public function boot(Application $app) { } }
<?php namespace Spika\Provider; use Spika\Db\CouchDb; use Spika\Db\MySQL; use Silex\Application; use Silex\ServiceProviderInterface; class SpikaDbServiceProvider implements ServiceProviderInterface { public function register(Application $app) { /* $app['spikadb'] = $app->share(function () use ($app) { return new CouchDb( $app['couchdb.couchDBURL'], $app['logger'] ); }); */ $app['spikadb'] = $app->share(function () use ($app) { return new MySQL( $app['couchdb.couchDBURL'], $app['logger'], $app['db'] ); }); } public function boot(Application $app) { } }
Add Trigger model to client and alias it as TriggerSpecification.
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from st2client.models import core LOG = logging.getLogger(__name__) class Sensor(core.Resource): _plural = 'Sensortypes' _repr_attributes = ['name', 'pack'] class TriggerType(core.Resource): _alias = 'Trigger' _display_name = 'Trigger' _plural = 'Triggertypes' _plural_display_name = 'Triggers' _repr_attributes = ['name', 'pack'] class Trigger(core.Resource): _alias = 'TriggerSpecification' _display_name = 'TriggerSpecification' _plural = 'Triggers' _plural_display_name = 'Triggers' _repr_attributes = ['name', 'pack'] class Rule(core.Resource): _plural = 'Rules'
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from st2client.models import core LOG = logging.getLogger(__name__) class Sensor(core.Resource): _plural = 'Sensortypes' _repr_attributes = ['name', 'pack'] class TriggerType(core.Resource): _alias = 'Trigger' _display_name = 'Trigger' _plural = 'Triggertypes' _plural_display_name = 'Triggers' _repr_attributes = ['name', 'pack'] class Rule(core.Resource): _plural = 'Rules'
Fix HTML escaping of TextPlugin, by feature/text-filters branch
""" Definition of the plugin. """ from django.utils.safestring import mark_safe from fluent_contents.extensions import ContentPlugin, plugin_pool, ContentItemForm from fluent_contents.plugins.text.models import TextItem class TextItemForm(ContentItemForm): """ Perform extra processing for the text item """ def clean_text(self, html): """ Perform the cleanup in the form, allowing to raise a ValidationError """ return self.instance.apply_pre_filters(html) @plugin_pool.register class TextPlugin(ContentPlugin): """ CMS plugin for WYSIWYG text items. """ model = TextItem form = TextItemForm admin_init_template = "admin/fluent_contents/plugins/text/admin_init.html" # TODO: remove the need for this. admin_form_template = ContentPlugin.ADMIN_TEMPLATE_WITHOUT_LABELS search_output = True def render(self, request, instance, **kwargs): # Included in a DIV, so the next item will be displayed below. # The text_final is allowed to be None, to migrate old plugins. text = instance.text if instance.text_final is None else instance.text_final return mark_safe(u'<div class="text">{0}</div>\n'.format(text))
""" Definition of the plugin. """ from django.utils.html import format_html from fluent_contents.extensions import ContentPlugin, plugin_pool, ContentItemForm from fluent_contents.plugins.text.models import TextItem class TextItemForm(ContentItemForm): """ Perform extra processing for the text item """ def clean_text(self, html): """ Perform the cleanup in the form, allowing to raise a ValidationError """ return self.instance.apply_pre_filters(html) @plugin_pool.register class TextPlugin(ContentPlugin): """ CMS plugin for WYSIWYG text items. """ model = TextItem form = TextItemForm admin_init_template = "admin/fluent_contents/plugins/text/admin_init.html" # TODO: remove the need for this. admin_form_template = ContentPlugin.ADMIN_TEMPLATE_WITHOUT_LABELS search_output = True def render(self, request, instance, **kwargs): # Included in a DIV, so the next item will be displayed below. # The text_final is allowed to be None, to migrate old plugins. text = instance.text if instance.text_final is None else instance.text_final return format_html(u'<div class="text">{0}</div>\n', text)
Remove unimported symbols from __all__ I don't quite understand, why flake8 didn't catch this...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from . import exceptions, low_level from ._legacy import ( hash_password, hash_password_raw, verify_password, ) from ._password_hasher import ( DEFAULT_HASH_LENGTH, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_RANDOM_SALT_LENGTH, DEFAULT_TIME_COST, PasswordHasher, ) from .low_level import Type __version__ = "16.1.0.dev0" __title__ = "argon2_cffi" __description__ = "The secure Argon2 password hashing algorithm." __uri__ = "https://argon2-cffi.readthedocs.org/" __author__ = "Hynek Schlawack" __email__ = "hs@ox.cx" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 {author}".format(author=__author__) __all__ = [ "DEFAULT_HASH_LENGTH", "DEFAULT_MEMORY_COST", "DEFAULT_PARALLELISM", "DEFAULT_RANDOM_SALT_LENGTH", "DEFAULT_TIME_COST", "PasswordHasher", "Type", "exceptions", "hash_password", "hash_password_raw", "low_level", "verify_password", ]
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from . import exceptions, low_level from ._legacy import ( hash_password, hash_password_raw, verify_password, ) from ._password_hasher import ( DEFAULT_HASH_LENGTH, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_RANDOM_SALT_LENGTH, DEFAULT_TIME_COST, PasswordHasher, ) from .low_level import Type __version__ = "16.1.0.dev0" __title__ = "argon2_cffi" __description__ = "The secure Argon2 password hashing algorithm." __uri__ = "https://argon2-cffi.readthedocs.org/" __author__ = "Hynek Schlawack" __email__ = "hs@ox.cx" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 {author}".format(author=__author__) __all__ = [ "DEFAULT_HASH_LENGTH", "DEFAULT_MEMORY_COST", "DEFAULT_PARALLELISM", "DEFAULT_RANDOM_SALT_LENGTH", "DEFAULT_TIME_COST", "PasswordHasher", "Type", "exceptions", "hash_password", "hash_password_raw", "hash_secret", "hash_secret_raw", "low_level", "verify_password", "verify_secret", ]
Fix in group DC licence
package io.car.server.rest.encoding.rdf.linker; import com.google.inject.Provider; import com.hp.hpl.jena.rdf.model.Model; import io.car.server.core.entities.Group; import io.car.server.rest.encoding.rdf.RDFLinker; import io.car.server.rest.resources.GroupsResource; import io.car.server.rest.resources.RootResource; import io.car.server.rest.rights.AccessRights; import javax.ws.rs.core.UriBuilder; /** * * @author Jan Wirwahn */ public class GroupDCTermsLinker implements RDFLinker<Group> { public static final String ODBL_URL = "http://opendatacommons.org/licenses/odbl/"; @Override public void link(Model m, Group t, AccessRights rights, Provider<UriBuilder> uriBuilder) { String uri = uriBuilder.get() .path(RootResource.class) .path(RootResource.GROUPS) .path(GroupsResource.GROUP) .build(t.getName()).toASCIIString(); m.createResource(uri).addProperty(DCTerms.rights, ODBL_URL); } }
package io.car.server.rest.encoding.rdf.linker; import com.google.inject.Provider; import com.hp.hpl.jena.rdf.model.Model; import io.car.server.core.entities.Group; import io.car.server.core.entities.Measurement; import io.car.server.rest.encoding.rdf.RDFLinker; import static io.car.server.rest.encoding.rdf.linker.MeasurementDCTermsLinker.ODBL_URL; import io.car.server.rest.resources.GroupsResource; import io.car.server.rest.resources.MeasurementsResource; import io.car.server.rest.resources.RootResource; import io.car.server.rest.rights.AccessRights; import javax.ws.rs.core.UriBuilder; /** * * @author Jan Wirwahn */ public class GroupDCTermsLinker implements RDFLinker<Group> { public static final String ODBL_URL = "http://opendatacommons.org/licenses/odbl/"; @Override public void link(Model m, Group t, AccessRights rights, Provider<UriBuilder> uriBuilder) { String uri = uriBuilder.get() .path(RootResource.class) .path(RootResource.GROUPS) .path(GroupsResource.GROUP) .build(t.getName()).toASCIIString(); m.createResource(uri).addProperty(DCTerms.rights, ODBL_URL); } }
Fix whois ip search (rename ranges/mult var)
from ipwhois import IPWhois import whois ''' ############################################ # WHOIS # ############################################ ''' def whois_target(host): # Technically this is still passive recon # because you still aren't hitting target w = whois.whois(host) return w.text, w.emails, w def whois_ip(ip): # Default to not found cidr, ranges = "CIDR not found", "Range not found" # Get whois for IP. Returns a list with dictionary ip_dict = IPWhois(ip).lookup_rws() if ip_dict['nets'][0].get('cidr') cidr = ip_dict['nets'][0].get('cidr') if ip_dict['nets'][0].get('range'): ranges = ip_dict['nets'][0].get('range') return cidr, ranges
from ipwhois import IPWhois import whois ''' ############################################ # WHOIS # ############################################ ''' def whois_target(host): # Technically this is still passive recon # because you still aren't hitting target w = whois.whois(host) return w.text, w.emails, w def whois_ip(ip): # Default to not found cidr, range = "Not found" # Get whois for IP. Returns a list with dictionary ip_dict = IPWhois(ip).lookup_rws() if ip_dict['nets'][0].get('cidr') cidr = ip_dict['nets'][0].get('cidr') if ip_dict['nets'][0].get('range'): range = ip_dict['nets'][0].get('range') return cidr, range
Use ioutil for certificate file reading. Currently we read certificate files into a buffer of 5000 bytes. This sets a max size for our certificates; above this max, we will get invalid certs, most likely, leading to runtime bad certificate errors.
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "io/ioutil" "k8s.io/klog" ) type certsContainer struct { caCert, serverKey, serverCert []byte } type certsConfig struct { clientCaFile, tlsCertFile, tlsPrivateKey *string } func readFile(filePath string) []byte { res, err := ioutil.ReadFile(filePath) if err != nil { klog.Errorf("Error reading certificate file at %s: %v", filePath, err) return nil } klog.V(3).Infof("Successfully read %d bytes from %v", len(res), filePath) return res } func initCerts(config certsConfig) certsContainer { res := certsContainer{} res.caCert = readFile(*config.clientCaFile) res.serverCert = readFile(*config.tlsCertFile) res.serverKey = readFile(*config.tlsPrivateKey) return res }
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "os" "k8s.io/klog" ) type certsContainer struct { caCert, serverKey, serverCert []byte } type certsConfig struct { clientCaFile, tlsCertFile, tlsPrivateKey *string } func readFile(filePath string) []byte { file, err := os.Open(filePath) if err != nil { klog.Error(err) return nil } res := make([]byte, 5000) count, err := file.Read(res) if err != nil { klog.Error(err) return nil } klog.Infof("Successfully read %d bytes from %v", count, filePath) return res[:count] } func initCerts(config certsConfig) certsContainer { res := certsContainer{} res.caCert = readFile(*config.clientCaFile) res.serverCert = readFile(*config.tlsCertFile) res.serverKey = readFile(*config.tlsPrivateKey) return res }
[master] Add LRU for relationship mapper.
#!/usr/bin/env python # -*- coding: utf-8 -*- """Contains functions to canonicalize relationships.""" from __future__ import absolute_import from __future__ import print_function import repoze.lru from nltk.corpus import wordnet from .utils import wordnet_helper from .utils import common @repoze.lru.lru_cache(4096) def canonicalize_relationship(text): words = common.clean_text(text).split() freq = [] for word in words: for pos in [wordnet.VERB, wordnet.ADV]: freq.extend(wordnet_helper.lemma_counter(word, pos=pos).most_common()) if freq: return max(freq, key=lambda x: x[1])[0] else: return None
#!/usr/bin/env python # -*- coding: utf-8 -*- """Contains functions to canonicalize relationships.""" from __future__ import absolute_import from __future__ import print_function from nltk.corpus import wordnet from .utils import wordnet_helper from .utils import common def canonicalize_relationship(text): words = common.clean_text(text).split() freq = [] for word in words: for pos in [wordnet.VERB, wordnet.ADV]: freq.extend(wordnet_helper.lemma_counter(word, pos=pos).most_common()) if freq: return max(freq, key=lambda x: x[1])[0] else: return None
Bump minimal Django version in install_requires.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-envelope', version=__import__('envelope').__version__, description='A contact form app for Django', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='http://github.com/zsiciarz/django-envelope', download_url='http://pypi.python.org/pypi/django-envelope', license='MIT', install_requires=['Django>=1.8'], packages=find_packages(exclude=['example_project', 'tests']), include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-envelope', version=__import__('envelope').__version__, description='A contact form app for Django', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='http://github.com/zsiciarz/django-envelope', download_url='http://pypi.python.org/pypi/django-envelope', license='MIT', install_requires=['Django>=1.5'], packages=find_packages(exclude=['example_project', 'tests']), include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], )
Fix index load sanity check using the wrong string
import { toHaveNoViolations } from "jest-axe"; expect.extend(toHaveNoViolations); jest.setTimeout(10000); describe("/", () => { let page; beforeAll(async () => { page = await global.BROWSER.newPage(); await page.goto(global.ROOT); await page.addScriptTag({ path: require.resolve("axe-core") }); }); it("loads", async () => { const text = await page.evaluate(() => document.body.textContent); expect(text).toContain("Draftail"); }); it("a11y", async () => { const result = await page.evaluate( () => new Promise((resolve) => { window.axe.run((err, results) => { if (err) throw err; resolve(results); }); }), ); expect(result).toHaveNoViolations(); }); });
import { toHaveNoViolations } from "jest-axe"; expect.extend(toHaveNoViolations); jest.setTimeout(10000); describe("/", () => { let page; beforeAll(async () => { page = await global.BROWSER.newPage(); await page.goto(global.ROOT); await page.addScriptTag({ path: require.resolve("axe-core") }); }); it("loads", async () => { const text = await page.evaluate(() => document.body.textContent); expect(text).toContain("draftail"); }); it("a11y", async () => { const result = await page.evaluate( () => new Promise((resolve) => { window.axe.run((err, results) => { if (err) throw err; resolve(results); }); }), ); expect(result).toHaveNoViolations(); }); });
Fix error in previous typo
const express = require('express'); const app = express(); const {db} = require('./database/db-config'); // add middleware require('./config/middleware.js')(app, express); // add routes require('./config/routes.js')(app, express); // set port depending on prod or dev const port = process.env.NODE_ENV === 'production' ? 80 : 3000; app.use(express.static('../client')); const listen = app.listen(port, () => { console.log('Server listening on port ' + port); db.sync(); // .then(() => { // console.log('Database is synced'); // }); }); var io = require('socket.io').listen(listen); io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => console.log('a user disconnected')); }); module.exports = app;
const express = require('express'); const app = express(); const {db} = require('./database/db-config'); const {db} = require('./database/db-config'); // add middleware require('./config/middleware.js')(app, express); // add routes require('./config/routes.js')(app, express); // set port depending on prod or dev const port = process.env.NODE_ENV === 'production' ? 80 : 3000; app.use(express.static('../client')); const listen = app.listen(port, () => { console.log('Server listening on port ' + port); db.sync(); // .then(() => { // console.log('Database is synced'); // }); }); var io = require('socket.io').listen(listen); io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => console.log('a user disconnected')); }); module.exports = app;
Fix php5.3 incompatible array definition
<?php namespace Knp\Bundle\SnappyBundle\Snappy\Response; use Symfony\Component\HttpFoundation\Response as Base; abstract class SnappyResponse extends Base { public function __construct($content, $fileName, $contentType, $contentDisposition = 'attachment', $status = 200, $headers = array()) { $contentDispositionDirectives = array('inline', 'attachment'); if (!in_array($contentDisposition, $contentDispositionDirectives)) { throw new \InvalidArgumentException(sprintf('Expected one of the following directives: "%s", "%s" given.', implode('", "', $contentDispositionDirectives), $contentDisposition)); } parent::__construct($content, $status, $headers); $this->headers->add(array('Content-Type' => $contentType)); $this->headers->add(array('Content-Disposition' => $this->headers->makeDisposition($contentDisposition, $fileName))); } }
<?php namespace Knp\Bundle\SnappyBundle\Snappy\Response; use Symfony\Component\HttpFoundation\Response as Base; abstract class SnappyResponse extends Base { public function __construct($content, $fileName, $contentType, $contentDisposition = 'attachment', $status = 200, $headers = array()) { $contentDispositionDirectives = ['inline', 'attachment']; if (!in_array($contentDisposition, $contentDispositionDirectives)) { throw new \InvalidArgumentException(sprintf('Expected one of the following directives: "%s", "%s" given.', implode('", "', $contentDispositionDirectives), $contentDisposition)); } parent::__construct($content, $status, $headers); $this->headers->add(array('Content-Type' => $contentType)); $this->headers->add(array('Content-Disposition' => $this->headers->makeDisposition($contentDisposition, $fileName))); } }
Improve mast and fin size facets
import React from 'react' import Range from '../Range' import RefinementList from '../RefinementList' import SidebarSection from '../SidebarSection' import './style.scss' function Facets () { return ( <div data-app='facets-wrapper'> <RefinementList title='category' attributeName='category' /> <RefinementList title='provider' attributeName='provider' /> <RefinementList title='type' attributeName='type' /> <RefinementList title='brand' attributeName='brand' /> <RefinementList title='model' attributeName='model' /> <RefinementList title='diameter' attributeName='diameter' /> <RefinementList title='box' attributeName='box' /> <SidebarSection title='carbon' item={<Range attributeName='carbon' />} /> <SidebarSection title='price' item={<Range attributeName='price' />} /> <SidebarSection title='sail size' item={<Range attributeName='sail.size' />} /> <SidebarSection title='board size' item={<Range attributeName='board.size' />} /> <RefinementList title='mast size' attributeName='mast.size' /> <RefinementList title='fin size' attributeName='fin.size' /> </div> ) } export default Facets
import React from 'react' import Range from '../Range' import RefinementList from '../RefinementList' import SidebarSection from '../SidebarSection' import './style.scss' function Facets () { return ( <div data-app='facets-wrapper'> <RefinementList title='category' attributeName='category' /> <RefinementList title='provider' attributeName='provider' /> <RefinementList title='type' attributeName='type' /> <RefinementList title='brand' attributeName='brand' /> <RefinementList title='model' attributeName='model' /> <RefinementList title='diameter' attributeName='diameter' /> <RefinementList title='box' attributeName='box' /> <SidebarSection title='carbon' item={<Range attributeName='carbon' />} /> <SidebarSection title='price' item={<Range attributeName='price' />} /> <SidebarSection title='sail size' item={<Range attributeName='sail.size' />} /> <SidebarSection title='board size' item={<Range attributeName='board.size' />} /> <SidebarSection title='mast size' item={<Range attributeName='mast.size' />} /> <SidebarSection title='fin size' item={<Range attributeName='fin.size' />} /> </div> ) } export default Facets
Return $this from the Size getter.
<?php /** * php-binary * A PHP library for parsing structured binary streams * * @package php-binary * @author Damien Walsh <me@damow.net> */ namespace Binary\Field; use Binary\Field\Property\PropertyInterface; /** * SizedField * Abstract. * * Represents a field that is of a fixed (but not necessarily predefined) length. * * @since 1.0 */ abstract class AbstractSizedField extends AbstractField { /** * The size of the field. * * @protected PropertyInterface */ protected $size; /** * @param PropertyInterface $size * @return $this */ public function setSize(PropertyInterface $size) { $this->size = $size; return $this; } /** * @return PropertyInterface */ public function getSize() { return $this->size; } }
<?php /** * php-binary * A PHP library for parsing structured binary streams * * @package php-binary * @author Damien Walsh <me@damow.net> */ namespace Binary\Field; use Binary\Field\Property\PropertyInterface; /** * SizedField * Abstract. * * Represents a field that is of a fixed (but not necessarily predefined) length. * * @since 1.0 */ abstract class AbstractSizedField extends AbstractField { /** * The size of the field. * * @protected PropertyInterface */ protected $size; /** * @param PropertyInterface $size */ public function setSize(PropertyInterface $size) { $this->size = $size; } /** * @return PropertyInterface */ public function getSize() { return $this->size; } }
Add raw option (even if ignored by esprima 1.1.x)
/** * espower-source - Power Assert instrumentor from source to source. * * https://github.com/twada/espower-source * * Copyright (c) 2014 Takuto Wada * Licensed under the MIT license. * https://raw.github.com/twada/espower-source/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), merge = require('lodash.merge'), sourceMap = require('convert-source-map'); function espowerSourceToSource(jsCode, filepath, options) { 'use strict'; var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map; jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, raw: true, source: filepath}); espowerOptions = merge(merge(espower.defaultOptions(), options), { destructive: true, path: filepath, source: jsCode }); modifiedAst = espower(jsAst, espowerOptions); escodegenOutput = escodegen.generate(modifiedAst, { sourceMap: true, sourceMapWithCode: true }); code = escodegenOutput.code; // Generated source code map = sourceMap.fromJSON(escodegenOutput.map); map.sourcemap.sourcesContent = [jsCode]; return code + '\n' + map.toComment() + '\n'; } module.exports = espowerSourceToSource;
/** * espower-source - Power Assert instrumentor from source to source. * * https://github.com/twada/espower-source * * Copyright (c) 2014 Takuto Wada * Licensed under the MIT license. * https://raw.github.com/twada/espower-source/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), merge = require('lodash.merge'), sourceMap = require('convert-source-map'); function espowerSourceToSource(jsCode, filepath, options) { 'use strict'; var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map; jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, source: filepath}); espowerOptions = merge(merge(espower.defaultOptions(), options), { destructive: true, path: filepath, source: jsCode }); modifiedAst = espower(jsAst, espowerOptions); escodegenOutput = escodegen.generate(modifiedAst, { sourceMap: true, sourceMapWithCode: true }); code = escodegenOutput.code; // Generated source code map = sourceMap.fromJSON(escodegenOutput.map); map.sourcemap.sourcesContent = [jsCode]; return code + '\n' + map.toComment() + '\n'; } module.exports = espowerSourceToSource;
Add missing isset() when checking for generators
<?php namespace Imbo\EventListener\AccessToken; use Imbo\EventListener\AccessToken\AccessTokenGenerator, Imbo\EventListener\AccessToken\SHA256; class MultipleAccessTokenGenerators extends AccessTokenGenerator { /** * The params array for this generator allows you to define a set of access token signature generators to be used * for different url parameters if present. Each will be tried in the sequence defined. * * 'generators' => [ * 'accessToken' => new SHA256(), * 'dummy' => new Dummy(), * ] * * .. will first try the SHA256() generator if the 'accessToken' parameter is present in the URL, before trying * the Dummy generator if the first authentication attempt fails. This allows you to introduce new access token * validation schemes while keeping backwards compatible signature algorithms valid. * * @param array $params Parameters to the MultipleAccessTokenGenerators. */ public function __construct(array $params = []) { if (!isset($params['generators'])) { $params['generators'] = []; } parent::__construct($params); } public function generateSignature($argumentKey, $data, $privateKey) { return $this->params['generators'][$argumentKey]->generateSignature($argumentKey, $data, $privateKey); } public function getArgumentKeys() { return array_keys($this->params['generators']); } }
<?php namespace Imbo\EventListener\AccessToken; use Imbo\EventListener\AccessToken\AccessTokenGenerator, Imbo\EventListener\AccessToken\SHA256; class MultipleAccessTokenGenerators extends AccessTokenGenerator { /** * The params array for this generator allows you to define a set of access token signature generators to be used * for different url parameters if present. Each will be tried in the sequence defined. * * 'generators' => [ * 'accessToken' => new SHA256(), * 'dummy' => new Dummy(), * ] * * .. will first try the SHA256() generator if the 'accessToken' parameter is present in the URL, before trying * the Dummy generator if the first authentication attempt fails. This allows you to introduce new access token * validation schemes while keeping backwards compatible signature algorithms valid. * * @param array $params Parameters to the MultipleAccessTokenGenerators. */ public function __construct(array $params = []) { if (!$params['generators']) { $params['generators'] = []; } parent::__construct($params); } public function generateSignature($argumentKey, $data, $privateKey) { return $this->params['generators'][$argumentKey]->generateSignature($argumentKey, $data, $privateKey); } public function getArgumentKeys() { return array_keys($this->params['generators']); } }
Add StethoInterceptor as a network interceptor
package info.izumin.android.sunazuri.infrastructure; import com.facebook.stetho.okhttp3.StethoInterceptor; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import javax.inject.Singleton; /** * Created by izumin on 6/7/2016 AD. */ @Module public class HttpClientModule { public static final String TAG = HttpClientModule.class.getSimpleName(); @Provides @Singleton OkHttpClient httpClient(HttpLoggingInterceptor loggingInterceptor) { return new OkHttpClient.Builder() .addNetworkInterceptor(new StethoInterceptor()) .addInterceptor(loggingInterceptor) .build(); } @Provides @Singleton HttpLoggingInterceptor loggingInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return interceptor; } }
package info.izumin.android.sunazuri.infrastructure; import com.facebook.stetho.okhttp3.StethoInterceptor; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import javax.inject.Singleton; /** * Created by izumin on 6/7/2016 AD. */ @Module public class HttpClientModule { public static final String TAG = HttpClientModule.class.getSimpleName(); @Provides @Singleton OkHttpClient httpClient(HttpLoggingInterceptor loggingInterceptor) { return new OkHttpClient.Builder() .addInterceptor(new StethoInterceptor()) .addInterceptor(loggingInterceptor) .build(); } @Provides @Singleton HttpLoggingInterceptor loggingInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return interceptor; } }
Add renderer global 'r' as alias for 'request'.
from akhet.urlgenerator import URLGenerator import pyramid.threadlocal as threadlocal from pyramid.exceptions import ConfigurationError from .lib import helpers def includeme(config): """Configure all application-specific subscribers.""" config.add_subscriber(create_url_generator, "pyramid.events.ContextFound") config.add_subscriber(add_renderer_globals, "pyramid.events.BeforeRender") def create_url_generator(event): """A subscriber for ``pyramid.events.ContextFound`` events. I create a URL generator and attach it to the request (``request.url_generator``). Templates and views can then use it to generate application URLs. """ request = event.request context = request.context url_generator = URLGenerator(context, request, qualified=False) request.url_generator = url_generator def add_renderer_globals(event): """A subscriber for ``pyramid.events.BeforeRender`` events. I add some :term:`renderer globals` with values that are familiar to Pylons users. """ renderer_globals = event renderer_globals["h"] = helpers request = event.get("request") or threadlocal.get_current_request() if not request: return renderer_globals["r"] = request #renderer_globals["c"] = request.tmpl_context #try: # renderer_globals["session"] = request.session #except ConfigurationError: # pass renderer_globals["url"] = request.url_generator
from akhet.urlgenerator import URLGenerator import pyramid.threadlocal as threadlocal from pyramid.exceptions import ConfigurationError from .lib import helpers def includeme(config): """Configure all application-specific subscribers.""" config.add_subscriber(create_url_generator, "pyramid.events.ContextFound") config.add_subscriber(add_renderer_globals, "pyramid.events.BeforeRender") def create_url_generator(event): """A subscriber for ``pyramid.events.ContextFound`` events. I create a URL generator and attach it to the request (``request.url_generator``). Templates and views can then use it to generate application URLs. """ request = event.request context = request.context url_generator = URLGenerator(context, request, qualified=False) request.url_generator = url_generator def add_renderer_globals(event): """A subscriber for ``pyramid.events.BeforeRender`` events. I add some :term:`renderer globals` with values that are familiar to Pylons users. """ renderer_globals = event renderer_globals["h"] = helpers request = event.get("request") or threadlocal.get_current_request() if not request: return #renderer_globals["c"] = request.tmpl_context #try: # renderer_globals["session"] = request.session #except ConfigurationError: # pass renderer_globals["url"] = request.url_generator
Add active to session type model
import Ember from 'ember'; import DS from 'ember-data'; const { String:EmberString, computed } = Ember; const { Model, attr, belongsTo, hasMany } = DS; const { htmlSafe } = EmberString; export default Model.extend({ title: attr('string'), calendarColor: attr('string'), active: attr('boolean'), assessment: attr('boolean'), assessmentOption: belongsTo('assessment-option', {async: true}), school: belongsTo('school', {async: true}), aamcMethods: hasMany('aamc-method', {async: true}), sessions: hasMany('session', {async: true}), safeCalendarColor: computed('calendarColor', function(){ const calendarColor = this.get('calendarColor'); const pattern = new RegExp("^#[a-fA-F0-9]{6}$"); if (pattern.test(calendarColor)) { return htmlSafe(calendarColor); } return ''; }), sessionCount: computed('sessions.[]', function(){ const sessons = this.hasMany('sessions'); return sessons.ids().length; }) });
import Ember from 'ember'; import DS from 'ember-data'; const { String:EmberString, computed } = Ember; const { Model, attr, belongsTo, hasMany } = DS; const { htmlSafe } = EmberString; export default Model.extend({ title: attr('string'), calendarColor: attr('string'), assessment: attr('boolean'), assessmentOption: belongsTo('assessment-option', {async: true}), school: belongsTo('school', {async: true}), aamcMethods: hasMany('aamc-method', {async: true}), sessions: hasMany('session', {async: true}), safeCalendarColor: computed('calendarColor', function(){ const calendarColor = this.get('calendarColor'); const pattern = new RegExp("^#[a-fA-F0-9]{6}$"); if (pattern.test(calendarColor)) { return htmlSafe(calendarColor); } return ''; }), sessionCount: computed('sessions.[]', function(){ const sessons = this.hasMany('sessions'); return sessons.ids().length; }) });
Fix bug where object comparison is done on null object.
export var ObjectUtilities = { isEqual: function (objA, objB) { if( !objA || !objB ) { return (!objA && !objB); } var aKeys = Object.keys(objA); var bKeys = Object.keys(objB); if (aKeys.length !== bKeys.length) { return false; } for (var i = 0, len = aKeys.length; i < len; i++) { var key = aKeys[i]; if (!objB.hasOwnProperty(key) || objA[key] !== objB[key]) { return false; } } return true; } }; export var StringUtil = { pluralize: function (str, count) { var s = str; if (count > 1) { if (str.endsWith("y")) { s = str.substring(0, str.length - 2) + 'ies'; } else { s += 's'; } } return s; } };
export var ObjectUtilities = { isEqual: function (objA, objB) { var aKeys = Object.keys(objA); var bKeys = Object.keys(objB); if (aKeys.length !== bKeys.length) { return false; } for (var i = 0, len = aKeys.length; i < len; i++) { var key = aKeys[i]; if (!objB.hasOwnProperty(key) || objA[key] !== objB[key]) { return false; } } return true; } }; export var StringUtil = { pluralize: function (str, count) { var s = str; if (count > 1) { if (str.endsWith("y")) { s = str.substring(0, str.length - 2) + 'ies'; } else { s += 's'; } } return s; } };
Fix typo in project grid event registration
(function() { var grid, projectItems; // setup grid { grid = $('.project-grid'); grid.isotope({ itemSelector: '.project-item', percentPosition: true, masonry: { columnWidth: '.project-grid-sizer' }, sortBy: 'sortIndex', getSortData: { sortIndex: '[data-sort-index]', } }); } // gray on hover { var restoreColorTimeout; projectItems = $('.project-item', grid); projectItems.on('mouseover touchstart', function(e) { clearTimeout(restoreColorTimeout); projectItems.addClass('gray'); $(e.currentTarget).removeClass('gray'); $(e.currentTarget).addClass('hover'); // force hover }); projectItems.on('mouseout touchend', function(e) { $(e.currentTarget).removeClass('hover'); // force unhover // debounce color restoration so we know that no for sure no other item has been moused over clearTimeout(restoreColorTimeout); restoreColorTimeout = setTimeout(function() { projectItems.removeClass('gray'); }, 50); }); } })()
(function() { var grid, projectItems; // setup grid { grid = $('.project-grid'); grid.isotope({ itemSelector: '.project-item', percentPosition: true, masonry: { columnWidth: '.project-grid-sizer' }, sortBy: 'sortIndex', getSortData: { sortIndex: '[data-sort-index]', } }); } // gray on hover { var restoreColorTimeout; projectItems = $('.project-item', grid); projectItems.on('mouseover touchstart', function(e) { clearTimeout(restoreColorTimeout); projectItems.addClass('gray'); $(e.currentTarget).removeClass('gray'); $(e.currentTarget).addClass('hover'); // force hover }); projectItems.on('mouseoout touchend', function(e) { $(e.currentTarget).removeClass('hover'); // force unhover // debounce color restoration so we know that no for sure no other item has been moused over clearTimeout(restoreColorTimeout); restoreColorTimeout = setTimeout(function() { projectItems.removeClass('gray'); }, 50); }); } })()
Update E2E assets mu-plugin to register script via new filter. This is to grant AMP-devmode compatibility to this asset which Site Kit does automatically for all of its assets.
<?php /** * Plugin Name: E2E Assets * Description: Enqueues assets needed for E2E tests. * * @package Google\Site_Kit * @copyright 2019 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ use Google\Site_Kit\Core\Assets\Script; add_filter( 'googlesitekit_assets', function ( $assets ) { $assets[] = new Script( 'googlesitekit-e2e-utilities', array( 'src' => plugins_url( 'dist/assets/js/e2e-utilities.js', GOOGLESITEKIT_PLUGIN_MAIN_FILE ), 'dependencies' => array( 'googlesitekit-apifetch-data' ), 'version' => md5_file( plugin_dir_path( GOOGLESITEKIT_PLUGIN_MAIN_FILE ) . 'dist/assets/js/e2e-utilities.js' ), ) ); return $assets; } ); // Enqueue E2E Utilities globally `wp_print_scripts` is called on admin and front. // If asset is not registered enqueuing is a no-op. add_action( 'wp_print_scripts', function () { wp_enqueue_script( 'googlesitekit-e2e-utilities' ); } );
<?php /** * Plugin Name: E2E Assets * Description: Enqueues assets needed for E2E tests. * * @package Google\Site_Kit * @copyright 2019 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ add_action( 'init', function () { if ( ! defined( 'GOOGLESITEKIT_PLUGIN_MAIN_FILE' ) ) { return; } wp_enqueue_script( 'googlesitekit-e2e-utilities', plugins_url( 'dist/assets/js/e2e-utilities.js', GOOGLESITEKIT_PLUGIN_MAIN_FILE ), array( 'googlesitekit-apifetch-data' ), md5_file( plugin_dir_path( GOOGLESITEKIT_PLUGIN_MAIN_FILE ) . 'dist/assets/js/e2e-utilities.js' ), true ); } );
Remove the listeners when the SSE stream is closed
const express = require('express') const connectSSE = require('connect-sse') const sse = connectSSE() module.exports = group => { const router = express.Router() function listen(res, event, handler) { group.on(event, handler) function removeListener() { group.removeListener(event, handler) res.removeListener('close', removeListener) res.removeListener('finish', removeListener) } res.on('close', removeListener) res.on('finish', removeListener) } router.get('/', sse, (req, res) => { function sendState() { res.json(group.list()) } // Bootstrap sendState() // Listen listen(res, 'change', sendState) }) router.get('/output', sse, (req, res) => { function sendOutput(id, data) { res.json({ id, output: data.toString() }) } // Bootstrap const list = group.list() Object.keys(list).forEach(id => { var mon = list[id] if (mon && mon.tail) { sendOutput(id, mon.tail) } }) // Listen listen(res, 'output', sendOutput) }) return router }
const express = require('express') const connectSSE = require('connect-sse') const sse = connectSSE() module.exports = group => { const router = express.Router() router.get('/', sse, (req, res) => { function sendState() { res.json(group.list()) } // Bootstrap sendState() // Listen group.on('change', sendState) }) router.get('/output', sse, (req, res) => { function sendOutput(id, data) { res.json({ id, output: data.toString() }) } // Bootstrap const list = group.list() Object.keys(list).forEach(id => { var mon = list[id] if (mon && mon.tail) { sendOutput(id, mon.tail) } }) // Listen group.on('output', sendOutput) }) return router }
Improve error message for SliceContains Also, use the types we defined in SliceContains for the params
package assert import ( "fmt" "strings" ) type Line []string func (line Line) String() string { return strings.Join(line, ", ") } type Lines []Line func SliceContains(actual Line, expected Lines, msgAndArgs ...interface{}) bool { expectedIndex := 0 for _, actualValue := range actual { allStringsFound := true for _, expectedValue := range expected[expectedIndex] { allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue)) } if allStringsFound { expectedIndex++ if expectedIndex == len(expected) { return true } } } return Fail(fmt.Sprintf("\"%s\" not found in actual:\n'%s'\n", expected[expectedIndex], actual), msgAndArgs...) } func SliceDoesNotContain(actual Line, expected Lines, msgAndArgs ...interface{}) bool { for i, actualValue := range actual { for _, expectedLine := range expected { allStringsFound := true for _, expectedValue := range expectedLine { allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue)) } if allStringsFound { return Fail(fmt.Sprintf("\"%s\" found on line %d", expectedLine, i), msgAndArgs...) } } } return true }
package assert import ( "fmt" "strings" ) type Line []string func (line Line) String() string { return strings.Join(line, ", ") } type Lines []Line func SliceContains(actual []string, expected Lines, msgAndArgs ...interface{}) bool { expectedIndex := 0 for _, actualValue := range actual { allStringsFound := true for _, expectedValue := range expected[expectedIndex] { allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue)) } if allStringsFound { expectedIndex++ if expectedIndex == len(expected) { return true } } } return Fail(fmt.Sprintf("\"%s\" not found", expected[expectedIndex]), msgAndArgs...) } func SliceDoesNotContain(actual []string, expected Lines, msgAndArgs ...interface{}) bool { for i, actualValue := range actual { for _, expectedLine := range expected { allStringsFound := true for _, expectedValue := range expectedLine { allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue)) } if allStringsFound { return Fail(fmt.Sprintf("\"%s\" found on line %d", expectedLine, i), msgAndArgs...) } } } return true }
Move Automaton class above exception classes
#!/usr/bin/env python3 import abc class Automaton(metaclass=abc.ABCMeta): def __init__(self, states, symbols, transitions, initial_state, final_states): """initialize a complete finite automaton""" self.states = states self.symbols = symbols self.transitions = transitions self.initial_state = initial_state self.final_states = final_states self.validate_automaton() @abc.abstractmethod def validate_input(self): pass @abc.abstractmethod def validate_automaton(self): pass class AutomatonError(Exception): """the base class for all automaton-related errors""" pass class InvalidStateError(AutomatonError): """a state is not a valid state for this automaton""" pass class InvalidSymbolError(AutomatonError): """a symbol is not a valid symbol for this automaton""" pass class MissingStateError(AutomatonError): """a state is missing from the transition function""" pass class MissingSymbolError(AutomatonError): """a symbol is missing from the transition function""" pass class FinalStateError(AutomatonError): """the automaton stopped at a non-final state""" pass
#!/usr/bin/env python3 import abc class AutomatonError(Exception): """the base class for all automaton-related errors""" pass class InvalidStateError(AutomatonError): """a state is not a valid state for this automaton""" pass class InvalidSymbolError(AutomatonError): """a symbol is not a valid symbol for this automaton""" pass class MissingStateError(AutomatonError): """a state is missing from the transition function""" pass class MissingSymbolError(AutomatonError): """a symbol is missing from the transition function""" pass class FinalStateError(AutomatonError): """the automaton stopped at a non-final state""" pass class Automaton(metaclass=abc.ABCMeta): def __init__(self, states, symbols, transitions, initial_state, final_states): """initialize a complete finite automaton""" self.states = states self.symbols = symbols self.transitions = transitions self.initial_state = initial_state self.final_states = final_states self.validate_automaton() @abc.abstractmethod def validate_input(self): pass @abc.abstractmethod def validate_automaton(self): pass
Add send element supprort Laravel 4.1
<?php /* |-------------------------------------------------------------------------- | Vietnamese Language for Laravel 4 |-------------------------------------------------------------------------- | | Translate by anhsk.ohbo@gmail.com | */ return array( /* |-------------------------------------------------------------------------- | Password Reminder Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ "password" => "Mật khẩu phải gồm 6 ký tự và khớp với phần xác nhận.", "user" => "Không tìm thấy user với địa chỉ email này.", "token" => "Mã reset mật khẩu không hợp lệ.", "sent" => "Cấp lại mật khẩu đã đuợc gửi!", );
<?php /* |-------------------------------------------------------------------------- | Vietnamese Language for Laravel 4 |-------------------------------------------------------------------------- | | Translate by anhsk.ohbo@gmail.com | */ return array( /* |-------------------------------------------------------------------------- | Password Reminder Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ "password" => "Mật khẩu phải gồm 6 ký tự và khớp với phần xác nhận.", "user" => "Không tìm thấy user với địa chỉ email này.", "token" => "Mã reset mật khẩu không hợp lệ.", "sent" => "Password reminder sent!", );
Check if requestAnimationFrame exists (for travis)
Tinytest.add( 'Loader - Load all critical files first', function (test) { var scripts = document.getElementsByTagName('script'); scripts = Array.prototype.slice.call(scripts); scripts = scripts.slice(0, 6).map(getSrc); var expected = [ '/packages/zones/assets/utils.js', '/packages/zones/assets/before.js', '/packages/zones/assets/zone.js', '/packages/zones/assets/tracer.js', '/packages/zones/assets/after.js', '/packages/zones/assets/reporters.js', ]; test.equal(expected, scripts); function getSrc(el) { return el.src.replace(location.origin, ''); } } ); Tinytest.add( 'Loader - do not override some functions', function (test) { var expected = 'function requestAnimationFrame() { [native code] }'; if(requestAnimationFrame) { test.equal(expected, requestAnimationFrame.toString()); } } );
Tinytest.add( 'Loader - Load all critical files first', function (test) { var scripts = document.getElementsByTagName('script'); scripts = Array.prototype.slice.call(scripts); scripts = scripts.slice(0, 6).map(getSrc); var expected = [ '/packages/zones/assets/utils.js', '/packages/zones/assets/before.js', '/packages/zones/assets/zone.js', '/packages/zones/assets/tracer.js', '/packages/zones/assets/after.js', '/packages/zones/assets/reporters.js', ]; test.equal(expected, scripts); function getSrc(el) { return el.src.replace(location.origin, ''); } } ); Tinytest.add( 'Loader - do not override some functions', function (test) { var expected = 'function requestAnimationFrame() { [native code] }'; test.equal(expected, requestAnimationFrame.toString()); } );
Validate reverse resolution before displaying the name
import { ens } from '/imports/lib/ethereum'; function validateName(claimedAddr, name, cb) { ens.resolver(name, (err, res) => { if (err) { return cb(err); } res.addr((err, actualAddr) => { if (err) { return cb(err); } cb(null, claimedAddr == actualAddr); }); }); } Template['components_address'].onCreated(function() { const template = Template.instance(); template.autorun(() => { const addr = Template.currentData().addr; TemplateVar.set(template, 'name', null); if (!addr) { return; } ens.reverse(addr, (err, resolver) =>{ if (!err && resolver.name) { resolver.name((err, name) => { validateName(addr, name, (err, isValid) => { if (!err && isValid) { TemplateVar.set(template, 'name', name); } }); }); } }) }) }) Template['components_address'].helpers({ mine() { return web3.eth.accounts.filter( (acc) => acc === Template.instance().data.addr ).length > 0; }, name() { return TemplateVar.get('name'); } })
import { ens } from '/imports/lib/ethereum'; Template['components_address'].onCreated(function() { const template = Template.instance(); template.autorun(() => { const addr = Template.currentData().addr; TemplateVar.set(template, 'name', null); if (!addr) { return; } ens.reverse(addr, (err, resolver) =>{ if (!err && resolver.name) { resolver.name((err, name) => { if (!err) { TemplateVar.set(template, 'name', name); } }); } }) }) }) Template['components_address'].helpers({ mine() { return web3.eth.accounts.filter( (acc) => acc === Template.instance().data.addr ).length > 0; }, name() { return TemplateVar.get('name'); } })
Create a camera using options with callbacks, not just an id
var cameraman = null; function CameraMan(opts) { var _self = this; this.options = opts; this.id = opts.id; this.getApp = function () { var name = _self.id; return (navigator.appName.indexOf ("Microsoft") != -1 ? window : document)[name]; }; this.takePhoto = function () { _self.getApp().takePhoto(); }; this.sendPhoto = function () { _self.getApp().sendPhoto(); }; this._tookPhoto = function () { if (_self.options.tookPhoto) { _self.options.tookPhoto.apply(_self); } }; this._sentPhoto = function (url) { if (_self.options.sentPhoto) { _self.options.sentPhoto.apply(_self, url); } }; } cameraman = new CameraMan();
var cameraman = null; function CameraMan(id) { var _self = this; this.id = id; this.getApp = function () { var name = _self.id; return (navigator.appName.indexOf ("Microsoft") != -1 ? window : document)[name]; }; this.takePhoto = function () { _self.getApp().takePhoto(); }; this.sendPhoto = function () { _self.getApp().sendPhoto(); }; this._tookPhoto = function () { $('#' + _self.id).trigger('tookPhoto'); }; this._sentPhoto = function (url) { $('#' + _self.id).trigger('sentPhoto', url); }; } cameraman = new CameraMan();
Change version tag to include v As discussed in imagemin/gifsicle-bin#55, some imagemin bin packages prepend their version tags with v and some don't. This PR changes the behavior of this package to prepend tags with`v`, as do the majority of packages. This reduces the probability that a wrong tag is published by mistake. Merging this PR means that the next tag must be prepended with a v! Pull Request URL: https://github.com/imagemin/optipng-bin/pull/63
'use strict'; var BinWrapper = require('bin-wrapper'); var path = require('path'); var pkg = require('../package.json'); var url = 'https://raw.github.com/imagemin/optipng-bin/v' + pkg.version + '/vendor/'; module.exports = new BinWrapper() .src(url + 'osx/optipng', 'darwin') .src(url + 'linux/x86/optipng', 'linux', 'x86') .src(url + 'linux/x64/optipng', 'linux', 'x64') .src(url + 'freebsd/optipng', 'freebsd') .src(url + 'sunos/x86/optipng', 'sunos', 'x86') .src(url + 'sunos/x64/optipng', 'sunos', 'x64') .src(url + 'win/optipng.exe', 'win32') .dest(path.join(__dirname, '../vendor')) .use(process.platform === 'win32' ? 'optipng.exe' : 'optipng') .version('>=0.7.5');
'use strict'; var BinWrapper = require('bin-wrapper'); var path = require('path'); var pkg = require('../package.json'); var url = 'https://raw.github.com/imagemin/optipng-bin/' + pkg.version + '/vendor/'; module.exports = new BinWrapper() .src(url + 'osx/optipng', 'darwin') .src(url + 'linux/x86/optipng', 'linux', 'x86') .src(url + 'linux/x64/optipng', 'linux', 'x64') .src(url + 'freebsd/optipng', 'freebsd') .src(url + 'sunos/x86/optipng', 'sunos', 'x86') .src(url + 'sunos/x64/optipng', 'sunos', 'x64') .src(url + 'win/optipng.exe', 'win32') .dest(path.join(__dirname, '../vendor')) .use(process.platform === 'win32' ? 'optipng.exe' : 'optipng') .version('>=0.7.5');
Use AnchorButton for anchor button
import React from 'react'; import {FormattedMessage} from "react-intl"; import {AnchorButton, Intent} from '@blueprintjs/core'; import queryString from "query-string"; const OAuthLogin = ({providers, onLogin}) => { const location = window.location; const targetUrl = `${location.protocol}//${location.host}/login`; const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`; return <div className="pt-button-group pt-vertical pt-align-left pt-large"> {providers.map(provider => <p key={provider.name}> <AnchorButton href={`${provider.login}${loginUrlQueryString}`} intent={Intent.PRIMARY}> <FormattedMessage id="login.provider" defaultMessage="Sign in with {label}" values={{label: provider.label}}/> </AnchorButton> </p>)} </div> }; export const handleOAuthCallback = (onLoginFn) => { const parsedHash = queryString.parse(location.hash); if (parsedHash.token) { onLoginFn(parsedHash.token); location.hash = ''; } }; export default OAuthLogin;
import React from 'react'; import {FormattedMessage} from "react-intl"; import queryString from "query-string"; const OAuthLogin = ({providers, onLogin}) => { const location = window.location; const targetUrl = `${location.protocol}//${location.host}/login`; const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`; return <div className="pt-button-group pt-vertical pt-align-left pt-large"> {providers.map(provider => <p key={provider.name}> <a href={`${provider.login}${loginUrlQueryString}`} className="pt-button pt-intent-primary pt-icon-log-in"> <FormattedMessage id="login.provider" defaultMessage="Sign in with {label}" values={{label: provider.label}}/> </a> </p>)} </div> }; export const handleOAuthCallback = (onLoginFn) => { const parsedHash = queryString.parse(location.hash); if (parsedHash.token) { onLoginFn(parsedHash.token); location.hash = ''; } }; export default OAuthLogin;
Fix "Fatal error: Parameter $innerMappings is variadic and has a type constraint"
<?php namespace Mw\JsonMapping; class MergeMapping extends ObjectMapping { /** * @var ObjectMapping[] */ private $innerMappings; /** * MergeMapping constructor. * * @param ObjectMapping[] ...$innerMappings */ public function __construct(...$innerMappings) { $this->innerMappings = $innerMappings; } /** * @param mixed $value * @return array */ public function map($value) { $mapped = []; foreach ($this->innerMappings as $mapping) { $newMapped = $mapping->map($value); $mapped = array_replace_recursive($mapped, $newMapped); } return $mapped; } /** * @param array $fieldNames * @return MergeMapping */ public function filter(array $fieldNames) { $newInnerMappings = []; foreach ($this->innerMappings as $innerMapping) { $newInnerMappings[] = $innerMapping->filter($fieldNames); } return new MergeMapping(...$newInnerMappings); } }
<?php namespace Mw\JsonMapping; class MergeMapping extends ObjectMapping { /** * @var ObjectMapping[] */ private $innerMappings; /** * MergeMapping constructor. * * @param ObjectMapping[] ...$innerMappings */ public function __construct(ObjectMapping ...$innerMappings) { $this->innerMappings = $innerMappings; } /** * @param mixed $value * @return array */ public function map($value) { $mapped = []; foreach ($this->innerMappings as $mapping) { $newMapped = $mapping->map($value); $mapped = array_replace_recursive($mapped, $newMapped); } return $mapped; } /** * @param array $fieldNames * @return MergeMapping */ public function filter(array $fieldNames) { $newInnerMappings = []; foreach ($this->innerMappings as $innerMapping) { $newInnerMappings[] = $innerMapping->filter($fieldNames); } return new MergeMapping(...$newInnerMappings); } }
Fix bug in !e command
// Copyright 2015 The tgbot Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package commands import ( "fmt" "io" "regexp" "strings" ) type cmdEcho struct { name string description string syntax string re *regexp.Regexp } func NewCmdEcho() Command { return cmdEcho{ syntax: "!e message", description: "Echo message", re: regexp.MustCompile(`^!e .+`), } } func (cmd cmdEcho) Syntax() string { return cmd.syntax } func (cmd cmdEcho) Description() string { return cmd.description } func (cmd cmdEcho) Match(text string) bool { return cmd.re.MatchString(text) } func (cmd cmdEcho) Run(w io.Writer, title, from, text string) error { echoText := strings.TrimSpace(strings.TrimPrefix(text, "!e")) fmt.Fprintf(w, "msg %s Echo: %s said \"%s\"\n", title, from, echoText) return nil }
// Copyright 2015 The tgbot Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package commands import ( "fmt" "io" "regexp" "strings" ) type cmdEcho struct { name string description string syntax string re *regexp.Regexp } func NewCmdEcho() Command { return cmdEcho{ syntax: "!e message", description: "Echo message", re: regexp.MustCompile(`^!e .+`), } } func (cmd cmdEcho) Syntax() string { return cmd.syntax } func (cmd cmdEcho) Description() string { return cmd.description } func (cmd cmdEcho) Match(text string) bool { return cmd.re.MatchString(text) } func (cmd cmdEcho) Run(w io.Writer, title, from, text string) error { echoText := strings.TrimSpace(strings.TrimPrefix(text, "!e")) fmt.Fprintf(w, "msg %s %s said: %s\n", title, from, echoText) return nil }
Add python module memcache dependency
#!/usr/bin/env python #coding: utf-8 from setuptools import setup, find_packages from os.path import join, dirname setup( name='mosecom_air', version='1.2', description='Web service dedicated to air pollution in Moscow.', long_description=open('README.md').read(), author='elsid', author_email='elsid.mail@gmail.com', packages=find_packages(), scripts=['manage.py', 'parse_html.py', 'request.py'], install_requires=[ 'django >= 1.6.1', 'djangorestframework >= 2.3.12', 'flup >= 1.0.2', 'johnny-cache >= 1.4', 'memcache >= 1.53', 'psycopg2 >= 2.4.5', 'pyquery >= 1.2.4', 'simplejson >= 3.3.1', 'yaml >= 3.10', ], )
#!/usr/bin/env python #coding: utf-8 from setuptools import setup, find_packages from os.path import join, dirname setup( name='mosecom_air', version='1.2', description='Web service dedicated to air pollution in Moscow.', long_description=open('README.md').read(), author='elsid', author_email='elsid.mail@gmail.com', packages=find_packages(), scripts=['manage.py', 'parse_html.py', 'request.py'], install_requires=[ 'django >= 1.6.1', 'djangorestframework >= 2.3.12', 'flup >= 1.0.2', 'johnny-cache >= 1.4', 'psycopg2 >= 2.4.5', 'pyquery >= 1.2.4', 'simplejson >= 3.3.1', 'yaml >= 3.10', ], )
Allow running tests with postgres
#!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'sqlite3' db_name = '' if not settings.configured: settings.configure( DATABASE_ENGINE = db_engine, DATABASE_NAME = db_name, INSTALLED_APPS = [ 'django.contrib.contenttypes', 'genericm2m', 'genericm2m.genericm2m_tests', ], ) from django.test.simple import run_tests def runtests(*test_args): if not test_args: test_args = ['genericm2m_tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if not settings.configured: settings.configure( DATABASE_ENGINE = 'sqlite3', INSTALLED_APPS = [ 'django.contrib.contenttypes', 'genericm2m', 'genericm2m.genericm2m_tests', ], ) from django.test.simple import run_tests def runtests(*test_args): if not test_args: test_args = ['genericm2m_tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Simplify the AutoUserModes mode type check
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class AutoUserModes(ModuleData): implements(IPlugin, IModuleData) name = "AutoUserModes" def actions(self): return [ ("welcome", 50, self.autoSetUserModes) ] def autoSetUserModes(self, user): try: modes = self.ircd.config["client_umodes_on_connect"] params = modes.split() modes = params.pop(0) parsedModes = [] for mode in modes: if mode not in self.ircd.userModeTypes: continue modeType = self.ircd.userModeTypes[mode] if modeType != ModeType.NoParam: parsedModes.append((True, mode, params.pop(0))) else: parsedModes.append((True, mode, None)) user.setModes(parsedModes, self.ircd.serverID) except KeyError: pass # No umodes defined. No action required. autoUserModes = AutoUserModes()
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class AutoUserModes(ModuleData): implements(IPlugin, IModuleData) name = "AutoUserModes" def actions(self): return [ ("welcome", 50, self.autoSetUserModes) ] def autoSetUserModes(self, user): try: modes = self.ircd.config["client_umodes_on_connect"] params = modes.split() modes = params.pop(0) parsedModes = [] for mode in modes: if mode not in self.ircd.userModeTypes: continue modeType = self.ircd.userModeTypes[mode] if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param): parsedModes.append((True, mode, params.pop(0))) else: parsedModes.append((True, mode, None)) user.setModes(parsedModes, self.ircd.serverID) except KeyError: pass # No umodes defined. No action required. autoUserModes = AutoUserModes()
Solve ESLint 80 chars line limit
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {validateData, loadScript} from '../3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function admanmedia(global, data) { validateData(data, ['id']); loadScript(global, `https://mona.admanmedia.com/go?id=${data.id}`, () => { const pattern = `script[src$="id=${data.id}"]`; const scriptTag = global.document.querySelector(pattern); scriptTag.setAttribute('id', `hybs-${data.id}`); global.context.renderStart(); }, () => { global.context.noContentAvailable(); }); }
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {validateData, loadScript} from '../3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function admanmedia(global, data) { validateData(data, ['id']); loadScript(global, `https://mona.admanmedia.com/go?id=${data.id}`, () => { const scriptTag = global.document.querySelector(`script[src$="id=${data.id}"]`); scriptTag.setAttribute('id', `hybs-${data.id}`); global.context.renderStart(); }, () => { global.context.noContentAvailable(); }); }
Update comment to point to node install
// Download the helper library from https://www.twilio.com/docs/node/install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Provide actions for the new task jokeActions = { actions: [ { say: 'I was going to look for my missing watch, but I could never find the time.' } ] } // Create a new task named 'tell_a_joke' // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list task = client.autopilot.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .tasks .create({ uniqueName: 'tell-a-joke', actions: jokeActions, }) .then(task => console.log(task.sid)) .done();
// Download the helper library from https://www.twilio.com/docs/python/install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Provide actions for the new task jokeActions = { actions: [ { say: 'I was going to look for my missing watch, but I could never find the time.' } ] } // Create a new task named 'tell_a_joke' // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list task = client.autopilot.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .tasks .create({ uniqueName: 'tell-a-joke', actions: jokeActions, }) .then(task => console.log(task.sid)) .done();
groupItemsById: Tweak type to accept read-only objects, too.
/* @flow strict */ export const caseInsensitiveCompareFunc = (a: string, b: string): number => a.toLowerCase().localeCompare(b.toLowerCase()); export const numberWithSeparators = (value: number | string): string => value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); export function deeperMerge<K, V>(obj1: { [K]: V }, obj2: { [K]: V }): { [K]: V } { return Array.from(new Set([...Object.keys(obj1), ...Object.keys(obj2)])).reduce((newObj, key) => { newObj[key] = obj1[key] === undefined ? obj2[key] : obj2[key] === undefined ? obj1[key] : { ...obj1[key], ...obj2[key] }; return newObj; }, ({}: { [K]: V })); } export const initialsFromString = (name: string): string => (name.match(/\S+\s*/g) || []).map(x => x[0].toUpperCase()).join(''); export function groupItemsById<T: { +id: number }>(items: T[]): { [id: number]: T } { return items.reduce((itemsById, item) => { itemsById[item.id] = item; return itemsById; }, {}); } export const isValidEmailFormat = (email: string = ''): boolean => /\S+@\S+\.\S+/.test(email);
/* @flow strict */ export const caseInsensitiveCompareFunc = (a: string, b: string): number => a.toLowerCase().localeCompare(b.toLowerCase()); export const numberWithSeparators = (value: number | string): string => value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); export function deeperMerge<K, V>(obj1: { [K]: V }, obj2: { [K]: V }): { [K]: V } { return Array.from(new Set([...Object.keys(obj1), ...Object.keys(obj2)])).reduce((newObj, key) => { newObj[key] = obj1[key] === undefined ? obj2[key] : obj2[key] === undefined ? obj1[key] : { ...obj1[key], ...obj2[key] }; return newObj; }, ({}: { [K]: V })); } export const initialsFromString = (name: string): string => (name.match(/\S+\s*/g) || []).map(x => x[0].toUpperCase()).join(''); export function groupItemsById<T: { id: number }>(items: T[]): { [id: number]: T } { return items.reduce((itemsById, item) => { itemsById[item.id] = item; return itemsById; }, {}); } export const isValidEmailFormat = (email: string = ''): boolean => /\S+@\S+\.\S+/.test(email);
CHANGE path of the snapshots files into the regular `__snapshots__` folder
import path from 'path'; import renderer from 'react-test-renderer'; import shallow from 'react-test-renderer/shallow'; import 'jest-specific-snapshot'; function getRenderedTree(story, context, options) { const storyElement = story.render(context); return renderer.create(storyElement, options).toJSON(); } function getSnapshotFileName(context) { const fileName = context.fileName; if (!fileName) { return null; } const { dir, name } = path.parse(fileName); return path.format({ dir: path.join(dir, '__snapshots__'), name, ext: '.storyshot' }); } export const snapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); expect(tree).toMatchSnapshot(); }; export const multiSnapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); const snapshotFileName = getSnapshotFileName(context); if (!snapshotFileName) { expect(tree).toMatchSnapshot(); return; } expect(tree).toMatchSpecificSnapshot(snapshotFileName); }; export const snapshot = snapshotWithOptions({}); export function shallowSnapshot({ story, context }) { const shallowRenderer = shallow.createRenderer(); const result = shallowRenderer.render(story.render(context)); expect(result).toMatchSnapshot(); } export function renderOnly({ story, context }) { const storyElement = story.render(context); renderer.create(storyElement); }
import path from 'path'; import renderer from 'react-test-renderer'; import shallow from 'react-test-renderer/shallow'; import 'jest-specific-snapshot'; function getRenderedTree(story, context, options) { const storyElement = story.render(context); return renderer.create(storyElement, options).toJSON(); } function getSnapshotFileName(context) { const fileName = context.fileName; if (!fileName) { return null; } const { dir, name } = path.parse(fileName); return path.format({ dir, name, ext: '.storyshot' }); } export const snapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); expect(tree).toMatchSnapshot(); }; export const multiSnapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); const snapshotFileName = getSnapshotFileName(context); if (!snapshotFileName) { expect(tree).toMatchSnapshot(); return; } expect(tree).toMatchSpecificSnapshot(snapshotFileName); }; export const snapshot = snapshotWithOptions({}); export function shallowSnapshot({ story, context }) { const shallowRenderer = shallow.createRenderer(); const result = shallowRenderer.render(story.render(context)); expect(result).toMatchSnapshot(); } export function renderOnly({ story, context }) { const storyElement = story.render(context); renderer.create(storyElement); }
Fix greetings kicking players from servers
package net.silentchaos512.gems.lib; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.silentchaos512.gems.SilentGems; import net.silentchaos512.lib.util.PlayerHelper; public class Greetings { public static final String PREFIX = "misc.silentgems:alpha"; public static void greetPlayer(EntityPlayer player) { // Reset the random object, because it seems to yield the same value each time. Huh? SilentGems.instance.random.setSeed(System.currentTimeMillis()); List<String> list = SilentGems.instance.localizationHelper.getDescriptionLines(PREFIX); if (list.size() > 0) { String msg = SilentGems.instance.localizationHelper.getLocalizedString(PREFIX + "Prefix") + " "; int index = SilentGems.instance.random.nextInt(list.size()); // SilentGems.instance.logHelper.debug(list.size(), index); msg += list.get(index); PlayerHelper.addChatMessage(player, TextFormatting.RED + msg); } // TODO: Remove this later. PlayerHelper.addChatMessage(player, "[Silent's Gems] Yes, the numbers in the upper-left are my fault. I'm working on it."); } }
package net.silentchaos512.gems.lib; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.silentchaos512.gems.SilentGems; import net.silentchaos512.lib.util.PlayerHelper; public class Greetings { public static final String PREFIX = "misc.silentgems:alpha"; public static void greetPlayer(EntityPlayer player) { // Reset the random object, because it seems to yield the same value each time. Huh? SilentGems.instance.random.setSeed(System.currentTimeMillis()); List<String> list = SilentGems.instance.localizationHelper.getDescriptionLines(PREFIX); String msg = SilentGems.instance.localizationHelper.getLocalizedString(PREFIX + "Prefix") + " "; int index = SilentGems.instance.random.nextInt(list.size()); // SilentGems.instance.logHelper.debug(list.size(), index); msg += list.get(index); PlayerHelper.addChatMessage(player, TextFormatting.RED + msg); // TODO: Remove this later. PlayerHelper.addChatMessage(player, "Yes, the numbers in the upper-left are my fault. I'm working on it."); } }
Use the correct Info.plist in the new version of FeedbackDemo
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
Make yes/no function definitions rather than function executions
angular.module( 'moviematch.match', [] ) .controller( 'MatchController', function( $scope, Match ) { $scope.movie = {}; $scope.session = {}; $scope.user = {}; $scope.user.name = "Julie"; $scope.session.name = "Girls Night Out"; $scope.movie = { name: "Gone With The Wind", year: "1939", rating: "G", runtime: "3h 58m", genres: [ "Drama", "Romance", "War" ], country: "USA", poster_path: "https://www.movieposter.com/posters/archive/main/30/MPW-15446", summary: "A manipulative southern belle carries on a turbulent affair with a blockade runner during the American Civil War.", director: "Victor Fleming", cast: "Clark Cable, Vivian Leigh, Thomas Mitchell" } $scope.yes = function() { Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, true ); } $scope.no = function() { Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, false ); } } );
angular.module( 'moviematch.match', [] ) .controller( 'MatchController', function( $scope, Match ) { $scope.movie = {}; $scope.session = {}; $scope.user = {}; $scope.user.name = "Julie"; $scope.session.name = "Girls Night Out"; $scope.movie = { name: "Gone With The Wind", year: "1939", rating: "G", runtime: "3h 58m", genres: [ "Drama", "Romance", "War" ], country: "USA", poster_path: "https://www.movieposter.com/posters/archive/main/30/MPW-15446", summary: "A manipulative southern belle carries on a turbulent affair with a blockade runner during the American Civil War.", director: "Victor Fleming", cast: "Clark Cable, Vivian Leigh, Thomas Mitchell" } $scope.yes = Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, true ); $scope.no = Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, false ); } );
Add connection string for connecting to virtool database in order to create a test database
import pytest from sqlalchemy import text from sqlalchemy.exc import ProgrammingError from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.ext.asyncio import AsyncSession from virtool.postgres import Base @pytest.fixture def test_pg_connection_string(request): return request.config.getoption("postgres_connection_string") @pytest.fixture(scope="function") async def pg_engine(test_pg_connection_string): pg_connection_string = test_pg_connection_string.split('/') pg_connection_string[-1] = 'virtool' engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT") async with engine.connect() as conn: try: await conn.execute(text("CREATE DATABASE test")) except ProgrammingError: pass return create_async_engine(test_pg_connection_string) @pytest.fixture(scope="function") async def test_session(pg_engine, loop): async with pg_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) session = AsyncSession(bind=pg_engine) yield session async with pg_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await session.close()
import pytest from sqlalchemy import text from sqlalchemy.exc import ProgrammingError from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.ext.asyncio import AsyncSession from virtool.postgres import Base @pytest.fixture def test_pg_connection_string(request): return request.config.getoption("postgres_connection_string") @pytest.fixture(scope="function") async def pg_engine(test_pg_connection_string): engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT") async with engine.connect() as conn: try: await conn.execute(text("CREATE DATABASE test")) except ProgrammingError: pass return create_async_engine(test_pg_connection_string) @pytest.fixture(scope="function") async def test_session(pg_engine, loop): async with pg_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) session = AsyncSession(bind=pg_engine) yield session async with pg_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await session.close()
:art: Use art instead of const in cli file
#!/usr/bin/env node 'use strict' process.title = 'ucompiler' require('debug').enable('UCompiler:*') var UCompiler = require('..') var knownCommands = ['go', 'watch'] var parameters = process.argv.slice(2) if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) { console.log('Usage: ucompiler go|watch [path]') process.exit(0) } if (parameters[0] === 'go') { UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) { console.error(e) process.exit(1) }) } else if (parameters[0] === 'watch') { if (!parameters[1]) { console.error('You must specify a path to watch') process.exit(1) } UCompiler.watch(parameters[1]) }
#!/usr/bin/env node 'use strict' process.title = 'ucompiler' require('debug').enable('UCompiler:*') const UCompiler = require('..') const knownCommands = ['go', 'watch'] const parameters = process.argv.slice(2) if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) { console.log('Usage: ucompiler go|watch [path]') process.exit(0) } if (parameters[0] === 'go') { UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) { console.error(e) process.exit(1) }) } else if (parameters[0] === 'watch') { if (!parameters[1]) { console.error('You must specify a path to watch') process.exit(1) } UCompiler.watch(parameters[1]) }
Use https now that we have certificates fixed
import { PureComponent } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import actions from './geolocation-provider-actions'; import reducers, { initialState } from './geolocation-provider-reducers'; const { IPSTACK_GEOLOCATION_API_KEY } = process.env; class GeolocationProvider extends PureComponent { componentDidMount() { const { requestLocation, locationProvider } = this.props; requestLocation(locationProvider); } render() { return null; } } GeolocationProvider.propTypes = { locationProvider: PropTypes.string.isRequired, requestLocation: PropTypes.func.isRequired }; GeolocationProvider.defaultProps = { locationProvider: `https://api.ipstack.com/check?access_key=${IPSTACK_GEOLOCATION_API_KEY}&format=1` }; export { actions, reducers, initialState }; export default connect(null, actions)(GeolocationProvider);
import { PureComponent } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import actions from './geolocation-provider-actions'; import reducers, { initialState } from './geolocation-provider-reducers'; const { IPSTACK_GEOLOCATION_API_KEY } = process.env; class GeolocationProvider extends PureComponent { componentDidMount() { const { requestLocation, locationProvider } = this.props; requestLocation(locationProvider); } render() { return null; } } GeolocationProvider.propTypes = { locationProvider: PropTypes.string.isRequired, requestLocation: PropTypes.func.isRequired }; GeolocationProvider.defaultProps = { locationProvider: `http://api.ipstack.com/check?access_key=${IPSTACK_GEOLOCATION_API_KEY}&format=1` }; export { actions, reducers, initialState }; export default connect(null, actions)(GeolocationProvider);
Add 2x in the example
<?php /* * Example 6 - How to get the currently activated payment methods. */ try { /* * Initialize the Mollie API library with your API key. * * See: https://www.mollie.com/dashboard/settings/profiles */ require "initialize.php"; /* * Get all the activated methods for this API key. */ $methods = $mollie->methods->all(); foreach ($methods as $method) { echo '<div style="line-height:40px; vertical-align:top">'; echo '<img src="' . htmlspecialchars($method->image->size1x) . '" srcset="' . htmlspecialchars($method->image->size2x) .' 2x"> '; echo htmlspecialchars($method->description) . ' (' . htmlspecialchars($method->id) . ')'; echo '</div>'; } } catch (Mollie_API_Exception $e) { echo "API call failed: " . htmlspecialchars($e->getMessage()); }
<?php /* * Example 6 - How to get the currently activated payment methods. */ try { /* * Initialize the Mollie API library with your API key. * * See: https://www.mollie.com/dashboard/settings/profiles */ require "initialize.php"; /* * Get all the activated methods for this API key. */ $methods = $mollie->methods->all(); foreach ($methods as $method) { echo '<div style="line-height:40px; vertical-align:top">'; echo '<img src="' . htmlspecialchars($method->image->size1x) . '"> '; echo htmlspecialchars($method->description) . ' (' . htmlspecialchars($method->id) . ')'; echo '</div>'; } } catch (Mollie_API_Exception $e) { echo "API call failed: " . htmlspecialchars($e->getMessage()); }
Change page section page - body
@extends('page::page-layouts.default') @section('title', 'Laravel Pages') @section('body') @include('page::shared.header', ["class_name" => "landing bg-5"]) @include('page::shared.nav') <section class="sub-header text-center"> <div class="container"> <h1> Just add content... </h1> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est error quae nostrum beatae, iusto accusantium repudiandae accusamus veritatis, voluptatum nesciunt dolorem aspernatur saepe a asperiores. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea doloribus similique officiis laudantium ratione praesentium. Voluptatibus, commodi saepe molestias ea iure optio dignissimos. Non, iusto. </p> </div> </section> @include('page::shared.footer') @endsection @push('styles') <style type="text/css"> .logo { display: none; } </style> @endpush @push('scripts') <script src="/packages/aos/aos.js"></script> <script> AOS.init(); $(document).ready(function(){ $('.logo').fadeToggle( 5000, "linear" ); }) </script> @endpush
@extends('page::page-layouts.default') @section('title', 'Laravel Pages') @section('page') @include('page::shared.header', ["class_name" => "landing bg-5"]) @include('page::shared.nav') <section class="sub-header text-center"> <div class="container"> <h1> Just add content... </h1> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est error quae nostrum beatae, iusto accusantium repudiandae accusamus veritatis, voluptatum nesciunt dolorem aspernatur saepe a asperiores. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea doloribus similique officiis laudantium ratione praesentium. Voluptatibus, commodi saepe molestias ea iure optio dignissimos. Non, iusto. </p> </div> </section> @include('page::shared.footer') @endsection @push('styles') <style type="text/css"> .logo { display: none; } </style> @endpush @push('scripts') <script src="/packages/aos/aos.js"></script> <script> AOS.init(); $(document).ready(function(){ $('.logo').fadeToggle( 5000, "linear" ); }) </script> @endpush
Fix paths in watch gulp task
var gulp = require('gulp'), concat = require('gulp-concat'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), gulpif = require('gulp-if'), react = require('gulp-react'); var paths = [ 'wrapper-header.js', 'cosmos.js', 'lib/**/*.js', 'mixins/**/*.js', 'components/**/*.jsx', 'wrapper-footer.js' ]; gulp.task('build', function() { gulp.src(paths) .pipe(gulpif(/\.jsx$/, react())) .pipe(concat('cosmos.js')) .pipe(gulp.dest('build')) .pipe(uglify()) .pipe(rename('cosmos.min.js')) .pipe(gulp.dest('build')); }); // Rerun the task when a file changes gulp.task('watch', function () { gulp.watch(paths, ['build']); }); gulp.task('default', ['build', 'watch']);
var gulp = require('gulp'), concat = require('gulp-concat'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), gulpif = require('gulp-if'), react = require('gulp-react'); var paths = [ 'wrapper-header.js', 'cosmos.js', 'lib/**/*.js', 'mixins/**/*.js', 'components/**/*.jsx', 'wrapper-footer.js' ]; gulp.task('build', function() { gulp.src(paths) .pipe(gulpif(/\.jsx$/, react())) .pipe(concat('cosmos.js')) .pipe(gulp.dest('build')) .pipe(uglify()) .pipe(rename('cosmos.min.js')) .pipe(gulp.dest('build')); }); // Rerun the task when a file changes gulp.task('watch', function () { gulp.watch(paths.core, ['build']); }); gulp.task('default', ['build', 'watch']);