text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use mako for templating instead of chameleon
import os from setuptools import setup, find_packages requires = [ 'pyramid', 'pyramid_debugtoolbar', 'pyramid_mako', 'waitress', ] setup(name='kimochi-consumer', version='0.0', description='kimochi-consumer', long_description="Example content consumer for Kimochi.", classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="kimochiconsumer", entry_points="""\ [paste.app_factory] main = kimochiconsumer:main """, )
import os from setuptools import setup, find_packages requires = [ 'pyramid', 'pyramid_chameleon', 'pyramid_debugtoolbar', 'waitress', ] setup(name='kimochi-consumer', version='0.0', description='kimochi-consumer', long_description="Example content consumer for Kimochi.", classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="kimochiconsumer", entry_points="""\ [paste.app_factory] main = kimochiconsumer:main """, )
Add subview's DOM before injecting to document
var $ = require('jquery'); var cdb = require('cartodb.js'); var TypeGuessingTogglerView = require('../../create/footer/type_guessing_toggler_view'); /** * Footer view for the add layer modal. */ module.exports = cdb.core.View.extend({ initialize: function() { this.elder('initialize'); this._template = cdb.templates.getTemplate('new_common/dialogs/map/add_layer/footer'); this._typeGuessingTogglerView = new TypeGuessingTogglerView({ model: this.model }); this._initBinds(); }, // implements cdb.ui.common.Dialog.prototype.render render: function() { this.clearSubViews(); var $el = $( this._template({ canUpload: this.model.canUpload(), listing: this.model.get('listing') }) ); $el.find('.js-footer-info').append(this._typeGuessingTogglerView.render().el); this.$el.html($el); return this; }, _initBinds: function() { this.model.upload.bind('change', this.render, this); this.model.bind('change:listing', this._onChangeListing, this); }, _onChangeListing: function() { switch (this.model.get('listing')) { case 'scratch': this.hide(); break; default: this.render(); this.show(); } } });
var cdb = require('cartodb.js'); var TypeGuessingTogglerView = require('../../create/footer/type_guessing_toggler_view'); /** * Footer view for the add layer modal. */ module.exports = cdb.core.View.extend({ initialize: function() { this.elder('initialize'); this._template = cdb.templates.getTemplate('new_common/dialogs/map/add_layer/footer'); this._typeGuessingTogglerView = new TypeGuessingTogglerView({ model: this.model }); this._initBinds(); }, // implements cdb.ui.common.Dialog.prototype.render render: function() { this.clearSubViews(); this.$el.html( this._template({ canUpload: this.model.canUpload(), listing: this.model.get('listing') }) ); this.$('.js-footer-info').append(this._typeGuessingTogglerView.render().$el); return this; }, _initBinds: function() { this.model.upload.bind('change', this.render, this); this.model.bind('change:listing', this._onChangeListing, this); }, _onChangeListing: function() { switch (this.model.get('listing')) { case 'scratch': this.hide(); break; default: this.render(); this.show(); } } });
Replace incorrect const with let
class EventEmitter { constructor() { this.observers = {}; } on(events, listener) { events.split(' ').forEach(event => { this.observers[event] = this.observers[event] || []; this.observers[event].push(listener); }); return this; } off(event, listener) { if (!this.observers[event]) { return; } const observers = this.observers[event]; for (let i = observers.length - 1; i >= 0; i--) { const observer = observers[i]; if (observer === listener) { observers.splice(i, 1); } } } emit(event, ...args) { if (this.observers[event]) { const cloned = [].concat(this.observers[event]); cloned.forEach(observer => { observer(...args); }); } if (this.observers['*']) { const cloned = [].concat(this.observers['*']); cloned.forEach(observer => { observer.apply(observer, [event, ...args]); }); } } } export default EventEmitter;
class EventEmitter { constructor() { this.observers = {}; } on(events, listener) { events.split(' ').forEach(event => { this.observers[event] = this.observers[event] || []; this.observers[event].push(listener); }); return this; } off(event, listener) { if (!this.observers[event]) { return; } const observers = this.observers[event]; for (const i = observers.length - 1; i >= 0; i--) { const observer = observers[i]; if (observer === listener) { observers.splice(i, 1); } } } emit(event, ...args) { if (this.observers[event]) { const cloned = [].concat(this.observers[event]); cloned.forEach(observer => { observer(...args); }); } if (this.observers['*']) { const cloned = [].concat(this.observers['*']); cloned.forEach(observer => { observer.apply(observer, [event, ...args]); }); } } } export default EventEmitter;
Fix spelling on groupID primary key
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersGroupsCatsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('usersgroupscats',function(Blueprint $table) { $table->integer('userID')->unsigned(); $table->integer('groupID')->unsigned(); $table->integer('catID')->unsigned(); $table->softDeletes(); $table->timestamps(); // $table->foreign('catID')->references('catID')->on('categories'); // $table->foreign('groupID')->references('groupID')->on('groups'); // $table->foreign('userID')->references('userID')->on('users'); $table->primary(['userID','groupID','catID']); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('UsersGroupsCats'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersGroupsCatsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('UsersGroupsCats',function(Blueprint $table) { $table->integer('userID')->unsigned(); $table->integer('groupID')->unsigned(); $table->integer('catID')->unsigned(); $table->softDeletes(); $table->timestamps(); // $table->foreign('catID')->references('catID')->on('categories'); // $table->foreign('groupID')->references('groupID')->on('groups'); // $table->foreign('userID')->references('userID')->on('users'); $table->primary(['userID','groupsID','catID']); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('UsersGroupsCats'); } }
Rewrite Runnable's methods to rely on Supplier's
package throwing; import throwing.function.ThrowingSupplier; @FunctionalInterface public interface ThrowingRunnable<X extends Throwable> { public void run() throws X; default public Runnable fallbackTo(Runnable fallback) { ThrowingRunnable<Nothing> t = fallback::run; return orTry(t)::run; } default public <Y extends Throwable> ThrowingRunnable<Y> orTry(ThrowingRunnable<? extends Y> r) { ThrowingSupplier<Void, X> s1 = () -> { run(); return null; }; return s1.orTry(() -> { r.run(); return null; })::get; } }
package throwing; @FunctionalInterface public interface ThrowingRunnable<X extends Throwable> { public void run() throws X; default public Runnable fallbackTo(Runnable fallback) { ThrowingRunnable<Nothing> t = fallback::run; return orTry(t)::run; } default public <Y extends Throwable> ThrowingRunnable<Y> orTry(ThrowingRunnable<? extends Y> r) { return () -> { try { run(); } catch (Throwable x) { try { r.run(); } catch (Throwable x2) { x2.addSuppressed(x); throw x2; } } }; } }
Add meta object containing `fixable` options
'use strict'; module.exports = { meta: { fixable: 'code', schema: [] }, create(context) { return { VariableDeclaration: function(node) { if (node.kind !== 'const') { return; } if (node.parent && node.parent.type === 'Program') { // Declaration is in root of module. return; } if (node.parent && node.parent.type === 'ExportNamedDeclaration' && node.parent.parent && node.parent.parent.type === 'Program') { // Declaration is a `export const foo = 'asdf'` in root of the module. return; } context.report({ node: node, message: '`const` should only be used in module scope (not inside functions/blocks).' }); } }; } }; module.exports.schema = []; // no options
'use strict'; module.exports = function(context) { return { VariableDeclaration: function(node) { if (node.kind !== 'const') { return; } if (node.parent && node.parent.type === 'Program') { // Declaration is in root of module. return; } if (node.parent && node.parent.type === 'ExportNamedDeclaration' && node.parent.parent && node.parent.parent.type === 'Program') { // Declaration is a `export const foo = 'asdf'` in root of the module. return; } context.report({ node: node, message: '`const` should only be used in module scope (not inside functions/blocks).' }); } }; }; module.exports.schema = []; // no options
Correct a typo (followup to r1425648 ) git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1426369 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.tomcat.websocket; import java.io.IOException; import javax.websocket.CloseReason; /** * Allows the WebSocket implementation to throw an {@link IOException} that * includes a {@link CloseReason} specific to the error that can be passed back * to the client. */ public class WsIOException extends IOException { private static final long serialVersionUID = 1L; private final CloseReason closeReason; public WsIOException(CloseReason closeReason) { this.closeReason = closeReason; } public CloseReason getCloseReason() { return closeReason; } }
/* * 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.tomcat.websocket; import java.io.IOException; import javax.websocket.CloseReason; /** * Allows the WebSocket implementation to throw an {@link IOException} that * includes an {@link CloseReason} specific to the error that can be passed back * to the client. */ public class WsIOException extends IOException { private static final long serialVersionUID = 1L; private final CloseReason closeReason; public WsIOException(CloseReason closeReason) { this.closeReason = closeReason; } public CloseReason getCloseReason() { return closeReason; } }
Add import fields to Movie
var mongoose = require('mongoose') var classification = { author: String, buyer: {_id: mongoose.Schema.Types.ObjectId, name: String}, billing: {_id: mongoose.Schema.Types.ObjectId, name: String}, format: String, duration: String, // for now matches a regexp in the client safe: Boolean, criteria: [Number], comments: {} } var Movie = exports.Movie = mongoose.model('movies', { 'emeku-id': { type: String, index: true }, name: String, deleted: Boolean, 'name-fi': String, 'name-sv': String, country: String, year: Number, 'production-companies': [{_id: mongoose.Schema.Types.ObjectId, name: String}], genre: String, directors: [String], actors: {type: [String], index: true}, synopsis: String, classifications: [classification] }) var ProductionCompany = exports.ProductionCompany = mongoose.model('production_companies', { name: {type: String, index: true} }) var Account = exports.Account = mongoose.model('accounts', { name: {type: String, index: true} })
var mongoose = require('mongoose') var classification = { author: String, buyer: {_id: mongoose.Schema.Types.ObjectId, name: String}, billing: {_id: mongoose.Schema.Types.ObjectId, name: String}, format: String, duration: String, // for now matches a regexp in the client safe: Boolean, criteria: [Number], comments: {} } var Movie = exports.Movie = mongoose.model('movies', { name: String, 'name-fi': String, 'name-sv': String, country: String, year: Number, 'production-companies': [{_id: mongoose.Schema.Types.ObjectId, name: String}], genre: String, directors: [String], actors: {type: [String], index: true}, synopsis: String, classifications: [classification] }) var ProductionCompany = exports.ProductionCompany = mongoose.model('production_companies', { name: {type: String, index: true} }) var Account = exports.Account = mongoose.model('accounts', { name: {type: String, index: true} })
Upgrade tangled.web 0.1a5 => 0.1a10
from setuptools import setup setup( name='tangled.mako', version='0.1a4.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a10', 'Mako>=1.0', ], extras_require={ 'dev': [ 'tangled.web[dev]>=0.1a10', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
from setuptools import setup setup( name='tangled.mako', version='0.1a4.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a5', 'Mako>=1.0', ], extras_require={ 'dev': [ 'tangled.web[dev]>=0.1a5', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
Use Object Literal Shorthand Syntax Looks like it's a miss as its already done at other instances like productId
import shop from '../api/shop' import * as types from '../constants/ActionTypes' const receiveProducts = products => ({ type: types.RECEIVE_PRODUCTS, products }) export const getAllProducts = () => dispatch => { shop.getProducts(products => { dispatch(receiveProducts(products)) }) } const addToCartUnsafe = productId => ({ type: types.ADD_TO_CART, productId }) export const addToCart = productId => (dispatch, getState) => { if (getState().products.byId[productId].inventory > 0) { dispatch(addToCartUnsafe(productId)) } } export const checkout = products => (dispatch, getState) => { const { cart } = getState() dispatch({ type: types.CHECKOUT_REQUEST }) shop.buyProducts(products, () => { dispatch({ type: types.CHECKOUT_SUCCESS, cart }) // Replace the line above with line below to rollback on failure: // dispatch({ type: types.CHECKOUT_FAILURE, cart }) }) }
import shop from '../api/shop' import * as types from '../constants/ActionTypes' const receiveProducts = products => ({ type: types.RECEIVE_PRODUCTS, products: products }) export const getAllProducts = () => dispatch => { shop.getProducts(products => { dispatch(receiveProducts(products)) }) } const addToCartUnsafe = productId => ({ type: types.ADD_TO_CART, productId }) export const addToCart = productId => (dispatch, getState) => { if (getState().products.byId[productId].inventory > 0) { dispatch(addToCartUnsafe(productId)) } } export const checkout = products => (dispatch, getState) => { const { cart } = getState() dispatch({ type: types.CHECKOUT_REQUEST }) shop.buyProducts(products, () => { dispatch({ type: types.CHECKOUT_SUCCESS, cart }) // Replace the line above with line below to rollback on failure: // dispatch({ type: types.CHECKOUT_FAILURE, cart }) }) }
Remove close_called test (no longer supported in python 3)
# CREATED: 10/15/16 7:52 PM by Justin Salamon <justin.salamon@nyu.edu> ''' Tests for functions in util.py ''' from scaper.util import _close_temp_files from scaper.util import _set_temp_logging_level import tempfile import os import logging def test_close_temp_files(): ''' Create a bunch of temp files and then make sure they've been closed and deleted. ''' tmpfiles = [] with _close_temp_files(tmpfiles): for _ in range(5): tmpfiles.append( tempfile.NamedTemporaryFile(suffix='.wav', delete=True)) for tf in tmpfiles: assert tf.file.closed assert not os.path.isfile(tf.name) def test_set_temp_logging_level(): ''' Ensure temp logging level is set as expected ''' logger = logging.getLogger() logger.setLevel('DEBUG') with _set_temp_logging_level('CRITICAL'): assert logging.getLevelName(logger.level) == 'CRITICAL' assert logging.getLevelName(logger.level) == 'DEBUG'
# CREATED: 10/15/16 7:52 PM by Justin Salamon <justin.salamon@nyu.edu> ''' Tests for functions in util.py ''' from scaper.util import _close_temp_files from scaper.util import _set_temp_logging_level import tempfile import os import logging def test_close_temp_files(): ''' Create a bunch of temp files and then make sure they've been closed and deleted. ''' tmpfiles = [] with _close_temp_files(tmpfiles): for _ in range(5): tmpfiles.append( tempfile.NamedTemporaryFile(suffix='.wav', delete=True)) for tf in tmpfiles: assert tf.close_called assert tf.file.closed assert not os.path.isfile(tf.name) def test_set_temp_logging_level(): ''' Ensure temp logging level is set as expected ''' logger = logging.getLogger() logger.setLevel('DEBUG') with _set_temp_logging_level('CRITICAL'): assert logging.getLevelName(logger.level) == 'CRITICAL' assert logging.getLevelName(logger.level) == 'DEBUG'
Upgrade six to the lastest
from setuptools import find_packages, setup setup( name='pyserializer', version='0.9.1', description='Simple python serialization library.', author='LocalMed', author_email='ecordell@localmed.com, pete@localmed.com, joeljames1985@gmail.com', # NOQA url='', license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, install_requires=[ 'six==1.11.0' ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', ], )
from setuptools import find_packages, setup setup( name='pyserializer', version='0.9.1', description='Simple python serialization library.', author='LocalMed', author_email='ecordell@localmed.com, pete@localmed.com, joeljames1985@gmail.com', # NOQA url='', license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, install_requires=[ 'six==1.8.0' ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', ], )
Make sure log level gets reset afterwards
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from sqlalchemy import Table, MetaData from corehq.db import connection_manager from corehq.util.decorators import change_log_level from django.db import migrations @change_log_level('sqlalchemy.engine', logging.INFO) # show SQL commands def drop_tables(apps, schema_editor): metadata = MetaData(bind=connection_manager.get_engine()) for table_name in [ 'fluff_OPMHierarchyFluff', 'fluff_OpmCaseFluff', 'fluff_OpmFormFluff', 'fluff_OpmHealthStatusAllInfoFluff', 'fluff_VhndAvailabilityFluff', ]: Table(table_name, metadata).drop(checkfirst=True) class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(drop_tables), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from sqlalchemy import Table, MetaData from corehq.db import connection_manager from django.db import migrations def drop_tables(apps, schema_editor): # show SQL commands logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) metadata = MetaData(bind=connection_manager.get_engine()) for table_name in [ 'fluff_OPMHierarchyFluff', 'fluff_OpmCaseFluff', 'fluff_OpmFormFluff', 'fluff_OpmHealthStatusAllInfoFluff', 'fluff_VhndAvailabilityFluff', ]: Table(table_name, metadata).drop(checkfirst=True) class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(drop_tables), ]
Replace app share with app singleton function for laravel 5.4 support
<?php namespace Dyaa\Pushover; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; class PushoverServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('pushover', function($app) { return new Pushover($app['config']); }); $this->app->booting(function() { $loader = AliasLoader::getInstance(); $loader->alias('Pushover', 'Dyaa\Pushover\Facades\Pushover'); }); $this->app->singleton('pushover.send', function () { return new Commands\PushoverCommand($this->app['pushover']); }); $this->commands( 'pushover.send' ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['pushover']; } }
<?php namespace Dyaa\Pushover; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; class PushoverServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $this->app['pushover'] = $this->app->share(function($app) { return new Pushover($app['config']); }); $this->app->booting(function() { $loader = AliasLoader::getInstance(); $loader->alias('Pushover', 'Dyaa\Pushover\Facades\Pushover'); }); $this->app['pushover.send'] = $this->app->share(function () { return new Commands\PushoverCommand($this->app['pushover']); }); $this->commands( 'pushover.send' ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['pushover']; } }
Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej =================================================================== --- test/win/gyptest-link-pdb.py (revision 1530) +++ test/win/gyptest-link-pdb.py (working copy) @@ -26,7 +26,9 @@ # Verify the specified PDB is created when ProgramDatabaseFile # is provided. - if not FindFile('name_set.pdb'): + if not FindFile('name_outdir.pdb'): test.fail_test() - else: - test.pass_test() \ No newline at end of file + if not FindFile('name_proddir.pdb'): + test.fail_test() + + test.pass_test() Index: test/win/linker-flags/program-database.gyp TBR=bradnelson@chromium.org Review URL: https://codereview.chromium.org/11368061
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
Remove usage of Ember.assign to support older version of Ember
import Ember from 'ember'; const assign = Ember.assign || Ember.merge; /** * @class Row * @extends Ember.ObjectProxy * @namespace SemanticUI */ const Row = Ember.ObjectProxy.extend({ /** * Whether the row is currently selected. * * @property selected * @type Boolean * @default false * @public */ selected: false, /** * Content for this row. See {{#crossLink "Ember.ObjectProxy"}}{{/crossLink}}. * * @property content * @type Object * @public */ content: null }); Row.reopenClass({ /** * @method create * @param {Object} content Content for this row. * @param {Object} options Properties to initialize in this object. * @return Row * @static */ create(content, options = {}) { let _options = assign({ content }, options); return this._super(_options); } }); export default Row;
import Ember from 'ember'; const { assign } = Ember; /** * @class Row * @extends Ember.ObjectProxy * @namespace SemanticUI */ const Row = Ember.ObjectProxy.extend({ /** * Whether the row is currently selected. * * @property selected * @type Boolean * @default false * @public */ selected: false, /** * Content for this row. See {{#crossLink "Ember.ObjectProxy"}}{{/crossLink}}. * * @property content * @type Object * @public */ content: null }); Row.reopenClass({ /** * @method create * @param {Object} content Content for this row. * @param {Object} options Properties to initialize in this object. * @return Row * @static */ create(content, options = {}) { let _options = assign({ content }, options); return this._super(_options); } }); export default Row;
Correct the note on vendor package path resolver.
// Takes a root path and an array of vendor package declarations and returns a // mapping of module names to absolute paths for the given packages. // It's similar to `require.resolve()` but resolves relative paths relative to // the given root directory instead of the current module's root. 'use strict'; var path = require('path'); var _ = require('lodash'); //////////////////////////////////////////////////////////////////////////////// module.exports = function (rootDir, vendorList) { var result = {}; _.forEach(vendorList || [], function (vendorPkg) { var asPair, depName, depPath, moduleName; if (_.isPlainObject(vendorPkg)) { asPair = _.pairs(vendorPkg); if (1 !== asPair.length) { throw 'Ill-formed list of vendor packages.'; } depName = asPair[0][0]; depPath = asPair[0][1]; } else { depName = depPath = vendorPkg; } moduleName = depPath.split(path.sep)[0]; if ('.' === moduleName || '..' === moduleName) { depPath = path.resolve(rootDir, depPath); } else { // WARNING: `require.resolve` searches for modules from 'nodeca.core' and // upper. If you embed any dependences into your application locally, // expect problems with "non-existent modules". depPath = require.resolve(depPath); } result[depName] = depPath; }); return result; };
// Takes a root path and an array of vendor package declarations and returns a // mapping of module names to absolute paths for the given packages. // It's similar to `require.resolve()` but resolves relative paths relative to // the given root directory instead of the current module's root. 'use strict'; var path = require('path'); var _ = require('lodash'); //////////////////////////////////////////////////////////////////////////////// module.exports = function (rootDir, vendorList) { var result = {}; _.forEach(vendorList || [], function (vendorPkg) { var asPair, depName, depPath, moduleName; if (_.isPlainObject(vendorPkg)) { asPair = _.pairs(vendorPkg); if (1 !== asPair.length) { throw 'Ill-formed list of vendor packages.'; } depName = asPair[0][0]; depPath = asPair[0][1]; } else { depName = depPath = vendorPkg; } moduleName = depPath.split(path.sep)[0]; if ('.' === moduleName || '..' === moduleName) { depPath = path.resolve(rootDir, depPath); } else { // Note `require.resolve` will look for a module relative to root // directory of `nodeca.core`. depPath = require.resolve(depPath); } result[depName] = depPath; }); return result; };
Fix mistake in previous commit.
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name PlacedItem * * @class The PlacedItem class is the base for any items that have a matrix * associated with them, describing their placement in the project, such as * {@link Raster} and {@link PlacedSymbol}. * * @extends Item */ var PlacedItem = this.PlacedItem = Item.extend(/** @lends PlacedItem# */{ // PlacedItem uses strokeBounds for bounds _boundsType: { bounds: 'strokeBounds' }, _hitTest: function(point, options, matrix) { var hitResult = this._symbol._definition.hitTest( this.matrix._transformPoint(point), options, matrix); // TODO: When the symbol's definition is a path, should hitResult contain // information like HitResult#curve? if (hitResult) hitResult.item = this; return hitResult; } });
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name PlacedItem * * @class The PlacedItem class is the base for any items that have a matrix * associated with them, describing their placement in the project, such as * {@link Raster} and {@link PlacedSymbol}. * * @extends Item */ var PlacedItem = this.PlacedItem = Item.extend(/** @lends PlacedItem# */{ // PlacedItem uses strokeBounds for bounds _boundsType: { bounds: 'strokeBounds' }, _hitTest: function(point, options, matrix) { var hitResult = this._symbol._definition.hitTest( point._transformPoint(this.matrix), options, matrix); // TODO: When the symbol's definition is a path, should hitResult contain // information like HitResult#curve? if (hitResult) hitResult.item = this; return hitResult; } });
Remove result of running demo.
package no.steria.skuldsku.example.basic.impl; import java.util.ArrayList; import java.util.List; import no.steria.skuldsku.example.basic.PlaceDao; public class InMemoryPlaceDao implements PlaceDao { private static List<String> places = new ArrayList<>(); private static void add(String name) { synchronized (places) { places.add(name); } } private static List<String> all() { synchronized (places) { return new ArrayList<>(places); } } @Override public void addPlace(String name) { InMemoryPlaceDao.add(name); } @Override public List<String> findMatches(String part) { if (part == null) { return all(); } ArrayList<String> result = new ArrayList<>(); for (String place : all()) { if (place.toUpperCase().contains(part.toUpperCase())) { result.add(place); } } return result; } }
package no.steria.skuldsku.example.basic.impl; import java.util.ArrayList; import java.util.List; import no.steria.skuldsku.example.basic.PlaceDao; public class InMemoryPlaceDao implements PlaceDao { private static List<String> places = new ArrayList<>(); private static void add(String name) { synchronized (places) { places.add(name); } } private static List<String> all() { synchronized (places) { return new ArrayList<>(places); } } @Override public void addPlace(String name) { //InMemoryPlaceDao.add(name); } @Override public List<String> findMatches(String part) { if (part == null) { return all(); } ArrayList<String> result = new ArrayList<>(); for (String place : all()) { if (place.toUpperCase().contains(part.toUpperCase())) { result.add(place); } } return result; } }
Fix Sieve of Eratosthenes Overview header
""" sieve_eratosthenes.py Implementation of the Sieve of Eratosthenes algorithm. Sieve of Eratosthenes Overview: ------------------------ Is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2. The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so). Time Complexity: O(n log log n) Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def eratosthenes(end,start=2): if start < 2: start = 2 primes = range(start,end) marker = 2 while marker < end: for i in xrange(marker, end+1): if marker*i in primes: primes.remove(marker*i) marker += 1 return primes
""" sieve_eratosthenes.py Implementation of the Sieve of Eratosthenes algorithm. Depth First Search Overview: ------------------------ Is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2. The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so). Time Complexity: O(n log log n) Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def eratosthenes(end,start=2): if start < 2: start = 2 primes = range(start,end) marker = 2 while marker < end: for i in xrange(marker, end+1): if marker*i in primes: primes.remove(marker*i) marker += 1 return primes
Set timeout to 20 seconds
""" Transport for Zuora SOAP API """ import httplib2 from suds.transport import Reply from suds.transport.http import HttpTransport from suds.transport.http import HttpAuthenticated class HttpTransportWithKeepAlive(HttpAuthenticated, object): def __init__(self): super(HttpTransportWithKeepAlive, self).__init__() self.http = httplib2.Http(timeout=20) def open(self, request): return HttpTransport.open(self, request) def send(self, request): headers, message = self.http.request(request.url, "POST", body=request.message, headers=request.headers) response = Reply(200, headers, message) return response
""" Transport for Zuora SOAP API """ import httplib2 from suds.transport import Reply from suds.transport.http import HttpTransport from suds.transport.http import HttpAuthenticated class HttpTransportWithKeepAlive(HttpAuthenticated, object): def __init__(self): super(HttpTransportWithKeepAlive, self).__init__() self.http = httplib2.Http(timeout=5) def open(self, request): return HttpTransport.open(self, request) def send(self, request): headers, message = self.http.request(request.url, "POST", body=request.message, headers=request.headers) response = Reply(200, headers, message) return response
Rename group variable in block to match the official name
package info.u_team.u_team_core.block; import info.u_team.u_team_core.api.registry.IBlockItemProvider; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; public class UBlock extends Block implements IBlockItemProvider { protected final BlockItem blockItem; public UBlock(Properties properties) { this(null, properties); } public UBlock(CreativeModeTab creativeTab, Properties properties) { this(creativeTab, properties, null); } public UBlock(Properties properties, Item.Properties blockItemProperties) { this(null, properties, blockItemProperties); } public UBlock(CreativeModeTab creativeTab, Properties properties, Item.Properties blockItemProperties) { super(properties); blockItem = createBlockItem(blockItemProperties == null ? new Item.Properties().tab(creativeTab) : creativeTab == null ? blockItemProperties : blockItemProperties.tab(creativeTab)); } protected BlockItem createBlockItem(Item.Properties blockItemProperties) { return new BlockItem(this, blockItemProperties); } @Override public BlockItem getBlockItem() { return blockItem; } }
package info.u_team.u_team_core.block; import info.u_team.u_team_core.api.registry.IBlockItemProvider; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; public class UBlock extends Block implements IBlockItemProvider { protected final BlockItem blockItem; public UBlock(Properties properties) { this(null, properties); } public UBlock(CreativeModeTab group, Properties properties) { this(group, properties, null); } public UBlock(Properties properties, Item.Properties blockItemProperties) { this(null, properties, blockItemProperties); } public UBlock(CreativeModeTab group, Properties properties, Item.Properties blockItemProperties) { super(properties); blockItem = createBlockItem(blockItemProperties == null ? new Item.Properties().tab(group) : group == null ? blockItemProperties : blockItemProperties.tab(group)); } protected BlockItem createBlockItem(Item.Properties blockItemProperties) { return new BlockItem(this, blockItemProperties); } @Override public BlockItem getBlockItem() { return blockItem; } }
Add nTopics to persp. jsd calculation file name
import logging import argparse import numpy as np from utils.experiment import load_config, get_corpus from utils.controversialissues import perspective_jsd_matrix logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) parser = argparse.ArgumentParser() parser.add_argument('json', help='json file containing experiment ' 'configuration.') args = parser.parse_args() config = load_config(args.json) corpus = get_corpus(config) nTopics = config.get('nTopics') perspectives = [p.name for p in corpus.perspectives] perspective_jsd = perspective_jsd_matrix(config, nTopics, perspectives) print perspective_jsd print perspective_jsd.sum(axis=(2, 1)) np.save(config.get('outDir').format('perspective_jsd_{}.npy'.format(nTopics)), perspective_jsd)
import logging import argparse import numpy as np from utils.experiment import load_config, get_corpus from utils.controversialissues import perspective_jsd_matrix logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) parser = argparse.ArgumentParser() parser.add_argument('json', help='json file containing experiment ' 'configuration.') args = parser.parse_args() config = load_config(args.json) corpus = get_corpus(config) nTopics = config.get('nTopics') perspectives = [p.name for p in corpus.perspectives] perspective_jsd = perspective_jsd_matrix(config, nTopics, perspectives) print perspective_jsd print perspective_jsd.sum(axis=(2, 1)) np.save(config.get('outDir').format('perspective_jsd.npy'), perspective_jsd)
Add the transaction mode to the reaction
package org.realityforge.arez.api2; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class Reaction extends Observer { /** * Flag indicating whether this reaction has been scheduled. i.e. has a pending reaction. */ private boolean _scheduled; /** * The transaction mode in which the action executes. */ @Nonnull private final TransactionMode _mode; Reaction( @Nonnull final ArezContext context, @Nullable final String name, @Nonnull final TransactionMode mode ) { super( context, name ); setOnStale( this::schedule ); _mode = Objects.requireNonNull( mode ); } /** * Return the transaction mode in which the action executes. * * @return the transaction mode in which the action executes. */ @Nonnull final TransactionMode getMode() { return _mode; } final boolean isScheduled() { return _scheduled; } final void schedule() { Guards.invariant( this::isActive, () -> String.format( "Observer named '%s' is not active but an attempt has been made to schedule observer.", getName() ) ); if ( !_scheduled ) { _scheduled = true; getContext().scheduleReaction( this ); } } }
package org.realityforge.arez.api2; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class Reaction extends Observer { /** * Flag indicating whether this reaction has been scheduled. i.e. has a pending reaction. */ private boolean _scheduled; Reaction( @Nonnull final ArezContext context, @Nullable final String name ) { super( context, name ); setOnStale( this::schedule ); } final boolean isScheduled() { return _scheduled; } final void schedule() { Guards.invariant( this::isActive, () -> String.format( "Observer named '%s' is not active but an attempt has been made to schedule observer.", getName() ) ); if ( !_scheduled ) { _scheduled = true; getContext().scheduleReaction( this ); } } }
Fix error after importing survey
import React, { Component } from 'react'; import { Button, Col, Container, Row } from 'reactstrap'; import { connect } from 'react-redux'; import L from 'utils/Labels' import RouterUtils from 'utils/RouterUtils' import SurveyImportForm from './SurveyImportForm'; class SurveyImportPage extends Component { constructor(props) { super(props) } componentWillReceiveProps(nextProps) { if (nextProps.surveyFileImported) { RouterUtils.navigateToSurveyEditPage(this.props.history, nextProps.importedSurveyId) } } render() { return ( <Container fluid> <Row> <Col md={{ size: 6, offset: 3 }}> <SurveyImportForm style={{width: "500px"}} /> </Col> </Row> </Container> ) } } const mapStateToProps = state => { const { surveyFileImported, importedSurveyId } = state.surveys return { surveyFileImported, importedSurveyId } } export default connect(mapStateToProps)(SurveyImportPage)
import React, { Component } from 'react'; import { Button, Col, Container, Row } from 'reactstrap'; import { connect } from 'react-redux'; import L from 'utils/Labels' import RouterUtils from 'utils/RouterUtils' import SurveyImportForm from './SurveyImportForm'; class SurveyImportPage extends Component { constructor(props) { super(props) } componentWillReceiveProps(nextProps) { if (nextProps.surveyFileImported) { RouterUtils.navigateToSurveyEditPage(this.props.history, nextProps.importedSurveyId) } } render() { return ( <Container fluid> <Row> <Col md={{ size: 6, offset: 3 }}> <SurveyImportForm style={{width: "500px"}} /> </Col> </Row> </Container> ) } } const mapStateToProps = state => { const { surveyFileImported } = state.surveys return { surveyFileImported } } export default connect(mapStateToProps)(SurveyImportPage)
Fix Base64 encoded secret length check
import { getSelectedAlgorithm } from "./utils.js"; import { secretInput, secretBase64Checkbox } from "../dom-elements.js"; import log from "loglevel"; import tippy from "tippy.js"; import b64u from "base64url"; export function minSecretLengthCheck(event) { const alg = getSelectedAlgorithm(); if (alg.indexOf("HS") !== 0) { log.error(`Secret input tooltip handler for wrong algorithm: ${alg}`); return; } const algBits = parseInt(alg.substr(2)); const inputBits = secretBase64Checkbox.checked ? b64u.toBuffer(secretInput.value).length * 8 : Buffer.from(secretInput.value).length * 8; if (inputBits < algBits) { if (!secretInput._tippy.state.visible) { secretInput._tippy.show(); } } else { secretInput._tippy.hide(); } } export function setupSecretLengthTooltip() { tippy(secretInput, { trigger: "manual", placement: "right", arrow: true, arrowTransform: "scale(0.75)", size: "large", }); }
import { getSelectedAlgorithm } from './utils.js'; import { secretInput, secretBase64Checkbox, } from '../dom-elements.js'; import log from 'loglevel'; import tippy from 'tippy.js'; import b64u from 'base64url'; export function minSecretLengthCheck(event) { const alg = getSelectedAlgorithm(); if(alg.indexOf('HS') !== 0) { log.error(`Secret input tooltip handler for wrong algorithm: ${alg}`); return; } const algBits = parseInt(alg.substr(2)); const inputBits = secretBase64Checkbox.checked ? b64u.decode(secretInput.value).length * 8 : Buffer.from(secretInput.value).length * 8; if(inputBits < algBits) { if(!secretInput._tippy.state.visible) { secretInput._tippy.show(); } } else { secretInput._tippy.hide(); } } export function setupSecretLengthTooltip() { tippy(secretInput, { trigger: 'manual', placement: 'right', arrow: true, arrowTransform: 'scale(0.75)', size: 'large' }); }
Allow skipping the ContactDetails step if users are logged in, with correct info already provided.
<?php class CheckoutStep_ContactDetails extends CheckoutStep{ private static $allowed_actions = array( 'contactdetails', 'ContactDetailsForm' ); public function contactdetails() { $form = $this->ContactDetailsForm(); $form->loadDataFrom(Member::currentUser()); if( ShoppingCart::curr() && Config::inst()->get("CheckoutStep_ContactDetails", "skip_if_logged_in") && $form->validate() ){ Controller::curr()->redirect($this->NextStepLink()); return; } return array( 'OrderForm' => $form ); } public function ContactDetailsForm() { $cart = ShoppingCart::curr(); if(!$cart){ return false; } $config = new CheckoutComponentConfig(ShoppingCart::curr()); $config->addComponent(new CustomerDetailsCheckoutComponent()); $form = new CheckoutForm($this->owner, 'ContactDetailsForm', $config); $form->setRedirectLink($this->NextStepLink()); $form->setActions(new FieldList( new FormAction("checkoutSubmit", "Continue") )); $this->owner->extend('updateContactDetailsForm', $form); return $form; } }
<?php class CheckoutStep_ContactDetails extends CheckoutStep{ private static $allowed_actions = array( 'contactdetails', 'ContactDetailsForm' ); public function contactdetails() { return array( 'OrderForm' => $this->ContactDetailsForm() ); } public function ContactDetailsForm() { $cart = ShoppingCart::curr(); if(!$cart){ return false; } $config = new CheckoutComponentConfig(ShoppingCart::curr()); $config->addComponent(new CustomerDetailsCheckoutComponent()); $form = new CheckoutForm($this->owner, 'ContactDetailsForm', $config); $form->setRedirectLink($this->NextStepLink()); $form->setActions(new FieldList( new FormAction("checkoutSubmit", "Continue") )); $this->owner->extend('updateContactDetailsForm', $form); return $form; } }
TBR: Fix circ dep issue with cbuildbot
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot_comm import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
Rename style property to match usage
import React, {Component} from 'react' import {StyleSheet, View, Text, TouchableHighlight} from 'react-native' import TabButton from './TabButton' export default class extends Component { state = {activeTab: 0} render = () => ( <View style={{flex: 1}}> <View style={Styles.tabWrapper}> { this.props.tabs.map(({title}, key) => { return <TabButton key={key} index={key} text={title} activeTab={this.state.activeTab} changeTab={this.changeTab.bind(this)} /> }) } </View> {this.renderTab()} </View> ) renderTab = () => ( this.props.tabs.map((tab, key) => { if (key == this.state.activeTab) { const ContentView = tab.content return <ContentView key={key}/> } }) ) changeTab = (key) => this.setState({activeTab: key}) } const Styles = StyleSheet.create({ tabWrapper: { flexDirection: 'row', alignSelf: 'stretch', alignContent: 'stretch', justifyContent: 'space-between', height: 40 } })
import React, {Component} from 'react' import {StyleSheet, View, Text, TouchableHighlight} from 'react-native' import TabButton from './TabButton' export default class extends Component { state = {activeTab: 0} render = () => ( <View style={{flex: 1}}> <View style={Styles.QuestionTypes}> { this.props.tabs.map(({title}, key) => { return <TabButton key={key} index={key} text={title} activeTab={this.state.activeTab} changeTab={this.changeTab.bind(this)} /> }) } </View> {this.renderTab()} </View> ) renderTab = () => ( this.props.tabs.map((tab, key) => { if (key == this.state.activeTab) { const ContentView = tab.content return <ContentView key={key}/> } }) ) changeTab = (key) => this.setState({activeTab: key}) } const Styles = StyleSheet.create({ QuestionTypes: { flexDirection: 'row', alignSelf: 'stretch', alignContent: 'stretch', justifyContent: 'space-between', height: 40 } })
Add var declaration to avoid global variable scope
var addTextLabel = require("./add-text-label"), addHtmlLabel = require("./add-html-label"), addSVGLabel = require("./add-svg-label"); module.exports = addLabel; function addLabel(root, node, location) { var label = node.label; var labelSvg = root.append("g"); // Allow the label to be a string, a function that returns a DOM element, or // a DOM element itself. if (node.labelType === "svg") { addSVGLabel(labelSvg, node); } else if (typeof label !== "string" || node.labelType === "html") { addHtmlLabel(labelSvg, node); } else { addTextLabel(labelSvg, node); } var labelBBox = labelSvg.node().getBBox(); var y; switch(location) { case "top": y = (-node.height / 2); break; case "bottom": y = (node.height / 2) - labelBBox.height; break; default: y = (-labelBBox.height / 2); } labelSvg.attr("transform", "translate(" + (-labelBBox.width / 2) + "," + y + ")"); return labelSvg; }
var addTextLabel = require("./add-text-label"), addHtmlLabel = require("./add-html-label"), addSVGLabel = require("./add-svg-label"); module.exports = addLabel; function addLabel(root, node, location) { var label = node.label; var labelSvg = root.append("g"); // Allow the label to be a string, a function that returns a DOM element, or // a DOM element itself. if (node.labelType === "svg") { addSVGLabel(labelSvg, node); } else if (typeof label !== "string" || node.labelType === "html") { addHtmlLabel(labelSvg, node); } else { addTextLabel(labelSvg, node); } var labelBBox = labelSvg.node().getBBox(); switch(location) { case "top": y = (-node.height / 2); break; case "bottom": y = (node.height / 2) - labelBBox.height; break; default: y = (-labelBBox.height / 2); } labelSvg.attr("transform", "translate(" + (-labelBBox.width / 2) + "," + y + ")"); return labelSvg; }
Use moment instead of new Date for timestamps Summary: new Date has inconsistent behavior between browsers: chrome assumes its input is utc by default, while firefox assumes its the local time. Just use moment instead. https://tails.corp.dropbox.com/F196477 Test Plan: see screenshot Reviewers: haoyi, josiah Reviewed By: josiah Subscribers: changesbot, mkedia Differential Revision: https://tails.corp.dropbox.com/D118110
define([ 'app', 'utils', 'moment', 'bootstrap/tooltip' ], function(app, utils, moment, tooltip_func) { 'use strict'; // we use a shared timeout for the page loop to avoid // extremely large amounts of $digest cycles and wasteful // amounts of defers window.setInterval(function(){ $('.ng-timesince').each(function(_, element){ var $element = angular.element(element), value = $element.data('datetime'); $element.text(utils.time.timeSince(value)); }); }, 1000); app.directive('timeSince', ['$timeout', function($timeout) { return function timeSince(scope, element, attrs) { var tagname = element[0].tagName.toLowerCase(); if (tagname == 'td' || tagname == 'dd') { var err = "applying the timeSince directive to <" + tagname + "> tags" + " can cause rendering issues. Instead, please put this on an" + " inner <span> tag"; console.warn(err); } var value = scope.$eval(attrs.timeSince); element.addClass('ng-timesince'); element.data('datetime', value); element.attr('title', moment.utc(value).toString()); element.attr('data-placement', 'left'); tooltip_func.bind(element)(); }; }]); });
define([ 'app', 'utils', 'bootstrap/tooltip' ], function(app, utils, tooltip_func) { 'use strict'; // we use a shared timeout for the page loop to avoid // extremely large amounts of $digest cycles and wasteful // amounts of defers window.setInterval(function(){ $('.ng-timesince').each(function(_, element){ var $element = angular.element(element), value = $element.data('datetime'); $element.text(utils.time.timeSince(value)); }); }, 1000); app.directive('timeSince', ['$timeout', function($timeout) { return function timeSince(scope, element, attrs) { var tagname = element[0].tagName.toLowerCase(); if (tagname == 'td' || tagname == 'dd') { var err = "applying the timeSince directive to <" + tagname + "> tags" + " can cause rendering issues. Instead, please put this on an" + " inner <span> tag"; console.warn(err); } var value = scope.$eval(attrs.timeSince); element.addClass('ng-timesince'); element.data('datetime', value); element.attr('title', (new Date(value)).toUTCString()); element.attr('data-placement', 'left'); tooltip_func.bind(element)(); }; }]); });
Convert `Metadata` to use private `class` fields Please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { objectFromMap } from "../shared/util.js"; class Metadata { #metadataMap; #data; constructor({ parsedData, rawData }) { this.#metadataMap = parsedData; this.#data = rawData; } getRaw() { return this.#data; } get(name) { return this.#metadataMap.get(name) ?? null; } getAll() { return objectFromMap(this.#metadataMap); } has(name) { return this.#metadataMap.has(name); } } export { Metadata };
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { objectFromMap } from "../shared/util.js"; class Metadata { constructor({ parsedData, rawData }) { this._metadataMap = parsedData; this._data = rawData; } getRaw() { return this._data; } get(name) { return this._metadataMap.get(name) ?? null; } getAll() { return objectFromMap(this._metadataMap); } has(name) { return this._metadataMap.has(name); } } export { Metadata };
Remove commas. Add name to each army
// import actions from '../actions/ArmyActionCreators' import gameActions from '../actions/GameActionCreators' const initialState = { armies: { '0': { id: '0', owner: 'albertoblaz', name: 'Grande Armée', provinceId: '22', }, '1': { id: '1', owner: 'albertoblaz', name: '2nd Republican Army', provinceId: '23', }, '2': { id: '2', owner: 'adriantom3', name: 'Imperial Army', provinceId: '32', }, }, } const handlers = { [gameActions.START_GAME]: (state) => Object.assign({}, state, initialState), } export default (reducer) => (state = initialState, action) => reducer(handlers, state, action)
import actions from '../actions/ArmyActionCreators' import gameActions from '../actions/GameActionCreators' const initialState = { armies: { '0': { 'id': '0', 'owner': 'albertoblaz', 'provinceId': '22', }, '1': { 'id': '1', 'owner': 'albertoblaz', 'provinceId': '23', }, '2': { 'id': '2', 'owner': 'adriantom3', 'provinceId': '32', }, }, } const handlers = { [gameActions.START_GAME]: (state) => Object.assign({}, state, initialState), } export default (reducer) => (state = initialState, action) => reducer(handlers, state, action)
Set a default width and height Set the default width and height for the resize mixin to be 0 so that we don't get error resulting from undefined values in the SVG viewBox attribute.
/* global window */ 'use strict'; var dom = require('util/dom'); module.exports = { paramAttributes: [ 'data-aspect' ], data: function () { return { aspect: 1, height: 0, width : 0 }; }, ready: function () { window.addEventListener('resize', this.onResize); }, computed: { viewBox: function () { return '0 0 ' + this.width + ' ' + this.height; } }, methods: { onResize: function () { if (!this.$el || !this.$el.parentElement) { return; } var content = dom.contentArea(this.$el.parentElement); this.$set('width', content.width); if (this.aspect) { this.$set('height', content.width / Number(this.aspect)); } this.$emit('invalidate-size'); } }, events: { 'hook:attached': function () { this.onResize(); } } };
/* global window */ 'use strict'; var dom = require('util/dom'); module.exports = { paramAttributes: [ 'data-aspect' ], data: function () { return { aspect: 1 }; }, ready: function () { window.addEventListener('resize', this.onResize); }, computed: { viewBox: function () { return '0 0 ' + this.width + ' ' + this.height; } }, methods: { onResize: function () { if (!this.$el || !this.$el.parentElement) { return; } var content = dom.contentArea(this.$el.parentElement); this.$set('width', content.width); if (this.aspect) { this.$set('height', content.width / Number(this.aspect)); } this.$emit('invalidate-size'); } }, events: { 'hook:attached': function () { this.onResize(); } } };
Add 'period' query param to news page
const express = require('express'); const router = express.Router(); const Media = require('../lib/models/media'); const decorate = require('../lib/decorate/index'); const render = require('../lib/push/render'); const tmdbApi = require('moviedb'); router.get('/', (req, res, next) => { const opts = { baseUrl: process.env.BASE_URL, replyTo: process.env.MAIL_REPLY_TO, premailer: false, api: tmdbApi(process.env.TMBDP_API_KEY), }; let period = 1; // days if (req.query && req.query.period) { const int = parseInt(req.query.period, 10); if (int > 1 && int < 7) { period = req.query.period; } } let added; let removed; Media.retrieveAdded(period) .then(docs => decorate(docs, opts)) .then(docs => { added = docs; }) .then(() => Media.retrieveRemoved(period)) .then(docs => { removed = docs; }) .then(() => render(added, removed, opts)) .then(html => res.end(html)) .catch(err => next(err)); }); module.exports = router;
const express = require('express'); const router = express.Router(); const Media = require('../lib/models/media'); const decorate = require('../lib/decorate/index'); const render = require('../lib/push/render'); const tmdbApi = require('moviedb'); /* GET home page. */ router.get('/', (req, res, next) => { const opts = { baseUrl: process.env.BASE_URL, replyTo: process.env.MAIL_REPLY_TO, premailer: false, api: tmdbApi(process.env.TMBDP_API_KEY), }; const period = 1; // day let added; let removed; Media.retrieveAdded(period) .then(docs => decorate(docs, opts)) .then(docs => { added = docs; }) .then(() => Media.retrieveRemoved(period)) .then(docs => { removed = docs; }) .then(() => render(added, removed, opts)) .then(html => res.end(html)) .catch(err => next(err)); }); module.exports = router;
[AC-9046] Fix filter for people and mentor urls
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = "/people" mentor_url = "/directory" community_url = "/community" SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') for siteredirectpage in SiteRedirectPage.objects.all(): has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)) if has_old_url.exists(): has_old_url.update(new_url=community_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations def update_url_to_community(apps, schema_editor): people_url = "/people" mentor_url = "/directory" community_url = "/community" SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') for siteredirectpage in SiteRedirectPage.objects.all(): has_old_url = siteredirectpage.objects.filter(new_url=people_url).filter(new_url=mentor_url) if has_old_url.exists(): has_old_url.update(new_url=community_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
Set data-old attribute automatically via JavaScript.
jQuery(function($) { $('.setting .js-save-on-change').each(function () { var $field = $(this); $field.closest('.setting').data('old', $field.val()); }); $(document).on('change', '.js-save-on-change', function() { var $field = $(this); var name = $field.attr('name'); var value = $field.val(); $field.closest('.setting').trigger('changed', [name, value]); }); $(document).on('changed', '.setting', function(event, name, value) { var $setting = $(this); var old = $setting.data('old'); $setting.removeClass('saved').addClass('saving'); if (old !== value) { FluxBB.ajax('POST', 'admin/settings/' + name, { value: value }).success(function(data) { $setting.data('old', value); $setting.addClass('saved'); }).always(function() { $setting.removeClass('saving'); }); } }); });
jQuery(function($) { $(document).on('change', '.js-save-on-change', function() { var $field = $(this); var name = $field.attr('name'); var value = $field.val(); $field.closest('.setting').trigger('changed', [name, value]); }); $(document).on('changed', '.setting', function(event, name, value) { var $setting = $(this); var old = $setting.data('old'); $setting.removeClass('saved').addClass('saving'); if (old !== value) { FluxBB.ajax('POST', 'admin/settings/' + name, { value: value }).success(function(data) { $setting.data('old', value); $setting.addClass('saved'); }).always(function() { $setting.removeClass('saving'); }); } }); });
Make sure plugins' .name property gets set
# Copyright 2013 John Reese # Licensed under the MIT license import importlib import os from functools import lru_cache from os import path from .base import Plugin @lru_cache() def load_plugins(config): """Import all the plugins, and return a set of plugin instances, filtering out any plugin whose name appears in the configurable blacklist.""" plugins = set(plugin(config=config) for plugin in Plugin.subclasses()) for plugin in plugins: if plugin.name in config.plugin_blacklist: plugins.remove(plugin) return plugins # import plugins cwd = path.abspath(path.dirname(__file__)) files = os.listdir(cwd) for filename in files: name, ext = path.splitext(filename) if name.startswith('_'): continue if ext == '.py': module = importlib.import_module('ircstat.plugins.' + name) for name, item in module.__dict__.items(): if type(item) == type and issubclass(item, Plugin): item.name = item.__name__ if item.name.endswith('Plugin'): item.name = item.name[:-6]
# Copyright 2013 John Reese # Licensed under the MIT license import importlib import os from functools import lru_cache from os import path from .base import Plugin @lru_cache() def load_plugins(config): """Import all the plugins, and return a set of plugin instances, filtering out any plugin whose name appears in the configurable blacklist.""" cwd = path.abspath(path.dirname(__file__)) files = os.listdir(cwd) for filename in files: name, ext = path.splitext(filename) if name.startswith('_'): continue if ext == '.py': importlib.import_module('ircstat.plugins.' + name) plugins = set(plugin() for plugin in Plugin.subclasses()) for plugin in plugins: if plugin.name in config.plugin_blacklist: plugins.remove(plugin) return plugins
Remove expression which breaks javac.
package com.redhat.ceylon.compiler.java.runtime.metamodel; import ceylon.language.meta.declaration.CallableConstructorDeclaration; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor; @Ceylon(major = 8) @com.redhat.ceylon.compiler.java.metadata.Class public class FreeClassWithConstructors extends FreeClass implements ceylon.language.meta.declaration.ClassWithConstructorsDeclaration { @Ignore public final static TypeDescriptor $TypeDescriptor$ = TypeDescriptor.klass(FreeClassWithConstructors.class); public FreeClassWithConstructors(com.redhat.ceylon.model.typechecker.model.Class declaration) { super(declaration); } //@Override @Ignore public ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl $ceylon$language$meta$declaration$ClassWithConstructorsDeclaration$impl() { return null;//new ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl(this); } @Ignore @Override public TypeDescriptor $getType$() { return $TypeDescriptor$; } @Override public CallableConstructorDeclaration getDefaultConstructor() { return (CallableConstructorDeclaration)getConstructorDeclaration(""); } }
package com.redhat.ceylon.compiler.java.runtime.metamodel; import ceylon.language.meta.declaration.CallableConstructorDeclaration; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor; @Ceylon(major = 8) @com.redhat.ceylon.compiler.java.metadata.Class public class FreeClassWithConstructors extends FreeClass implements ceylon.language.meta.declaration.ClassWithConstructorsDeclaration { @Ignore public final static TypeDescriptor $TypeDescriptor$ = TypeDescriptor.klass(FreeClassWithConstructors.class); public FreeClassWithConstructors(com.redhat.ceylon.model.typechecker.model.Class declaration) { super(declaration); } @Override @Ignore public ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl $ceylon$language$meta$declaration$ClassWithConstructorsDeclaration$impl() { return new ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl(this); } @Ignore @Override public TypeDescriptor $getType$() { return $TypeDescriptor$; } @Override public CallableConstructorDeclaration getDefaultConstructor() { return (CallableConstructorDeclaration)getConstructorDeclaration(""); } }
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-white-space/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/typography/white-space/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-white-space/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/white-space/index.html', html)
Use the standard pathlib after Python 3.4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Setup script for csft """ import sys from setuptools import find_packages, setup import csft requires = [ 'argparse >= 1.2.1', 'pandas >= 0.20.1', ] if sys.version < '3.4': requires.append('pathlib >= 1.0.1') if sys.version < '3.5': requires.append('scandir >= 1.5') setup( name=csft.__name__, description=csft.__doc__, version=csft.__version__, author=csft.__author__, license=csft.__license__, author_email=csft.__email__, url=csft.__url__, packages=find_packages(), entry_points={ 'console_scripts': ( 'csft = csft.__main__:main', ), }, install_requires=requires, )
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Setup script for csft """ import sys from setuptools import find_packages, setup import csft requires = [ 'argparse >= 1.2.1', 'pandas >= 0.20.1', 'pathlib >= 1.0.1', ] if sys.version <= '3.5': requires.append('scandir >= 1.5') setup( name=csft.__name__, description=csft.__doc__, version=csft.__version__, author=csft.__author__, license=csft.__license__, author_email=csft.__email__, url=csft.__url__, packages=find_packages(), entry_points={ 'console_scripts': ( 'csft = csft.__main__:main', ), }, install_requires=requires, )
bugfix: Remove plugins configured with `severity: 0` from reports
var _ = require('lodash'); module.exports = function(ast, filePath, plugins) { var errors = [], warnings = []; _.each(plugins, function(plugin){ var results = plugin.test(ast, filePath, plugin.options), array; if (!results || !results.length || !_.isArray(results)){ return; } if (plugin.severity === 2) { array = errors; } else if (plugin.severity === 1) { array = warnings; } else { return; } // Remove failures that are on plugins with inline configs _.each(results, function (result){ if (!result.node || !result.node.ruleConfig) { return; } if (result.node.ruleConfig[plugin.name] === false) { results = _.without(results, result); } }); _.each(results, function(result){ array.push({ plugin: _.pick(plugin, ['name', 'message', 'severity']), error: result }); }); }); return { errors : errors, warnings : warnings }; };
var _ = require('lodash'); module.exports = function(ast, filePath, plugins) { var errors = [], warnings = []; _.each(plugins, function(plugin){ var results = plugin.test(ast, filePath, plugin.options), array; if (!results || !results.length || !_.isArray(results)){ return; } if (plugin.severity === 2) { array = errors; } else { array = warnings; } // Remove failures that are on plugins with inline configs _.each(results, function (result){ if (!result.node || !result.node.ruleConfig) { return; } if (result.node.ruleConfig[plugin.name] === false) { results = _.without(results, result); } }); _.each(results, function(result){ array.push({ plugin: _.pick(plugin, ['name', 'message', 'severity']), error: result }); }); }); return { errors : errors, warnings : warnings }; };
Fix passing of environment flag
#!/usr/bin/env node const UI = require('console-ui'); const cli = require('cli'); const Project = require('../models/project'); const CommandFactory = require('../commands/command-factory'); const discovery = require('../tasks/discover'); let options = cli.parse({ environment: [ 'e', 'A configured deployment environment, i.e. "staging", "production".', 'string', 'production'], verbose: ['v', 'Toggle verbosity', 'bool', false], revision: ['r', '("activate" only) revision to activate', 'string', false], activate: ['a', '("deploy" only) directly activate the deployed revision', 'bool', false] }, ['deploy', 'list', 'activate']); let ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, writeLevel: 'INFO' }); let commandFactory = new CommandFactory(); discovery.list().then(function(dependencies) { let project = new Project(dependencies, ui); commandFactory.run(cli.command, project, options); }).catch(function(error) { console.log((error && error.message) ? '[ERROR] -- ' + error.message : error); });
#!/usr/bin/env node const UI = require('console-ui'); const cli = require('cli'); const Project = require('../models/project'); const CommandFactory = require('../commands/command-factory'); const discovery = require('../tasks/discover'); let options = cli.parse({ environment: [ 'e', 'A configured deployment environment, i.e. "staging", "production".', 'environment', 'production'], verbose: ['v', 'Toggle verbosity', 'bool', false], revision: ['r', '("activate" only) revision to activate', 'string', false], activate: ['a', '("deploy" only) directly activate the deployed revision', 'bool', false] }, ['deploy', 'list', 'activate']); let ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, writeLevel: 'INFO' }); let commandFactory = new CommandFactory(); discovery.list().then(function(dependencies) { let project = new Project(dependencies, ui); commandFactory.run(cli.command, project, options); }).catch(function(error) { console.log((error && error.message) ? '[ERROR] -- ' + error.message : error); });
Check 'role_list' before sending it to little_chef
"""Dashboard template filters""" from django import template import littlechef from kitchen.settings import REPO register = template.Library() @register.filter(name='get_role_list') def get_role_list(run_list): """Returns the role sublist from the given run_list""" if run_list: all_roles = littlechef.lib.get_roles_in_node( {'run_list': run_list}) role_list = [] for role in all_roles: if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX']): # Only add if it doesn't start with excluded role prefixes role_list.append(role) return role_list else: return [] @register.filter(name='get_recipe_list') def get_recipe_list(run_list): """Returns the recipe sublist from the given run_list""" if run_list: return littlechef.lib.get_recipes_in_node({'run_list': run_list}) else: return []
"""Dashboard template filters""" from django import template import littlechef from kitchen.settings import REPO register = template.Library() @register.filter(name='get_role_list') def get_role_list(run_list): """Returns the role sublist from the given run_list""" prev_role_list = littlechef.lib.get_roles_in_node({'run_list': run_list}) role_list = [] for role in prev_role_list: if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX']): # Only add if it doesn't start with excluded role prefixes role_list.append(role) return role_list @register.filter(name='get_recipe_list') def get_recipe_list(run_list): """Returns the recipe sublist from the given run_list""" return littlechef.lib.get_recipes_in_node({'run_list': run_list})
Fix RelaxNG tests in CE
/* * Copyright 2007 Sascha Weinreuter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.relaxNG; import com.intellij.testFramework.ParsingTestCase; import com.intellij.testFramework.PlatformTestUtil; import org.intellij.plugins.relaxNG.compact.RncParserDefinition; /* * Created by IntelliJ IDEA. * User: sweinreuter * Date: 24.08.2007 */ public abstract class AbstractParsingTest extends ParsingTestCase { public AbstractParsingTest(String s) { super("psi/" + s, "rnc", new RncParserDefinition()); } protected String getTestDataPath() { return PlatformTestUtil.getCommunityPath() + "/xml/relaxng/testData/parsing"; } }
/* * Copyright 2007 Sascha Weinreuter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.relaxNG; import com.intellij.openapi.application.PathManager; import com.intellij.testFramework.ParsingTestCase; import org.intellij.plugins.relaxNG.compact.RncParserDefinition; /* * Created by IntelliJ IDEA. * User: sweinreuter * Date: 24.08.2007 */ public abstract class AbstractParsingTest extends ParsingTestCase { public AbstractParsingTest(String s) { super("psi/"+s, "rnc", new RncParserDefinition()); } protected String getTestDataPath() { return PathManager.getHomePath() + "/community/xml/relaxng/testData/parsing"; } }
Fix returning to current nodes when clearing searching
(function() { 'use strict'; function sequoiaSearchDirective(){ return { restrict: 'AE', replace: true, templateUrl: 'sequoia-search.html', scope: { 'tree': '=', 'isSearching': '=' }, link: function(scope) { scope.search = function() { if(scope.query.length) { scope.isSearching = scope.query ? true : false; scope.tree.setNodesInPath(scope.tree.nodes); scope.tree.setCurrentNodes(scope.tree.find(scope.tree.template.title, scope.query)); } else { scope.clear(); } }; scope.clear = function() { scope.query = ''; scope.isSearching = false; scope.tree.setCurrentNodes(scope.tree.getNodesInPath()); }; } }; } angular.module('ngSequoia') .directive('sequoiaSearch', sequoiaSearchDirective); })();
(function() { 'use strict'; function sequoiaSearchDirective(){ return { restrict: 'AE', replace: true, templateUrl: 'sequoia-search.html', scope: { 'tree': '=', 'isSearching': '=' }, link: function(scope) { scope.search = function() { if(scope.query.length) { scope.isSearching = scope.query ? true : false; scope.tree.setCurrentNodes(scope.tree.find(scope.tree.template.title, scope.query)); } else { scope.clear(); } }; scope.clear = function() { scope.query = ''; scope.isSearching = false; scope.tree.setCurrentNodes(); }; } }; } angular.module('ngSequoia') .directive('sequoiaSearch', sequoiaSearchDirective); })();
Exclude 'spec' package from installation. This prevents some weird behavior when running specs for another package because mamba will load its own spec package since is first in the PYTHONPATH.
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from mamba import __version__ setup(name='mamba', version=__version__, description="The definitive testing tool for Python. Born under the banner of Behavior Driven Development.", long_description=open('README.md').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing' ], keywords='', author=u'Néstor Salceda', author_email='nestor.salceda@gmail.com', url='http://nestorsalceda.github.io/mamba', license='MIT/X11', packages=find_packages(exclude=['ez_setup', 'examples', 'spec', 'spec.*']), include_package_data=True, zip_safe=False, install_requires=[line for line in open('requirements.txt')], entry_points={ 'console_scripts': [ 'mamba = mamba.cli:main' ] })
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from mamba import __version__ setup(name='mamba', version=__version__, description="The definitive testing tool for Python. Born under the banner of Behavior Driven Development.", long_description=open('README.md').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing' ], keywords='', author=u'Néstor Salceda', author_email='nestor.salceda@gmail.com', url='http://nestorsalceda.github.io/mamba', license='MIT/X11', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[line for line in open('requirements.txt')], entry_points={ 'console_scripts': [ 'mamba = mamba.cli:main' ] })
Add a route to ownedMangas
var subscriptions = new SubsManager(); Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound' }); Router.route('/', { name: 'home', fastRender: true }); Router.route('/ownedMangas', { name: 'ownedMangas', waitOn: function() { return subscriptions.subscribe('allOwnedMangas', Meteor.userId()); } }); Router.route('/missingMangas', { name: 'missingMangas', waitOn: function() { return subscriptions.subscribe('allMissingMangas', Meteor.userId()); } }); Router.route('/:mangasName/tome/:tomeNumber/:_id', { name: 'tomeDetails', waitOn: function() { return [subscriptions.subscribe('tomeDetails', this.params._id), subscriptions.subscribe('allTomes', Meteor.userId(), this.params.mangasName)]; }, data: function() { return Mangas.findOne(this.params._id); } }); Router.route('/:author', { name: 'mangaka', waitOn: function() { return subscriptions.subscribe('mangaka', Meteor.userId(), this.params.author); } });
var subscriptions = new SubsManager(); Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound' }); Router.route('/', { name: 'home', waitOn: function() { return subscriptions.subscribe('allOwnedMangas', Meteor.userId()); }, fastRender: true }); Router.route('/missingMangas', { name: 'missingMangas', waitOn: function() { return subscriptions.subscribe('allMissingMangas', Meteor.userId()); } }); Router.route('/:mangasName/tome/:tomeNumber/:_id', { name: 'tomeDetails', waitOn: function() { return [subscriptions.subscribe('tomeDetails', this.params._id), subscriptions.subscribe('allTomes', Meteor.userId(), this.params.mangasName)]; }, data: function() { return Mangas.findOne(this.params._id); } }); Router.route('/:author', { name: 'mangaka', waitOn: function() { return subscriptions.subscribe('mangaka', Meteor.userId(), this.params.author); } });
Move log enabling out of submodule
# __BEGIN_LICENSE__ # Copyright (C) 2008-2010 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # __END_LICENSE__ """ This app may define some new parameters that can be modified in the Django settings module. Let's say one such parameter is XGDS_DATA_FOO. The default value for XGDS_DATA_FOO is defined in this file, like this: XGDS_DATA_FOO = 'my default value' If the admin for the site doesn't like the default value, they can override it in the site-level settings module, like this: XGDS_DATA_FOO = 'a better value' Other modules can access the value of FOO like this: from xgds_data import settings print settings.XGDS_DATA_FOO Don't try to get the value of XGDS_DATA_FOO from django.conf.settings. That settings object will not know about the default value! """ # choose models to support in siteSettings.py. mostly obsolete. XGDS_DATA_SEARCH_MODELS = () # choose django apps not to list for search purposes XGDS_DATA_SEARCH_SKIP_APP_PATTERNS = ( r'^django\..*', r'^geocam.*', r'^pipeline$', ) # XGDS_DATA_LOG_ENABLED = False
# __BEGIN_LICENSE__ # Copyright (C) 2008-2010 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # __END_LICENSE__ """ This app may define some new parameters that can be modified in the Django settings module. Let's say one such parameter is XGDS_DATA_FOO. The default value for XGDS_DATA_FOO is defined in this file, like this: XGDS_DATA_FOO = 'my default value' If the admin for the site doesn't like the default value, they can override it in the site-level settings module, like this: XGDS_DATA_FOO = 'a better value' Other modules can access the value of FOO like this: from xgds_data import settings print settings.XGDS_DATA_FOO Don't try to get the value of XGDS_DATA_FOO from django.conf.settings. That settings object will not know about the default value! """ # choose models to support in siteSettings.py. mostly obsolete. XGDS_DATA_SEARCH_MODELS = () # choose django apps not to list for search purposes XGDS_DATA_SEARCH_SKIP_APP_PATTERNS = ( r'^django\..*', r'^geocam.*', r'^pipeline$', ) XGDS_DATA_LOG_ENABLED = False
Fix class-level constants in PHP.
<?php /* NOTE: This module requires bson_encode() and bson_decode(), which can be obtained by installing the MongoDB driver. For example, on Debian/Ubuntu: $ sudo apt-get install php5-mongo */ require_once('gorpc.php'); class BsonRpcClient extends GoRpcClient { const LEN_PACK_FORMAT = 'V'; const LEN_PACK_SIZE = 4; protected function send_request(GoRpcRequest $req) { $this->write(bson_encode($req->header)); $this->write(bson_encode($req->body)); } protected function read_response() { // Read the header. $data = $this->read_n(self::LEN_PACK_SIZE); $len = unpack(self::LEN_PACK_FORMAT, $data)[0]; $header = $data . $this->read_n($len - self::LEN_PACK_SIZE); // Read the body. $data = $this->read_n(self::LEN_PACK_SIZE); $len = unpack(self::LEN_PACK_FORMAT, $data)[0]; $body = $data . $this->read_n($len - self::LEN_PACK_SIZE); // Decode and return. return new GoRpcResponse(bson_decode($header), bson_decode($body)); } }
<?php /* NOTE: This module requires bson_encode() and bson_decode(), which can be obtained by installing the MongoDB driver. For example, on Debian/Ubuntu: $ sudo apt-get install php5-mongo */ require_once('gorpc.php'); class BsonRpcClient extends GoRpcClient { const LEN_PACK_FORMAT = 'V'; const LEN_PACK_SIZE = 4; protected function send_request(GoRpcRequest $req) { $this->write(bson_encode($req->header)); $this->write(bson_encode($req->body)); } protected function read_response() { // Read the header. $data = $this->read_n(LEN_PACK_SIZE); $len = unpack(LEN_PACK_FORMAT, $data)[0]; $header = $data . $this->read_n($len - LEN_PACK_SIZE); // Read the body. $data = $this->read_n(LEN_PACK_SIZE); $len = unpack(LEN_PACK_FORMAT, $data)[0]; $body = $data . $this->read_n($len - LEN_PACK_SIZE); // Decode and return. return new GoRpcResponse(bson_decode($header), bson_decode($body)); } }
Add an option to API.fetch to not trigger the loader
import NProgress from 'nprogress' import 'nprogress/nprogress.css' NProgress.configure({ parent: '.header' }) const API = { fetch(url, params) { params = params || {} params.credentials = 'same-origin' params.headers = params.headers || {} params.headers['Accept'] = 'application/json' if (params.showLoader !== false) API.startLoading() delete params.showLoader return window.fetch(url, params) .then(response => response.json()) .then(response => { API.stopLoading() return response }) }, send(url, data, params) { params = params || {} params.method = params.method || 'POST' params.body = JSON.stringify(data) params.headers = params.headers || {} params.headers['Content-Type'] = 'application/json' return API.fetch(url, params) }, query(query, variables) { query = 'query { ' + query + ' }' variables = variables || {} return API.send('/graphql', {query, variables}).then(json => json.data) }, startLoading() { NProgress.start() NProgress.set(0.5) }, stopLoading() { NProgress.done() }, } export default API
import NProgress from 'nprogress' import 'nprogress/nprogress.css' NProgress.configure({ parent: '.header' }) const API = { fetch(url, params) { params = params || {} params.credentials = 'same-origin' params.headers = params.headers || {} params.headers['Accept'] = 'application/json' API.startLoading() return window.fetch(url, params) .then(response => response.json()) .then(response => { API.stopLoading() return response }) }, send(url, data, params) { params = params || {} params.method = params.method || 'POST' params.body = JSON.stringify(data) params.headers = params.headers || {} params.headers['Content-Type'] = 'application/json' return API.fetch(url, params) }, query(query, variables) { query = 'query { ' + query + ' }' variables = variables || {} return API.send('/graphql', {query, variables}).then(json => json.data) }, startLoading() { NProgress.start() NProgress.set(0.5) }, stopLoading() { NProgress.done() }, } export default API
Include show page, add, and delete routes
const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const methodOverride = require('method-override'); app.set('view engine', 'pug'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({extended: true})); app.use(methodOverride('_method')); if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } var collection = []; var id = 1; // '/' app.get('/', function(req, res, next) { res.redirect('/collection'); }); // '/collection' app.get('/collection', function(req, res, next) { res.render('show', {collection}); }); // '/add' app.post('/add', function(req, res, next) { collection.push(); }); // '/delete' app.delete('/collection/:id', function(req, res, next) { }); app.listen(3000, function() { console.log('Server is listening on port 3000'); });
const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const methodOverride = require('method-override'); app.set('view engine', 'pug'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({extended: true})); if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } var collection = []; var id = 1; // '/' app.get('/', function(req, res, next) { res.send('Hellooooo'); }); // '/collection' // '/add' // '/delete' app.listen(3000, function() { console.log('Server is listening on port 3000'); });
Add rpc host and remove --allow-pending.
var argv = require('cmdenv')('micromono') /** * Parse commmand line and environment options */ argv .allowUnknownOption() .option('-s --service [services]', 'Names of services to require. Use comma to separate multiple services. (e.g. --service account,cache) Env name: MICROMONO_SERVICE') .option('-d --service-dir [dir]', 'Directory of locally available services. Env name: MICROMONO_SERVICE_DIR') .option('-p --port [port]', 'The http port which balancer/service binds to.') .option('-H --host [host]', 'The host which balancer/service binds to.') .option('-r --rpc [type]', 'Type of rpc to use.', 'axon') .option('--rpc-port [port]', 'The port which service binds the rpc server to.') .option('--rpc-host [host]', 'The host which service binds the rpc server to.') .option('-b --bundle-asset', 'Bundle production ready version of asset files.') module.exports = argv
var argv = require('cmdenv')('micromono') /** * Parse commmand line and environment options */ argv .allowUnknownOption() .option('-s --service [services]', 'Names of services to require. Use comma to separate multiple services. (e.g. --service account,cache) Env name: MICROMONO_SERVICE') .option('-d --service-dir [dir]', 'Directory of locally available services. Env name: MICROMONO_SERVICE_DIR') .option('-w --allow-pending', 'White list mode - allow starting the balancer without all required services are loaded/probed.') .option('-p --port [port]', 'The http port which balancer/service binds to.') .option('-H --host [host]', 'The host which balancer/service binds to.') .option('-r --rpc [type]', 'Type of rpc to use.', 'axon') .option('--rpc-port [port]', 'The port which service binds the rpc server to.') .option('-b --bundle-asset', 'Bundle production ready version of asset files.') module.exports = argv
Support trailing slashes in URLs.
/*jslint node: true, nomen: true, white: true, unparam: true*/ /*! * Sitegear3 * Copyright(c) 2014 Ben New, Sitegear.org * MIT Licensed */ (function (_) { "use strict"; module.exports = function (app) { return { page: function () { return function (request, response) { var prefix = 'page', // TODO Get from settings (?) separator = '.', // TODO Get from settings (?) baseKey = prefix + separator + request.path.replace(/\/+$/, '') + separator, keys = [ 'main', 'title' ], // TODO Get from settings (?) fragments = {}; _.each(keys, function (key) { app.redis.get(baseKey + key, function (error, data) { fragments[key] = data; if (_.size(fragments) >= keys.length) { response.render('index', { fragments: fragments }); } }); }); } } } }; }(require('lodash')));
/*jslint node: true, nomen: true, white: true, unparam: true*/ /*! * Sitegear3 * Copyright(c) 2014 Ben New, Sitegear.org * MIT Licensed */ (function (_) { "use strict"; module.exports = function (app) { return { page: function () { return function (request, response) { var prefix = 'page', // TODO Get from settings (?) separator = '.', // TODO Get from settings (?) keys = [ 'main', 'title' ], // TODO Get from settings (?) fragments = {}; _.each(keys, function (key) { app.redis.get(prefix + separator + request.path + separator + key, function (error, data) { fragments[key] = data; if (_.size(fragments) >= keys.length) { response.render('index', { fragments: fragments }); } }); }); } } } }; }(require('lodash')));
Bring file input above OPEN label
import React from 'react'; import { processLicenseFile } from 'util'; import { processingDelay } from 'data/constants'; let fileReader; export default class FileHandler extends React.Component { static propTypes = { requestResults: React.PropTypes.func }; render() { return ( <input type="file" onChange={this.onChange} style={style.fileInput} /> ); } componentDidMount() { fileReader = new FileReader(); fileReader.addEventListener('load', this.handleNewFile); } componentWillUnmount() { fileReader.removeEventListener('load', this.handleNewFile); } onChange = (event) => { if (event.target.files[0]) { fileReader.readAsText(event.target.files[0]); } }; handleNewFile = (event) => { setTimeout(() => { this.props.requestResults( processLicenseFile(event.target.result) ); }, processingDelay); }; } const style = { fileInput: { opacity: 0, top: 0, bottom: 0, left: 0, right: 0, cursor: 'pointer', position: 'absolute', width: '100%', zIndex: 999 } };
import React from 'react'; import { processLicenseFile } from 'util'; import { processingDelay } from 'data/constants'; let fileReader; export default class FileHandler extends React.Component { static propTypes = { requestResults: React.PropTypes.func }; render() { return ( <input type="file" onChange={this.onChange} style={style.fileInput} /> ); } componentDidMount() { fileReader = new FileReader(); fileReader.addEventListener('load', this.handleNewFile); } componentWillUnmount() { fileReader.removeEventListener('load', this.handleNewFile); } onChange = (event) => { if (event.target.files[0]) { fileReader.readAsText(event.target.files[0]); } }; handleNewFile = (event) => { setTimeout(() => { this.props.requestResults( processLicenseFile(event.target.result) ); }, processingDelay); }; } const style = { fileInput: { opacity: 0, top: 0, bottom: 0, left: 0, right: 0, cursor: 'pointer', position: 'absolute', width: '100%' } };
Refactor into a named static inner class. Depend upon UTF-8 encoding for proper handling of text.
/* * Copyright 2012-2015 Johns Hopkins University HLTCOE. All rights reserved. * See LICENSE in the project root directory. */ package edu.jhu.hlt.utilt.sys; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; /** * Disable/enable System.err calls. * <br><br> * Mainly used to quiet the large amount of output from Stanford CoreNLP. */ public class SystemErrDisabler { private final PrintStream err; /** * Default ctor. Save a pointer to the current System.err so it can be enabled/disabled. */ public SystemErrDisabler() { this.err = System.err; } /** * Disable writing to System.err. * * @throws UnsupportedEncodingException if the system does not support {@link StandardCharsets#UTF_8}. */ public void disable() throws UnsupportedEncodingException { PrintStream ps = new PrintStream(new EmptyOutputStream(), false, StandardCharsets.UTF_8.toString()); System.setErr(ps); } private static class EmptyOutputStream extends OutputStream { /* (non-Javadoc) * @see java.io.OutputStream#write(int) */ @Override public void write(int b) throws IOException { } } /** * Enable writing to System.err. */ public void enable() { System.setErr(this.err); } }
/* * Copyright 2012-2015 Johns Hopkins University HLTCOE. All rights reserved. * See LICENSE in the project root directory. */ package edu.jhu.hlt.utilt.sys; import java.io.OutputStream; import java.io.PrintStream; /** * Disable/enable System.err calls. * <br><br> * Mainly used to quiet the large amount of output from Stanford CoreNLP. */ public class SystemErrDisabler { private final PrintStream err; /** * Default ctor. Save a pointer to the current System.err so it can be enabled/disabled. */ public SystemErrDisabler() { this.err = System.err; } /** * Disable writing to System.err. */ public void disable() { System.setErr(new PrintStream(new OutputStream() { public void write(int b) { } })); } /** * Enable writing to System.err. */ public void enable() { System.setErr(this.err); } }
Remove old Django compatibility code
from django.contrib import admin from django.forms import ModelForm from django.utils.timezone import now from article.models import Article class ArticleAdminForm(ModelForm): def __init__(self, *args, **kwargs): super(ArticleAdminForm, self).__init__(*args, **kwargs) self.fields['publication_date'].required = False # The admin's .save() method fills in a default. class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} form = ArticleAdminForm fieldsets = ( (None, { 'fields': ('title', 'slug',), }), ("Contents", { 'fields': ('content',), }), ("Publication settings", { 'fields': ('publication_date', 'enable_comments',), }), ) def save_model(self, request, obj, form, change): if not obj.publication_date: # auto_now_add makes the field uneditable. # a default in the model fills the field before the post is written (too early) obj.publication_date = now() obj.save() admin.site.register(Article, ArticleAdmin)
from django.contrib import admin from django.forms import ModelForm from article.models import Article # The timezone support was introduced in Django 1.4, fallback to standard library for 1.3. try: from django.utils.timezone import now except ImportError: from datetime import datetime now = datetime.now class ArticleAdminForm(ModelForm): def __init__(self, *args, **kwargs): super(ArticleAdminForm, self).__init__(*args, **kwargs) self.fields['publication_date'].required = False # The admin's .save() method fills in a default. class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} form = ArticleAdminForm fieldsets = ( (None, { 'fields': ('title', 'slug',), }), ("Contents", { 'fields': ('content',), }), ("Publication settings", { 'fields': ('publication_date', 'enable_comments',), }), ) def save_model(self, request, obj, form, change): if not obj.publication_date: # auto_now_add makes the field uneditable. # a default in the model fills the field before the post is written (too early) obj.publication_date = now() obj.save() admin.site.register(Article, ArticleAdmin)
Use threading.Event() to stop PeriodicTasks This is a lot more cpu efficient and results in less tasks swapping randomly.
from ..vtask import VTask import time from ..sparts import option from threading import Event class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): while not self.service._stop: t0 = time.time() self.execute() to_sleep = time.time() - (t0 + self.interval) if to_sleep > 0: if self.stop_event.wait(to_sleep): return def execute(self, context=None): self.logger.debug('execute')
from ..vtask import VTask import time from ..sparts import option class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None def _runloop(self): while not self.service._stop: end_time = time.time() + self.interval self.execute() while not self.service._stop: tn = time.time() to_sleep = end_time - tn if to_sleep <= 0: break time.sleep(min(0.1, to_sleep)) def execute(self, context=None): self.logger.debug('execute')
Fix alignment of date column in plain text view This got broken by 2a6a1c63cb21015009fe4fd13f62cdac64e1fe36 and 05a4d686b578794c180ddfaf4945a9d7443f330e. Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>
<?php $dateformat = "r"; $lengths["date"] = max($lengths["date"], strlen(date($dateformat, time()))); echo mb_str_pad($fields["id"], $lengths["id"])." | " .mb_str_pad($fields["filename"], $lengths["filename"])." | " .mb_str_pad($fields["mimetype"], $lengths["mimetype"])." | " .mb_str_pad($fields["date"], $lengths["date"])." | " .mb_str_pad($fields["hash"], $lengths["hash"])." | " .mb_str_pad($fields["filesize"], $lengths["filesize"])."\n"; foreach($query as $key => $item) { echo mb_str_pad($item["id"], $lengths["id"])." | " .mb_str_pad($item["filename"], $lengths["filename"])." | " .mb_str_pad($item["mimetype"], $lengths["mimetype"])." | " .date($dateformat, $item["date"])." | " .$item["hash"]." | " .$item["filesize"]."\n"; } ?> Total sum of your distinct uploads: <?php echo $total_size; ?>.
<?php echo mb_str_pad($fields["id"], $lengths["id"])." | " .mb_str_pad($fields["filename"], $lengths["filename"])." | " .mb_str_pad($fields["mimetype"], $lengths["mimetype"])." | " .mb_str_pad($fields["date"], $lengths["date"])." | " .mb_str_pad($fields["hash"], $lengths["hash"])." | " .mb_str_pad($fields["filesize"], $lengths["filesize"])."\n"; foreach($query as $key => $item) { echo mb_str_pad($item["id"], $lengths["id"])." | " .mb_str_pad($item["filename"], $lengths["filename"])." | " .mb_str_pad($item["mimetype"], $lengths["mimetype"])." | " .date("r", $item["date"])." | " .$item["hash"]." | " .$item["filesize"]."\n"; } ?> Total sum of your distinct uploads: <?php echo $total_size; ?>.
FIX free cuda after we use it and not before
import process.Conf; import process.training.Classifier; public class Main { public static void main(String[] args) { // TODO : TO CONSTANTS float overallTargetDetectionRate = 0.80f; float overallTargetFalsePositiveRate = 0.000001f; float targetDetectionRate = 0.995f; float targetFalsePositiveRate = 0.5f; if (Conf.USE_CUDA) Conf.haarExtractor.setUp(19, 19); Classifier classifier = new Classifier("data/trainset", "data/testset", 19, 19); classifier.train(overallTargetDetectionRate, overallTargetFalsePositiveRate, targetDetectionRate, targetFalsePositiveRate); if (Conf.haarExtractor != null) Conf.haarExtractor.freeCuda(); } }
import process.Conf; import process.training.Classifier; public class Main { public static void main(String[] args) { // TODO : TO CONSTANTS float overallTargetDetectionRate = 0.80f; float overallTargetFalsePositiveRate = 0.000001f; float targetDetectionRate = 0.995f; float targetFalsePositiveRate = 0.5f; if (Conf.USE_CUDA) Conf.haarExtractor.setUp(19, 19); if (Conf.haarExtractor != null) Conf.haarExtractor.freeCuda(); Classifier classifier = new Classifier("data/trainset", "data/testset", 19, 19); classifier.train(overallTargetDetectionRate, overallTargetFalsePositiveRate, targetDetectionRate, targetFalsePositiveRate); } }
Remove token from being stored
# Copyright 2014 Dave Kludt # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from dateutil import tz from dateutil.relativedelta import relativedelta UTC = tz.tzutc() class Region: def __init__(self, data): self.name = data.get('name').title() self.abbreviation = data.get('abbreviation').upper() self.active = bool(data.get('active')) class Account: def __init__(self, data): self.account_number = data.get('account_number') self.cache_expiration = self.set_expiration() self.host_servers = data.get('host_servers') self.region = data.get('region').lower() self.servers = data.get('servers') def set_expiration(self): return datetime.now(UTC) + relativedelta(days=1)
# Copyright 2014 Dave Kludt # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from dateutil import tz from dateutil.relativedelta import relativedelta UTC = tz.tzutc() class Region: def __init__(self, data): self.name = data.get('name').title() self.abbreviation = data.get('abbreviation').upper() self.active = bool(data.get('active')) class Account: def __init__(self, data): self.account_number = data.get('account_number') self.token = data.get('token') self.cache_expiration = self.set_expiration() self.host_servers = data.get('host_servers') self.region = data.get('region').lower() self.servers = data.get('servers') def set_expiration(self): return datetime.now(UTC) + relativedelta(days=1)
Change test for make_kernel(kerneltype='airy') from class to function
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_SCIPY') def test_airy(): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7)
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose, assert_equal from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False class TestMakeKernel(object): """ Test the make_kernel function """ @pytest.mark.skipif('not HAS_SCIPY') def test_airy(self): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') k2 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='brickwall') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7) assert_equal(k1, k2)
Allow array of src strings to be passed in
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(source => new Promise(resolve => { // Convert strings to objects if (typeof source === 'string') { source = {src: source}; } // Resolve source and img when loaded const img = new Image(); img.onload = () => resolve(Object.assign({}, source, {img})); img.src = source.src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(...images.map(image => image.img.width)); canvas.height = Math.max(...images.map(image => image.img.height)); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(source => new Promise(resolve => { const img = new Image(); img.onload = () => resolve(Object.assign({}, source, {img})); img.src = source.src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(...images.map(image => image.img.width)); canvas.height = Math.max(...images.map(image => image.img.height)); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
Change permissions and add ability to make jobs
var artistController = require('../controllers/artist-controller'); var genreController = require('../controllers/genre-controller'); var queue = require('../workers/queue'); module.exports = function(app, passport) { app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email', 'user_likes'] })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect : '/' }), function(req, res) { queue.crawlUser(req.user.dataValues); res.redirect('/'); }); app.get('/profile', function(req, res) { return res.send(200); }); app.post('/api/artist/:id/like', artistController.likeArtist); app.get('/api/artist/recommendation', artistController.getArtistRecommendations); app.get('/api/genre', genreController.getGenres); app.get('/api/genre/artists', genreController.getArtistsByGenre); app.get('*', function(req, res) { return res.render('index.html'); }); };
var artistController = require('../controllers/artist-controller'); var genreController = require('../controllers/genre-controller'); module.exports = function(app, passport) { app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect : '/', successRedirect : '/' })); app.get('/profile', function(req, res) { return res.send(200); }); app.post('/api/artist/:id/like', artistController.likeArtist); app.get('/api/artist/recommendation', artistController.getArtistRecommendations); app.get('/api/genre', genreController.getGenres); app.get('/api/genre/artists', genreController.getArtistsByGenre); app.get('*', function(req, res) { return res.render('index.html'); }); };
Add in unit tests for validate.py
import pytest import mock import synapseclient import pytest from genie import validate center = "SAGE" syn = mock.create_autospec(synapseclient.Synapse) @pytest.fixture(params=[ # tuple with (input, expectedOutput) (["data_CNA_SAGE.txt"], "cna"), (["data_clinical_supp_SAGE.txt"], "clinical"), (["data_clinical_supp_sample_SAGE.txt", "data_clinical_supp_patient_SAGE.txt"], "clinical")]) def filename_fileformat_map(request): return request.param def test_perfect_get_filetype(filename_fileformat_map): (filepath_list, fileformat) = filename_fileformat_map assert validate.determine_filetype( syn, filepath_list, center) == fileformat def test_wrongfilename_get_filetype(): with pytest.raises( ValueError, match="Your filename is incorrect! " "Please change your filename before you run " "the validator or specify --filetype if you are " "running the validator locally"): validate.determine_filetype(syn, ['wrong.txt'], center)
import pytest import mock import synapseclient from genie import validate center = "SAGE" syn = mock.create_autospec(synapseclient.Synapse) @pytest.fixture(params=[ # tuple with (input, expectedOutput) (["data_CNA_SAGE.txt"], "cna"), (["data_clinical_supp_SAGE.txt"], "clinical"), (["data_clinical_supp_sample_SAGE.txt", "data_clinical_supp_patient_SAGE.txt"], "clinical")]) def filename_fileformat_map(request): return request.param def test_perfect_get_filetype(filename_fileformat_map): (filepath_list, fileformat) = filename_fileformat_map assert validate.determine_filetype( syn, filepath_list, center) == fileformat # def test_wrongfilename_get_filetype(): # assert input_to_database.get_filetype(syn, ['wrong.txt'], center) is None
Use correct syntax to mark class as internal @var internal looks like a mistake
<?php declare(strict_types=1); namespace Doctrine\Migrations\Version; use Doctrine\Migrations\Configuration\Configuration; /** * The Factory class is responsible for creating instances of the Version class for a version number * and a migration class name. * * @internal */ class Factory { /** @var Configuration */ private $configuration; /** @var ExecutorInterface */ private $versionExecutor; public function __construct(Configuration $configuration, ExecutorInterface $versionExecutor) { $this->configuration = $configuration; $this->versionExecutor = $versionExecutor; } public function createVersion(string $version, string $migrationClassName): Version { return new Version( $this->configuration, $version, $migrationClassName, $this->versionExecutor ); } }
<?php declare(strict_types=1); namespace Doctrine\Migrations\Version; use Doctrine\Migrations\Configuration\Configuration; /** * The Factory class is responsible for creating instances of the Version class for a version number * and a migration class name. * * @var internal */ class Factory { /** @var Configuration */ private $configuration; /** @var ExecutorInterface */ private $versionExecutor; public function __construct(Configuration $configuration, ExecutorInterface $versionExecutor) { $this->configuration = $configuration; $this->versionExecutor = $versionExecutor; } public function createVersion(string $version, string $migrationClassName): Version { return new Version( $this->configuration, $version, $migrationClassName, $this->versionExecutor ); } }
Add support for single param instead of array/object.
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri, params = typeof params !== 'object' ? [params] : params, paramsArrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, ''); paramsArrayKey++; if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri, paramsArrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, ''); paramsArrayKey++; if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
Add article-identifier to article in HTML
'use strict'; var ArticleLoader = new Class({ feed: 12, page: 0, initialize: function (feed) { this.feed = feed; this.getArticles(); }, getArticles: function () { new Request.JSON({ method: 'get', url: window.ZerobRSS.apiUri + '/v1/feeds/' + this.feed + '/articles?page=' + this.page, onComplete: function (response) { var template = Handlebars.compile($('news-card-template').get('html')); response.each(function (article) { var a = new Element('article'); a.set('data-id', article.identifier); a.set('html', template(article)); a.inject($('content')); }); } }).send(); } });
'use strict'; var ArticleLoader = new Class({ feed: 12, page: 0, initialize: function (feed) { this.feed = feed; this.getArticles(); }, getArticles: function () { new Request.JSON({ method: 'get', url: window.ZerobRSS.apiUri + '/v1/feeds/' + this.feed + '/articles?page=' + this.page, onComplete: function (response) { var template = Handlebars.compile($('news-card-template').get('html')); response.each(function (article) { var a = new Element('article'); a.set('html', template(article)); a.inject($('content')); }); } }).send(); } });
Use os.path.join() to join paths
import numpy as np import pickle import os import sys import ws.bad as bad mydir = os.path.abspath(os.path.dirname(__file__)) lookupmatrix = pickle.load(open(os.path.join(mydir, 'accuweather_location_codes.dump'), 'rb')) lookuplist = lookupmatrix.tolist() def build_url(city): # check whether input is a string if type(city) != str: raise(bad.Type("The input city " +str(city) +" wasn't of type string")) index = lookuplist[1].index(city) accuweather_index = lookuplist[0][index] url = 'http://realtek.accu-weather.com/widget/realtek/weather-data.asp' \ + '?location=cityId:' \ + str(accuweather_index) return url
import numpy as np import pickle import os import sys import ws.bad as bad mydir = os.path.abspath(os.path.dirname(__file__)) print(mydir) lookupmatrix = pickle.load(open( \ mydir +'/accuweather_location_codes.dump','rb')) lookuplist = lookupmatrix.tolist() def build_url(city): # check whether input is a string if type(city) != str: raise(bad.Type("The input city " +str(city) +" wasn't of type string")) index = lookuplist[1].index(city) accuweather_index = lookuplist[0][index] url = 'http://realtek.accu-weather.com/widget/realtek/weather-data.asp' \ + '?location=cityId:' \ + str(accuweather_index) return url
Remove download URL since Github doesn't get his act together. Damnit committer: Jannis Leidel <jannis@leidel.info> --HG-- extra : convert_revision : 410200249f2c4981c9e0e8e5cf9334b0e17ec3d4
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
Add host and port parameters
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self, host='localhost', port=2379): self.channel = grpc.insecure_channel('{host}:{port}'.format( host=host, port=port) ) self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client(host='localhost', port=2379)
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client()
Set profile "default" as a default
package cmd import ( "fmt" "os" "github.com/spf13/cobra" ) // RootCmd define root command var RootCmd = &cobra.Command{ Use: "s3-edit", Short: "Edit directly a file on Amazon S3", Long: "Edit directly a file on Amazon S3", Run: func(cmd *cobra.Command, args []string) { if isShowVersion { ShowVersion() return } cmd.Usage() }, } // Execute execute root command func Execute() { err := RootCmd.Execute() if err != nil { fmt.Println(err) os.Exit(1) } } var isShowVersion bool var awsProfile string func init() { RootCmd.Flags().BoolVarP(&isShowVersion, "version", "v", false, "print the version of s3-edit") RootCmd.PersistentFlags().StringVarP(&awsProfile, "profile", "", "default", "Use a specific profile from your credential file") }
package cmd import ( "fmt" "os" "github.com/spf13/cobra" ) // RootCmd define root command var RootCmd = &cobra.Command{ Use: "s3-edit", Short: "Edit directly a file on Amazon S3", Long: "Edit directly a file on Amazon S3", Run: func(cmd *cobra.Command, args []string) { if isShowVersion { ShowVersion() return } cmd.Usage() }, } // Execute execute root command func Execute() { err := RootCmd.Execute() if err != nil { fmt.Println(err) os.Exit(1) } } var isShowVersion bool var awsProfile string func init() { RootCmd.Flags().BoolVarP(&isShowVersion, "version", "v", false, "print the version of s3-edit") RootCmd.PersistentFlags().StringVarP(&awsProfile, "profile", "", "", "Use a specific profile from your credential file") }
Revert to old compilation format except compile JSX
const del = require('del') const { dest, series, src } = require('gulp') const { init: sourceMapsInit, write: sourceMapsWrite, } = require('gulp-sourcemaps') const { createProject } = require('gulp-typescript') const tsProject = createProject('tsconfig.json', { declaration: true, isolatedModules: false, noEmit: false, sourceMap: true, }) const clean = () => del(['dist/**/*']) const compileTS = () => src([ 'src/**/*.ts', 'src/**/*.tsx', '!src/**/*.d.ts', '!src/**/*.stories.tsx', '!src/**/*.test.ts', '!src/setupTests.ts', ]) .pipe(sourceMapsInit()) .pipe(tsProject()) .pipe(sourceMapsWrite()) .pipe(dest('dist')) const copyStyles = () => src(['src/**/*.css', 'src/**/*.scss']).pipe(dest('dist')) exports.default = series(clean, compileTS, copyStyles)
const del = require('del') const { dest, series, src } = require('gulp') const { init: sourceMapsInit, write: sourceMapsWrite, } = require('gulp-sourcemaps') const { createProject } = require('gulp-typescript') const tsProject = createProject('tsconfig.json', { declaration: true, isolatedModules: false, jsx: 'react', module: 'amd', noEmit: false, resolveJsonModule: false, sourceMap: true, }) const clean = () => del(['dist/**/*']) const compileTS = () => src([ 'src/**/*.ts', 'src/**/*.tsx', '!src/**/*.d.ts', '!src/**/*.stories.tsx', '!src/**/*.test.ts', '!src/setupTests.ts', ]) .pipe(sourceMapsInit()) .pipe(tsProject()) .pipe(sourceMapsWrite()) .pipe(dest('dist')) const copyStyles = () => src(['src/**/*.css', 'src/**/*.scss']).pipe(dest('dist')) exports.default = series(clean, compileTS, copyStyles)
Add a "magic license comment"
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.controller; import org.junit.Assert; import org.junit.Test; import edu.cornell.mannlib.vitro.webapp.web.ContentType; public class EntityControllerTest { @Test public void testAcceptHeader(){ EntityController entityController = new EntityController(); /* Check to see if vitro would send RDF/XML to tabulator */ String tabulatorsAcceptHeader = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.5,text/plain;q=0.5," + "image/png,*/*;q=0.1," + "application/rdf+xml;q=1.0,text/n3;q=0.4"; ContentType result = entityController.checkForLinkedDataRequest("http://notUsedInThisTestCase.com/bogus",tabulatorsAcceptHeader); Assert.assertTrue( result != null ); Assert.assertTrue( "application/rdf+xml".equals( result.toString()) ); } }
package edu.cornell.mannlib.vitro.webapp.controller; import org.junit.Assert; import org.junit.Test; import edu.cornell.mannlib.vitro.webapp.web.ContentType; public class EntityControllerTest { @Test public void testAcceptHeader(){ EntityController entityController = new EntityController(); /* Check to see if vitro would send RDF/XML to tabulator */ String tabulatorsAcceptHeader = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.5,text/plain;q=0.5," + "image/png,*/*;q=0.1," + "application/rdf+xml;q=1.0,text/n3;q=0.4"; ContentType result = entityController.checkForLinkedDataRequest("http://notUsedInThisTestCase.com/bogus",tabulatorsAcceptHeader); Assert.assertTrue( result != null ); Assert.assertTrue( "application/rdf+xml".equals( result.toString()) ); } }
Add missing semicolon, remove trailing whitespace.
$(function() { yourCollection = new Models.ItemListings(); friendCollection = new Models.ItemListings(); featuredCollection = new Models.ItemListings(); publicCollection = new Models.ItemListings(); yourView = new Views.ListingView({ collection: yourCollection, el: $('#you-listing')[0] }); friendView = new Views.ListingView({ collection: friendCollection, el: $('#friend-listing')[0] }); featuredView = new Views.ListingView({ collection: featuredCollection, el: $('#featured-listing')[0] }); publicView = new Views.ListingView({ collection: publicCollection, el: $('#public-listing')[0] }); yourCollection.add({ id: 0, name: "Test Item", price: "(USD) $5", location: "Singapore", buyers: [0], owner: 0, imageUrl: 'http://placehold.it/96x96' }); friendCollection.add({ id: 1, name: "Another Item", price: "(USD) $25", location: "Singapore", buyers: [0, 1, 2], owner: 1, imageUrl: 'http://placehold.it/96x96' }); });
$(function() { yourCollection = new Models.ItemListings(); friendCollection = new Models.ItemListings(); featuredCollection = new Models.ItemListings(); publicCollection = new Models.ItemListings(); yourView = new Views.ListingView({ collection: yourCollection, el: $('#you-listing')[0] }); friendView = new Views.ListingView({ collection: friendCollection, el: $('#friend-listing')[0] }); featuredView = new Views.ListingView({ collection: featuredCollection, el: $('#featured-listing')[0] }); publicView = new Views.ListingView({ collection: publicCollection, el: $('#public-listing')[0] }) yourCollection.add({ id: 0, name: "Test Item", price: "(USD) $5", location: "Singapore", buyers: [0], owner: 0, imageUrl: 'http://placehold.it/96x96' }); friendCollection.add({ id: 1, name: "Another Item", price: "(USD) $25", location: "Singapore", buyers: [0, 1, 2], owner: 1, imageUrl: 'http://placehold.it/96x96' }); });
Add microdata to youtube embeds
define([ 'jquery' ], function ( $ ) { $.fn.activateYoutube = function(trigger) { if (trigger === undefined) { trigger = true; } $('.youtube', this).empty().each(function(index, element) { $youtube = $(element); var thumbsrc = "//i.ytimg.com/vi/" + $youtube.data('id') + "/hqdefault.jpg"; var embedUrl = '//www.youtube.com/embed/' + $youtube.data('id') + '?autoplay=1&'+$youtube.data('params'); $youtube.css('background-image', "url('"+thumbsrc+"')"); $youtube.attr({itemprop: 'video', itemscope:'', itemtype:"http://schema.org/VideoObject"}); $youtube.append($('<meta itemprop="thumbnail" content="'+thumbsrc+'" /><meta itemprop="embedUrl" content="'+embedUrl+'" /><span class="fa-stack play"><i class="fa fa-circle fa-stack-1x"></i> <i class="fa fa-youtube-play fa-stack-1x"></i></span>')); if (trigger) { $youtube.click(function(event) { $(this).html('<iframe src="'+embedUrl+'" allowfullscreen>'); }); } }); }; return $; });
define([ 'jquery' ], function ( $ ) { $.fn.activateYoutube = function(trigger) { if (trigger === undefined) { trigger = true; } $('.youtube', this).empty().each(function(index, element) { $youtube = $(element); var thumbsrc = "//i.ytimg.com/vi/" + $youtube.data('id') + "/hqdefault.jpg"; $youtube.css('background-image', "url('"+thumbsrc+"')"); $youtube.append($('<span class="fa-stack play"><i class="fa fa-circle fa-stack-1x"></i> <i class="fa fa-youtube-play fa-stack-1x"></i></span>')); if (trigger) { $youtube.click(function(event) { $(this).html('<iframe src="//www.youtube.com/embed/' + $(this).data('id') + '?autoplay=1&'+$(this).data('params')+'" allowfullscreen>'); }); } }); }; return $; });
Add Edge to the targets list Part of https://github.com/vector-im/element-web/issues/9175
module.exports = { "sourceMaps": "inline", "presets": [ ["@babel/preset-env", { "targets": [ "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions", "last 2 Edge versions", ], }], "@babel/preset-typescript", "@babel/preset-flow", "@babel/preset-react", ], "plugins": [ ["@babel/plugin-proposal-decorators", {legacy: true}], "@babel/plugin-proposal-export-default-from", "@babel/plugin-proposal-numeric-separator", "@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-object-rest-spread", "@babel/plugin-transform-flow-comments", "@babel/plugin-syntax-dynamic-import", "@babel/plugin-transform-runtime", ], };
module.exports = { "sourceMaps": "inline", "presets": [ ["@babel/preset-env", { "targets": [ "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions" ], }], "@babel/preset-typescript", "@babel/preset-flow", "@babel/preset-react" ], "plugins": [ ["@babel/plugin-proposal-decorators", {legacy: true}], "@babel/plugin-proposal-export-default-from", "@babel/plugin-proposal-numeric-separator", "@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-object-rest-spread", "@babel/plugin-transform-flow-comments", "@babel/plugin-syntax-dynamic-import", "@babel/plugin-transform-runtime" ] };
Add acceptance test for closing alert
import Ember from 'ember'; import { module, test } from 'qunit'; import startApp from 'component-integration-tests/tests/helpers/start-app'; let application; module('Acceptance | index', { beforeEach() { application = startApp(); }, afterEach() { Ember.run(application, 'destroy'); } }); test('creating alert with demo form', function(assert) { visit('/').then(() => { assert.equal(find('.alert-banner').length, 0, 'no alerts by default'); }); fillIn('input[placeholder="Alert text"]', 'My alert text here').then(() => { return click('input[type=checkbox]:eq(0)'); }).then(() => { return click('button:contains(Create alert)'); }).then(() => { let alert = find('.alert-banner'); assert.equal(alert.length, 1, 'alert created'); assert.equal(alert.text().trim(), 'My alert text here', 'shows text'); }); }); test('closing alert', function(assert) { visit('/'); fillIn('input[placeholder="Alert text"]', 'Alert'); click('button:contains(Create alert)').then(() => { assert.equal(find('.alert-banner').length, 1, 'alert created'); }); click('.alert-banner button.close').then(() => { assert.equal(find('.alert-banner').length, 0, 'alert closed'); }); });
import Ember from 'ember'; import { module, test } from 'qunit'; import startApp from 'component-integration-tests/tests/helpers/start-app'; let application; module('Acceptance | index', { beforeEach() { application = startApp(); }, afterEach() { Ember.run(application, 'destroy'); } }); test('creating alert with demo form', function(assert) { visit('/').then(() => { assert.equal(find('.alert-banner').length, 0, 'no alerts by default'); }); fillIn('input[placeholder="Alert text"]', 'My alert text here').then(() => { return click('input[type=checkbox]:eq(0)'); }).then(() => { return click('button:contains(Create alert)'); }).then(() => { let alert = find('.alert-banner'); assert.equal(alert.length, 1, 'alert created'); assert.equal(alert.text().trim(), 'My alert text here', 'shows text'); }); });
Allow to change the default storage configuration
package de.fernunihagen.dna.jkn.scalephant.storage; import java.util.HashMap; import java.util.Map; public class StorageInterface { /** * A map with all created storage instances */ protected static Map<String, StorageManager> instances; /** * The used storage configuration */ protected static StorageConfiguration storageConfiguration; static { storageConfiguration = new StorageConfiguration(); } /** * Get the storage manager for a given table. If the storage manager does not * exist, it will be created * * @return */ public static synchronized StorageManager getStorageManager(final String table) { if(instances == null) { instances = new HashMap<String, StorageManager>(); } if(instances.containsKey(table)) { return instances.get(table); } final StorageManager storageManager = new StorageManager(table, storageConfiguration); storageManager.init(); instances.put(table, storageManager); return storageManager; } @Override protected void finalize() throws Throwable { super.finalize(); if(instances != null) { for(final String table : instances.keySet()) { final StorageManager storageManager = instances.get(table); storageManager.shutdown(); } } } /** * Get the current storage configuration * @return */ public static StorageConfiguration getStorageConfiguration() { return storageConfiguration; } /** * Set a new storage configuration * @param storageConfiguration */ public static void setStorageConfiguration( StorageConfiguration storageConfiguration) { StorageInterface.storageConfiguration = storageConfiguration; } }
package de.fernunihagen.dna.jkn.scalephant.storage; import java.util.HashMap; import java.util.Map; public class StorageInterface { private static Map<String, StorageManager> instances; /** * Get the storage manager for a given table. If the storage manager does not * exist, it will be created * * @return */ public static synchronized StorageManager getStorageManager(final String table) { if(instances == null) { instances = new HashMap<String, StorageManager>(); } if(instances.containsKey(table)) { return instances.get(table); } final StorageConfiguration storageConfiguration = new StorageConfiguration(); final StorageManager storageManager = new StorageManager(table, storageConfiguration); storageManager.init(); instances.put(table, storageManager); return storageManager; } @Override protected void finalize() throws Throwable { super.finalize(); if(instances != null) { for(final String table : instances.keySet()) { final StorageManager storageManager = instances.get(table); storageManager.shutdown(); } } } }
Use `beforeInstall` instead of `afterInstall` for peer dependencies.
var path = require('path'); module.exports = { description: 'Initialize files needed for typescript compilation', files: function() { return [ path.join(this.path, 'files', 'tsconfig.json'), path.join(this.path, 'files', 'app', 'config', 'environment.d.ts') ]; }, mapFile: function() { var result = this._super.mapFile.apply(this, arguments); if (result.indexOf('/tsconfig.json')>-1) { return 'tsconfig.json'; } else if (result.indexOf('/app/')>-1) { var pos = result.indexOf('/app/'); return result.substring(pos+1); } }, normalizeEntityName: function() { // Entity name is optional right now, creating this hook avoids an error. }, beforeInstall: function() { return this.addPackagesToProject([ { name: 'typescript', target: '^2.1' }, { name: '@types/ember', target: '^2.7.34' } ]); } }
var path = require('path'); module.exports = { description: 'Initialize files needed for typescript compilation', files: function() { return [ path.join(this.path, 'files', 'tsconfig.json'), path.join(this.path, 'files', 'app', 'config', 'environment.d.ts') ]; }, mapFile: function() { var result = this._super.mapFile.apply(this, arguments); if (result.indexOf('/tsconfig.json')>-1) { return 'tsconfig.json'; } else if (result.indexOf('/app/')>-1) { var pos = result.indexOf('/app/'); return result.substring(pos+1); } }, normalizeEntityName: function() { // Entity name is optional right now, creating this hook avoids an error. }, afterInstall: function() { return this.addPackagesToProject([ { name: 'typescript', target: '^2.1' }, { name: '@types/ember', target: '^2.7.34' } ]); } }
Use the prototype instead of "private" property backups
// An array with a max length. // // When max length is surpassed, items are removed from // the front of the array. // Native array methods let { push, splice } = Array.prototype; // Ember array prototype extension let { insertAt } = Array.prototype; // Using Classes to extend Array is unsupported in Babel so this less // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes export default function RollingArray(maxLength, ...items) { const array = new Array(...items); array.maxLength = maxLength; // Bring the length back down to maxLength by removing from the front array._limit = function() { const surplus = this.length - this.maxLength; if (surplus > 0) { this.splice(0, surplus); } }; array.push = function(...items) { push.apply(this, items); this._limit(); return this.length; }; array.splice = function(...args) { const returnValue = splice.apply(this, args); this._limit(); return returnValue; }; // All mutable array methods build on top of insertAt array.insertAt = function(...args) { const returnValue = insertAt.apply(this, args); this._limit(); this.arrayContentDidChange(); return returnValue; }; array.unshift = function() { throw new Error('Cannot unshift onto a RollingArray'); }; return array; }
// An array with a max length. // // When max length is surpassed, items are removed from // the front of the array. // Using Classes to extend Array is unsupported in Babel so this less // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes export default function RollingArray(maxLength, ...items) { const array = new Array(...items); array.maxLength = maxLength; // Capture the originals of each array method, but // associate them with the array to prevent closures. array._push = array.push; array._splice = array.splice; array._unshift = array.unshift; // All mutable array methods build on top of insertAt array._insertAt = array.insertAt; // Bring the length back down to maxLength by removing from the front array._limit = function() { const surplus = this.length - this.maxLength; if (surplus > 0) { this.splice(0, surplus); } }; array.push = function(...items) { this._push(...items); this._limit(); return this.length; }; array.splice = function(...args) { const returnValue = this._splice(...args); this._limit(); return returnValue; }; array.insertAt = function(...args) { const returnValue = this._insertAt(...args); this._limit(); this.arrayContentDidChange(); return returnValue; }; array.unshift = function() { throw new Error('Cannot unshift onto a RollingArray'); }; return array; }
Refactor xhr functionality into ajax object
'use strict'; var events = []; var requestInterval = 5000; window.addEventListener('click', function(e) { e = event || window.event; events.push(processEvent(e)); }); var processEvent = function(e) { // Event attributes var eventProps = ['type', 'timeStamp']; // Event target attributes var targetProps = ['nodeName', 'innerHTML']; // Trimmed event var result = {}; eventProps.forEach(function(prop) { if (e[prop]) { result[prop] = e[prop]; } }); if(e.target) { targetProps.forEach(function(prop) { if(e.target[prop]) { result[prop] = e.target[prop]; } }); } console.log('event result: ' + JSON.stringify(result)); return result; }; var ajax = {}; ajax.postUrl ='http://sextant-ng-b.herokuapp.com/api/0_0_1/data'; ajax.createXHR = function() { try { return new XMLHttpRequest(); } catch(e) { throw new Error('No XHR object.'); } }; ajax.post = function(data) { var xhr = this.createXHR(); xhr.open('POST', this.postUrl, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(data); }; var sendEvents = setInterval(function() { if (!events.length) return; ajax.post(JSON.stringify(events)); events = []; }, requestInterval);
'use strict'; var events = []; var requestInterval = 5000; window.addEventListener('click', function(e) { e = event || window.event; events.push(processEvent(e)); }); var processEvent = function(e) { // Event attributes var eventProps = ['type', 'timeStamp']; // Event target attributes var targetProps = ['nodeName', 'innerHTML']; // Trimmed event var result = {}; eventProps.forEach(function(prop) { if (e[prop]) { result[prop] = e[prop]; } }); if(e.target) { targetProps.forEach(function(prop) { if(e.target[prop]) { result[prop] = e.target[prop]; } }); } console.log('event result: ' + JSON.stringify(result)); return result; }; var PostRequest = function() { var xhr; try { xhr = new XMLHttpRequest(); } catch(e) { throw new Error('No XHR object'); } var url = 'http://sextant-ng-b.herokuapp.com/api/0_0_1/data'; xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/json'); return xhr; }; var sendEvents = setInterval(function() { if (!events.length) return; var request = new PostRequest(); request.send(JSON.stringify(events)); events = []; }, requestInterval);
Add Color to Login Button
<div class="container"> <br/> <div class="row"> <?php echo validation_errors(); ?> <?php echo form_open('admin/login'); ?> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-danger" style="padding: 5%;"> <h1 class="text-center"><?php echo $title; ?></h1><br/> <div class="form-group"> <?php if($this->session->flashdata('user_loggedout')): ?> <?php echo '<p class="alert alert-info">'.$this->session->flashdata('user_loggedout').'</p>'; ?> <?php endif; ?> <?php if($this->session->flashdata('login_failed')): ?> <?php echo '<p class="alert alert-danger">'.$this->session->flashdata('login_failed').'</p>'; ?> <?php endif; ?> <b><input type="text" name="username" class="form-control" placeholder="Enter Username" required autofocus autocomplete='off'></b> </div> <div class="form-group"> <b><input type="password" name="password" class="form-control" placeholder="Enter Password" required autofocus></b> </div> <button style="background-color:#5cb85c; color:white;" type="submit" class="btn btn-success btn-block"><b>Login</b></button> </div> <?php echo form_close(); ?> </div> </div>
<div class="container"> <br/> <div class="row"> <?php echo validation_errors(); ?> <?php echo form_open('admin/login'); ?> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-danger" style="padding: 5%;"> <h1 class="text-center"><?php echo $title; ?></h1><br/> <div class="form-group"> <?php if($this->session->flashdata('user_loggedout')): ?> <?php echo '<p class="alert alert-info">'.$this->session->flashdata('user_loggedout').'</p>'; ?> <?php endif; ?> <?php if($this->session->flashdata('login_failed')): ?> <?php echo '<p class="alert alert-danger">'.$this->session->flashdata('login_failed').'</p>'; ?> <?php endif; ?> <b><input type="text" name="username" class="form-control" placeholder="Enter Username" required autofocus autocomplete='off'></b> </div> <div class="form-group"> <b><input type="password" name="password" class="form-control" placeholder="Enter Password" required autofocus></b> </div> <button type="submit" class="btn btn-success btn-block"><b>Login</b></button> </div> <?php echo form_close(); ?> </div> </div>
Clarify current behavior regarding inheritance
from django.views.generic.base import View from mock import MagicMock from ..permissions import is_location_safe, location_safe @location_safe def safe_fn_view(request, domain): return "hello" def unsafe_fn_view(request, domain): return "hello" @location_safe class SafeClsView(View): pass class UnsafeClsView(View): pass class UnSafeChildOfSafeClsView(SafeClsView): """This inherits its parent class's safety""" # TODO change this behavior @location_safe class SafeChildofUnsafeClsView(UnsafeClsView): """This shouldn't hoist its safety up to the parent class""" def test_view_safety(): def _assert(view_fn, is_safe): assert is_location_safe(view_fn, MagicMock(), (), {}) == is_safe, \ f"{view_fn} {'IS NOT' if is_safe else 'IS'} marked as location-safe" for view, is_safe in [ (safe_fn_view, True), (unsafe_fn_view, False), (SafeClsView.as_view(), True), (UnsafeClsView.as_view(), False), (UnSafeChildOfSafeClsView.as_view(), True), (SafeChildofUnsafeClsView.as_view(), True), ]: yield _assert, view, is_safe
from django.views.generic.base import View from mock import MagicMock from ..permissions import is_location_safe, location_safe @location_safe def safe_fn_view(request, domain): return "hello" def unsafe_fn_view(request, domain): return "hello" @location_safe class SafeClsView(View): pass class UnsafeClsView(View): pass class UnSafeChildOfSafeClsView(SafeClsView): """This inherits its parent class's safety""" # TODO change this behavior @location_safe class SafeChildofUnsafeClsView(UnsafeClsView): """This shouldn't hoist its safety up to the parent class""" def test_view_safety(): def _assert(view_fn, is_safe): assert is_location_safe(view_fn, MagicMock(), (), {}) == is_safe, \ f"{view_fn} {'IS NOT' if is_safe else 'IS'} marked as location-safe" for view, is_safe in [ (safe_fn_view, True), (unsafe_fn_view, False), (SafeClsView, True), (UnsafeClsView, False), ]: yield _assert, view, is_safe
Clarify that Submit config is not currently used
/* # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015, 2016 */ package quarks.execution; import java.util.concurrent.Future; import com.google.gson.JsonObject; /** * An interface for submission of an executable. * <p> * The class implementing this interface is responsible * for the semantics of this operation. e.g., an direct topology * provider would run the topology as threads in the current jvm. * * @param <E> the executable type * @param <J> the submitted executable's future */ public interface Submitter<E, J extends Job> { /** * Submit an executable. * No configuration options are specified, * this is equivalent to {@code submit(executable, new JsonObject())}. * * @param executable executable to submit * @return a future for the submitted executable */ Future<J> submit(E executable); /** * Submit an executable. * * @param executable executable to submit * @param config reserved for future use: context information for the submission. * @return a future for the submitted executable */ Future<J> submit(E executable, JsonObject config); }
/* # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015, 2016 */ package quarks.execution; import java.util.concurrent.Future; import com.google.gson.JsonObject; /** * An interface for submission of an executable. * <p> * The class implementing this interface is responsible * for the semantics of this operation. e.g., an direct topology * provider would run the topology as threads in the current jvm. * * @param <E> the executable type * @param <J> the submitted executable's future */ public interface Submitter<E, J extends Job> { /** * Submit an executable. * No configuration options are specified, * this is equivalent to {@code submit(executable, new JsonObject())}. * * @param executable executable to submit * @return a future for the submitted executable */ Future<J> submit(E executable); /** * Submit an executable. * * @param executable executable to submit * @param config context information for the submission. * @return a future for the submitted executable */ Future<J> submit(E executable, JsonObject config); }
Fix filebroker response when the file wasn't found
package fi.csc.microarray.messaging.message; import java.net.MalformedURLException; import java.net.URL; import javax.jms.JMSException; import javax.jms.MapMessage; public class UrlMessage extends ChipsterMessage { private final static String KEY_URL = "url"; private URL url; public UrlMessage() { super(); } public UrlMessage(URL url) { super(); this.url = url; } public URL getUrl() { return url; } public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); String urlString = from.getString(KEY_URL); if (urlString == null) { this.url = null; } else { try { this.url = new URL(from.getString(KEY_URL)); } catch (MalformedURLException e) { handleException(e); } } } public void marshal(MapMessage mapMessage) throws JMSException { super.marshal(mapMessage); String urlString = null; if (this.url != null) { urlString = this.url.toString(); } mapMessage.setString(KEY_URL, urlString); } }
package fi.csc.microarray.messaging.message; import java.net.MalformedURLException; import java.net.URL; import javax.jms.JMSException; import javax.jms.MapMessage; public class UrlMessage extends ChipsterMessage { private final static String KEY_URL = "url"; private URL url; public UrlMessage() { super(); } public UrlMessage(URL url) { super(); this.url = url; } public URL getUrl() { return url; } public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); try { this.url = new URL(from.getString(KEY_URL)); } catch (MalformedURLException e) { handleException(e); } } public void marshal(MapMessage mapMessage) throws JMSException { super.marshal(mapMessage); String urlString = null; if (this.url != null) { urlString = this.url.toString(); } mapMessage.setString(KEY_URL, urlString); } }
Update zebra puzzle to reflect LogicProblem changes.
import astor from data import warehouse from puzzle.examples.public_domain import zebra_puzzle from puzzle.problems import logic_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('zebra_puzzle'): with description('solution'): with before.all: warehouse.save() prod_config.init() self.subject = zebra_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('identifies puzzle type'): problems = self.subject.problems() expect(problems).to(have_len(1)) problem = problems[0] expect(problem).to(be_a(logic_problem.LogicProblem)) with it('parses expressions'): parsed = logic_problem._parse(zebra_puzzle.SOURCE.split('\n')) expect(astor.to_source(parsed)).to(look_like(zebra_puzzle.PARSED)) with it('models puzzle'): model = logic_problem._model(zebra_puzzle.SOURCE.split('\n')) print(str(model)) with it('exports a solution'): problem = self.subject.problems()[0] expect(problem.solution).to(look_like(zebra_puzzle.SOLUTION))
import astor from data import warehouse from puzzle.examples.public_domain import zebra_puzzle from puzzle.problems import logic_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('zebra_puzzle'): with description('solution'): with before.all: warehouse.save() prod_config.init() self.subject = zebra_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('identifies puzzle type'): problems = self.subject.problems() expect(problems).to(have_len(1)) problem = problems[0] expect(problem).to(be_a(logic_problem.LogicProblem)) with it('parses expressions'): problem = self.subject.problems()[0] expect(astor.to_source(problem._parse())).to( look_like(zebra_puzzle.PARSED)) with it('exports a model'): problem = self.subject.problems()[0] expect(problem.solution).to(look_like(zebra_puzzle.SOLUTION))
Fix link to event page
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Link from '../link' import Section from './section' const Events = ({ t }) => ( <Section title={t('eventsSectionTitle')}> <Link href='/events'> <a>{t('eventsLink')}</a> </Link> <style jsx>{` @import 'colors'; a { color: $darkgrey; display: block; margin-top: 1em; &:focus, &:hover { color: $black; } } `}</style> </Section> ) Events.propTypes = { t: PropTypes.func.isRequired } export default translate('home')(Events)
import React from 'react' import PropTypes from 'prop-types' import Link from 'next/link' import { translate } from 'react-i18next' import Section from './section' const Events = ({ t }) => ( <Section title={t('eventsSectionTitle')}> <Link href='/events'> <a>{t('eventsLink')}</a> </Link> <style jsx>{` @import 'colors'; a { color: $darkgrey; display: block; margin-top: 1em; &:focus, &:hover { color: $black; } } `}</style> </Section> ) Events.propTypes = { t: PropTypes.func.isRequired } export default translate('home')(Events)
Use default IPython profile when converting to HTML
from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags from nbgrader.templates import get_template_path aliases = {} aliases.update(base_aliases) aliases.update({ 'regexp': 'FindStudentID.regexp' }) flags = {} flags.update(base_flags) flags.update({ 'serve': ( {'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}}, "Run the form grading server" ) }) class FormgradeApp(CustomNbConvertApp): name = Unicode(u'nbgrader-formgrade') description = Unicode(u'Grade a notebook using an HTML form') aliases = aliases flags = flags ipython_dir = "/tmp" student_id = Unicode(u'', config=True) def _export_format_default(self): return 'html' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.FindStudentID' ] self.extra_config.Exporter.template_file = 'formgrade' self.extra_config.Exporter.template_path = ['.', get_template_path()] self.config.merge(self.extra_config)
from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags from nbgrader.templates import get_template_path aliases = {} aliases.update(base_aliases) aliases.update({ 'regexp': 'FindStudentID.regexp' }) flags = {} flags.update(base_flags) flags.update({ 'serve': ( {'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}}, "Run the form grading server" ) }) class FormgradeApp(CustomNbConvertApp): name = Unicode(u'nbgrader-formgrade') description = Unicode(u'Grade a notebook using an HTML form') aliases = aliases flags = flags student_id = Unicode(u'', config=True) def _export_format_default(self): return 'html' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.FindStudentID' ] self.extra_config.Exporter.template_file = 'formgrade' self.extra_config.Exporter.template_path = ['.', get_template_path()] self.config.merge(self.extra_config)
Fix dependency link for Django 1.5rc1
#! /usr/bin/env python #-*- coding=utf-8 -*- from setuptools import setup setup(name='kitabu', author=u'Adrian Duraj & Marek Brzóska', author_email='adrian.duraj@gmail.com, brzoskamarek@gmail.com', description="Django library to build reservation application", license='MIT', version='dev', url='https://github.com/mbad/kitabu', packages=['kitabu'], #include_package_data=True, install_requires=[ 'Django>=1.5c1', 'South>=0.7.6', ], dependency_links=[ 'http://github.com/django/django/tarball/1.5c1#egg=Django-1.5c1', ], )
#! /usr/bin/env python #-*- coding=utf-8 -*- from setuptools import setup setup(name='kitabu', author=u'Adrian Duraj & Marek Brzóska', author_email='adrian.duraj@gmail.com, brzoskamarek@gmail.com', description="Django library to build reservation application", license='MIT', version='dev', url='https://github.com/mbad/kitabu', packages=['kitabu'], #include_package_data=True, install_requires=[ 'Django==1.5c1', 'South>=0.7.6', ], dependency_links=[ 'http://github.com/mbad/kitabu/tarball/master#egg=kitabu-dev' ], )
feat: Enable delete and update post on home page
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Post from "./Post"; import PropTypes from 'prop-types'; class CategoryBody extends Component { render() { return ( <div className="card-body"> <div className="row"> { this.props.posts.map((post, index) => ( <div className="col-md-6" key={index} > <Post post={post} isEditEnabled={true} isDeleteEnabled={true}/> <br/> </div> )) } </div> </div> ) } } CategoryBody.propTypes = { posts: PropTypes.array.isRequired }; export default CategoryBody;
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Post from "./Post"; import PropTypes from 'prop-types'; class CategoryBody extends Component { render() { return ( <div className="card-body"> <div className="row"> { this.props.posts.map((post, index) => ( <div className="col-md-4" key={index}> <Post post={post}/> <br/> </div> )) } </div> </div> ) } } CategoryBody.propTypes = { posts: PropTypes.array.isRequired }; export default CategoryBody;
Add decode(utf-8) to return on encrypt
import base64 from Crypto.Cipher import AES from Crypto import Random def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') def decrypt(enc, key): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) result = unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') return result def pad(s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(s): return s[:-ord(s[len(s)-1:])]
import base64 from Crypto.Cipher import AES from Crypto import Random def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)) def decrypt(enc, key): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) result = unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') return result def pad(s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(s): return s[:-ord(s[len(s)-1:])]
Revert: Allow upgrade of transaction from readonly to exclusive
/** * Copyright 2010 - 2017 JetBrains s.r.o. * * 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 jetbrains.exodus.entitystore; import org.jetbrains.annotations.NotNull; public class ReadonlyPersistentStoreTransaction extends PersistentStoreTransaction { ReadonlyPersistentStoreTransaction(@NotNull final PersistentEntityStoreImpl store) { super(store, TransactionType.Readonly); } @Override public boolean isIdempotent() { if (!super.isIdempotent()) { throw new IllegalStateException("ReadonlyPersistentStoreTransaction should be idempotent"); } return true; } public PersistentStoreTransaction getUpgradedTransaction() { return new PersistentStoreTransaction(this, TransactionType.Regular); } }
/** * Copyright 2010 - 2017 JetBrains s.r.o. * * 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 jetbrains.exodus.entitystore; import org.jetbrains.annotations.NotNull; public class ReadonlyPersistentStoreTransaction extends PersistentStoreTransaction { ReadonlyPersistentStoreTransaction(@NotNull final PersistentEntityStoreImpl store) { super(store, TransactionType.Readonly); } @Override public boolean isIdempotent() { if (!super.isIdempotent()) { throw new IllegalStateException("ReadonlyPersistentStoreTransaction should be idempotent"); } return true; } public PersistentStoreTransaction getUpgradedTransaction(boolean exclusive) { return new PersistentStoreTransaction(this, exclusive ? TransactionType.Exclusive : TransactionType.Regular); } public PersistentStoreTransaction getUpgradedTransaction() { return getUpgradedTransaction(false); } }
Add `text.md` to the default grammars
'use babel'; import Controller from './controller.js'; export default { config: { grammars: { type : 'array', default: ['source.gfm', 'text.md'], items : { type: 'string' } }, minimumContentWidth: { type : 'integer', default: 3, minimum: 3 }, useEastAsianWidth: { type : 'boolean', default : false, description: 'Compute character width' + ' based on the Unicode East Asian Width specification' }, smartCursor: { type : 'boolean', default : false, description: '(experimental) Enable smart cursor movement' } }, controler: null, activate() { this.controller = new Controller(); }, deactivate() { this.controller.destroy(); }, serialize() { } };
'use babel'; import Controller from './controller.js'; export default { config: { grammars: { type : 'array', default: ['source.gfm'], items : { type: 'string' } }, minimumContentWidth: { type : 'integer', default: 3, minimum: 3 }, useEastAsianWidth: { type : 'boolean', default : false, description: 'Compute character width' + ' based on the Unicode East Asian Width specification' }, smartCursor: { type : 'boolean', default : false, description: '(experimental) Enable smart cursor movement' } }, controler: null, activate() { this.controller = new Controller(); }, deactivate() { this.controller.destroy(); }, serialize() { } };
Raise exception if HTTP request failed
from __future__ import absolute_import import requests from graphql.execution import ExecutionResult from graphql.language.printer import print_ast from .http import HTTPTransport class RequestsHTTPTransport(HTTPTransport): def __init__(self, auth=None, *args, **kwargs): super(RequestsHTTPTransport, self).__init__(*args, **kwargs) self.auth = auth def execute(self, document, variable_values=None): query_str = print_ast(document) request = requests.post( self.url, data={ 'query': query_str, 'variables': variable_values }, headers=self.client_headers, auth=self.auth ) request.raise_for_status() result = request.json() assert 'errors' in result or 'data' in result, 'Received non-compatible response "{}"'.format(result) return ExecutionResult( errors=result.get('errors'), data=result.get('data') )
from __future__ import absolute_import import requests from graphql.execution import ExecutionResult from graphql.language.printer import print_ast from .http import HTTPTransport class RequestsHTTPTransport(HTTPTransport): def __init__(self, auth=None, *args, **kwargs): super(RequestsHTTPTransport, self).__init__(*args, **kwargs) self.auth = auth def execute(self, document, variable_values=None): query_str = print_ast(document) request = requests.post( self.url, data={ 'query': query_str, 'variables': variable_values }, headers=self.client_headers, auth=self.auth ) result = request.json() assert 'errors' in result or 'data' in result, 'Received non-compatible response "{}"'.format(result) return ExecutionResult( errors=result.get('errors'), data=result.get('data') )
Allow 'cache-path' key to be passed to cefclient.
var spawn = require('child_process').spawn; var path = require('path'); module.exports = function (options) { options = options || {}; options.url = options.url || 'http://nodejs.org'; options.name = options.name || 'nodejs'; var client; var keys = []; switch (process.platform) { case 'win32': client = path.resolve(__dirname + '/cefclient/cefclient'); keys = ['url', 'name', 'width', 'height', 'minwidth', 'minheight', 'ico', 'cache-path']; break; case 'linux': client = path.resolve(__dirname + '/build/default/topcube'); keys = ['url', 'name', 'width', 'height', 'minwidth', 'minheight']; break; default: console.warn(''); return null; break; } var args = []; for (var key in options) { if (keys.indexOf(key) !== -1) { args.push('--' + key + '=' + options[key]); } } var child = spawn(client, args); child.on('exit', function(code) { process.exit(code); }); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); return child; };
var spawn = require('child_process').spawn; var path = require('path'); module.exports = function (options) { options = options || {}; options.url = options.url || 'http://nodejs.org'; options.name = options.name || 'nodejs'; var client; var keys = []; switch (process.platform) { case 'win32': client = path.resolve(__dirname + '/cefclient/cefclient'); keys = ['url', 'name', 'width', 'height', 'minwidth', 'minheight', 'ico']; break; case 'linux': client = path.resolve(__dirname + '/build/default/topcube'); keys = ['url', 'name', 'width', 'height', 'minwidth', 'minheight']; break; default: console.warn(''); return null; break; } var args = []; for (var key in options) { if (keys.indexOf(key) !== -1) { args.push('--' + key + '=' + options[key]); } } var child = spawn(client, args); child.on('exit', function(code) { process.exit(code); }); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); return child; };
Add East Riding of Yorkshire Council to migration
"""empty message Revision ID: 0165_another_letter_org Revises: 0164_add_organisation_to_service Create Date: 2017-06-29 12:44:16.815039 """ # revision identifiers, used by Alembic. revision = '0165_another_letter_org' down_revision = '0164_add_organisation_to_service' from alembic import op NEW_ORGANISATIONS = [ ('502', 'Welsh Revenue Authority'), ('503', 'East Riding of Yorkshire Council'), ] def upgrade(): for numeric_id, name in NEW_ORGANISATIONS: op.execute(""" INSERT INTO dvla_organisation VALUES ('{}', '{}') """.format(numeric_id, name)) def downgrade(): for numeric_id, _ in NEW_ORGANISATIONS: op.execute(""" DELETE FROM dvla_organisation WHERE id = '{}' """.format(numeric_id))
"""empty message Revision ID: 0165_another_letter_org Revises: 0164_add_organisation_to_service Create Date: 2017-06-29 12:44:16.815039 """ # revision identifiers, used by Alembic. revision = '0165_another_letter_org' down_revision = '0164_add_organisation_to_service' from alembic import op NEW_ORGANISATIONS = [ ('502', 'Welsh Revenue Authority'), ] def upgrade(): for numeric_id, name in NEW_ORGANISATIONS: op.execute(""" INSERT INTO dvla_organisation VALUES ('{}', '{}') """.format(numeric_id, name)) def downgrade(): for numeric_id, _ in NEW_ORGANISATIONS: op.execute(""" DELETE FROM dvla_organisation WHERE id = '{}' """.format(numeric_id))
Fix bug: KeyframeCollection.toJSON() without options
/** 关键帧collection @module **/ define([ 'backbone', 'relationalScope', 'model.keyframe' ], function( Backbone, relationalScope, Keyframe ){ var KeyframeCollection; /** @class KeyframeCollection @extends Backbone.Collection **/ KeyframeCollection = Backbone.Collection.extend({ /** Start: backbone内置属性/方法 **/ model: Keyframe, comparator: 'time', toJSON: function(options){ var json; options = options || {}; if('time' in options){ json = this.where({time: options.time})[0].toJSON(); json = [json]; } else{ json = KeyframeCollection.__super__.toJSON.call(this, options); } return json; } /** End: backbone内置属性/方法 **/ }); relationalScope.KeyframeCollection = KeyframeCollection; return KeyframeCollection; });
/** 关键帧collection @module **/ define([ 'backbone', 'relationalScope', 'model.keyframe' ], function( Backbone, relationalScope, Keyframe ){ var KeyframeCollection; /** @class KeyframeCollection @extends Backbone.Collection **/ KeyframeCollection = Backbone.Collection.extend({ /** Start: backbone内置属性/方法 **/ model: Keyframe, comparator: 'time', toJSON: function(options){ var json; if('time' in options){ json = this.where({time: options.time})[0].toJSON(); json = [json]; } else{ json = KeyframeCollection.__super__.toJSON.call(this, options); } return json; } /** End: backbone内置属性/方法 **/ }); relationalScope.KeyframeCollection = KeyframeCollection; return KeyframeCollection; });
Use long array syntax for older PHP versions
<?php namespace Craft; use Twig_Extension; use Twig_Function_Method; use InvalidArgumentException; class AssetRevTwigExtension extends Twig_Extension { /** * Returns the name of the extension. * * @return string The extension name */ public function getName() { return 'Club Asset Rev'; } /** * Get Twig Functions * * @return array */ public function getFunctions() { return array( 'rev' => new Twig_Function_Method($this, 'getAssetRevisionFilename'), ); } /** * Get the filename of a asset revision from the asset manifest * * @param $file * @param null $manifestPath * * @return mixed */ public function getAssetRevisionFilename($file, $manifestPath = null) { static $manifest = null; $manifestPath = !is_null($manifestPath) ? $manifestPath : CRAFT_BASE_PATH.'../resources/assets/assets.json'; if (is_null($manifest)) { $manifest = json_decode(file_get_contents($manifestPath), true); } if (!isset($manifest[$file])) { throw new InvalidArgumentException("File {$file} not found in assets manifest"); } return $manifest[$file]; } }
<?php namespace Craft; use Twig_Extension; use Twig_Function_Method; use InvalidArgumentException; class AssetRevTwigExtension extends Twig_Extension { /** * Returns the name of the extension. * * @return string The extension name */ public function getName() { return 'Club Asset Rev'; } /** * Get Twig Functions * * @return array */ public function getFunctions() { return [ 'rev' => new Twig_Function_Method($this, 'getAssetRevisionFilename'), ]; } /** * Get the filename of a asset revision from the asset manifest * * @param $file * @param null $manifestPath * * @return mixed */ public function getAssetRevisionFilename($file, $manifestPath = null) { static $manifest = null; $manifestPath = !is_null($manifestPath) ? $manifestPath : CRAFT_BASE_PATH.'../resources/assets/assets.json'; if (is_null($manifest)) { $manifest = json_decode(file_get_contents($manifestPath), true); } if (!isset($manifest[$file])) { throw new InvalidArgumentException("File {$file} not found in assets manifest"); } return $manifest[$file]; } }
Add framework of events system
const { exec } = require('child_process'); const EventEmitter = require('events'); class Execute extends EventEmitter { constructor(options) { super(); let { fullCmd, params } = options; this.fullCmd = fullCmd; this.params = params; } run() { RunCmd(BuildCmd(this.fullCmd, this.params)) .then((msg) => { this.emit('end', msg); }) .catch((error) => { this.emit('error', error) }); } static run(fullCmd) { return RunCmd(fullCmd); } static cmd(base, params) { return BuildCmd(base, params); } } module.exports = Execute; function RunCmd(fullCmd) { return new Promise((resolve, reject) => { console.log(`Executing command: ${ fullCmd }`); exec(fullCmd, (error, stdout, stderr) => { if (stderr || error) { reject(stderr || error); } resolve(stdout); }); }); } function BuildCmd(base, params) { if (!params && base) { return base; } if (params.constructor !== Array) { throw new Error('params must be an Array'); } return base + ' ' + params.join(' '); }
const { exec } = require('child_process'); const EventEmitter = require('events'); class Execute extends EventEmitter { constructor() { super(); } static run(fullCmd) { return new Promise((resolve, reject) => { console.log(`Executing command: ${ fullCmd }`); exec(fullCmd, (error, stdout, stderr) => { if (stderr || error) { reject(stderr || error); } resolve(stdout); }); }); } static cmd(base, params) { if (params.constructor !== Array) { throw new Error('params must be an Array'); } return base + ' ' + params.join(' '); } } module.exports.Execute = Execute;