text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Upgrade the file cordova dependency to 1.3.3
Package.describe({ summary: "Update the client when new client code is available", version: '1.1.4' }); Cordova.depends({ 'org.apache.cordova.file': '1.3.3', 'org.apache.cordova.file-transfer': '0.4.8' }); Package.onUse(function (api) { api.use('webapp', 'server'); api.use(['tracker', 'retry'], 'client'); api.use(['ddp', 'mongo', 'underscore'], ['client', 'server']); api.use('tracker', 'client'); api.use('reload', 'client', {weak: true}); api.use(['http', 'random'], 'web.cordova'); api.export('Autoupdate'); api.addFiles('autoupdate_server.js', 'server'); api.addFiles('autoupdate_client.js', 'web.browser'); api.addFiles('autoupdate_cordova.js', 'web.cordova'); });
Package.describe({ summary: "Update the client when new client code is available", version: '1.1.4' }); Cordova.depends({ 'org.apache.cordova.file': '1.3.2', 'org.apache.cordova.file-transfer': '0.4.8' }); Package.onUse(function (api) { api.use('webapp', 'server'); api.use(['tracker', 'retry'], 'client'); api.use(['ddp', 'mongo', 'underscore'], ['client', 'server']); api.use('tracker', 'client'); api.use('reload', 'client', {weak: true}); api.use(['http', 'random'], 'web.cordova'); api.export('Autoupdate'); api.addFiles('autoupdate_server.js', 'server'); api.addFiles('autoupdate_client.js', 'web.browser'); api.addFiles('autoupdate_cordova.js', 'web.cordova'); });
Fix issue with MessageBox causing a Buffer is not defined on client.
/* eslint-disable import/no-unresolved */ import { Meteor } from 'meteor/meteor'; import SimpleSchema from 'simpl-schema'; import MessageBox from 'message-box'; /* We check for server code here to deal with a buffer issue in meteor-message-box * This shouldn't be a major issue as I doubt we will need to display this error * on the client at this point. Should be fixed though. * https://github.com/aldeed/meteor-message-box/issues/1 */ if (Meteor.isServer) { MessageBox.defaults({ messages: { en: { Untrusted: 'Inserts/Updates from untrusted code not supported', }, }, }); } SimpleSchema.denyUntrusted = function denyUntrusted() { if (this.isSet) { const autoValue = this.definition.autoValue && this.definition.autoValue.call(this); const defaultValue = this.definition.defaultValue; if (this.value !== defaultValue && this.value !== autoValue && !this.isFromTrustedCode) { return 'Untrusted'; } } return undefined; };
/* eslint-disable import/no-unresolved */ import SimpleSchema from 'simpl-schema'; import MessageBox from 'message-box'; MessageBox.defaults({ messages: { en: { Untrusted: 'Inserts/Updates from untrusted code not supported', }, }, }); SimpleSchema.denyUntrusted = function denyUntrusted() { if (this.isSet) { const autoValue = this.definition.autoValue && this.definition.autoValue.call(this); const defaultValue = this.definition.defaultValue; if (this.value !== defaultValue && this.value !== autoValue && !this.isFromTrustedCode) { return 'Untrusted'; } } return undefined; };
Remove console.log from debugging session
const path = require('path') const { log } = require('../shared/log.utils') const { ConfigurationFileNotExist } = require('../services/config') const { ScriptNotExist, BadScriptPermission } = require('../services/file') module.exports = exports = (configService, fileService) => (scriptName, options) => { Promise.resolve() .then(scriptPath => log({ type: 'info', message: `Running "${scriptName}" script.` })) .then(() => fileService.runScript(scriptName)) .then(() => log({ type: 'success', message: `"${scriptName}" script execution is finished.` })) .catch(error => { if (error instanceof ConfigurationFileNotExist) { log({ type: 'error', message: 'No configuration file. You need to run the init command before.' }) return } if (error instanceof ScriptNotExist) { log({ type: 'error', message: error.message }) return } if (error instanceof BadScriptPermission) { log({ type: 'error', message: error.message, prefix: ' Fail ' }) return } log({ type: 'error', message: 'An error occured.', prefix: ' Fail ' }) }) }
const path = require('path') const { log } = require('../shared/log.utils') const { ConfigurationFileNotExist } = require('../services/config') const { ScriptNotExist, BadScriptPermission } = require('../services/file') module.exports = exports = (configService, fileService) => (scriptName, options) => { Promise.resolve() .then(scriptPath => log({ type: 'info', message: `Running "${scriptName}" script.` })) .then(() => fileService.runScript(scriptName)) .then(() => log({ type: 'success', message: `"${scriptName}" script execution is finished.` })) .catch(error => { if (error instanceof ConfigurationFileNotExist) { log({ type: 'error', message: 'No configuration file. You need to run the init command before.' }) return } if (error instanceof ScriptNotExist) { log({ type: 'error', message: error.message }) return } if (error instanceof BadScriptPermission) { log({ type: 'error', message: error.message, prefix: ' Fail ' }) return } log({ type: 'error', message: 'An error occured.', prefix: ' Fail ' }) console.log(error) }) }
Add constant definition for Proton end of stream git-svn-id: 33ed6c3feaacb64944efc691d1ae8e09b17f2bf9@1343343 13f79535-47bb-0310-9956-ffa450edef68
/* * * Licensed to the Apache Software Foundation (ASF) 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. * */ package org.apache.qpid.proton.engine; /** * Transport * * @opt operations * @opt types * */ public interface Transport extends Endpoint { public int END_OF_STREAM = -1; /** * @param bytes input bytes for consumption * @param offset the offset within bytes where input begins * @param size the number of bytes available for input * * @return the number of bytes consumed */ public int input(byte[] bytes, int offset, int size); /** * @param bytes array for output bytes * @param offset the offset within bytes where output begins * @param size the number of bytes available for output * * @return the number of bytes written */ public int output(byte[] bytes, int offset, int size); }
/* * * Licensed to the Apache Software Foundation (ASF) 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. * */ package org.apache.qpid.proton.engine; /** * Transport * * @opt operations * @opt types * */ public interface Transport extends Endpoint { /** * @param bytes input bytes for consumption * @param offset the offset within bytes where input begins * @param size the number of bytes available for input * * @return the number of bytes consumed */ public int input(byte[] bytes, int offset, int size); /** * @param bytes array for output bytes * @param offset the offset within bytes where output begins * @param size the number of bytes available for output * * @return the number of bytes written */ public int output(byte[] bytes, int offset, int size); }
Fix typo and use thisNode
// Copyright 2014-2015, University of Colorado Boulder /** * Base module for model elements whose position and opacity can change. * * @author John Blanco * @author Andrew Adare */ define( function( require ) { 'use strict'; var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); /** * @param {PositionableFadableModelElement} modelElement * @param {ModelViewTransform} modelViewTransform * @constructor */ function EFACBaseNode( modelElement, modelViewTransform ) { Node.call( this ); var thisNode = this; /** * Update the overall offset based on the model position. * * @param {Vector2} offset */ modelElement.positionProperty.link( function( offset ) { thisNode.setTranslation( modelViewTransform.modelToViewPosition( offset ) ); } ); /** * Update the overall opacity base on model element opacity. * * @param {Number} opacity */ modelElement.opacityProperty.link( function( opacity ) { thisNode.setOpacity( opacity ); } ); } return inherit( Node, EFACBaseNode ); } );
// Copyright 2014-2015, University of Colorado Boulder /** * Base module for model elements whose position and opacity can change. * * @author John Blanco * @author Andrew Adare */ define( function( require ) { 'use strict'; var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); /** * @param {PositionableFadableModelElement} modelElement * @param {ModelViewTransform} modelViewTransform * @constructor */ function EFACBaseNode( modelElement, modelViewTransform ) { Node.call( this ); /** * Update the overall offset based on the model position. * * @param {Vector2} offset */ modelElement.positionProperty.link( function( offset ) { this.setTranslation( modelViewTransform.ModelToViewPosition( offset ) ); } ); /** * Update the overall opacity base on model element opacity. * * @param {Number} opacity */ modelElement.opacityProperty.link( function( opacity ) { this.setOpacity( opacity ); } ); } return inherit( Node, EFACBaseNode ); } );
Allow a custom login logo to be displayed on login This is to allow team logos to be shown when a user registers with a team email.
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); module.exports = React.createClass({ displayName: 'VectorLoginHeader', statics: { replaces: 'LoginHeader', }, propTypes: { icon: React.PropTypes.string, }, render: function() { return ( <div className="mx_Login_logo"> <img src={this.props.icon || "img/logo.png"} width="195" height="195" alt="Riot"/> </div> ); } });
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); module.exports = React.createClass({ displayName: 'VectorLoginHeader', statics: { replaces: 'LoginHeader', }, render: function() { return ( <div className="mx_Login_logo"> <img src="img/logo.png" width="195" height="195" alt="Riot"/> </div> ); } });
Use same settings in smoke test as in real use
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.config_from_object('django.conf:settings') conn.connect() conn.release()
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
Fix test for PHP 5.3.3
<?php /** * PHP-DI * * @link http://php-di.org/ * @copyright Matthieu Napoli (http://mnapoli.fr/) * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file) */ namespace DI\Test\IntegrationTest\Definitions; use DI\ContainerBuilder; /** * Test object definitions * * TODO add more tests * * @coversNothing */ class ObjectDefinitionTest extends \PHPUnit_Framework_TestCase { public function test_object_without_autowiring() { $builder = new ContainerBuilder(); $builder->useAutowiring(false); $builder->useAnnotations(false); $builder->addDefinitions(array( // with the same name 'stdClass' => \DI\object('stdClass'), // with a different name 'object' => \DI\object('ArrayObject') ->constructor(array()), )); $container = $builder->build(); $this->assertInstanceOf('stdClass', $container->get('stdClass')); $this->assertInstanceOf('ArrayObject', $container->get('object')); } }
<?php /** * PHP-DI * * @link http://php-di.org/ * @copyright Matthieu Napoli (http://mnapoli.fr/) * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file) */ namespace DI\Test\IntegrationTest\Definitions; use DI\ContainerBuilder; /** * Test object definitions * * TODO add more tests * * @coversNothing */ class ObjectDefinitionTest extends \PHPUnit_Framework_TestCase { public function test_object_without_autowiring() { $builder = new ContainerBuilder(); $builder->useAutowiring(false); $builder->useAnnotations(false); $builder->addDefinitions(array( // with the same name 'stdClass' => \DI\object('stdClass'), // with a different name 'object' => \DI\object('DateTime') ->constructor('now', null), )); $container = $builder->build(); $this->assertInstanceOf('stdClass', $container->get('stdClass')); $this->assertInstanceOf('DateTime', $container->get('object')); } }
Update fetch source, add parameters
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const NUMBER = 2; const OFFSET = 3; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/builders'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
Make filtering & url generic
import logging import webapp2 from google.appengine.api import urlfetch from google.appengine.ext import vendor vendor.add('lib') import icalendar class CalendarFilterPage(webapp2.RequestHandler): def get(self): calendar_url = self.request.get('url') result = urlfetch.fetch(calendar_url) # http://www.arsenal.com/_scripts/ical.ics?tid=1006&sid=123 calendar = icalendar.Calendar.from_ical(result.content) filtered_cal = icalendar.Calendar() for k, v in calendar.items(): filtered_cal.add(k, v) filter_spec = FilterSpec(self.request.get('filter')) for component in calendar.subcomponents: if filter_spec.ShouldFilter(component): filtered_cal.add_component(component) self.response.content_type = 'text/calendar' self.response.headers.add( 'Cache-Control', 'max-age=3600') self.response.headers.add( 'Content-Disposition', 'attachment; filename="calendar.ical"') self.response.out.write(filtered_cal.to_ical()) class FilterSpec(object): def __init__(self, filter_spec): split = filter_spec.split(':') self.property = split[0] self.content = split[1] def ShouldFilter(self, event): return self.property in event and self.content in event[self.property] app = webapp2.WSGIApplication([ ('/calendar', CalendarFilterPage), ], debug=True)
import webapp2 from google.appengine.api import urlfetch from google.appengine.ext import vendor vendor.add('lib') import icalendar class MainPage(webapp2.RequestHandler): def get(self): result = urlfetch.fetch( 'http://www.arsenal.com/_scripts/ical.ics?tid=1006&sid=123') calendar = icalendar.Calendar.from_ical(result.content) filtered_cal = icalendar.Calendar() filtered_cal.add('prodid', '-//Filtered Arsenal Calendar//foo//') filtered_cal.add('version', '2.0') for component in calendar.subcomponents: if 'LOCATION' in component: if 'Emirates Stadium' in component['LOCATION']: filtered_cal.add_component(component) self.response.content_type = 'text/calendar' self.response.headers.add( 'Cache-Control', 'max-age=3600') self.response.out.write(filtered_cal.to_ical()) app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True)
Change asakusafw project template catalog URL.
/** * Copyright 2013 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.shafu.internal.asakusafw.preferences; /** * Preference constants of Shafu Asakusa Plug-in. */ public final class ShafuAsakusaPreferenceConstants { /** * The URL (prefix) of download site. */ private static final String URL_DOWNLOAD_SITE = "http://www.asakusafw.com/download/gradle-plugin/"; //$NON-NLS-1$ /** * The preference key of catalog URL. */ public static final String KEY_CATALOG_URL = "catalog"; //$NON-NLS-1$ /** * The default value of catalog URL. */ public static final String DEFAULT_CATALOG_URL = URL_DOWNLOAD_SITE + "template-catalog-release.txt"; //$NON-NLS-1$ private ShafuAsakusaPreferenceConstants() { return; } }
/** * Copyright 2013 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.shafu.internal.asakusafw.preferences; /** * Preference constants of Shafu Asakusa Plug-in. */ public final class ShafuAsakusaPreferenceConstants { /** * The preference key of catalog URL. */ public static final String KEY_CATALOG_URL = "catalog"; //$NON-NLS-1$ /** * The default value of catalog URL. */ public static final String DEFAULT_CATALOG_URL = "http://www.asakusafw.com/download/gradle-plugin/template-catalog.txt"; //$NON-NLS-1$ private ShafuAsakusaPreferenceConstants() { return; } }
Exclude tests directory from installation Fixes #223
import setuptools from server.version import VERSION setuptools.setup( name='electrumx', version=VERSION.split()[-1], scripts=['electrumx_server.py', 'electrumx_rpc.py'], python_requires='>=3.5.3', # "irc" package is only required if IRC connectivity is enabled # via environment variables, in which case I've tested with 15.0.4 # "x11_hash" package (1.4) is required to sync DASH network. install_requires=['plyvel', 'pylru', 'irc', 'aiohttp >= 1'], packages=setuptools.find_packages(exclude=['tests']), description='ElectrumX Server', author='Neil Booth', author_email='kyuupichan@gmail.com', license='MIT Licence', url='https://github.com/kyuupichan/electrumx/', long_description='Server implementation for the Electrum wallet', classifiers=[ 'Development Status :: 3 - Alpha', 'Topic :: Internet', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', ], )
import setuptools from server.version import VERSION setuptools.setup( name='electrumx', version=VERSION.split()[-1], scripts=['electrumx_server.py', 'electrumx_rpc.py'], python_requires='>=3.5.3', # "irc" package is only required if IRC connectivity is enabled # via environment variables, in which case I've tested with 15.0.4 # "x11_hash" package (1.4) is required to sync DASH network. install_requires=['plyvel', 'pylru', 'irc', 'aiohttp >= 1'], packages=setuptools.find_packages(), description='ElectrumX Server', author='Neil Booth', author_email='kyuupichan@gmail.com', license='MIT Licence', url='https://github.com/kyuupichan/electrumx/', long_description='Server implementation for the Electrum wallet', classifiers=[ 'Development Status :: 3 - Alpha', 'Topic :: Internet', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', ], )
Change Link component for a tag in LinkedIn logo external links require an a tag to work correctly
//@flow import React from "react"; import { pure, compose, withState, withHandlers } from "recompose"; import { ThemeProvider } from "styled-components"; import mainTheme from "../../global/style/mainTheme"; import { Logo } from "./Logo"; const enhance = compose( withState("isActive", "setActive", false), withHandlers({ addActive: props => () => props.setActive(true), rmActive: props => () => props.setActive(false) }), pure ); export const LinkedInLogo = enhance( ({ addActive, rmActive, isActive, ...props }: { addActive: () => any, rmActive: () => any, isActive: boolean }) => ( <ThemeProvider theme={mainTheme}> <a href="https://www.linkedin.com/in/oliver-askew-5791a333/" onMouseEnter={addActive} onMouseLeave={rmActive} > <Logo isActive={isActive} /> </a> </ThemeProvider> ) );
//@flow import React from "react"; import { Link } from "react-router-dom"; import { pure, compose, withState, withHandlers } from "recompose"; import { ThemeProvider } from "styled-components"; import mainTheme from "../../global/style/mainTheme"; import { Logo } from "./Logo"; const enhance = compose( withState("isActive", "setActive", false), withHandlers({ addActive: props => () => props.setActive(true), rmActive: props => () => props.setActive(false) }), pure ); export const LinkedInLogo = enhance( ({ addActive, rmActive, isActive }: { addActive: () => any, rmActive: () => any, isActive: boolean }) => ( <ThemeProvider theme={mainTheme}> <Link to="https://www.linkedin.com/in/oliver-askew-5791a333/" onMouseEnter={addActive} onMouseLeave={rmActive} > <Logo isActive={isActive} /> </Link> </ThemeProvider> ) );
Make the server example listen on 0.0.0.0 by default.
import argparse import math from pythonosc import dispatcher from pythonosc import osc_server def print_volume_handler(args, volume): print("[{0}] ~ {1}".format(args[0], volume)) def print_compute_handler(args, volume): try: print("[{0}] ~ {1}".format(args[0], args[1](volume))) except ValueError: pass if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--ip", default="0.0.0.0", help="The ip to listen on") parser.add_argument("--port", type=int, default=5005, help="The port to listen on") args = parser.parse_args() dispatcher = dispatcher.Dispatcher() dispatcher.map("/debug", print) dispatcher.map("/volume", print_volume_handler, "Volume") dispatcher.map("/logvolume", print_compute_handler, "Log volume", math.log) server = osc_server.ThreadingOSCUDPServer( (args.ip, args.port), dispatcher) print("Serving on {}".format(server.server_address)) server.serve_forever()
import argparse import math from pythonosc import dispatcher from pythonosc import osc_server def print_volume_handler(args, volume): print("[{0}] ~ {1}".format(args[0], volume)) def print_compute_handler(args, volume): try: print("[{0}] ~ {1}".format(args[0], args[1](volume))) except ValueError: pass if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--ip", default="127.0.0.1", help="The ip to listen on") parser.add_argument("--port", type=int, default=5005, help="The port to listen on") args = parser.parse_args() dispatcher = dispatcher.Dispatcher() dispatcher.map("/debug", print) dispatcher.map("/volume", print_volume_handler, "Volume") dispatcher.map("/logvolume", print_compute_handler, "Log volume", math.log) server = osc_server.ThreadingOSCUDPServer( (args.ip, args.port), dispatcher) print("Serving on {}".format(server.server_address)) server.serve_forever()
Fix baseURL for github pages.
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'katana', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/katana'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'katana', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Update the sample proxy list
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "212.87.220.2:3128", # (Example) - set your own proxy here "example2": "51.75.147.44:3128", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "45.133.182.18:18080", # (Example) - set your own proxy here "example2": "95.174.67.50:18080", # (Example) - set your own proxy here "example3": "83.97.23.90:18080", # (Example) - set your own proxy here "example4": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Check that we have a current model in Filter.Thematic This filter can get invoked on app start up (by Selection.AllSets) even though there is no current model in the history store yet. Obviously in this case, it can't filter using the current model so in that situation we just return true in the include method. Clearly this means the filter is not actually doing its job but it doesnt matter because the filter will get invoked again before the user actually sees this content. https://phabricator.endlessm.com/T12388
// Copyright 2016 Endless Mobile, Inc. /* exported Thematic */ const GObject = imports.gi.GObject; const Filter = imports.app.interfaces.filter; const HistoryStore = imports.app.historyStore; const Module = imports.app.interfaces.module; /** * Class: Filter.Thematic * * If the current item in our history model is featured, filter for non-featured * models. If the current item in our history is not featured, filter for * featured models. */ const Thematic = new Module.Class({ Name: 'Filter.Thematic', Extends: GObject.Object, Implements: [Filter.Filter], _init: function (props={}) { this.parent(props); HistoryStore.get_default().connect('changed', () => { this.emit('filter-changed'); }); }, // Filter implementation include_impl: function (model) { let item = HistoryStore.get_default().get_current_item(); // Kind of silly but without this check the filter throws on app startup // because Selection.AllSets always loads its content right away on // init. It will get refiltered properly once a user clicks on a set // object. if (item && item.model) return (model.featured != item.model.featured); return true; }, });
// Copyright 2016 Endless Mobile, Inc. /* exported Thematic */ const GObject = imports.gi.GObject; const Filter = imports.app.interfaces.filter; const HistoryStore = imports.app.historyStore; const Module = imports.app.interfaces.module; /** * Class: Filter.Thematic * * If the current item in our history model is featured, filter for non-featured * models. If the current item in our history is not featured, filter for * featured models. */ const Thematic = new Module.Class({ Name: 'Filter.Thematic', Extends: GObject.Object, Implements: [Filter.Filter], _init: function (props={}) { this.parent(props); HistoryStore.get_default().connect('changed', () => { this.emit('filter-changed'); }); }, // Filter implementation include_impl: function (model) { return (model.featured != HistoryStore.get_default().get_current_item().model.featured); }, });
Add sleep effect via event
package me.rkfg.xmpp.bot.plugins.game.event; import me.rkfg.xmpp.bot.plugins.game.IGameObject; import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect; import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect.SleepType; import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute; public class SetSleepEvent extends AbstractEvent { public static final String TYPE = "setsleep"; public static final TypedAttribute<SleepType> SLEEP_ATTR = TypedAttribute.of("sleeptype"); public SetSleepEvent(SleepType type, IGameObject source) { super(TYPE, source); setAttribute(SLEEP_ATTR, type); setAttribute(COMMENT, "Персонаж выбирает стратегию сна: " + type.getLocalized()); } @Override public void apply() { getAttribute(SLEEP_ATTR).ifPresent(st -> { target.enqueueAttachEffect(new SleepEffect(st, source)); super.apply(); }); } }
package me.rkfg.xmpp.bot.plugins.game.event; import me.rkfg.xmpp.bot.plugins.game.IGameObject; import me.rkfg.xmpp.bot.plugins.game.effect.IAttachDetachEffect; import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect; import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect.SleepType; import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute; public class SetSleepEvent extends AbstractEvent { public static final String TYPE = "setsleep"; public static final TypedAttribute<SleepType> SLEEP_ATTR = TypedAttribute.of("sleeptype"); public SetSleepEvent(SleepType type, IGameObject source) { super(TYPE, source); setAttribute(SLEEP_ATTR, type); setAttribute(COMMENT, "Персонаж выбирает стратегию сна: " + type.getLocalized()); } @Override public void apply() { getAttribute(SLEEP_ATTR).ifPresent(st -> { ((IAttachDetachEffect) target).attachEffect(new SleepEffect(st, source)); super.apply(); }); } }
Add `grunt test` and `grunt build`
module.exports = function(grunt) { grunt.initConfig({ watch: { jasmine: { files: [ 'aviator.js', 'spec/*_spec.js' ], tasks: [ 'jasmine:all' ], options: { interrupt: true } }, browserify: { files: [ 'src/**/*.js' ], tasks: [ 'browserify:aviator' ], options: { interrupt: true } } }, jasmine: { all: { src: 'aviator.js', options: { specs: 'spec/*_spec.js' } } }, browserify: { aviator: { src: 'src/main.js', dest: 'aviator.js' } } }); grunt.registerTask('test', ['jasmine']); grunt.registerTask('build', ['browserify']); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-watch'); };
module.exports = function(grunt) { grunt.initConfig({ watch: { jasmine: { files: [ 'aviator.js', 'spec/*_spec.js' ], tasks: [ 'jasmine:all' ], options: { interrupt: true } }, browserify: { files: [ 'src/**/*.js' ], tasks: [ 'browserify:aviator' ], options: { interrupt: true } } }, jasmine: { all: { src: 'aviator.js', options: { specs: 'spec/*_spec.js' } } }, browserify: { aviator: { src: 'src/main.js', dest: 'aviator.js' } } }); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-watch'); };
Hide enable link when dtenable is set
/* eslint-disable no-console */ // <nowiki> (function() { var updateLinks = function() { $('a').each(function(i, e) { var shorthref = e.getAttribute('href') || ''; if (shorthref.match(/^(|#)$/)) { return; } try { var url = new URL(e.href); if (url.host.match(/\.(wikipedia|wiktionary|wikiquote|wikisource|wikinews|wikivoyage|wikibooks|wikiversity|wikimedia|mediawiki|wikidata)\.org$/)) { url.searchParams.set('dtenable', '1'); e.href = url.href; } } catch (err) { console.error(e, err); } }); }; setTimeout(updateLinks, 1000); if (mw.util.getParamValue('dtenable') === null) { var url = new URL(window.location.href); url.searchParams.set('dtenable', '1'); mw.util.addPortletLink( 'p-tb', url.href, 'Enable DiscussionTools', 't-dtenable' ); } } )(); // </nowiki>
/* eslint-disable no-console */ // <nowiki> (function() { var updateLinks = function() { $('a').each(function(i, e) { var shorthref = e.getAttribute('href') || ''; if (shorthref.match(/^(|#)$/)) { return; } try { var url = new URL(e.href); if (url.host.match(/\.(wikipedia|wiktionary|wikiquote|wikisource|wikinews|wikivoyage|wikibooks|wikiversity|wikimedia|mediawiki|wikidata)\.org$/)) { url.searchParams.set('dtenable', '1'); e.href = url.href; } } catch (err) { console.error(e, err); } }); }; setTimeout(updateLinks, 1000); var url = new URL(window.location.href); url.searchParams.set('dtenable', '1'); mw.util.addPortletLink( 'p-tb', url.href, 'Enable DiscussionTools', 't-dtenable' ); } )(); // </nowiki>
Fix typo in Thrift trunk Summary: $classl => $class git-svn-id: 8d8e29b1fb681c884914062b88f3633e3a187774@665376 13f79535-47bb-0310-9956-ffa450edef68
<?php /** * Copyright (c) 2006- Facebook * Distributed under the Thrift Software License * * See accompanying file LICENSE or visit the Thrift site at: * http://developers.facebook.com/thrift/ * * @package thrift * @author Mark Slee <mcslee@facebook.com> */ /** * Include this file if you wish to use autoload with your PHP generated Thrift * code. The generated code will *not* include any defined Thrift classes by * default, except for the service interfaces. The generated code will populate * values into $GLOBALS['THRIFT_AUTOLOAD'] which can be used by the autoload * method below. If you have your own autoload system already in place, rename your * __autoload function to something else and then do: * $GLOBALS['AUTOLOAD_HOOKS'][] = 'my_autoload_func'; * * Generate this code using the -phpa Thrift generator flag. */ $GLOBALS['THRIFT_AUTOLOAD'] = array(); $GLOBALS['AUTOLOAD_HOOKS'] = array(); if (!function_exists('__autoload')) { function __autoload($class) { global $THRIFT_AUTOLOAD; $classl = strtolower($class); if (isset($THRIFT_AUTOLOAD[$classl])) { include_once $GLOBALS['THRIFT_ROOT'].'/packages/'.$THRIFT_AUTOLOAD[$classl]; } else if (!empty($GLOBALS['AUTOLOAD_HOOKS'])) { foreach ($GLOBALS['AUTOLOAD_HOOKS'] as $hook) { $hook($class); } } } }
<?php /** * Copyright (c) 2006- Facebook * Distributed under the Thrift Software License * * See accompanying file LICENSE or visit the Thrift site at: * http://developers.facebook.com/thrift/ * * @package thrift * @author Mark Slee <mcslee@facebook.com> */ /** * Include this file if you wish to use autoload with your PHP generated Thrift * code. The generated code will *not* include any defined Thrift classes by * default, except for the service interfaces. The generated code will populate * values into $GLOBALS['THRIFT_AUTOLOAD'] which can be used by the autoload * method below. If you have your own autoload system already in place, rename your * __autoload function to something else and then do: * $GLOBALS['AUTOLOAD_HOOKS'][] = 'my_autoload_func'; * * Generate this code using the -phpa Thrift generator flag. */ $GLOBALS['THRIFT_AUTOLOAD'] = array(); $GLOBALS['AUTOLOAD_HOOKS'] = array(); if (!function_exists('__autoload')) { function __autoload($class) { global $THRIFT_AUTOLOAD; $classl = strtolower($classl); if (isset($THRIFT_AUTOLOAD[$classl])) { include_once $GLOBALS['THRIFT_ROOT'].'/packages/'.$THRIFT_AUTOLOAD[$classl]; } else if (!empty($GLOBALS['AUTOLOAD_HOOKS'])) { foreach ($GLOBALS['AUTOLOAD_HOOKS'] as $hook) { $hook($class); } } } }
Use urljoin to form urls.
import json import urlparse import requests class Client(object): LAUNCHPAD_URL = 'https://launchpad.37signals.com/' BASE_URL = 'https://basecamp.com/%s/api/v1/' def __init__(self, access_token, user_agent, account_id=None): """Initialize client for making requests. user_agent -- string identifying the app, and an url or email related to the app; e.g. "BusyFlow (http://busyflow.com)". """ self.account_id = account_id self.session = requests.session( headers={'User-Agent': user_agent, 'Authorization': 'Bearer %s' % access_token, 'Content-Type': 'application/json; charset=utf-8'}) def accounts(self): url = urlparse.urljoin(self.LAUNCHPAD_URL,'authorization.json') return json.loads(self.session.get(url).content)
import json import requests class Client(object): LAUNCHPAD_URL = 'https://launchpad.37signals.com' BASE_URL = 'https://basecamp.com/%s/api/v1' def __init__(self, access_token, user_agent, account_id=None): """Initialize client for making requests. user_agent -- string identifying the app, and an url or email related to the app; e.g. "BusyFlow (http://busyflow.com)". """ self.account_id = account_id self.session = requests.session( headers={'User-Agent': user_agent, 'Authorization': 'Bearer %s' % access_token, 'Content-Type': 'application/json; charset=utf-8'}) def accounts(self): url = '%s/authorization.json' % self.LAUNCHPAD_URL return json.loads(self.session.get(url).content)
Fix FBTest, the inline editor can be opened async on Mac
function runTest() { FBTest.sysout("issue5504.START"); FBTest.openNewTab(basePath + "html/5504/issue5504.html", function(win) { FBTest.openFirebug(); var panel = FBTest.selectPanel("html"); // Get the selected element and execute "New Attribute" action on it. var nodeBox = getSelectedNodeBox(); FBTest.executeContextMenuCommand(nodeBox, "htmlNewAttribute", function() { // Wait till the inline editor is available. var config = {tagName: "input", classes: "textEditorInner"}; FBTest.waitForDisplayedElement("html", config, function(editor) { FBTest.compare("", editor.value, "The default value must be an empty string"); FBTest.testDone("issue5504.DONE"); }); }); }); } // xxxHonza: use the one from FBTest (should be in FBTest 1.10b5) function getSelectedNodeBox() { var panel = FBTest.getPanel("html"); return panel.panelNode.querySelector(".nodeBox.selected"); }
function runTest() { FBTest.sysout("issue5504.START"); FBTest.openNewTab(basePath + "html/5504/issue5504.html", function(win) { FBTest.openFirebug(); var panel = FBTest.selectPanel("html"); // Get the selected element and execute "New Attribute" action on it. var nodeBox = getSelectedNodeBox(); FBTest.executeContextMenuCommand(nodeBox, "htmlNewAttribute", function() { var editor = panel.panelNode.getElementsByClassName("textEditorInner").item(0); FBTest.compare("", editor.value, "The default value must be an empty string"); FBTest.testDone("issue5504.DONE"); }); }); } // xxxHonza: use the one from FBTest (should be in FBTest 1.10b5) function getSelectedNodeBox() { var panel = FBTest.getPanel("html"); return panel.panelNode.querySelector(".nodeBox.selected"); }
Use e.message as error name
ErrorModel = function (appId) { var self = this; this.appId = appId; this.errors = {}; this.startTime = Date.now(); } _.extend(ErrorModel.prototype, KadiraModel.prototype); ErrorModel.prototype.buildPayload = function() { var metrics = _.values(this.errors); this.startTime = Date.now(); this.errors = {}; return {errors: metrics}; }; ErrorModel.prototype.trackError = function(ex, source) { if(this.errors[ex.message]) { this.errors[ex.message].count++; } else { this.errors[ex.message] = this._formatError(ex, source); } }; ErrorModel.prototype._formatError = function(ex, source) { var now = Date.now(); return { appId : this.appId, name : ex.message, source : source, startTime : now, type : 'server', stack : [{at: now, events: [], stack: ex.stack}], count: 1, } };
ErrorModel = function (appId) { var self = this; this.appId = appId; this.errors = {}; this.startTime = Date.now(); } _.extend(ErrorModel.prototype, KadiraModel.prototype); ErrorModel.prototype.buildPayload = function() { var metrics = _.values(this.errors); this.startTime = Date.now(); this.errors = {}; return {errors: metrics}; }; ErrorModel.prototype.trackError = function(ex, source) { var name = ex.name + ': ' + ex.message; if(this.errors[name]) { this.errors[name].count++; } else { this.errors[name] = this._formatError(ex, source); } }; ErrorModel.prototype._formatError = function(ex, source) { var name = ex.name + ': ' + ex.message; var now = Date.now(); return { appId : this.appId, name : name, source : source, startTime : now, type : 'server', stack : [{at: now, events: [], stack: ex.stack}], count: 1, } };
Fix the display name of admin profile in the admin admin
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
BUGFIX: Make migration regex more precise (cherry picked from commit f7c459c3794dbe9d441196ddf42e786ea902ab29)
<?php namespace Neos\Flow\Core\Migrations; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ /** * Adjust DB migrations to Doctrine Migrations 3.0 * * - use Doctrine\Migrations\AbstractMigration instead of Doctrine\DBAL\Migrations\AbstractMigration * - adjust method signatures */ class Version20201109224100 extends AbstractMigration { /** * @return string */ public function getIdentifier() { return 'Neos.Flow-20201109224100'; } /** * @return void */ public function up() { $this->searchAndReplace('Doctrine\DBAL\Migrations\AbstractMigration', 'Doctrine\Migrations\AbstractMigration', ['php']); $this->searchAndReplaceRegex('/(namespace Neos\\\Flow\\\Persistence\\\Doctrine\\\Migrations.+)public function getDescription\(\)(\s*\{)?$/sm', '$1public function getDescription(): string $2', ['php']); $this->searchAndReplaceRegex('/public function (up|down|preUp|postUp|preDown|postDown)\(Schema \$schema\)(\s*\{)?$/m', 'public function $1(Schema \$schema): void $2', ['php']); } }
<?php namespace Neos\Flow\Core\Migrations; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ /** * Adjust DB migrations to Doctrine Migrations 3.0 * * - use Doctrine\Migrations\AbstractMigration instead of Doctrine\DBAL\Migrations\AbstractMigration * - adjust method signatures */ class Version20201109224100 extends AbstractMigration { /** * @return string */ public function getIdentifier() { return 'Neos.Flow-20201109224100'; } /** * @return void */ public function up() { $this->searchAndReplace('Doctrine\DBAL\Migrations\AbstractMigration', 'Doctrine\Migrations\AbstractMigration', ['php']); $this->searchAndReplaceRegex('/(Neos\\\Flow\\\Persistence\\\Doctrine\\\Migrations.+)public function getDescription\(\)(\s*\{)?$/sm', '$1public function getDescription(): string $2', ['php']); $this->searchAndReplaceRegex('/public function (up|down|preUp|postUp|preDown|postDown)\(Schema \$schema\)(\s*\{)?$/m', 'public function $1(Schema \$schema): void $2', ['php']); } }
Fix temp directory, failure on os.tmpdir() warnings in newer nodes
var _ = require('lodash'); var fs = require('fs'); var path = require("path"); var spawnSync = require("child_process").spawnSync; var Locator = require("./locator"); var mochaSettings = require("./settings"); var reporter = path.resolve(__dirname, 'test_capture.js'); module.exports = function(settings) { var OUTPUT_PATH = path.resolve(settings.tempDir, 'get_mocha_tests.json'); if (!fs.existsSync(settings.tempDir)){ fs.mkdirSync(settings.tempDir); } var cmd = './node_modules/.bin/mocha'; var args = ['--reporter', reporter]; if (mochaSettings.mochaOpts) { args.push('--opts', mochaSettings.mochaOpts); } args = args.concat(mochaSettings.mochaTestFolders); var env = _.extend({}, process.env, {MOCHA_CAPTURE_PATH: OUTPUT_PATH}); var capture = spawnSync(cmd, args, {env: env}); if (capture.status !== 0) { console.error('Could not capture mocha tests. To debug, run the following command:\nMOCHA_CAPTURE_PATH=%s %s %s', OUTPUT_PATH, cmd, args.join(' ')); process.exit(1); } var tests = fs.readFileSync(OUTPUT_PATH, 'utf-8'); fs.unlinkSync(OUTPUT_PATH); tests = JSON.parse(tests).map(function(t) { return new Locator(t.fullTitle, t.file, t.pending, t.title); }); return tests; };
var _ = require('lodash'); var fs = require('fs'); var path = require("path"); var spawnSync = require("child_process").spawnSync; var Locator = require("./locator"); var mochaSettings = require("./settings"); var reporter = path.resolve(__dirname, 'test_capture.js'); module.exports = function(settings) { var OUTPUT_PATH = path.resolve(settings.tempDir, 'get_mocha_tests.json'); var cmd = './node_modules/.bin/mocha'; var args = ['--reporter', reporter]; if (mochaSettings.mochaOpts) { args.push('--opts', mochaSettings.mochaOpts); } args = args.concat(mochaSettings.mochaTestFolders); var env = _.extend({}, process.env, {MOCHA_CAPTURE_PATH: OUTPUT_PATH}); var capture = spawnSync(cmd, args, {env: env}); if (capture.status !== 0 || capture.stderr.toString()) { console.error('Could not capture mocha tests. To debug, run the following command:\nMOCHA_CAPTURE_PATH=%s %s %s', OUTPUT_PATH, cmd, args.join(' ')); process.exit(1); } var tests = fs.readFileSync(OUTPUT_PATH, 'utf-8'); fs.unlinkSync(OUTPUT_PATH); tests = JSON.parse(tests).map(function(t) { return new Locator(t.fullTitle, t.file, t.pending, t.title); }); return tests; };
Remove duplicate funct in CmdUtil.findUser()
package co.phoenixlab.discord.commands; import co.phoenixlab.discord.MessageContext; import co.phoenixlab.discord.api.entities.Channel; import co.phoenixlab.discord.api.entities.Message; import co.phoenixlab.discord.api.entities.User; public class CommandUtil { static User findUser(MessageContext context, String username) { Message message = context.getMessage(); User user; Channel channel = context.getApiClient().getChannelById(message.getChannelId()); // Attempt to find the given user // If the user is @mentioned, try that first if (message.getMentions() != null && message.getMentions().length > 0) { user = message.getMentions()[0]; } else { // Try exact match, frontal match, ID match, and fuzzy match user = context.getApiClient().findUser(username, channel.getParent()); } return user; } }
package co.phoenixlab.discord.commands; import co.phoenixlab.discord.MessageContext; import co.phoenixlab.discord.api.DiscordApiClient; import co.phoenixlab.discord.api.entities.Channel; import co.phoenixlab.discord.api.entities.Message; import co.phoenixlab.discord.api.entities.User; public class CommandUtil { static User findUser(MessageContext context, String username) { Message message = context.getMessage(); User user; Channel channel = context.getApiClient().getChannelById(message.getChannelId()); // Attempt to find the given user // If the user is @mentioned, try that first if (message.getMentions() != null && message.getMentions().length > 0) { user = message.getMentions()[0]; } else { user = context.getApiClient().findUser(username, channel.getParent()); } // Try matching by ID if (user == DiscordApiClient.NO_USER) { user = context.getApiClient().getUserById(username, channel.getParent()); } return user; } }
Correct minor snafu * SNAFU: Situation Normal. All Fucked Up.
package events import ( "gpio" "time" ) type EdgeEvent struct { BeforeEvent int AfterEvent int Timestamp time.Time } func edgeTrigger(pin gpio.GPIO, eventCh chan EdgeEvent, ctrlCh chan bool) (error) { lastState, err := pin.ReadValue() if err != nil { panic(err) // improve } for true { select { case <-ctrlCh: return nil default: newState, err := pin.ReadValue() if err != nil { panic(err) // improve } if newState != lastState { eventCh <- EdgeEvent{BeforeEvent: lastState, AfterEvent: newState, Timestamp: time.Now()} lastState = newState } } } return nil } func StartEdgeTrigger(pin gpio.GPIO) (chan EdgeEvent, chan bool) { eventCh := make(chan EdgeEvent) // this should have a buffer ctrlCh := make(chan bool) go edgeTrigger(pin, eventCh, ctrlCh) return eventCh, ctrlCh } func StopEdgeTrigger(ctrlCh chan bool) { ctrlCh <- true }
package events import ( "gpio" "time" ) type EdgeEvent struct { BeforeEvent int AfterEvent int Timestamp time.Time } func edgeTrigger(pin gpio.GPIO, eventCh chan EdgeEvent, ctrlCh chan bool) (error) { lastState, err := pin.ReadValue() if err != nil { panic(err) // improve } for true { select { case <-ctrlCh: return nil default: newState, err := pin.ReadValue() if err != nil { panic(err) // improve } if newState != lastState { lastState = newState eventCh <- EdgeEvent{BeforeEvent: lastState, AfterEvent: newState, Timestamp: time.Now()} } } } return nil } func StartEdgeTrigger(pin gpio.GPIO) (chan EdgeEvent, chan bool) { eventCh := make(chan EdgeEvent) // this should have a buffer ctrlCh := make(chan bool) go edgeTrigger(pin, eventCh, ctrlCh) return eventCh, ctrlCh } func StopEdgeTrigger(ctrlCh chan bool) { ctrlCh <- true }
Correct click version requirement to >= 7.0 We need the show_envvar kwarg since 1a0f77b33150c02648652e793974f0312a17e7d7 which was added in pallets/click#710 and released in Click 7.0.
# -*- coding: utf-8 -*- from setuptools import find_packages, setup from valohai_cli import __version__ setup( name='valohai-cli', version=__version__, entry_points={'console_scripts': ['vh=valohai_cli.cli:cli']}, author='Valohai', author_email='hait@valohai.com', license='MIT', install_requires=[ 'click>=7.0', 'six>=1.10.0', 'valohai-yaml>=0.8', 'requests[security]>=2.0.0', 'requests-toolbelt>=0.7.1', ], packages=find_packages(include=('valohai_cli*',)), )
# -*- coding: utf-8 -*- from setuptools import find_packages, setup from valohai_cli import __version__ setup( name='valohai-cli', version=__version__, entry_points={'console_scripts': ['vh=valohai_cli.cli:cli']}, author='Valohai', author_email='hait@valohai.com', license='MIT', install_requires=[ 'click>=6.0', 'six>=1.10.0', 'valohai-yaml>=0.8', 'requests[security]>=2.0.0', 'requests-toolbelt>=0.7.1', ], packages=find_packages(include=('valohai_cli*',)), )
Fix tests to not use deprecated file
<?php $file = __DIR__.'/../vendor/autoload.php'; if (file_exists($file)) { $autoload = require $file; } else { throw new RuntimeException('Install dependencies to run test suite.'); } $files = array_filter(array( __DIR__.'/../vendor/symfony/symfony/src/Symfony/Bridge/PhpUnit/bootstrap.php', __DIR__.'/../vendor/symfony/phpunit-bridge/bootstrap.php', ), 'file_exists'); if ($files) { require_once current($files); } use Doctrine\Common\Annotations\AnnotationRegistry; AnnotationRegistry::registerLoader(array($autoload, 'loadClass')); //AnnotationRegistry::registerFile(__DIR__.'/../lib/Doctrine/ODM/PHPCR/Mapping/Annotations/DoctrineAnnotations.php'); // tests are not autoloaded the composer.json $autoload->add('Doctrine\Tests', __DIR__);
<?php $file = __DIR__.'/../vendor/autoload.php'; if (file_exists($file)) { $autoload = require $file; } else { throw new RuntimeException('Install dependencies to run test suite.'); } $files = array_filter(array( __DIR__.'/../vendor/symfony/symfony/src/Symfony/Bridge/PhpUnit/bootstrap.php', __DIR__.'/../vendor/symfony/phpunit-bridge/bootstrap.php', ), 'file_exists'); if ($files) { require_once current($files); } use Doctrine\Common\Annotations\AnnotationRegistry; AnnotationRegistry::registerLoader(array($autoload, 'loadClass')); AnnotationRegistry::registerFile(__DIR__.'/../lib/Doctrine/ODM/PHPCR/Mapping/Annotations/DoctrineAnnotations.php'); // tests are not autoloaded the composer.json $autoload->add('Doctrine\Tests', __DIR__);
Watch stylus files for changes
'use strict'; module.exports = function(grunt) { grunt.config.set('watch', { livereload: { options: { livereload: true, }, files: ['src/**/*.{js,html}', 'prod/*'], }, jshintrc: { files: ['**/.jshintrc'], tasks: ['jshint'], }, build: { files: ['<%= jshint.build.src %>'], tasks: ['jscs', 'jshint:build'], }, scripts: { files: ['<%= jshint.app.src %>'], tasks: ['jscs', 'jshint:app'], }, stylus: { files: ['src/**/*.styl'], tasks: ['stylus:dev'], }, }); grunt.loadNpmTasks('grunt-contrib-watch'); };
'use strict'; module.exports = function(grunt) { grunt.config.set('watch', { livereload: { options: { livereload: true, }, files: ['src/**/*.{js,css,html}'], }, jshintrc: { files: ['**/.jshintrc'], tasks: ['jshint'], }, build: { files: ['<%= jshint.build.src %>'], tasks: ['jscs', 'jshint:build'], }, scripts: { files: ['<%= jshint.app.src %>'], tasks: ['jscs', 'jshint:app'], }, }); grunt.loadNpmTasks('grunt-contrib-watch'); };
[Cache] Fix wrong classname in deprecation message
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Cache\Simple; use Symfony\Component\Cache\Adapter\ApcuAdapter; use Symfony\Component\Cache\Traits\ApcuTrait; use Symfony\Contracts\Cache\CacheInterface; @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" and type-hint for "%s" instead.', ApcuCache::class, ApcuAdapter::class, CacheInterface::class), E_USER_DEPRECATED); /** * @deprecated since Symfony 4.3, use ApcuAdapter and type-hint for CacheInterface instead. */ class ApcuCache extends AbstractCache { use ApcuTrait; public function __construct(string $namespace = '', int $defaultLifetime = 0, string $version = null) { $this->init($namespace, $defaultLifetime, $version); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Cache\Simple; use Symfony\Component\Cache\Traits\ApcuTrait; @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" and type-hint for "%s" instead.', ApcuCache::class, ApcuAdapter::class, CacheInterface::class), E_USER_DEPRECATED); /** * @deprecated since Symfony 4.3, use ApcuAdapter and type-hint for CacheInterface instead. */ class ApcuCache extends AbstractCache { use ApcuTrait; public function __construct(string $namespace = '', int $defaultLifetime = 0, string $version = null) { $this->init($namespace, $defaultLifetime, $version); } }
Fix property name in CondSet Signed-off-by: Harsh Gupta <c4bd8559369e527b4bb1785ff84e8ff50fde87c0@gmail.com>
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class CondSet(Set): """ Set of elements which satisfies a given condition. {x | cond(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, FiniteSet, Lambda, pi >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) lamda = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def _is_multivariate(self): return len(self.lamda.variables) > 1 def _contains(self, other): # XXX: probably we should check if self.cond is returning only true or # false return self.cond(other)
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class CondSet(Set): """ Set of elements which satisfies a given condition. {x | cond(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, FiniteSet, Lambda, pi >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) cond = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def _is_multivariate(self): return len(self.lamda.variables) > 1 def _contains(self, other): # XXX: probably we should check if self.cond is returning only true or # false return self.cond(other)
Set start-time for scenes to ’now’ instead of calculating timestamps
// @flow import type { CronJob, Task } from '../../types'; import shortid from 'shortid'; import { assoc, lens, map, pipe, prop, replace, set, view } from 'ramda'; const jobTemplate: CronJob = { jobId: 'cronjobs/', name: 'temporary scene cron-job ', at: '13:15:00', repeat: 'oneShot', scheduled: false, running: false, lastRun: null, tasks: null, }; function buildCronjobWithTasks(name: string, tasks: Array<Task>) { const jobIdLens = lens(prop('jobId'), assoc('jobId')); const orgJobId = view(jobIdLens)(jobTemplate); // Remove slash in scene-name and append unique id const newJobId = set( jobIdLens, `${orgJobId}${replace(/\//, '', name)}-${shortid.generate()}` ); return pipe(newJobId, assoc('tasks', tasks))(jobTemplate); } function scheduleJobForNow(job: CronJob) { return assoc('at', 'now', job); } function invertTaskActions(tasks: Array<Task>) { const invert = act => { switch (act) { case 'on': return 'off'; case 'off': return 'on'; default: return act; } }; return map(t => assoc('act', invert(prop('act', t)), t), tasks); } export { buildCronjobWithTasks, scheduleJobForNow, invertTaskActions };
// @flow import type { CronJob, Task } from '../../types'; import shortid from 'shortid'; import { format, addSeconds } from 'date-fns'; import { assoc, lens, map, pipe, prop, replace, set, view } from 'ramda'; const jobTemplate: CronJob = { jobId: 'cronjobs/', name: 'temporary scene cron-job ', at: '13:15:00', repeat: 'oneShot', scheduled: false, running: false, lastRun: null, tasks: null, }; function buildCronjobWithTasks(name: string, tasks: Array<Task>) { const jobIdLens = lens(prop('jobId'), assoc('jobId')); const orgJobId = view(jobIdLens)(jobTemplate); // Remove slash in scene-name and append unique id const newJobId = set( jobIdLens, `${orgJobId}${replace(/\//, '', name)}-${shortid.generate()}` ); return pipe(newJobId, assoc('tasks', tasks))(jobTemplate); } function scheduleJobForNow(job: CronJob) { const ts = new Date(); return assoc('at', format(addSeconds(ts, 2), 'HH:mm:s'), job); } function invertTaskActions(tasks: Array<Task>) { const invert = act => { switch (act) { case 'on': return 'off'; case 'off': return 'on'; default: return act; } }; return map(t => assoc('act', invert(prop('act', t)), t), tasks); } export { buildCronjobWithTasks, scheduleJobForNow, invertTaskActions };
Change classNames from array to string
import Component from '@ember/component'; import { A } from '@ember/array'; import { computed } from '@ember/object'; export default Component.extend({ /** * Class names for the component * @type {Array.string} * @default */ classNames: 'tumblr-blog', /** * Route to link posts to * @type {string} * @default */ postsRoute: null, /** * Determines whether or not the blog can collapse its posts * @type {boolean} * @default */ collapsible: false, /** * Default all posts to collapsed * @type {boolean} * @default */ collapseByDefault: true, /** * Use date formatting * @type {boolean} * @default */ formatDates: true, /** * Display an error message instead of attempting to render posts when none are returned * @type {boolean} * @default */ showErrors: true, /** * Error message to display when no posts were found */ errorMessage: "We're sorry, we were unable to retrieve any posts. Please check back later!", /** * Configurable Sort Options * @type {Array.string} * @default */ sortBy: [], /** * Posts to be displayed * @type {Array.Tumblr-Post} * @default */ posts: A([]), /** * Sorted array of posts * @type {Array.Tumblr-Post} * @default */ sortedPosts: computed.sort('posts', 'sortBy') });
import Component from '@ember/component'; import { A } from '@ember/array'; import { computed } from '@ember/object'; export default Component.extend({ /** * Class names for the component * @type {Array.string} * @default */ classNames: ['tumblr-blog'], /** * Route to link posts to * @type {string} * @default */ postsRoute: null, /** * Determines whether or not the blog can collapse its posts * @type {boolean} * @default */ collapsible: false, /** * Default all posts to collapsed * @type {boolean} * @default */ collapseByDefault: true, /** * Use date formatting * @type {boolean} * @default */ formatDates: true, /** * Display an error message instead of attempting to render posts when none are returned * @type {boolean} * @default */ showErrors: true, /** * Error message to display when no posts were found */ errorMessage: "We're sorry, we were unable to retrieve any posts. Please check back later!", /** * Configurable Sort Options * @type {Array.string} * @default */ sortBy: [], /** * Posts to be displayed * @type {Array.Tumblr-Post} * @default */ posts: A([]), /** * Sorted array of posts * @type {Array.Tumblr-Post} * @default */ sortedPosts: computed.sort('posts', 'sortBy') });
Delete useless property (I do not clear why it was)
package org.bricolages.streaming; import lombok.Getter; import lombok.Setter; import org.bricolages.streaming.s3.ObjectMapper; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component @ConfigurationProperties(prefix = "bricolage") public class Config { @Getter private final EventQueue eventQueue = new EventQueue(); @Getter private final LogQueue logQueue = new LogQueue(); @Getter private List<ObjectMapper.Entry> mappings = new ArrayList<>(); @Setter static class EventQueue { String url; int visibilityTimeout; int maxNumberOfMessages; int waitTimeSeconds; } @Setter static class LogQueue { String url; } // preflight @Getter @Setter private String srcDs; @Getter @Setter private String destDs; }
package org.bricolages.streaming; import lombok.Getter; import lombok.Setter; import org.bricolages.streaming.preflight.domains.DomainDefaultValues; import org.bricolages.streaming.s3.ObjectMapper; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component @ConfigurationProperties(prefix = "bricolage") public class Config { @Getter private final EventQueue eventQueue = new EventQueue(); @Getter private final LogQueue logQueue = new LogQueue(); @Getter private List<ObjectMapper.Entry> mappings = new ArrayList<>(); @Setter static class EventQueue { String url; int visibilityTimeout; int maxNumberOfMessages; int waitTimeSeconds; } @Setter static class LogQueue { String url; } // preflight @Getter @Setter private String srcDs; @Getter @Setter private String destDs; @Getter @Setter private DomainDefaultValues defaults; }
Fix TableName tests for empty table name
<?php use Mdd\QueryBuilder\Queries\Parts; class TableNameTest extends PHPUnit_Framework_TestCase { /** * @dataProvider providerTestTableName */ public function testTableName($expected, $tableName, $alias) { $qb = new Parts\TableName($tableName, $alias); $this->assertSame($qb->toString(), $expected); } public function providerTestTableName() { return array( 'nominal' => array('poney AS p', 'poney', 'p'), 'alias is table name' => array('poney AS poney', 'poney', 'poney'), 'empty alias' => array('poney', 'poney', ''), 'null alias' => array('poney', 'poney', null), ); } /** * @dataProvider providerTestEmptyTableName * @expectedException \InvalidArgumentException */ public function testEmptyTableName($tableName) { $qb = new Parts\TableName($tableName); $qb->toString($tableName); } public function providerTestEmptyTableName() { return array( 'empty table name' => array(''), 'null table name' => array(null), ); } }
<?php use Mdd\QueryBuilder\Queries\Parts; class TableNameTest extends PHPUnit_Framework_TestCase { /** * @dataProvider providerTestTableName */ public function testTableName($expected, $tableName, $alias) { $qb = new Parts\TableName($tableName, $alias); $this->assertSame($qb->toString(), $expected); } public function providerTestTableName() { return array( 'nominal' => array('poney AS p', 'poney', 'p'), 'alias is table name' => array('poney AS poney', 'poney', 'poney'), 'empty alias' => array('poney', 'poney', ''), 'null alias' => array('poney', 'poney', null), ); } /** * @dataProvider providerTestEmptyTableName * @expectedException \InvalidArgumentException */ public function testEmptyTableName($tableName) { $qb = new Parts\From($tableName); $qb->toString($tableName); } public function providerTestEmptyTableName() { return array( 'empty table name' => array(''), 'null table name' => array(null), ); } }
Test the HttpRequestHelper by loading a google search URL instead of Yahoo. Yahoo recently changed something that broke this.
package edu.pdx.cs410J.web; import org.junit.Test; import java.io.IOException; import java.net.HttpURLConnection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Unit tests for the <code>HttpRequestHelper</code> class */ public class HttpRequestHelperTest { private HttpRequestHelper helper = new HttpRequestHelper(); @Test public void testGet() throws IOException { HttpRequestHelper.Response response = helper.get("http://www.google.com"); assertEquals(HttpURLConnection.HTTP_OK, response.getCode()); assertTrue(response.getContent().contains("Google")); } @Test public void testGetWithParameters() throws IOException { HttpRequestHelper.Response response = helper.get("https://www.google.com/search", "p", "Java"); assertEquals(HttpURLConnection.HTTP_OK, response.getCode()); assertTrue(response.getContent().contains("Java")); } }
package edu.pdx.cs410J.web; import org.junit.Test; import java.io.IOException; import java.net.HttpURLConnection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Unit tests for the <code>HttpRequestHelper</code> class */ public class HttpRequestHelperTest { private HttpRequestHelper helper = new HttpRequestHelper(); @Test public void testGet() throws IOException { HttpRequestHelper.Response response = helper.get("http://www.google.com"); assertEquals(HttpURLConnection.HTTP_OK, response.getCode()); assertTrue(response.getContent().contains("Google")); } @Test public void testGetWithParameters() throws IOException { HttpRequestHelper.Response response = helper.get("http://search.yahoo.com/search", "p", "Java"); assertEquals(HttpURLConnection.HTTP_OK, response.getCode()); assertTrue(response.getContent().contains("Java")); } }
Fix typo in 'terminal-notifier' instructions
package main import ( "fmt" "github.com/onsi/ginkgo/ginkgo/testsuite" "os" "os/exec" ) func verifyNotificationsAreAvailable() { _, err := exec.LookPath("terminal-notifier") if err != nil { fmt.Printf(`--notify requires terminal-notifier, which you don't seem to have installed. To remedy this: brew install terminal-notifier To learn more about terminal-notifier: https://github.com/alloy/terminal-notifier `) os.Exit(1) } } func sendSuiteCompletionNotification(suite *testsuite.TestSuite, suitePassed bool) { if suitePassed { sendNotification("Ginkgo [PASS]", fmt.Sprintf(`Test suite for "%s" passed.`, suite.PackageName)) } else { sendNotification("Ginkgo [FAIL]", fmt.Sprintf(`Test suite for "%s" failed.`, suite.PackageName)) } } func sendNotification(title string, subtitle string) { args := []string{"-title", title, "-subtitle", subtitle, "-group", "com.onsi.ginkgo"} terminal := os.Getenv("TERM_PROGRAM") if terminal == "iTerm.app" { args = append(args, "-activate", "com.googlecode.iterm2") } else if terminal == "Apple_Terminal" { args = append(args, "-activate", "com.apple.Terminal") } if notify { exec.Command("terminal-notifier", args...).Run() } }
package main import ( "fmt" "github.com/onsi/ginkgo/ginkgo/testsuite" "os" "os/exec" ) func verifyNotificationsAreAvailable() { _, err := exec.LookPath("terminal-notifier") if err != nil { fmt.Printf(`--notify requires terminal-notifier, which you don't seem to have installed. To remedy this: brew install terminal-notifer To learn more about terminal-notifier: https://github.com/alloy/terminal-notifier `) os.Exit(1) } } func sendSuiteCompletionNotification(suite *testsuite.TestSuite, suitePassed bool) { if suitePassed { sendNotification("Ginkgo [PASS]", fmt.Sprintf(`Test suite for "%s" passed.`, suite.PackageName)) } else { sendNotification("Ginkgo [FAIL]", fmt.Sprintf(`Test suite for "%s" failed.`, suite.PackageName)) } } func sendNotification(title string, subtitle string) { args := []string{"-title", title, "-subtitle", subtitle, "-group", "com.onsi.ginkgo"} terminal := os.Getenv("TERM_PROGRAM") if terminal == "iTerm.app" { args = append(args, "-activate", "com.googlecode.iterm2") } else if terminal == "Apple_Terminal" { args = append(args, "-activate", "com.apple.Terminal") } if notify { exec.Command("terminal-notifier", args...).Run() } }
Use system env for secret values
package config import ( "os" ) type Config struct { Secret string Host string Port int DB *DBConfig SlackApp *SlackAppConfig } type DBConfig struct { Dialect string Username string Password string Name string Charset string } type SlackAppConfig struct { ClientID string ClientSecret string TokenURL string } func GetConfig() *Config { DefaultHost := "localhost" DefaultPort := 8080 return &Config{ Secret: os.Getenv("API_SECRET_VALUE"), Host: DefaultHost, Port: DefaultPort, DB: &DBConfig{ Dialect: "mysql", Username: os.Getenv("DB_USERNAME"), Password: os.Getenv("DB_PASSWORD"), Name: "meetup", Charset: "utf8", }, SlackApp: &SlackAppConfig{ ClientID: os.Getenv("SLACK_CLIENT_ID"), ClientSecret: os.Getenv("SLACK_CLIENT_SECRET"), TokenURL: "https://slack.com/api/oauth.access", }, } }
package config import "fmt" type Config struct { Secret string Host string Port int DB *DBConfig SlackApp *SlackAppConfig } type DBConfig struct { Dialect string Username string Password string Name string Charset string } type SlackAppConfig struct { ClientId string ClientSecret string RedirectURL string } func GetConfig() *Config { DefaultHost := "localhost" DefaultPort := 8080 return &Config{ Secret: "...", Host: DefaultHost, Port: DefaultPort, DB: &DBConfig{ Dialect: "mysql", Username: "...", Password: "...", Name: "meetup", Charset: "utf8", }, SlackApp: &SlackAppConfig{ ClientId: "...", ClientSecret: "...", RedirectURL: fmt.Sprintf("http://%s:%d/auth", DefaultHost, DefaultPort), }, } }
Add "SNAPDIR" and simple vim modeline
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, 'SNAPDIR=' + self.builddir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) # vim:set ts=4 noet:
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ])
FIX Return array instead of object in Query Context handlers
/* * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of iotagent-thinking-things * * iotagent-thinking-things is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * iotagent-thinking-things is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with iotagent-thinking-things. * If not, seehttp://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with::[iot_support@tid.es] */ 'use strict'; var responseGenerator = require('./responseGenerator'); function updateContextHandler(id, type, attributes, callback) { responseGenerator.continueSynchOperation(id, attributes); callback(null, { type: type, isPattern: false, id: id, attributes: attributes }); } function queryContextHandler(id, type, attributes, callback) { callback(null, []); } exports.updateContextHandler = updateContextHandler; exports.queryContextHandler = queryContextHandler;
/* * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of iotagent-thinking-things * * iotagent-thinking-things is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * iotagent-thinking-things is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with iotagent-thinking-things. * If not, seehttp://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with::[iot_support@tid.es] */ 'use strict'; var responseGenerator = require('./responseGenerator'); function updateContextHandler(id, type, attributes, callback) { responseGenerator.continueSynchOperation(id, attributes); callback(null, { type: type, isPattern: false, id: id, attributes: attributes }); } function queryContextHandler(id, type, attributes, callback) { callback(null, {}); } exports.updateContextHandler = updateContextHandler; exports.queryContextHandler = queryContextHandler;
Fix a bad, silly bug where selectors were not being added to matchers in the Persist AOP module
package com.google.sitebricks.persist; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.matcher.Matcher; import java.lang.reflect.AnnotatedElement; import static com.google.inject.matcher.Matchers.annotatedWith; import static com.google.inject.matcher.Matchers.any; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public final class PersistAopModule extends AbstractModule { private final AbstractPersistenceModule module; public PersistAopModule(AbstractPersistenceModule module) { this.module = module; } @Override protected void configure() { Key<Persister> persisterKey = module.selectorKey(Persister.class); WorkInterceptor workInterceptor = new WorkInterceptor(persisterKey); TransactionInterceptor transactionInterceptor = new TransactionInterceptor(persisterKey); requestInjection(workInterceptor); requestInjection(transactionInterceptor); Matcher<AnnotatedElement> workMatcher = annotatedWith(Work.class); Matcher<AnnotatedElement> txnMatcher = annotatedWith(Transactional.class); // Visible persistence APIs. if (module.selector != null) { workMatcher = workMatcher.and(annotatedWith(module.selector)); txnMatcher = txnMatcher.and(annotatedWith(module.selector)); } bindInterceptor(any(), workMatcher, workInterceptor); bindInterceptor(any(), txnMatcher, transactionInterceptor); } }
package com.google.sitebricks.persist; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.matcher.Matcher; import java.lang.reflect.AnnotatedElement; import static com.google.inject.matcher.Matchers.annotatedWith; import static com.google.inject.matcher.Matchers.any; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public final class PersistAopModule extends AbstractModule { private final AbstractPersistenceModule module; public PersistAopModule(AbstractPersistenceModule module) { this.module = module; } @Override protected void configure() { Key<Persister> persisterKey = module.selectorKey(Persister.class); WorkInterceptor workInterceptor = new WorkInterceptor(persisterKey); TransactionInterceptor transactionInterceptor = new TransactionInterceptor(persisterKey); requestInjection(workInterceptor); requestInjection(transactionInterceptor); Matcher<AnnotatedElement> workMatcher = annotatedWith(Work.class); Matcher<AnnotatedElement> txnMatcher = annotatedWith(Transactional.class); // Visible persistence APIs. if (module.selector != null) { workMatcher.and(annotatedWith(module.selector)); txnMatcher.and(annotatedWith(module.selector)); } bindInterceptor(any(), workMatcher, workInterceptor); bindInterceptor(any(), txnMatcher, transactionInterceptor); } }
Fix NEI addon crashing servers
package net.mcft.copy.betterstorage.addon.nei; import net.mcft.copy.betterstorage.addon.Addon; import net.mcft.copy.betterstorage.client.gui.GuiCraftingStation; import net.mcft.copy.betterstorage.content.BetterStorageTiles; import net.mcft.copy.betterstorage.misc.Constants; import net.minecraft.item.ItemStack; import codechicken.nei.api.API; import codechicken.nei.recipe.DefaultOverlayHandler; import cpw.mods.fml.common.FMLCommonHandler; public class NEIAddon extends Addon { public NEIAddon() { super("NotEnoughItems"); } @Override public void postInitialize() { if (FMLCommonHandler.instance().getEffectiveSide().isServer()) return; NEIRecipeHandler handler = new NEIRecipeHandler(); API.registerRecipeHandler(handler); API.registerUsageHandler(handler); API.registerGuiOverlay(GuiCraftingStation.class, Constants.modId + ".craftingStation"); API.registerGuiOverlayHandler(GuiCraftingStation.class, new DefaultOverlayHandler(), Constants.modId + ".craftingStation"); API.hideItem(new ItemStack(BetterStorageTiles.lockableDoor)); } }
package net.mcft.copy.betterstorage.addon.nei; import net.mcft.copy.betterstorage.addon.Addon; import net.mcft.copy.betterstorage.client.gui.GuiCraftingStation; import net.mcft.copy.betterstorage.content.BetterStorageTiles; import net.mcft.copy.betterstorage.misc.Constants; import net.minecraft.item.ItemStack; import codechicken.nei.api.API; import codechicken.nei.recipe.DefaultOverlayHandler; public class NEIAddon extends Addon { public NEIAddon() { super("NotEnoughItems"); } @Override public void postInitialize() { NEIRecipeHandler handler = new NEIRecipeHandler(); API.registerRecipeHandler(handler); API.registerUsageHandler(handler); API.registerGuiOverlay(GuiCraftingStation.class, Constants.modId + ".craftingStation"); API.registerGuiOverlayHandler(GuiCraftingStation.class, new DefaultOverlayHandler(), Constants.modId + ".craftingStation"); API.hideItem(new ItemStack(BetterStorageTiles.lockableDoor)); } }
Switch TicketAdminPage to new DataTable API
<?php ini_set('display_errors', 1); error_reporting(E_ALL); require_once('class.TicketAdminPage.php'); $page = new TicketAdminPage('Burning Flipside - Tickets'); $page->add_js_from_src('js/index.js'); $data_set = DataSetFactory::get_data_set('tickets'); $data_table = $data_set['Problems']; $settings = \Tickets\DB\TicketSystemSettings::getInstance(); $year = $settings['year']; $page->body .= ' <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Dashboard</h1> </div> </div> <div class="row">'; $page->add_card('fa-file', '<div id="requestCount">?</div>', 'Ticket Requests', 'requests.php'); $page->add_card('fa-tag', '<div id="requestedTicketCount">?</div>', 'Requested Tickets', 'request_tickets.php', $page::CARD_GREEN); $page->add_card('fa-fire', $data_table->count(new \Data\Filter('year eq '.$year)), 'Problem Requests', 'problems.php', $page::CARD_RED); $page->add_card('fa-usd', '<div id="soldTicketCount">?</div>', 'Sold Tickets', 'sold_tickets.php', $page::CARD_YELLOW); $page->body.='</div>'; $page->print_page(); // vim: set tabstop=4 shiftwidth=4 expandtab: ?>
<?php ini_set('display_errors', 1); error_reporting(E_ALL); require_once('class.TicketAdminPage.php'); require_once('class.FlipsideTicketDB.php'); $page = new TicketAdminPage('Burning Flipside - Tickets'); $page->add_js_from_src('js/index.js'); $db = new FlipsideTicketDB(); $page->body .= ' <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Dashboard</h1> </div> </div> <div class="row">'; $page->add_card('fa-file', '<div id="requestCount">?</div>', 'Ticket Requests', 'requests.php'); $page->add_card('fa-tag', '<div id="requestedTicketCount">?</div>', 'Requested Tickets', 'request_tickets.php', $page::CARD_GREEN); $page->add_card('fa-fire', $db->getProblemRequestCount(), 'Problem Requests', 'problems.php', $page::CARD_RED); $page->add_card('fa-usd', '<div id="soldTicketCount">?</div>', 'Sold Tickets', 'sold_tickets.php', $page::CARD_YELLOW); $page->body.='</div>'; $page->print_page(); // vim: set tabstop=4 shiftwidth=4 expandtab: ?>
Fix for when matching index is 0.
"use strict"; var immutable = require("seamless-immutable"); function concatArrayMerger(current, other) { if (!(current instanceof Array) || !(other instanceof Array)) return; return current.concat(other); } function updatingByIdArrayMerger(current, other, config) { if (!(current instanceof Array) || !(other instanceof Array)) return; if (current.length === 0 || other.length === 0) return; var identifier = config.mergerObjectIdentifier; if (current[0] === null || !(typeof current[0] === "object") || !current[0][identifier]) return; if (other[0] === null || !(typeof other[0] === "object") || !other[0][identifier]) return; var currentMap = {}; for (var i = 0; i < current.length; i++) { currentMap[current[i][identifier]] = i; } var resultList = current.asMutable(); for (var j = 0; j < other.length; j++) { var matchingCurrentIndex = currentMap[other[j][identifier]]; if (matchingCurrentIndex === undefined) { resultList.push(other[j]); } else { resultList[matchingCurrentIndex] = resultList[matchingCurrentIndex].merge(other[j], config); } } return immutable(resultList); } // Export the library var immutableMergers = { concatArrayMerger: concatArrayMerger, updatingByIdArrayMerger: updatingByIdArrayMerger }; Object.freeze(immutableMergers); module.exports = immutableMergers;
"use strict"; var immutable = require("seamless-immutable"); function concatArrayMerger(current, other) { if (!(current instanceof Array) || !(other instanceof Array)) return; return current.concat(other); } function updatingArrayMerger(current, other, config) { if (!(current instanceof Array) || !(other instanceof Array)) return; if (current.length === 0 || other.length === 0) return; var identifier = config.mergerObjectIdentifier; if (current[0] === null || !(typeof current[0] === "object") || !current[0][identifier]) return; if (other[0] === null || !(typeof other[0] === "object") || !other[0][identifier]) return; var currentMap = {}; for (var i = 0; i < current.length; i++) { currentMap[current[i][identifier]] = i; } var resultList = current.asMutable(); for (var j = 0; j < other.length; j++) { var matchingCurrentIndex = currentMap[other[j][identifier]]; if (!matchingCurrentIndex) { resultList.push(other[j]); } else { resultList[matchingCurrentIndex] = resultList[matchingCurrentIndex].merge(other[j], config); } } return immutable(resultList); } // Export the library var immutableMergers = { concatArrayMerger: concatArrayMerger, updatingArrayMerger: updatingArrayMerger }; Object.freeze(immutableMergers); module.exports = immutableMergers;
Fix issue with selecting text input on iOS
angular.module('app') .directive('selectOnClick', function () { return { restrict: 'A', link: function (scope, element) { var focusedElement; element.on('click', function () { if (focusedElement != this) { this.setSelectionRange(0, this.value.length); focusedElement = this; } }); element.on('blur', function () { focusedElement = null; }); } }; })
angular.module('app') .directive('selectOnClick', function () { return { restrict: 'A', link: function (scope, element) { var focusedElement; element.on('click', function () { if (focusedElement != this) { this.select(); focusedElement = this; } }); element.on('blur', function () { focusedElement = null; }); } }; })
Include six as a requirement.
# -*- coding: utf-8 -*- from setuptools import setup setup( name='django-post_office', version='1.1.1', author='Selwin Ong', author_email='selwin.ong@gmail.com', packages=['post_office'], url='https://github.com/ui/django-post_office', license='MIT', description='A Django app to monitor and send mail asynchronously, complete with template support.', long_description=open('README.rst').read(), zip_safe=False, include_package_data=True, package_data={'': ['README.rst']}, install_requires=['django>=1.4', 'jsonfield', 'six', ], 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.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
# -*- coding: utf-8 -*- from setuptools import setup setup( name='django-post_office', version='1.1.1', author='Selwin Ong', author_email='selwin.ong@gmail.com', packages=['post_office'], url='https://github.com/ui/django-post_office', license='MIT', description='A Django app to monitor and send mail asynchronously, complete with template support.', long_description=open('README.rst').read(), zip_safe=False, include_package_data=True, package_data={'': ['README.rst']}, install_requires=['django>=1.4', 'jsonfield'], 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.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Fix backward compatiblity for MDTrajTopology
def missing_openmm(*args, **kwargs): raise RuntimeError("Install OpenMM to use this feature") try: import simtk.openmm import simtk.openmm.app except ImportError: HAS_OPENMM = False Engine = missing_openmm empty_snapshot_from_openmm_topology = missing_openmm snapshot_from_pdb = missing_openmm snapshot_from_testsystem = missing_openmm to_openmm_topology = missing_openmm trajectory_from_mdtraj = missing_openmm trajectory_to_mdtraj = missing_openmm Snapshot = missing_openmm MDSnapshot = missing_openmm else: from .engine import OpenMMEngine as Engine from .tools import ( empty_snapshot_from_openmm_topology, snapshot_from_pdb, snapshot_from_testsystem, to_openmm_topology, trajectory_from_mdtraj, trajectory_to_mdtraj ) from . import features from .snapshot import Snapshot, MDSnapshot from . import topology from openpathsampling.engines import NoEngine, SnapshotDescriptor
def missing_openmm(*args, **kwargs): raise RuntimeError("Install OpenMM to use this feature") try: import simtk.openmm import simtk.openmm.app except ImportError: HAS_OPENMM = False Engine = missing_openmm empty_snapshot_from_openmm_topology = missing_openmm snapshot_from_pdb = missing_openmm snapshot_from_testsystem = missing_openmm to_openmm_topology = missing_openmm trajectory_from_mdtraj = missing_openmm trajectory_to_mdtraj = missing_openmm Snapshot = missing_openmm MDSnapshot = missing_openmm else: from .engine import OpenMMEngine as Engine from .tools import ( empty_snapshot_from_openmm_topology, snapshot_from_pdb, snapshot_from_testsystem, to_openmm_topology, trajectory_from_mdtraj, trajectory_to_mdtraj ) from . import features from .snapshot import Snapshot, MDSnapshot from openpathsampling.engines import NoEngine, SnapshotDescriptor
Enable colorization and pretty printing be default
'use strict'; const winston = require('winston'); // Setup winston default instance const LOGGER_LEVEL = process.env.LOGGER_LEVEL || 'info'; const LOGGER_TIMESTAMP = !(process.env.LOGGER_TIMESTAMP === 'false'); const LOGGER_COLORIZE = !(process.env.LOGGER_COLORIZE === 'false'); const LOGGER_PRETTY_PRINT = !(process.env.LOGGER_PRETTY_PRINT === 'false'); winston.configure({ transports: [ new winston.transports.Console({ prettyPrint: LOGGER_PRETTY_PRINT, colorize: LOGGER_COLORIZE, level: LOGGER_LEVEL, timestamp: LOGGER_TIMESTAMP, }), ], exceptionHandlers: [ new winston.transports.Console({ prettyPrint: LOGGER_PRETTY_PRINT, colorize: LOGGER_COLORIZE, }), ], });
'use strict'; const winston = require('winston'); // Setup winston default instance const LOGGER_LEVEL = process.env.LOGGER_LEVEL || 'info'; const LOGGER_TIMESTAMP = !(process.env.LOGGER_TIMESTAMP === 'false'); const LOGGER_COLORIZE = process.env.LOGGER_COLORIZE === 'true' const LOGGER_PRETTY_PRINT = process.env.LOGGER_PRETTY_PRINT === 'true'; winston.configure({ transports: [ new winston.transports.Console({ prettyPrint: LOGGER_PRETTY_PRINT, colorize: LOGGER_COLORIZE, level: LOGGER_LEVEL, timestamp: LOGGER_TIMESTAMP, }), ], exceptionHandlers: [ new winston.transports.Console({ prettyPrint: LOGGER_PRETTY_PRINT, colorize: LOGGER_COLORIZE, }), ], });
Fix typo in variable names
import React from 'react'; import PropTypes from 'prop-types'; import styles from './teamCard.css'; const TeamCard = ({ name, role, slackUsername, email, isBoard, description, imageSrc }) => ( <div className={styles.teamCard}> {imageSrc && (<img src={imageSrc} alt={`Headshot of ${name}`} />)} <h6 className={styles.name}>{name}</h6> <i className={styles.role}>{role}</i> <hr className={styles.hr} /> {!isBoard && ( <span className={styles.detail}> <span className={styles.slack}> <text>{slackUsername}</text> </span> <span className={styles.email}> <text>{email}</text> </span> </span> )} {isBoard && description && ( <span className={styles.descriptionText}> <text>{description}</text> </span> )} </div> ); TeamCard.propTypes = { name: PropTypes.string.isRequired, role: PropTypes.string.isRequired, slackUsername: PropTypes.string, email: PropTypes.string, isBoard: PropTypes.bool, imageSrc: PropTypes.string, description: PropTypes.string, }; TeamCard.defaultProps = { description: null, email: '', isBoard: true, imageSrc: '', slackUsername: '', }; export default TeamCard;
import React from 'react'; import PropTypes from 'prop-types'; import styles from './teamCard.css'; const TeamCard = ({ name, role, slackUsername, email, isBoard, description, imageSrc }) => ( <div className={styles.teamCard}> {imageSrc && (<img src={imageSrc} alt={`Headshot of ${name}`} />)} <h6 className={styles.name}>{name}</h6> <i className={styles.role}>{role}</i> <hr className={styles.hr} /> {!isBoard && ( <span className={styles.detail}> <span className={styles.slackUsername}> <text>{slack}</text> </span> <span className={styles.email}> <text>{email}</text> </span> </span> )} {isBoard && description && ( <span className={styles.descriptionText}> <text>{description}</text> </span> )} </div> ); TeamCard.propTypes = { name: PropTypes.string.isRequired, role: PropTypes.string.isRequired, slackUsername: PropTypes.string, email: PropTypes.string, isBoard: PropTypes.bool, imageSrc: PropTypes.string, description: PropTypes.string, }; TeamCard.defaultProps = { description: null, email: '', isBoard: true, imageSrc: '', slackUsername: '', }; export default TeamCard;
Clean up the make release script
var childProcess = require('child_process'); var fs = require('fs-extra'); var glob = require('glob'); var path = require('path'); var sortPackageJson = require('sort-package-json'); // Run a production build with Typescript source maps. childProcess.execSync('npm run build:prod', {stdio:[0,1,2]}); // Update the package.app.json file. var data = require('./package.json'); data['scripts'] = { 'build': 'webpack' }; data['jupyterlab']['outputDir'] = '..'; text = JSON.stringify(sortPackageJson(data), null, 2) + '\n'; fs.writeFileSync('./package.app.json', text); // Update our app index file. fs.copySync('./index.js', './index.app.js'); // Add the release metadata. var release_data = { version: data.jupyterlab.version }; text = JSON.stringify(release_data, null, 2) + '\n'; fs.writeFileSync('./build/release_data.json', text);
var childProcess = require('child_process'); var fs = require('fs-extra'); var glob = require('glob'); var path = require('path'); var sortPackageJson = require('sort-package-json'); // Update the core. require('./update-core'); // Update the package.app.json file. var data = require('./package.json'); data['scripts']['build'] = 'webpack' data['jupyterlab']['outputDir'] = '..'; text = JSON.stringify(sortPackageJson(data), null, 2) + '\n'; fs.writeFileSync('./package.app.json', text); // Update our app index file. fs.copySync('./index.js', './index.app.js') // Run a standard build with Typescript source maps working. childProcess.execSync('npm run build:prod'); // Add the release metadata. var release_data = { version: version }; text = JSON.stringify(release_data, null, 2) + '\n'; fs.writeFileSync('./build/release_data.json', text);
Fix build to test goci
package stl import ( "fmt" "io" ) // Write writes the triangle mesh to the writer using ASCII STL codec. func Write(w io.Writer, t []Triangle) error { var err error printf := func(format string, a ...interface{}) { if err != nil { return } _, err = fmt.Fprintf(w, format, a...) } printf("solid object\n") for _, tt := range t { if err != nil { return err } printf("facet normal %f %f %f\n", tt.N[0], tt.N[1], tt.N[2]) printf(" outer loop\n") for _, v := range tt.V { printf(" vertex %f %f %f\n", v[0], v[1], v[2]) } printf(" endloop\n") printf("endfacet\n") } printf("endsolid object\n") return nil }
package stl import ( "fmt" "io" ) // Write writes the triangle mesh to the writer using ASCII STL codec. zfunc Write(w io.Writer, t []Triangle) error { var err error printf := func(format string, a ...interface{}) { if err != nil { return } _, err = fmt.Fprintf(w, format, a...) } printf("solid object\n") for _, tt := range t { if err != nil { return err } printf("facet normal %f %f %f\n", tt.N[0], tt.N[1], tt.N[2]) printf(" outer loop\n") for _, v := range tt.V { printf(" vertex %f %f %f\n", v[0], v[1], v[2]) } printf(" endloop\n") printf("endfacet\n") } printf("endsolid object\n") return nil }
Add support for RubyNext and RubyExperimental
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Contributors: Francis Gulotta, Josh Hagins # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the Rubocop plugin class.""" from SublimeLinter.lint import RubyLinter class Rubocop(RubyLinter): """Provides an interface to rubocop.""" syntax = ('ruby', 'ruby on rails', 'rspec', 'betterruby', 'ruby experimental') cmd = 'ruby -S rubocop --format emacs' version_args = '-S rubocop --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.15.0' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(:?(?P<warning>[RCW])|(?P<error>[EF])): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', '.rubocop.yml')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Contributors: Francis Gulotta, Josh Hagins # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the Rubocop plugin class.""" from SublimeLinter.lint import RubyLinter class Rubocop(RubyLinter): """Provides an interface to rubocop.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby -S rubocop --format emacs' version_args = '-S rubocop --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.15.0' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(:?(?P<warning>[RCW])|(?P<error>[EF])): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', '.rubocop.yml')
Add meted only if exist
// @flow const extendBy = (object: Object, { metadata } : { metadata : any }) => { if (metadata) return { ...object, metadata } return object } const promiseBindMiddleware = ( { dispatch } : { dispatch : Function }, ) => (next: Function) => (action: Object) => { if (action && action.promise && typeof action.promise === 'function') { const { type, metadata, promise, promiseArg } = action dispatch(extendBy({ type: `${type}_START`, }, { metadata })) return promise(...(Array.isArray(promiseArg) ? promiseArg : [promiseArg])) .then((data) => { dispatch(extendBy({ type: `${type}_SUCCESS`, payload: data, }, { metadata })) return data }, (ex) => { dispatch(extendBy({ type: `${type}_ERROR`, payload: ex, }, { metadata })) // TODO change to throw an error return ex }) } return next(action) } export default promiseBindMiddleware
// @flow const promiseBindMiddleware = ( { dispatch } : { dispatch : Function }, ) => (next: Function) => (action: Object) => { if (action && action.promise && typeof action.promise === 'function') { const { type, metadata, promise, promiseArg } = action dispatch({ type: `${type}_START`, metadata, }) return promise(...(Array.isArray(promiseArg) ? promiseArg : [promiseArg])) .then((data) => { dispatch({ type: `${type}_SUCCESS`, payload: data, metadata, }) return data }, (ex) => { dispatch({ type: `${type}_ERROR`, payload: ex, metadata, }) return ex }) } return next(action) } export default promiseBindMiddleware
Switch to proper api for reading from streams
import querystring from 'querystring' export default class FormData { constructor(req) { this.req = req this.parsed = false this.data = {} } async get(key) { let data = await this.parse() return data[key] } async parse() { if (this.parsed) { return this.data } return new Promise((resolve, reject) => { let body = '' this.req.setEncoding('utf8') this.req.on('readable', () => { let buf = this.req.read() if (buf === null) { this.data = querystring.parse(body) this.parsed = true resolve(this.data) } else { body += buf } }) }) } }
import querystring from 'querystring' export default class FormData { constructor(req) { this.req = req this.parsed = false this.data = {} } async get(key) { let data = await this.parse() return data[key] } async parse() { if (this.parsed) { return this.data } return new Promise((resolve, reject) => { let body = '' this.req.setEncoding('utf8') this.req.on('data', (chunk) => { body += chunk }) this.req.on('end', () => { this.data = querystring.parse(body) this.parsed = true resolve(this.data) }) }) } }
Fix grammar in login error message
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) attrs['user'] = user return attrs else: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password"') raise serializers.ValidationError(msg)
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) attrs['user'] = user return attrs else: msg = _('Unable to login with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password"') raise serializers.ValidationError(msg)
Throw error if auth plugin wasn't registered, first
import setupMutations from './mutations' import setupActions from './actions' export default function setupAuthModule (store, options) { if (!options.auth) { return () => {} } return feathers => { if (!feathers.passport) { throw new Error('You must register the feathers-authentication-client plugin before Feathers-Vuex') } const { auth } = options const { name } = auth const state = { accessToken: undefined, // The JWT payload: undefined, // The JWT payload isPending: false, isError: false, error: undefined } // If a userService string was passed, add a user attribute if (auth.userService) { state.user = undefined } const combinedState = Object.assign(state, auth.state) const mutations = setupMutations(feathers, options) const actions = setupActions(feathers, options) store.registerModule(name, { namespaced: true, state: combinedState, mutations, actions }) } }
import setupMutations from './mutations' import setupActions from './actions' export default function setupAuthModule (store, options) { if (!options.auth) { return () => {} } return feathers => { const { auth } = options const { name } = auth const state = { accessToken: undefined, // The JWT payload: undefined, // The JWT payload isPending: false, isError: false, error: undefined } // If a userService string was passed, add a user attribute if (auth.userService) { state.user = undefined } const combinedState = Object.assign(state, auth.state) const mutations = setupMutations(feathers, options) const actions = setupActions(feathers, options) store.registerModule(name, { namespaced: true, state: combinedState, mutations, actions }) } }
Apply CodeMirror to output textarea.
var socket = io.connect('/'); var waitMilliSec = 1000; var oldJavaCode = ''; var oldClassName = ''; var outputBcCM; socket.on('byte_code', function(data) { outputBcCM.setValue(data.code); }); socket.on('wrong', function(data) { outputBcCM.setValue(data.err); }); $(function() { var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), { mode: 'clike', lineNumbers: true }); outputBcCM = CodeMirror.fromTextArea(document.getElementById('output_bc'), { mode: 'clike', lineNumbers: true }); var idleIntervalId = setInterval(function() { newJavaCode = inputJavaCM.getValue(); newClassName = $('#class_name').val(); checkDiff(newJavaCode, newClassName); } , waitMilliSec); function checkDiff(newJavaCode, newClassName) { if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) { socket.emit('code_sent', { code: newJavaCode, className: newClassName }); oldJavaCode = newJavaCode; oldClassName = newClassName; } } });
var socket = io.connect('/'); var waitMilliSec = 1000; var oldJavaCode = ''; var oldClassName = ''; socket.on('byte_code', function(data) { $('#output_bc').val(data.code); }); socket.on('wrong', function(data) { $('#output_bc').val(data.err); }); $(function() { var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), { mode: 'clike', lineNumbers: true }); var idleIntervalId = setInterval(function() { newJavaCode = inputJavaCM.getValue(); newClassName = $('#class_name').val(); checkDiff(newJavaCode, newClassName); } , waitMilliSec); function checkDiff(newJavaCode, newClassName) { if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) { socket.emit('code_sent', { code: newJavaCode, className: newClassName }); oldJavaCode = newJavaCode; oldClassName = newClassName; } } });
Use stats.select() instead of re-implementing all of this. This is preparation for being able to squash statistics in different ways. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6563 e27351fd-9f3e-4f54-a53b-843176b1656c
import sys, pickle from benchlib import select def main(): if len(sys.argv) < 5: print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],) else: stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5]) if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) else: getattr(stat, sys.argv[5])(samples)
import sys, pickle def main(): statistics = pickle.load(file(sys.argv[1])) if len(sys.argv) == 2: print 'Available benchmarks' print '\t' + '\n\t'.join(statistics.keys()) return statistics = statistics[sys.argv[2]] if len(sys.argv) == 3: print 'Available parameters' print '\t' + '\n\t'.join(map(str, statistics.keys())) return statistics = statistics[int(sys.argv[3])] if len(sys.argv) == 4: print 'Available statistics' print '\t' + '\n\t'.join([s.name for s in statistics]) return for stat in statistics: if stat.name == sys.argv[4]: samples = statistics[stat] break if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) return getattr(stat, sys.argv[5])(samples)
Refactor aws uploader to make bucket name dynamic
const AWS = require("aws-sdk"); const uuidv4 = require("uuid/v4"); const logError = require("./log-error.js"); AWS.config.update({ region: process.env.AWS_REGION }); function uploadToAWS(base64String) { const newFileName = uuidv4(); const s3 = new AWS.S3({ apiVersion: "2006-03-01" }); const base64Data = Buffer.from( base64String.split(";")[1].split(",")[1], "base64" ); const contentType = base64String.split(":")[1].split(";")[0]; const uploadParams = { Bucket: `${process.env.AWS_S3_BUCKET}`, Key: newFileName, Body: base64Data, ContentEncoding: "base64", ContentType: contentType, ACL: "public-read", }; s3.upload(uploadParams, (err, data) => { if (err) { logError(err); } }); return `${process.env.AWS_UPLOADS_URL}${newFileName}`; } module.exports = uploadToAWS;
const AWS = require("aws-sdk"); const uuidv4 = require("uuid/v4"); const logError = require("./log-error.js"); AWS.config.update({ region: process.env.AWS_REGION }); function uploadToAWS(base64String) { const newFileName = uuidv4(); const s3 = new AWS.S3({ apiVersion: "2006-03-01" }); const base64Data = Buffer.from( base64String.split(";")[1].split(",")[1], "base64" ); const contentType = base64String.split(":")[1].split(";")[0]; const uploadParams = { Bucket: "uploads.participedia.xyz", Key: newFileName, Body: base64Data, ContentEncoding: "base64", ContentType: contentType, ACL: "public-read", }; s3.upload(uploadParams, (err, data) => { if (err) { logError(err); } }); return `${process.env.AWS_UPLOADS_URL}${newFileName}`; } module.exports = uploadToAWS;
Throw an error if you don't pass a secret to verifyToken hook
import jwt from 'jsonwebtoken'; import errors from 'feathers-errors'; /** * Verifies that a JWT token is valid * * @param {Object} options - An options object * @param {String} options.secret - The JWT secret */ export default function(options = {}){ const secret = options.secret; if (!secret) { console.log('no secret', options); throw new Error('You need to pass `options.secret` to the verifyToken() hook.'); } return function(hook) { const token = hook.params.token; if (!token) { return Promise.resolve(hook); } return new Promise(function(resolve, reject){ jwt.verify(token, secret, options, function (error, payload) { if (error) { // Return a 401 if the token has expired or is invalid. return reject(new errors.NotAuthenticated(error)); } // Attach our decoded token payload to the params hook.params.payload = payload; resolve(hook); }); }); }; }
import jwt from 'jsonwebtoken'; import errors from 'feathers-errors'; /** * Verifies that a JWT token is valid * * @param {Object} options - An options object * @param {String} options.secret - The JWT secret */ export default function(options = {}){ const secret = options.secret; return function(hook) { const token = hook.params.token; if (!token) { return Promise.resolve(hook); } return new Promise(function(resolve, reject){ jwt.verify(token, secret, options, function (error, payload) { if (error) { // Return a 401 if the token has expired or is invalid. return reject(new errors.NotAuthenticated(error)); } // Attach our decoded token payload to the params hook.params.payload = payload; resolve(hook); }); }); }; }
Check if mMap is null before running demo. Necessary to show the "Play services is out of date" button.
package com.google.maps.android.utils.demo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; public abstract class BaseDemoActivity extends FragmentActivity { private GoogleMap mMap; protected int getLayoutId() { return R.layout.map; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); if (getMap() != null) { startDemo(); } } private void setUpMapIfNeeded() { if (mMap != null) { return; } mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); } /** * Run the demo-specific code. */ protected abstract void startDemo(); protected GoogleMap getMap() { setUpMapIfNeeded(); return mMap; } }
package com.google.maps.android.utils.demo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; public abstract class BaseDemoActivity extends FragmentActivity { private GoogleMap mMap; protected int getLayoutId() { return R.layout.map; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); startDemo(); } private void setUpMapIfNeeded() { if (mMap != null) { return; } mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); } /** * Run the demo-specific code. */ protected abstract void startDemo(); protected GoogleMap getMap() { setUpMapIfNeeded(); return mMap; } }
Return -1 when tests fail
#!/usr/bin/env python """ This is the front end to the pcapfile test SUITE. """ import unittest import sys from pcapfile.test.linklayer_test import TestCase as LinklayerTest from pcapfile.test.savefile_test import TestCase as SavefileTest from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTest from pcapfile.test.protocols_linklayer_wifi import TestCase as WifiTest from pcapfile.test.protocols_network_ip import TestCase as IpTest from pcapfile.test.protocols_transport_tcp import TestCase as TcpTest if __name__ == '__main__': TEST_CLASSES = [SavefileTest, LinklayerTest, EthernetTest, WifiTest, IpTest, TcpTest] SUITE = unittest.TestSuite() LOADER = unittest.TestLoader() for test_class in TEST_CLASSES: SUITE.addTests(LOADER.loadTestsFromTestCase(test_class)) result = unittest.TextTestRunner(verbosity=2).run(SUITE) if not result.wasSuccessful(): sys.exit(1)
#!/usr/bin/env python """ This is the front end to the pcapfile test SUITE. """ import unittest from pcapfile.test.linklayer_test import TestCase as LinklayerTest from pcapfile.test.savefile_test import TestCase as SavefileTest from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTest from pcapfile.test.protocols_linklayer_wifi import TestCase as WifiTest from pcapfile.test.protocols_network_ip import TestCase as IpTest from pcapfile.test.protocols_transport_tcp import TestCase as TcpTest if __name__ == '__main__': TEST_CLASSES = [SavefileTest, LinklayerTest, EthernetTest, WifiTest, IpTest, TcpTest] SUITE = unittest.TestSuite() LOADER = unittest.TestLoader() for test_class in TEST_CLASSES: SUITE.addTests(LOADER.loadTestsFromTestCase(test_class)) unittest.TextTestRunner(verbosity=2).run(SUITE)
Remove failing example from entry file for now
#!/usr/bin/env node 'use strict'; // Load base requirements const program = require('commander'), dotenv = require('dotenv').config(), path = require('path'); // Load our libraries const utils = require('./libs/utils'), logger = require('./libs/log'), i18n = require('./libs/locale'), queue = require('./libs/queue'), task = require('./libs/task'); // Create new task task.create({ "name": "Two Brothers, One Impala", "directory": path.resolve('test/data/task/metadata'), "type": "show", "seasons": [1, 2], "options": { "preset": "slow", "video" : { "bitrate": 3500, "quality": 0 } } }).then((data) => { console.log(data); console.log(data.jobs); }).catch((err) => { console.log(err); });
#!/usr/bin/env node 'use strict'; // Load base requirements const program = require('commander'), dotenv = require('dotenv').config(), path = require('path'); // Load our libraries const utils = require('./libs/utils'), logger = require('./libs/log'), i18n = require('./libs/locale'), queue = require('./libs/queue'), task = require('./libs/task'); // Create new task task.create({ "name": "Two Brothers, One Impala", "directory": path.resolve('test/data/task/metadata'), "type": "show", "seasons": [1, 2], "options": { "preset": "slow", "video" : { "bitrate": 3500, "quality": 0 } } }).then((data) => { console.log('Resolved 1 -'); console.log(data); }).catch((err) => { console.log('Error 1 -'); console.log(err); }); // Create a second task instance task.create({ "name": "Less Drama, More Zombies", "directory": "Less Drama, More Zombies/", "type": "show", "seasons": [1, 2, 3, "4"], "options": { "preset": "slow", "video" : { "bitrate": 4000, "quality": 0 } } }).then((data) => { console.log('Resolved 2 -'); console.log(data); }).catch((err) => { console.log('Error 2 -'); console.log(err); });
Move supervisor autocomplete into function Change-Id: Iebcd27893f1801084ab8b39753b9c779bab16ead
var supervisor_autocomplete = function() { var supervisor_provider = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: '/employees?q=%QUERY' }); supervisor_provider.initialize(); $('.typeahead-supervisor').typeahead(null, { name: 'supervisor', displayKey: 'value', source: supervisor_provider.ttAdapter(), templates: { empty: [ '<div class="empty-message">', $.i18n._('notice_supervisor_not_found'), '</div>' ].join('\n'), suggestion: Handlebars.compile([ '<p class="element-data">{{value}}</p>', '<p class="academy-unit">{{academy_unit}}</p>' ].join('')) } }).on('typeahead:selected', function(event, datum) { $(event.target).closest("div").children().last().val(datum.id); }); $('.typeahead.input-sm').siblings('input.tt-hint').addClass('hint-small'); $('.typeahead.input-lg').siblings('input.tt-hint').addClass('hint-large'); }; $(document).ready(function() { supervisor_autocomplete(); });
$(document).ready(function() { var supervisor_provider = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: '/employees?q=%QUERY' }); supervisor_provider.initialize(); $('.typeahead-supervisor').typeahead(null, { name: 'supervisor', displayKey: 'value', source: supervisor_provider.ttAdapter(), templates: { empty: [ '<div class="empty-message">', $.i18n._('notice_supervisor_not_found'), '</div>' ].join('\n'), suggestion: Handlebars.compile([ '<p class="element-data">{{value}}</p>', '<p class="academy-unit">{{academy_unit}}</p>' ].join('')) } }).on('typeahead:selected', function(event, datum) { $(event.target).closest("div").children().last().val(datum.id); }); $('.typeahead.input-sm').siblings('input.tt-hint').addClass('hint-small'); $('.typeahead.input-lg').siblings('input.tt-hint').addClass('hint-large'); });
Improve filename parser regex (hopefully)
// karaoke-forever string to artist/title parser defaults module.exports = { // regex or string; artist/song get split around this match (default='-') delimiter: '-', // bool; whether artist is on left side of delimiter (default=true) artistFirst: true, // string; override Artist for songs in this file's scope (default='') artist: '', // each stage is configured with regexes and/or strings and // simply removes matches by default (repl=''); use an array // to pass a replacement param/string, e.g. [find, repl] replacements: { // applied to input string before split to Artist/Title preSplit: [ // at least 2 word chars followed by at least 3 digits /\D{2,}[^\s]\d{3,}/i, // track numbers /^[\d\-.\s]+/, // remove text between (), [], or {} /[([{].*[)\]}]/ig, ], // applied to both Artist and Title after split postSplit: [ // correct for "..., The" [/(.*)(, The)$/i, 'The $1'], ], // applied to Artist after split artist: [ // Last, First [Middle] -> First [Middle] Last [/^(\w+?), ?(\w* ?\w*.?)$/ig, '$2 $1'], ], // applied to Title after split title: [ ], } }
// karaoke-forever string to artist/title parser defaults module.exports = { // regex or string; artist/song get split around this match (default='-') delimiter: '-', // bool; whether artist is on left side of delimiter (default=true) artistFirst: true, // string; override Artist for songs in this file's scope (default='') artist: '', // each stage is configured with regexes and/or strings and // simply removes matches by default (repl=''); use an array // to pass a replacement param/string, e.g. [find, repl] replacements: { // applied to input string before split to Artist/Title preSplit: [ // remove non-digits follwed by digits /[\D]+[\d]+/i, // remove digits between non-word characters /\W*\d+\W*/i, // remove text between (), [], or {} /[([{].*[)\]}]/ig, ], // applied to both Artist and Title after split postSplit: [ // correct for "..., The" [/(.*)(, The)$/i, 'The $1'], ], // applied to Artist after split artist: [ // Last, First [Middle] -> First [Middle] Last [/^(\w+?), ?(\w* ?\w*.?)$/ig, '$2 $1'], ], // applied to Title after split title: [ ], } }
Fix typo in babel presets
var path = require('path'); module.exports = function (module) { return { "module": false, "port": 5000, "liveReloadPort": 35729, "bundleFilename": "main", "distribution": "dist", "targets": "targets", "babel": { presets: [ path.resolve(__dirname, "../node_modules/babel-preset-es2015"), path.resolve(__dirname, "../node_modules/babel-preset-stage-1") ] }, "styles": "styles", "test": "test/**/*", "images": "images", "views": "views", "assets": "assets", "autoprefixerRules": ["last 2 versions", "> 1%"], "scripts": module ? "lib/*" : "scripts/*", "preBuild": [], // { source: "", ext: "", dest: ""} "postBuild": [], // { source: "", ext: "", dest: ""} "manifest": null, "revisionExclude": [] }; };
var path = require('path'); module.exports = function (module) { return { "module": false, "port": 5000, "liveReloadPort": 35729, "bundleFilename": "main", "distribution": "dist", "targets": "targets", "babel": { presets: [ path.resolve(__dirname, "../node_modules/babel-preset-es2015"), path.resolve(__dirname, "../node_modules/babel-preset-stage1") ] }, "styles": "styles", "test": "test/**/*", "images": "images", "views": "views", "assets": "assets", "autoprefixerRules": ["last 2 versions", "> 1%"], "scripts": module ? "lib/*" : "scripts/*", "preBuild": [], // { source: "", ext: "", dest: ""} "postBuild": [], // { source: "", ext: "", dest: ""} "manifest": null, "revisionExclude": [] }; };
Remove offer with model name
import pytest from .. import base @base.bootstrapped @pytest.mark.asyncio async def test_offer(event_loop): async with base.CleanModel() as model: application = await model.deploy( 'cs:~jameinel/ubuntu-lite-7', application_name='ubuntu', series='bionic', channel='stable', ) assert 'ubuntu' in model.applications await model.block_until( lambda: all(unit.workload_status == 'active' for unit in application.units)) await model.create_offer("ubuntu:ubuntu") offers = await model.list_offers() await model.block_until( lambda: all(offer.application_name == 'ubuntu' for offer in offers)) await model.remove_offer("admin/{}.ubuntu".format(model.info.name), force=True)
import pytest from .. import base @base.bootstrapped @pytest.mark.asyncio async def test_offer(event_loop): async with base.CleanModel() as model: application = await model.deploy( 'cs:~jameinel/ubuntu-lite-7', application_name='ubuntu', series='bionic', channel='stable', ) assert 'ubuntu' in model.applications await model.block_until( lambda: all(unit.workload_status == 'active' for unit in application.units)) await model.create_offer("ubuntu:ubuntu") offers = await model.list_offers() await model.block_until( lambda: all(offer.application_name == 'ubuntu' for offer in offers)) await model.remove_offer("ubuntu", force=True)
Extend patchup for builtin excel dialect
#!/usr/bin/env python # -*- coding: utf-8 -*- """ openslides.utils.csv_ext ~~~~~~~~~~~~~~~~~~~~~~~~ Additional dialect definitions for pythons CSV module. :copyright: 2011 by the OpenSlides team, see AUTHORS. :license: GNU GPL, see LICENSE for more details. """ from csv import Dialect, excel, register_dialect class excel_semikolon(Dialect): delimiter = ';' doublequote = True lineterminator = '\r\n' quotechar = '"' quoting = 0 skipinitialspace = False def patchup(dialect): if dialect: if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \ dialect.quotechar == excel_semikolon.quotechar: # walks like a duck and talks like a duck.. must be one dialect.doublequote = True return dialect register_dialect("excel_semikolon", excel_semikolon)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ openslides.utils.csv_ext ~~~~~~~~~~~~~~~~~~~~~~~~ Additional dialect definitions for pythons CSV module. :copyright: 2011 by the OpenSlides team, see AUTHORS. :license: GNU GPL, see LICENSE for more details. """ from csv import Dialect, excel, register_dialect class excel_semikolon(Dialect): delimiter = ';' doublequote = True lineterminator = '\r\n' quotechar = '"' quoting = 0 skipinitialspace = False def patchup(dialect): if dialect: if dialect.delimiter == excel_semikolon.delimiter and \ dialect.quotechar == excel_semikolon.quotechar: # walks like a duck and talks like a duck.. must be one dialect.doublequote = True return dialect register_dialect("excel_semikolon", excel_semikolon)
Use underscore notation rather than camel case for item properties
jsio('from shared.javascript import Class, bind') exports = Class(function() { this.init = function() { var allProjects = fin.getItemSet({ type: 'project' }) allProjects.addDependant(bind(this, '_onProjectsChange')) } this._onProjectsChange = function(mutation) { if (mutation.add) { var projectId = mutation.add var taskSet = fin.getItemSet({ type: 'task', status: 'incomplete', project: projectId }) taskSet.reduce({ sum: 'estimated_time' }, bind(this, '_onRemainingTimeChange', projectId)) } if (mutation.remove) { logger.warn("TODO: Release item set and it's reduce") } } this._onRemainingTimeChange = function(projectId, newTimeRemaining) { var newHistoryItem = { timestamp: new Date().getTime(), timeRemaining: newTimeRemaining } fin.getItem(projectId).mutate({ property: 'burndown_history', append: newHistoryItem }) } })
jsio('from shared.javascript import Class, bind') exports = Class(function() { this.init = function() { var allProjects = fin.getItemSet({ type: 'project' }) allProjects.addDependant(bind(this, '_onProjectsChange')) } this._onProjectsChange = function(mutation) { if (mutation.add) { var projectId = mutation.add var taskSet = fin.getItemSet({ type: 'task', status: 'incomplete', project: projectId }) taskSet.reduce({ sum: 'estimated_time' }, bind(this, '_onRemainingTimeChange', projectId)) } if (mutation.remove) { logger.warn("TODO: Release item set and it's reduce") } } this._onRemainingTimeChange = function(projectId, newTimeRemaining) { var newHistoryItem = { timestamp: new Date().getTime(), timeRemaining: newTimeRemaining } fin.getItem(projectId).mutate({ property: 'burndownHistory', append: newHistoryItem }) } })
Add a warning when native code is not loaded.
'use strict'; import {Platform, NativeModules} from "react-native"; const {RNDocumentPicker} = NativeModules; if (!RNDocumentPicker) { // Use a timeout to ensure the warning is displayed in the YellowBox setTimeout(() => { console.warn('RNDocumentPicker: Native module is not available, make sure you have finished the installation process and rebuilt your app'); }, 0); } class DocumentPicker { static show(opts) { opts = opts || {}; return RNDocumentPicker.show(opts); } } /** * Android requires mime types, iOS is a bit more complicated: * * @see https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html */ class DocumentPickerUtil { static allFiles() { return (Platform.OS === 'android') ? "*/*" : "public.content"; } static images() { return (Platform.OS === 'android') ? "image/*" : "public.image"; } static plainText() { return (Platform.OS === 'android') ? "text/plain" : "public.plain-text"; } static audio() { return (Platform.OS === 'android') ? "audio/*" : "public.audio"; } static pdf() { return (Platform.OS === 'android') ? "application/pdf" : "com.adobe.pdf"; } } module.exports = {DocumentPickerUtil, DocumentPicker};
'use strict'; import {Platform, NativeModules} from "react-native"; const DocumentPicker = NativeModules.RNDocumentPicker; /** * Android requires mime types, iOS is a bit more complicated: * * @see https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html */ class DocumentPickerUtil { static allFiles() { return (Platform.OS === 'android') ? "*/*" : "public.content"; } static images() { return (Platform.OS === 'android') ? "image/*" : "public.image"; } static plainText() { return (Platform.OS === 'android') ? "text/plain" : "public.plain-text"; } static audio() { return (Platform.OS === 'android') ? "audio/*" : "public.audio"; } static pdf() { return (Platform.OS === 'android') ? "application/pdf" : "com.adobe.pdf"; } } module.exports = {DocumentPickerUtil, DocumentPicker};
Fix bug on unset $app['flow'] when mapping does not exist
<?php /** * Controller for the Skyflow API. * * @license http://opensource.org/licenses/MIT The MIT License (MIT) */ namespace skyflow\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Request; /** * Controller for the Skyflow API. */ class ApiController { /** * Handle execution of a flow from a provided event name. * * The event name is provided as a URL parameter. The request * must be a HTTP POST request that may contain parameters provided * in JSON format in the HTTP request content. * * @param string $event The Event name. * @param Request $request The JSON request. * @param Application $app The Silex application. * @return mixed */ public function flowAction($event, Request $request, Application $app) { if (isset($app['flow'])) { $result = $app['flow']->event($request); return $app->json($result); } } }
<?php /** * Controller for the Skyflow API. * * @license http://opensource.org/licenses/MIT The MIT License (MIT) */ namespace skyflow\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Request; /** * Controller for the Skyflow API. */ class ApiController { /** * Handle execution of a flow from a provided event name. * * The event name is provided as a URL parameter. The request * must be a HTTP POST request that may contain parameters provided * in JSON format in the HTTP request content. * * @param string $event The Event name. * @param Request $request The JSON request. * @param Application $app The Silex application. * @return mixed */ public function flowAction($event, Request $request, Application $app) { if ($app['flow']) { $result = $app['flow']->event($request); return $app->json($result); } } }
Fix error on line 33
(function(){ // Create your component here // http://x-tags.org/docs xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } this.active = this.querySelector("[active]").id; }, inserted: function() {}, removed: function() {}, attributeChanged: function() {} }, events: { "press:delegate([role='tab'])": function (event) { var tabid = event.target.id; if (this.active === tabid) { xtag.fireEvent(this, "activeTapPress", this.active); } else { this.active = tabid; xtag.fireEvent(this, "tabChange", this.active); } } }, accessors: { role: { attribute: true }, active: true }, methods: { } }); })();
(function(){ // Create your component here // http://x-tags.org/docs xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } this.active = this.querySelector("[active]").id; }, inserted: function() {}, removed: function() {}, attributeChanged: function() {} }, events: { "press:delegate([role='tab'])": function (event) { var tabid = event.target.id; if (this.active === tabid) { xtag.fireEvent(this, "activeTapPress", this.active); } else { this.active = tabid; xtag.fireEvent(this, "tabChange", this.active); } } }, accessors: { role: { attribute: true } active: true }, methods: { } }); })();
Add comment on dist of first function
import pandas import numpy import matplotlib.pyplot as plt def univariate_stats(): # Generate 1000 random numbers from a normal distribution num_examples = 1000 z = pandas.Series(numpy.random.randn(num_examples)) # Minimum print(z.min()) # Maximum print(z.max()) # Mean print(z.mean()) # Median print(z.median()) # Variance print(z.var()) # Standard deviation print(z.std()) # Mean absolute deviation print(z.mad()) # Interquartile range print(z.quantile(0.75) - z.quantile(0.25)) z.plot(kind="hist") def multivariate_stats(): num_examples = 1000 x = pandas.Series(numpy.random.randn(num_examples)) y = x + pandas.Series(numpy.random.randn(num_examples)) z = x + pandas.Series(numpy.random.randn(num_examples)) # Covariance print(y.cov(z)) # Covariance of y with itself is equal to variance print(y.cov(y), y.var()) # Correlation print(y.corr(z)) univariate_stats() multivariate_stats() plt.show()
import pandas import numpy import matplotlib.pyplot as plt def univariate_stats(): num_examples = 1000 z = pandas.Series(numpy.random.randn(num_examples)) # Minimum print(z.min()) # Maximum print(z.max()) # Mean print(z.mean()) # Median print(z.median()) # Variance print(z.var()) # Standard deviation print(z.std()) # Mean absolute deviation print(z.mad()) # Interquartile range print(z.quantile(0.75) - z.quantile(0.25)) z.plot(kind="hist") def multivariate_stats(): num_examples = 1000 x = pandas.Series(numpy.random.randn(num_examples)) y = x + pandas.Series(numpy.random.randn(num_examples)) z = x + pandas.Series(numpy.random.randn(num_examples)) # Covariance print(y.cov(z)) # Covariance of y with itself is equal to variance print(y.cov(y), y.var()) # Correlation print(y.corr(z)) univariate_stats() multivariate_stats() plt.show()
Fix an error jenkins found
<?php /** * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ class OC_L10N_String{ protected $l10n; public function __construct($l10n, $text, $parameters, $count = 1) { $this->l10n = $l10n; $this->text = $text; $this->parameters = $parameters; $this->count = $count; } public function __toString() { $translations = $this->l10n->getTranslations(); $localizations = $this->l10n->getLocalizations(); $text = $this->text; if(array_key_exists($this->text, $translations)) { if(is_array($translations[$this->text])) { $id = $localizations["selectplural"]( $count ); $text = $translations[$this->text][$id]; } else{ $text = $translations[$this->text]; } } // Replace %n first (won't interfere with vsprintf) $text = str_replace('%n', $this->count, $text); return vsprintf($text, $this->parameters); } }
<?php /** * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ class OC_L10N_String{ protected $l10n; public function __construct($l10n, $text, $parameters, $count = 1) { $this->l10n = $l10n; $this->text = $text; $this->parameters = $parameters; $this->count = $count; } public function __toString() { $translations = $this->l10n->getTranslations(); $localizations = $this->l10n->getLocalizations(); $text = $this->text; if(array_key_exists($this->text, $translations)) { if(is_array($translations[$this->text])) { $id = $localizations["selectplural"]( $count ); $text = $translations[$this->text][$id] } else{ $text = $translations[$this->text]; } } // Replace %n first (won't interfere with vsprintf) $text = str_replace('%n', $this->count, $text); return vsprintf($text, $this->parameters); } }
Move temporary directory location into a constant
<?php define('JAVA_PATH', '/usr/bin/java'); define('TMP_DIR', '/tmp'); define('FFF_PATH', dirname(dirname(__FILE__))); define('CLASSPATH', FFF_PATH . '/itext.jar:' . FFF_PATH . '/json-org.jar:' . FFF_PATH . '/'); $template_tmp = isset($_FILES['template']['tmp_name']) ? $_FILES['template']['tmp_name'] : ''; $config_tmp = isset($_FILES['config']['tmp_name']) ? $_FILES['config']['tmp_name'] : ''; $template = tempnam(TMP_DIR, 'FFF'); $config = tempnam(TMP_DIR, 'FFF'); $output = tempnam(TMP_DIR, 'FFF'); // Move uploaded files, otherwise they may be deleted before we call FFF move_uploaded_file($template_tmp, $template); move_uploaded_file($config_tmp, $config); $execstr = JAVA_PATH . ' -classpath ' . CLASSPATH . " FormFillFlatten $config $template $output"; exec($execstr); echo file_get_contents($output); ?>
<?php define('JAVA_PATH', '/usr/bin/java'); define('FFF_PATH', dirname(dirname(__FILE__))); define('CLASSPATH', FFF_PATH . '/itext.jar:' . FFF_PATH . '/json-org.jar:' . FFF_PATH . '/'); $template_tmp = isset($_FILES['template']['tmp_name']) ? $_FILES['template']['tmp_name'] : ''; $config_tmp = isset($_FILES['config']['tmp_name']) ? $_FILES['config']['tmp_name'] : ''; $template = tempnam('/tmp', 'FFF'); $config = tempnam('/tmp', 'FFF'); $output = tempnam('/tmp', 'FFF'); // Move uploaded files, otherwise they may be deleted before we call FFF move_uploaded_file($template_tmp, $template); move_uploaded_file($config_tmp, $config); $execstr = JAVA_PATH . ' -classpath ' . CLASSPATH . " FormFillFlatten $config $template $output"; exec($execstr); echo file_get_contents($output); ?>
Update the ignoring error message
from bitHopper.Website import app, flask import btcnet_info import bitHopper.Configuration.Workers import logging @app.route("/worker", methods=['POST', 'GET']) def worker(): #Check if this is a form submission handle_worker_post(flask.request.form) #Get a list of currently configured workers pools_workers = {} for pool in btcnet_info.get_pools(): if pool.name is None: logging.debug('Ignoring a Pool. If no pools apear on /worker please update your version of btcnet_info') continue pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name) return flask.render_template('worker.html', pools = pools_workers) def handle_worker_post(post): for item in ['method','username','password', 'pool']: if item not in post: return if post['method'] == 'remove': bitHopper.Configuration.Workers.remove( post['pool'], post['username'], post['password']) elif post['method'] == 'add': bitHopper.Configuration.Workers.add( post['pool'], post['username'], post['password'])
from bitHopper.Website import app, flask import btcnet_info import bitHopper.Configuration.Workers import logging @app.route("/worker", methods=['POST', 'GET']) def worker(): #Check if this is a form submission handle_worker_post(flask.request.form) #Get a list of currently configured workers pools_workers = {} for pool in btcnet_info.get_pools(): if pool.name is None: logging.debug('Ignoring %s', pool) continue pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name) return flask.render_template('worker.html', pools = pools_workers) def handle_worker_post(post): for item in ['method','username','password', 'pool']: if item not in post: return if post['method'] == 'remove': bitHopper.Configuration.Workers.remove( post['pool'], post['username'], post['password']) elif post['method'] == 'add': bitHopper.Configuration.Workers.add( post['pool'], post['username'], post['password'])
Add staging profile to digidoc
package ee.tuleva.onboarding.config; import static org.digidoc4j.Configuration.Mode.PROD; import static org.digidoc4j.Configuration.Mode.TEST; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class DigiDocConfiguration { @Bean @Profile({"production", "staging"}) public org.digidoc4j.Configuration digiDocConfigProd() { return new org.digidoc4j.Configuration(PROD); } @Bean @ConditionalOnMissingBean(org.digidoc4j.Configuration.class) public org.digidoc4j.Configuration digiDocConfigDev() { // use PROD for testing signing return new org.digidoc4j.Configuration(TEST); } }
package ee.tuleva.onboarding.config; import static org.digidoc4j.Configuration.Mode.PROD; import static org.digidoc4j.Configuration.Mode.TEST; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class DigiDocConfiguration { @Bean @Profile("production") public org.digidoc4j.Configuration digiDocConfigProd() { return new org.digidoc4j.Configuration(PROD); } @Bean @ConditionalOnMissingBean(org.digidoc4j.Configuration.class) public org.digidoc4j.Configuration digiDocConfigDev() { // use PROD for testing signing return new org.digidoc4j.Configuration(TEST); } }
Check that GreatestCommonDivisor accepts negative second argument
package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } @Test public void acceptsNegativeSecondArgument() { assertThat(GreatestCommonDivisor.of(6, -4), is(2)); } }
package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } }
Fix type at color variable
package com.nulabinc.backlog4j.api.option; import com.nulabinc.backlog4j.Project; import com.nulabinc.backlog4j.http.NameValuePair; /** * Parameters for update status API. * * @author nulab-inc */ public class UpdateStatusParams extends PatchParams { private Object projectIdOrKey; private Object statusId; public UpdateStatusParams(Object projectIdOrKey, Object statusId, String name, Project.CustomStatusColor color) { this.projectIdOrKey = projectIdOrKey; this.statusId = statusId; parameters.add(new NameValuePair("name", name)); parameters.add(new NameValuePair("color", color.getStrValue())); } public String getProjectIdOrKeyString() { return projectIdOrKey.toString(); } public String getStatusId() { return statusId.toString(); } }
package com.nulabinc.backlog4j.api.option; import com.nulabinc.backlog4j.http.NameValuePair; /** * Parameters for update status API. * * @author nulab-inc */ public class UpdateStatusParams extends PatchParams { private Object projectIdOrKey; private Object statusId; public UpdateStatusParams(Object projectIdOrKey, Object statusId, String name, String color) { this.projectIdOrKey = projectIdOrKey; this.statusId = statusId; parameters.add(new NameValuePair("name", name)); parameters.add(new NameValuePair("color", color)); } public String getProjectIdOrKeyString() { return projectIdOrKey.toString(); } public String getStatusId() { return statusId.toString(); } }
Make submit workflow's local_workflow be False
from flow_workflow.commands.launch_base import LaunchWorkflowCommandBase from flow.configuration.inject.broker import BrokerConfiguration from flow.configuration.inject.redis_conf import RedisConfiguration from flow.configuration.inject.service_locator import ServiceLocatorConfiguration from twisted.internet import defer class SubmitWorkflowCommand(LaunchWorkflowCommandBase): injector_modules = [ BrokerConfiguration, RedisConfiguration, ServiceLocatorConfiguration, ] local_workflow = False def setup_services(self, net): pass def wait_for_results(self, net, block): if block: return self.setup_completion_handler(net) else: return defer.succeed(block)
from flow_workflow.commands.launch_base import LaunchWorkflowCommandBase from flow.configuration.inject.broker import BrokerConfiguration from flow.configuration.inject.redis_conf import RedisConfiguration from flow.configuration.inject.service_locator import ServiceLocatorConfiguration from twisted.internet import defer class SubmitWorkflowCommand(LaunchWorkflowCommandBase): injector_modules = [ BrokerConfiguration, RedisConfiguration, ServiceLocatorConfiguration, ] local_workflow = True def setup_services(self, net): pass def wait_for_results(self, net, block): if block: return self.setup_completion_handler(net) else: return defer.succeed(block)
Use splitlines instead of hard-coding the line endings. git-svn-id: 15b99a5ef70b6649222be30eb13433ba2eb40757@14 cdb1d5cb-5653-0410-9e46-1b5f511687a6
import sha from django.contrib.contenttypes.models import ContentType from versioning import _registry from versioning.diff import unified_diff from versioning.models import Revision def pre_save(instance, **kwargs): """ """ model = kwargs["sender"] fields = _registry[model] original = model._default_manager.get(pk=instance.pk) ct = ContentType.objects.get_for_model(model) diff = [] for field in fields: original_data = getattr(original, field) new_data = getattr(instance, field) data_diff = unified_diff(original_data.splitlines(), new_data.splitlines(), context=3) diff.extend(["--- %s.%s" % (model.__name__, field), "+++ %s.%s" % (model.__name__, field)]) for line in data_diff: diff.append(line) delta = "\n".join(diff) sha1 = sha.new(delta) rev = Revision(sha1=sha1.hexdigest(), object_pk=instance.pk, content_type=ct, delta=delta) rev.save()
import sha from django.contrib.contenttypes.models import ContentType from versioning import _registry from versioning.diff import unified_diff from versioning.models import Revision def pre_save(instance, **kwargs): """ """ model = kwargs["sender"] fields = _registry[model] original = model._default_manager.get(pk=instance.pk) ct = ContentType.objects.get_for_model(model) diff = [] for field in fields: original_data = getattr(original, field) new_data = getattr(instance, field) data_diff = unified_diff(original_data.split("\n"), new_data.split("\n"), context=3) diff.extend(["--- %s.%s" % (model.__name__, field), "+++ %s.%s" % (model.__name__, field)]) for line in data_diff: diff.append(line) delta = "\n".join(diff) sha1 = sha.new(delta) rev = Revision(sha1=sha1.hexdigest(), object_pk=instance.pk, content_type=ct, delta=delta) rev.save()
Use a grey solid instead of the damn frog.
#!/usr/bin/python from pyquery import PyQuery as pq import requests import subprocess APPLESCRIPT = """/usr/bin/osascript<<END tell application "Finder" set desktop picture to POSIX file "%s" end tell END""" def main(): # Load main site. root = 'http://www.shorpy.com' r = requests.get(root) j = pq(r.content) # Load first photo. first_photo = root + j('div.node div.content a').eq(1).attr('href') r = requests.get(first_photo) j = pq(r.content) image = j('img').eq(0).attr('src') with open('/tmp/dailyshorpy.jpg', 'wb') as handle: # To reset the cached dailyshorpy.jpg. subprocess.Popen(APPLESCRIPT % '/Library/Desktop Pictures/Solid Colors/Solid Gray Light.png', shell=True) request = requests.get(image, stream=True) for block in request.iter_content(1024): if not block: break handle.write(block) subprocess.Popen(APPLESCRIPT % '/tmp/dailyshorpy.jpg', shell=True) if __name__ == '__main__': main()
#!/usr/bin/python from pyquery import PyQuery as pq import requests import subprocess APPLESCRIPT = """/usr/bin/osascript<<END tell application "Finder" set desktop picture to POSIX file "%s" end tell END""" def main(): # Load main site. root = 'http://www.shorpy.com' r = requests.get(root) j = pq(r.content) # Load first photo. first_photo = root + j('div.node div.content a').eq(1).attr('href') r = requests.get(first_photo) j = pq(r.content) image = j('img').eq(0).attr('src') with open('/tmp/dailyshorpy.jpg', 'wb') as handle: # To reset the cached dailyshorpy.jpg. subprocess.Popen(APPLESCRIPT % '/Library/Desktop Pictures/Frog.jpg', shell=True) request = requests.get(image, stream=True) for block in request.iter_content(1024): if not block: break handle.write(block) subprocess.Popen(APPLESCRIPT % '/tmp/dailyshorpy.jpg', shell=True) if __name__ == '__main__': main()
Create product in setUp() method for DRY Create the product to be reused in the test methods in the setUp method that is run before each test method
from .base import FunctionalTest from store.tests.factories import * class ProductTest(FunctionalTest): def setUp(self): super(ProductTest, self).setUp() # Create a product self.product = ProductFactory.create() def test_product_navigation(self): # Get the product detail page self.browser.get(self.live_server_url + self.product.get_absolute_url()) # Assert that the title is as expected self.assertIn(self.product.name, self.browser.title) def test_product_navigation_from_homepage(self): # Get the homepage self.browser.get(self.live_server_url) # Navigate to the Product Page self.browser.find_element_by_link_text(self.product.name).click() # Assert that the page is the one expected self.assertIn(self.product.name, self.browser.title)
from .base import FunctionalTest from store.tests.factories import * class ProductTest(FunctionalTest): def test_product_navigation(self): # Create a product product = ProductFactory.create() # Get the product detail page self.browser.get(self.live_server_url + product.get_absolute_url()) # Assert that the title is as expected self.assertIn(product.name, self.browser.title) def test_product_navigation_from_homepage(self): # Create a sample product product1 = ProductFactory.create() # Get the homepage self.browser.get(self.live_server_url) # Navigate to the Product Page self.browser.find_element_by_link_text(product1.name).click() # Assert that the page is the one expected self.assertIn(product1.name, self.browser.title)
Ember: Use explicit "index" route for /keywords/:id The "index" route would be generated automatically but only if the function() {} exists. Having an empty function in the definition looks strange though so should define the route explicitly here.
import Ember from 'ember'; import config from './config/environment'; import googlePageview from './mixins/google-pageview'; const Router = Ember.Router.extend(googlePageview, { location: config.locationType }); Router.map(function() { this.route('logout'); this.route('login'); this.route('github_login'); this.route('github_authorize', { path: '/authorize/github' }); this.route('crates'); this.route('crate', { path: '/crates/*crate_id' }, function() { this.route('download'); this.route('versions'); this.route('reverse_dependencies'); // Well-known routes this.route('docs'); }); this.route('me', function() { this.route('crates'); this.route('following'); }); this.route('install'); this.route('search'); this.route('dashboard'); this.route('keywords'); this.route('keyword', { path: '/keywords/:keyword_id' }, function() { this.route('index', { path: '/' }); }); this.route('catchAll', { path: '*path' }); }); export default Router;
import Ember from 'ember'; import config from './config/environment'; import googlePageview from './mixins/google-pageview'; const Router = Ember.Router.extend(googlePageview, { location: config.locationType }); Router.map(function() { this.route('logout'); this.route('login'); this.route('github_login'); this.route('github_authorize', { path: '/authorize/github' }); this.route('crates'); this.route('crate', { path: '/crates/*crate_id' }, function() { this.route('download'); this.route('versions'); this.route('reverse_dependencies'); // Well-known routes this.route('docs'); }); this.route('me', function() { this.route('crates'); this.route('following'); }); this.route('install'); this.route('search'); this.route('dashboard'); this.route('keywords'); this.route('keyword', { path: '/keywords/*keyword_id' }, function() { }); this.route('catchAll', { path: '*path' }); }); export default Router;
Fix failed Continue Integration. use hasDefinition to check existence of jms_metadata_parser
<?php namespace Tpg\ExtjsBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class SerializerParserPass implements CompilerPassInterface { /** * You can modify the container here before it is dumped to PHP code. * * @param ContainerBuilder $container * * @api */ public function process(ContainerBuilder $container) { if ( $container->hasDefinition("nelmio_api_doc.parser.jms_metadata_parser") && ( $container->getAlias("fos_rest.serializer") == "tpg_extjs.orm_serializer" || $container->getAlias("fos_rest.serializer") == "tpg_extjs.odm_serializer" || $container->getAlias("fos_rest.serializer") == "tpg_extjs.serializer" ) ) { $container ->getDefinition("nelmio_api_doc.parser.jms_metadata_parser") ->replaceArgument(1, new Reference("tpg_extjs.naming_strategy")); } } }
<?php namespace Tpg\ExtjsBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class SerializerParserPass implements CompilerPassInterface { /** * You can modify the container here before it is dumped to PHP code. * * @param ContainerBuilder $container * * @api */ public function process(ContainerBuilder $container) { if ( $container->getDefinition("nelmio_api_doc.parser.jms_metadata_parser") !== null && ( $container->getAlias("fos_rest.serializer") == "tpg_extjs.orm_serializer" || $container->getAlias("fos_rest.serializer") == "tpg_extjs.odm_serializer" || $container->getAlias("fos_rest.serializer") == "tpg_extjs.serializer" ) ) { $container ->getDefinition("nelmio_api_doc.parser.jms_metadata_parser") ->replaceArgument(1, new Reference("tpg_extjs.naming_strategy")); } } }
Fix teardown of routeless engines mounted from Route. Specify `ViewClass` instead of instantiating `view` to ensure that `ownerView` will be set properly.
import Ember from 'ember'; const { Route, getOwner, run } = Ember; Route.reopen({ mount(engine, options) { console.log('mount', options); let owner = getOwner(this); let Engine = owner.lookup(`engine:${engine}`); let engineInstance = Engine.buildInstance(); engineInstance.boot({parent: owner}); let template = engineInstance.lookup('template:application'); let controller = engineInstance.lookup('controller:application'); let ViewClass = engineInstance._lookupFactory('view:application'); let renderOptions = { owner: engineInstance, into: options && options.into && options.into.replace(/\//g, '.'), outlet: (options && options.outlet) || 'main', template, controller, ViewClass }; this.connections.push(renderOptions); run.once(this.router, '_setOutlets'); } });
import Ember from 'ember'; const { Route, getOwner, run } = Ember; Route.reopen({ mount(engine, options) { console.log('mount', options); let owner = getOwner(this); let Engine = owner.lookup(`engine:${engine}`); let engineInstance = Engine.buildInstance(); engineInstance.boot({parent: owner}); let template = engineInstance.lookup('template:application'); let controller = engineInstance.lookup('controller:application'); let view = engineInstance.lookup('view:application'); let renderOptions = { owner: engineInstance, into: options && options.into && options.into.replace(/\//g, '.'), outlet: (options && options.outlet) || 'main', template, controller, view }; this.connections.push(renderOptions); run.once(this.router, '_setOutlets'); } });
Set componentsInited once they get inited
package com.opensymphony.workflow.designer.editor; import javax.swing.*; import com.opensymphony.workflow.designer.WorkflowCell; import com.opensymphony.workflow.designer.WorkflowEdge; /** * @author Hani Suleiman (hani@formicary.net) * Date: May 20, 2003 * Time: 10:27:26 AM */ public abstract class DetailPanel extends JPanel { private WorkflowCell cell; private WorkflowEdge edge; private boolean componentsInited = false; public WorkflowCell getCell() { return cell; } public WorkflowEdge getEdge() { return edge; } protected void viewClosed() { } public final void closeView() { viewClosed(); } public final void setCell(WorkflowCell cell) { if(!componentsInited) { initComponents(); componentsInited = true; } this.cell = cell; setName(cell.getClass().getName()); updateView(); } protected abstract void initComponents(); protected abstract void updateView(); public String getTitle() { return "Details"; } public void setEdge(WorkflowEdge edge) { if(!componentsInited) { initComponents(); componentsInited = true; } componentsInited = true; this.edge = edge; setName(edge.getClass().getName()); updateView(); } }
package com.opensymphony.workflow.designer.editor; import javax.swing.*; import com.opensymphony.workflow.designer.WorkflowCell; import com.opensymphony.workflow.designer.WorkflowEdge; /** * @author Hani Suleiman (hani@formicary.net) * Date: May 20, 2003 * Time: 10:27:26 AM */ public abstract class DetailPanel extends JPanel { private WorkflowCell cell; private WorkflowEdge edge; private boolean componentsInited = false; public WorkflowCell getCell() { return cell; } public WorkflowEdge getEdge() { return edge; } protected void viewClosed() { } public final void closeView() { viewClosed(); } public final void setCell(WorkflowCell cell) { if(!componentsInited) initComponents(); this.cell = cell; setName(cell.getClass().getName()); updateView(); } protected abstract void initComponents(); protected abstract void updateView(); public String getTitle() { return "Details"; } public void setEdge(WorkflowEdge edge) { if(!componentsInited) initComponents(); this.edge = edge; setName(edge.getClass().getName()); updateView(); } }
Fix shop-payment by enforcing order reload.
<?php use SilverStripe\Omnipay\Service\ServiceResponse; /** * Customisations to {@link Payment} specifically for the shop module. * * @package shop */ class ShopPayment extends DataExtension { private static $has_one = array( 'Order' => 'Order', ); public function onAwaitingAuthorized(ServiceResponse $response) { $this->placeOrder(); } public function onAwaitingCaptured(ServiceResponse $response) { $this->placeOrder(); } public function onAuthorized(ServiceResponse $response) { $this->placeOrder(); } public function onCaptured(ServiceResponse $response) { // ensure order is being reloaded from DB, to prevent dealing with stale data! /** @var Order $order */ $order = Order::get()->byID($this->owner->OrderID); if ($order && $order->exists()) { OrderProcessor::create($order)->completePayment(); } } protected function placeOrder() { // ensure order is being reloaded from DB, to prevent dealing with stale data! /** @var Order $order */ $order = Order::get()->byID($this->owner->OrderID); if ($order && $order->exists()) { OrderProcessor::create($order)->placeOrder(); } } }
<?php use SilverStripe\Omnipay\Service\ServiceResponse; /** * Customisations to {@link Payment} specifically for the shop module. * * @package shop */ class ShopPayment extends DataExtension { private static $has_one = array( 'Order' => 'Order', ); public function onAwaitingAuthorized(ServiceResponse $response) { $this->placeOrder(); } public function onAwaitingCaptured(ServiceResponse $response) { $this->placeOrder(); } public function onAuthorized(ServiceResponse $response) { $this->placeOrder(); } public function onCaptured(ServiceResponse $response) { $order = $this->owner->Order(); if ($order->exists()) { OrderProcessor::create($order)->completePayment(); } } protected function placeOrder() { $order = $this->owner->Order(); if ($order->exists()) { OrderProcessor::create($order)->placeOrder(); } } }
Add new one site to filter
chrome.webRequest.onBeforeRequest.addListener( (details) => { chrome.tabs.sendMessage(details.tabId, { content: "message" }, () => {}); const startTime = new Date().getTime(); let randNumber; while ((new Date().getTime() - startTime) < 5000) { /* prevent errors on empty fn in loop */ randNumber = Math.random(); } return { cancel: (randNumber + 1) > 0 }; }, { urls: [ "*://*.piguiqproxy.com/*", "*://*.amgload.net/*", "*://*.dsn-fishki.ru/*", "*://*.rcdn.pro/*", "*://*.smcheck.org/*", "*://*.zmctrack.net/*", ] }, ["blocking"] );
chrome.webRequest.onBeforeRequest.addListener( (details) => { chrome.tabs.sendMessage(details.tabId, { content: "message" }, () => {}); const startTime = new Date().getTime(); let randNumber; while ((new Date().getTime() - startTime) < 5000) { /* prevent errors on empty fn in loop */ randNumber = Math.random(); } return { cancel: (randNumber + 1) > 0 }; }, { urls: [ "*://*.piguiqproxy.com/*", "*://*.amgload.net/*", "*://*.dsn-fishki.ru/*", "*://*.rcdn.pro/*", "*://*.smcheck.org/*", ] }, ["blocking"] );
Migrate from strongly discouraged @Test(expected = ...) to assertThrows(...). We got an internal auto-generated cleanup CL. Release-Notes: skip Change-Id: I40bfdf671f7ef25b23c79a60e505cd5d6a54eb82
// Copyright (C) 2019 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.acceptance.api.plugin; import static com.google.gerrit.testing.GerritJUnit.assertThrows; import com.google.gerrit.acceptance.AbstractDaemonTest; import com.google.gerrit.acceptance.NoHttpd; import com.google.gerrit.acceptance.config.GerritConfig; import com.google.gerrit.server.plugins.MissingMandatoryPluginsException; import org.junit.Test; import org.junit.runner.Description; @NoHttpd public class PluginLoaderIT extends AbstractDaemonTest { Description testDescription; @Override protected void beforeTest(Description description) throws Exception { this.testDescription = description; } @Override protected void afterTest() throws Exception {} @Test @GerritConfig(name = "plugins.mandatory", value = "my-mandatory-plugin") public void shouldFailToStartGerritWhenMandatoryPluginsAreMissing() throws Exception { assertThrows(MissingMandatoryPluginsException.class, () -> super.beforeTest(testDescription)); } }
// Copyright (C) 2019 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.acceptance.api.plugin; import com.google.gerrit.acceptance.AbstractDaemonTest; import com.google.gerrit.acceptance.NoHttpd; import com.google.gerrit.acceptance.config.GerritConfig; import com.google.gerrit.server.plugins.MissingMandatoryPluginsException; import org.junit.Test; import org.junit.runner.Description; @NoHttpd public class PluginLoaderIT extends AbstractDaemonTest { Description testDescription; @Override protected void beforeTest(Description description) throws Exception { this.testDescription = description; } @Override protected void afterTest() throws Exception {} @Test(expected = MissingMandatoryPluginsException.class) @GerritConfig(name = "plugins.mandatory", value = "my-mandatory-plugin") public void shouldFailToStartGerritWhenMandatoryPluginsAreMissing() throws Exception { super.beforeTest(testDescription); } }
Update googlemaps to 2.5.0 version
from setuptools import setup, find_packages import politicalplaces setup( name='django-political-map', version=politicalplaces.__version__, description='Django application to store geolocalized places and organize them according to political hierarchy.', author='20tab S.r.l.', author_email='info@20tab.com', #url='https://gitlab.20tab.com/20tab/django-political-map', url='https://github.com/20tab/django-political-map.git', license='MIT License', install_requires=[ 'googlemaps==2.5.0', ], packages=find_packages(), include_package_data=True, package_data={ '': ['*.html', '*.css', '*.js', '*.gif', '*.png', ], } )
from setuptools import setup, find_packages import politicalplaces setup( name='django-political-map', version=politicalplaces.__version__, description='Django application to store geolocalized places and organize them according to political hierarchy.', author='20tab S.r.l.', author_email='info@20tab.com', #url='https://gitlab.20tab.com/20tab/django-political-map', url='https://github.com/20tab/django-political-map.git', license='MIT License', install_requires=[ 'googlemaps==2.4.6', ], packages=find_packages(), include_package_data=True, package_data={ '': ['*.html', '*.css', '*.js', '*.gif', '*.png', ], } )
Refactor building command using join()
# pyinfra # File: pyinfra/modules/pip.py # Desc: manage virtualenvs ''' Manage Python virtual environments ''' from __future__ import unicode_literals from pyinfra.api import operation from pyinfra.modules import files @operation def virtualenv( state, host, path, python=None, site_packages=False, always_copy=False, present=True, ): ''' Manage virtualenv. + python: python interpreter to use + site_packages: give access to the global site-packages + always_copy: always copy files rather than symlinking + present: whether the virtualenv should be installed ''' if present is False and host.fact.directory(path): # Ensure deletion of unwanted virtualenv # no 'yield from' in python 2.7 yield files.directory(state, host, path, present=False) elif present and not host.fact.directory(path): # Create missing virtualenv command = ['/usr/bin/virtualenv'] if python: command.append('-p {}'.format(python)) if site_packages: command.append('--system-site-packages') if always_copy: command.append('--always-copy') command.append(path) yield ' '.join(command)
# pyinfra # File: pyinfra/modules/pip.py # Desc: manage virtualenvs ''' Manage Python virtual environments ''' from __future__ import unicode_literals from pyinfra.api import operation from pyinfra.modules import files @operation def virtualenv( state, host, path, python=None, site_packages=False, always_copy=False, present=True, ): ''' Manage virtualenv. + python: python interpreter to use + site_packages: give access to the global site-packages + always_copy: always copy files rather than symlinking + present: whether the virtualenv should be installed ''' if present is False and host.fact.directory(path): # Ensure deletion of unwanted virtualenv # no 'yield from' in python 2.7 yield files.directory(state, host, path, present=False) elif present and not host.fact.directory(path): # Create missing virtualenv command = '/usr/bin/virtualenv' if python: command += ' -p {}'.format(python) if site_packages: command += ' --system-site-packages' if always_copy: command += ' --always-copy' command += ' ' + path yield command
Create the phone table when it existn't
let db; try { db = require("rethinkdbdash")(require("../config").connectionOpts); } catch (err) { console.error("You haven't installed rethinkdbdash npm module or you didn't have configured the bot yet! Please do so."); } (async function () { if (!db) return; const tables = await db.tableList(); if (!tables.includes("blacklist")) await db.tableCreate("blacklist"); if (!tables.includes("session")) await db.tableCreate("session"); if (!tables.includes("configs")) await db.tableCreate("configs"); if (!tables.includes("feedback")) await db.tableCreate("feedback"); if (!tables.includes("tags")) await db.tableCreate("tags"); if (!tables.includes("profile")) await db.tableCreate("profile"); if (!tables.includes("modlog")) await db.tableCreate("modlog"); if (!tables.includes("extensions")) await db.tableCreate("extensions"); if (!tables.includes("extension_store")) await db.tableCreate("extension_store"); if (!tables.includes("phone")) await db.tableCreate("phone"); console.log("All set up!"); process.exit(0); })();
let db; try { db = require("rethinkdbdash")(require("../config").connectionOpts); } catch (err) { console.error("You haven't installed rethinkdbdash npm module or you didn't have configured the bot yet! Please do so."); } (async function () { if (!db) return; const tables = await db.tableList(); if (!tables.includes("blacklist")) await db.tableCreate("blacklist"); if (!tables.includes("session")) await db.tableCreate("session"); if (!tables.includes("configs")) await db.tableCreate("configs"); if (!tables.includes("feedback")) await db.tableCreate("feedback"); if (!tables.includes("tags")) await db.tableCreate("tags"); if (!tables.includes("profile")) await db.tableCreate("profile"); if (!tables.includes("modlog")) await db.tableCreate("modlog"); if (!tables.includes("extensions")) await db.tableCreate("extensions"); if (!tables.includes("extension_store")) await db.tableCreate("extension_store"); console.log("All set up!"); process.exit(0); })();
Insert custom commands through the getCommands() function.
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Weblinks * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Weblinks Toolbar Class * * @author Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun> * @category Nooku * @package Nooku_Server * @subpackage Weblinks */ class ComWeblinksControllerToolbarWeblinks extends ComDefaultControllerToolbarDefault { public function getCommands() { $this->addSeperator() ->addEnable() ->addDisable() ->addSeperator() ->addPreferences(); return parent::getCommands(); } }
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Weblinks * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Weblinks Toolbar Class * * @author Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun> * @category Nooku * @package Nooku_Server * @subpackage Weblinks */ class ComWeblinksControllerToolbarWeblinks extends ComDefaultControllerToolbarDefault { public function __construct(KConfig $config) { parent::__construct($config); $this->addSeperator() ->addEnable() ->addDisable() ->addSeperator() ->addPreferences(); } }
[TASK] Disable registering of non-existing TextImagePreviewRenderer
<?php if (!defined('TYPO3_MODE')) { die('Access denied.'); } /* * Mark the delivered TypoScript templates as "content rendering template" */ $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'][] = 'themes/Configuration/TypoScript/'; /* * Add RTE configuration for theme_bootstrap4 */ $GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['default'] = 'EXT:theme_bootstrap4/Configuration/RteCkeditor/Default.yaml'; /* * Register for hook to show preview of tt_content element of CType="themebootstrap4_xxx" in page module */ // @todo The TextImagePreviewRenderer does not exist anymore, there's now a TextMediaPreviewRenderer, this should be registered and the function should be tested //$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawItem']['themebootstrap4_text_image'] = //\KayStrobach\ThemeBootstrap4\Hooks\PageLayoutView\TextImagePreviewRenderer::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawItem']['themebootstrap4_image'] = \KayStrobach\ThemeBootstrap4\Hooks\PageLayoutView\ImagePreviewRenderer::class;
<?php if (!defined('TYPO3_MODE')) { die('Access denied.'); } /* * Mark the delivered TypoScript templates as "content rendering template" */ $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'][] = 'themes/Configuration/TypoScript/'; /* * Add RTE configuration for theme_bootstrap4 */ $GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['default'] = 'EXT:theme_bootstrap4/Configuration/RteCkeditor/Default.yaml'; /* * Register for hook to show preview of tt_content element of CType="themebootstrap4_xxx" in page module */ $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawItem']['themebootstrap4_text_image'] = \KayStrobach\ThemeBootstrap4\Hooks\PageLayoutView\TextImagePreviewRenderer::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawItem']['themebootstrap4_image'] = \KayStrobach\ThemeBootstrap4\Hooks\PageLayoutView\ImagePreviewRenderer::class;
Document the service spec blacklist constant
const ServiceSpecConstants = { /** * List of service `_itemData` keys that don't belong to a service spec * as the data is either describing the service state or from sources * other than Marathon. * * @type {array.<string>} */ BLACKLIST: [ 'uris', 'ports', 'version', 'versions', 'versionInfo', 'deployments', 'queue', 'lastTaskFailure', 'tasks', 'taskStats', 'tasksHealthy', 'tasksRunning', 'tasksStaged', 'tasksUnhealthy', 'name', 'pid', 'used_resources', 'offered_resources', 'capabilities', 'hostname', 'webui_url', 'active', 'TASK_STAGING', 'TASK_STARTING', 'TASK_RUNNING', 'TASK_KILLING', 'TASK_FINISHED', 'TASK_KILLED', 'TASK_FAILED', 'TASK_LOST', 'TASK_ERROR', 'slave_ids' ] }; module.exports = ServiceSpecConstants;
const ServiceSpecConstants = { BLACKLIST: [ 'uris', 'ports', 'version', 'versions', 'versionInfo', 'deployments', 'queue', 'lastTaskFailure', 'tasks', 'taskStats', 'tasksHealthy', 'tasksRunning', 'tasksStaged', 'tasksUnhealthy', 'name', 'pid', 'used_resources', 'offered_resources', 'capabilities', 'hostname', 'webui_url', 'active', 'TASK_STAGING', 'TASK_STARTING', 'TASK_RUNNING', 'TASK_KILLING', 'TASK_FINISHED', 'TASK_KILLED', 'TASK_FAILED', 'TASK_LOST', 'TASK_ERROR', 'slave_ids' ] }; module.exports = ServiceSpecConstants;
Add loading data log message.
var Cache = require('./cache'); var fs = require('fs'); var handlers = require('./handlers'); var Ute = require('ute'); var util = require('./util'); function FeedPaper() { this.ute = new Ute(); this.init(); } FeedPaper.prototype.init = function () { var categoryList = []; var urlLookup = {}; console.log('[i] Loading data'); var conf = JSON.parse(fs.readFileSync('conf/data.json')); conf.forEach(function (category) { var feeds = []; category.feeds.forEach(function (feed) { var feedId = util.slug(feed.title); feeds.push({ id : feedId, title: feed.title, url : feed.url }); urlLookup[feedId] = feed.url; }); categoryList.push({ id : util.slug(category.title), title: category.title, feeds: feeds }); }); this.cache = new Cache(categoryList, urlLookup); }; FeedPaper.prototype.start = function () { var self = this; handlers.cache = this.cache; this.ute.start(handlers); this.cache.build(function (err) { if (err) { console.error(err); } self.cache.refresh(); }); }; module.exports = FeedPaper;
var Cache = require('./cache'); var fs = require('fs'); var handlers = require('./handlers'); var Ute = require('ute'); var util = require('./util'); function FeedPaper() { this.ute = new Ute(); this.init(); } FeedPaper.prototype.init = function () { var categoryList = []; var urlLookup = {}; var conf = JSON.parse(fs.readFileSync('conf/data.json')); conf.forEach(function (category) { var feeds = []; category.feeds.forEach(function (feed) { var feedId = util.slug(feed.title); feeds.push({ id : feedId, title: feed.title, url : feed.url }); urlLookup[feedId] = feed.url; }); categoryList.push({ id : util.slug(category.title), title: category.title, feeds: feeds }); }); this.cache = new Cache(categoryList, urlLookup); }; FeedPaper.prototype.start = function () { var self = this; handlers.cache = this.cache; this.ute.start(handlers); this.cache.build(function (err) { if (err) { console.error(err); } self.cache.refresh(); }); }; module.exports = FeedPaper;