text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Make sure themes come in if no config present
module.exports = { name: 'ember-cli-toggle', included: function(app) { app.import('vendor/ember-cli-toggle/base.css'); // Use configuration to decide which theme css files // to import, thus not populating the user's app this.importThemes(app); }, importThemes: function(app) { var projectConfig = this.project.config(app.env); var config = projectConfig['ember-cli-toggle']; if (config) { var allThemes = ['light', 'ios', 'default', 'flat', 'skewed', 'flip']; var included = config.includedThemes; var excluded = config.excludedThemes; var themes = []; if (included && Array.isArray(included)) { themes = themes.concat(included); } else { themes = allThemes; } if (excluded && Array.isArray(excluded)) { themes = themes.filter(function (theme) { return excluded.indexOf(theme) === -1; }); } themes = themes.filter(function (theme) { return theme && allThemes.indexOf(theme) !== -1; }); themes.forEach(function (theme) { app.import('vendor/ember-cli-toggle/themes/' + theme + '.css'); }); } } };
module.exports = { name: 'ember-cli-toggle', included: function(app) { app.import('vendor/ember-cli-toggle/base.css'); // Use configuration to decide which theme css files // to import, thus not populating the user's app this.importThemes(app); }, importThemes: function(app) { var projectConfig = this.project.config(app.env); var config = projectConfig['ember-cli-toggle']; if (config && Object.keys(config).length) { var allThemes = ['light', 'ios', 'default', 'flat', 'skewed', 'flip']; var included = config.includedThemes; var excluded = config.excludedThemes; var themes = []; if (included && Array.isArray(included)) { themes = themes.concat(included); } else { themes = allThemes; } if (excluded && Array.isArray(excluded)) { themes = themes.filter(function (theme) { return excluded.indexOf(theme) === -1; }); } themes = themes.filter(function (theme) { return theme && allThemes.indexOf(theme) !== -1; }); themes.forEach(function (theme) { app.import('vendor/ember-cli-toggle/themes/' + theme + '.css'); }); } } };
Add tra to plugin info git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@31052 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ // Wiki plugin to output superscript <sup>...</sup> // based on sub plugin function wikiplugin_sup_help() { return tra("Displays text in superscript.").":<br />~np~{SUP()}text{SUP}~/np~"; } function wikiplugin_sup_info() { return array( 'name' => tra( 'Superscript' ), 'documentation' => tra('PluginSup'), 'description' => tra('Displays text in superscript (exponent).'), 'prefs' => array( 'wikiplugin_sup' ), 'body' => tra('text'), 'icon' => 'pics/icons/text_superscript.png', 'params' => array( ), ); } function wikiplugin_sup($data, $params) { global $tikilib; extract ($params,EXTR_SKIP); return "<sup>$data</sup>"; }
<?php // (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ // Wiki plugin to output superscript <sup>...</sup> // based on sub plugin function wikiplugin_sup_help() { return tra("Displays text in superscript.").":<br />~np~{SUP()}text{SUP}~/np~"; } function wikiplugin_sup_info() { return array( 'name' => tra( 'Superscript' ), 'documentation' => 'PluginSup', 'description' => tra('Displays text in superscript (exponent).'), 'prefs' => array( 'wikiplugin_sup' ), 'body' => tra('text'), 'icon' => 'pics/icons/text_superscript.png', 'params' => array( ), ); } function wikiplugin_sup($data, $params) { global $tikilib; extract ($params,EXTR_SKIP); return "<sup>$data</sup>"; }
Reset mock befor running test. Not strictly required however ensures test doesn't fail if run multiple times in succession.
from __future__ import absolute_import from __future__ import unicode_literals from guardian.compat import get_user_model from guardian.compat import mock from guardian.compat import unittest from guardian.management import create_anonymous_user import django mocked_get_init_anon = mock.Mock() class TestGetAnonymousUser(unittest.TestCase): @unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only") @mock.patch('guardian.management.guardian_settings') def test_uses_custom_function(self, guardian_settings): mocked_get_init_anon.reset_mock() path = 'guardian.testapp.tests.test_management.mocked_get_init_anon' guardian_settings.GET_INIT_ANONYMOUS_USER = path guardian_settings.ANONYMOUS_USER_ID = 219 User = get_user_model() anon = mocked_get_init_anon.return_value = mock.Mock() create_anonymous_user('sender') mocked_get_init_anon.assert_called_once_with(User) self.assertEqual(anon.pk, 219) anon.save.assert_called_once_with()
from __future__ import absolute_import from __future__ import unicode_literals from guardian.compat import get_user_model from guardian.compat import mock from guardian.compat import unittest from guardian.management import create_anonymous_user import django mocked_get_init_anon = mock.Mock() class TestGetAnonymousUser(unittest.TestCase): @unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only") @mock.patch('guardian.management.guardian_settings') def test_uses_custom_function(self, guardian_settings): path = 'guardian.testapp.tests.test_management.mocked_get_init_anon' guardian_settings.GET_INIT_ANONYMOUS_USER = path guardian_settings.ANONYMOUS_USER_ID = 219 User = get_user_model() anon = mocked_get_init_anon.return_value = mock.Mock() create_anonymous_user('sender') mocked_get_init_anon.assert_called_once_with(User) self.assertEqual(anon.pk, 219) anon.save.assert_called_once_with()
Set the text area readOnly and added a onClick function.
import React from 'react'; import CsvToSqlForm from './CsvToSqlForm' export const ConvertCsv = (props) => ( <div className=""> <CsvToSqlForm></CsvToSqlForm> <div style={{marginTop : '1em'}} className="form-horizontal"> <div className="form-group"> <label htmlFor="sqlOutput" className="col-sm-2 control-label">SQL Output</label> <div className="col-sm-10"> <textarea value={props.sqlOutput} readOnly onClick={event => event.target.select()} name="sqlOutput" id="sqlOutput" className="form-control" rows="10"></textarea> </div> </div> </div> </div> ); ConvertCsv.propTypes = { sqlOutput: React.PropTypes.string }; export default ConvertCsv;
import React from 'react'; import CsvToSqlForm from './CsvToSqlForm' export const ConvertCsv = (props) => ( <div className=""> <CsvToSqlForm></CsvToSqlForm> <div style={{marginTop : '1em'}} className="form-horizontal"> <div className="form-group"> <label htmlFor="sqlOutput" className="col-sm-2 control-label">SQL Output</label> <div className="col-sm-10"> <textarea value={props.sqlOutput} name="sqlOutput" id="sqlOutput" className="form-control" rows="10"></textarea> </div> </div> </div> </div> ); ConvertCsv.propTypes = { sqlOutput: React.PropTypes.string }; export default ConvertCsv;
Split copy tasks to fix the failing test Splitting the build:copy tasks into two smaller tasks, one to copy the scss and one to copy components ensures that the files to be copied to the public and fractal directories are available when the tests run.
'use strict' const paths = require('../../config/paths.json') const gulp = require('gulp') const runSequence = require('run-sequence') const rename = require('gulp-rename') const flatten = require('gulp-flatten') const sass = require('gulp-sass') const nano = require('gulp-cssnano') // Compile Sass to CSS gulp.task('build:styles', cb => { runSequence('lint:styles', 'build:styles:copy', 'build:styles:compile', cb) }) gulp.task('build:styles:copy', cb => { runSequence('build:styles:copy:scss', 'build:styles:copy:components', cb) }) gulp.task('build:styles:copy:scss', () => { return gulp.src(paths.assetsScss + '**/*.scss') .pipe(gulp.dest(paths.bundleScss)) }) gulp.task('build:styles:copy:components', () => { return gulp.src(paths.srcComponents + '**/*.scss') .pipe(flatten()) .pipe(gulp.dest(paths.bundleScss + 'components')) }) gulp.task('build:styles:compile', () => { return gulp.src(paths.bundleScss + '**/*.scss') .pipe(sass.sync().on('error', sass.logError)) .pipe(gulp.dest(paths.bundleCss)) .pipe(gulp.dest(paths.publicCss)) .pipe(rename({ suffix: '.min' })) .pipe(nano()) .pipe(gulp.dest(paths.bundleCss)) })
'use strict' const paths = require('../../config/paths.json') const gulp = require('gulp') const runSequence = require('run-sequence') const rename = require('gulp-rename') const flatten = require('gulp-flatten') const sass = require('gulp-sass') const nano = require('gulp-cssnano') // Compile Sass to CSS gulp.task('build:styles', cb => { runSequence('lint:styles', 'build:styles:copy', 'build:styles:compile', cb) }) gulp.task('build:styles:copy', cb => { gulp.src(paths.assetsScss + '**/*.scss').pipe(gulp.dest(paths.bundleScss)) gulp.src(paths.srcComponents + '**/*.scss') .pipe(flatten()) .pipe(gulp.dest(paths.bundleScss + 'components')) return cb() }) gulp.task('build:styles:compile', () => { return gulp.src(paths.bundleScss + '**/*.scss') .pipe(sass.sync().on('error', sass.logError)) .pipe(gulp.dest(paths.bundleCss)) .pipe(gulp.dest(paths.publicCss)) .pipe(rename({ suffix: '.min' })) .pipe(nano()) .pipe(gulp.dest(paths.bundleCss)) })
Update Gulp Test to run automatically before Gulp Serve runs. If tests fail, Gulp Serve will not run.
var gulp = require('gulp'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var karma = require('karma').server; /* build our app to the dist folder */ gulp.task('default',['serve']); /* run all tests */ gulp.task('test', function (done) { karma.start({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done); }); /* serve the app */ gulp.task('serve', ['test'], function () { browserSync({ notify: false, port: 8080, server: { baseDir: ['app'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch([ 'app/*.html', 'app/scripts/**/*.js', ]).on('change', reload); }); /* serve the output of the test runner (for debugging) */ gulp.task('serve-test',function(){ browserSync({ notify: false, port: 8080, server: { baseDir: ['test','app'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch([ 'app/*.html', 'app/scripts/**/*.js', 'test/spec/**/*.js' ]).on('change', reload); })
var gulp = require('gulp'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var karma = require('karma').server; /* build our app to the dist folder */ gulp.task('default',function(){ console.log("King to B6."); }); /* run all tests */ gulp.task('test', function (done) { karma.start({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done); }); /* serve the app */ gulp.task('serve', function () { browserSync({ notify: false, port: 8080, server: { baseDir: ['app'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch([ 'app/*.html', 'app/scripts/**/*.js', ]).on('change', reload); }); /* serve the output of the test runner (for debugging) */ gulp.task('serve-test',function(){ browserSync({ notify: false, port: 8080, server: { baseDir: ['test','app'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch([ 'app/*.html', 'app/scripts/**/*.js', 'test/spec/**/*.js' ]).on('change', reload); })
Add eval sourcemap for increased recompile speed
import webpack from 'webpack'; import path from 'path'; import CopyWebpackPlugin from 'copy-webpack-plugin'; import autoprefixer from 'autoprefixer'; import loaders from './webpack.loaders'; import config from './config'; const HOST = config.server.host const PORT = config.server.port export default { entry: [ 'webpack-hot-middleware/client', 'webpack/hot/dev-server', `./src/client/index.jsx` ], devtool: process.env.WEBPACK_DEVTOOL || '#eval-source-map', output: { path: "/", publicPath: "http://" +HOST+ ":" +PORT+ "/", filename: 'app.bundle.js' }, resolve: { extensions: ['', '.js', '.jsx', '.css', '.scss', '.sass'] }, module: { loaders }, devServer: { contentBase: "./dist", noInfo: false, // --no-info option hot: true, inline: true, port: PORT, host: HOST }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }) ], postcss: function () { return [autoprefixer]; } };
import webpack from 'webpack'; import path from 'path'; import CopyWebpackPlugin from 'copy-webpack-plugin'; import autoprefixer from 'autoprefixer'; import loaders from './webpack.loaders'; import config from './config'; const HOST = config.server.host const PORT = config.server.port export default { entry: [ 'webpack-hot-middleware/client', 'webpack/hot/dev-server', `./src/client/index.jsx` ], devtool: process.env.WEBPACK_DEVTOOL || 'source-map', output: { path: "/", publicPath: "http://" +HOST+ ":" +PORT+ "/", filename: 'app.bundle.js' }, resolve: { extensions: ['', '.js', '.jsx', '.css', '.scss', '.sass'] }, module: { loaders }, devServer: { contentBase: "./dist", noInfo: false, // --no-info option hot: true, inline: true, port: PORT, host: HOST }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }) ], postcss: function () { return [autoprefixer]; } };
Load i18n Vue plugin for Jest tests
import Vue from 'vue'; import Translate from '~/vue_shared/translate'; import axios from '~/lib/utils/axios_utils'; const testTimeoutInMs = 300; jest.setTimeout(testTimeoutInMs); let testStartTime; // https://github.com/facebook/jest/issues/6947 beforeEach(() => { testStartTime = Date.now(); }); afterEach(() => { const elapsedTimeInMs = Date.now() - testStartTime; if (elapsedTimeInMs > testTimeoutInMs) { throw new Error(`Test took too long (${elapsedTimeInMs}ms > ${testTimeoutInMs}ms)!`); } }); // fail tests for unmocked requests beforeEach(done => { axios.defaults.adapter = config => { const error = new Error(`Unexpected unmocked request: ${JSON.stringify(config, null, 2)}`); error.config = config; done.fail(error); return Promise.reject(error); }; done(); }); Vue.use(Translate);
import axios from '~/lib/utils/axios_utils'; const testTimeoutInMs = 300; jest.setTimeout(testTimeoutInMs); let testStartTime; // https://github.com/facebook/jest/issues/6947 beforeEach(() => { testStartTime = Date.now(); }); afterEach(() => { const elapsedTimeInMs = Date.now() - testStartTime; if (elapsedTimeInMs > testTimeoutInMs) { throw new Error(`Test took too long (${elapsedTimeInMs}ms > ${testTimeoutInMs}ms)!`); } }); // fail tests for unmocked requests beforeEach(done => { axios.defaults.adapter = config => { const error = new Error(`Unexpected unmocked request: ${JSON.stringify(config, null, 2)}`); error.config = config; done.fail(error); return Promise.reject(error); }; done(); });
Fix regex for different output from scss-lint 0.49.0
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Sergey Margaritov # Copyright (c) 2013 Sergey Margaritov # # License: MIT # """This module exports the scss-lint plugin linter class.""" import os from SublimeLinter.lint import RubyLinter, util class Scss(RubyLinter): """Provides an interface to the scss-lint executable.""" syntax = ('css', 'sass', 'scss') cmd = 'ruby -S scss-lint' regex = r'^.+?:(?P<line>\d+)(?::(?P<column>\d+))? (?:(?P<error>\[E\])|(?P<warning>\[W\])) (?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' tempfile_suffix = 'scss' defaults = { '--include-linter:,': '', '--exclude-linter:,': '' } inline_overrides = ('bundle-exec', 'include-linter', 'exclude-linter') comment_re = r'^\s*/[/\*]' config_file = ('--config', '.scss-lint.yml', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Sergey Margaritov # Copyright (c) 2013 Sergey Margaritov # # License: MIT # """This module exports the scss-lint plugin linter class.""" import os from SublimeLinter.lint import RubyLinter, util class Scss(RubyLinter): """Provides an interface to the scss-lint executable.""" syntax = ('css', 'sass', 'scss') cmd = 'ruby -S scss-lint' regex = r'^.+?:(?P<line>\d+) (?:(?P<error>\[E\])|(?P<warning>\[W\])) (?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' tempfile_suffix = 'scss' defaults = { '--include-linter:,': '', '--exclude-linter:,': '' } inline_overrides = ('bundle-exec', 'include-linter', 'exclude-linter') comment_re = r'^\s*/[/\*]' config_file = ('--config', '.scss-lint.yml', '~')
Use the new interface to notification.send to explicitly override the default behavior and queue notifications for announcements. git-svn-id: 0d26805d86c51913b6a91884701d7ea9499c7fc0@37 4e50ab13-fc4d-0410-b010-e1608ea6a288
from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ try: from notification import models as notification except ImportError: notification = None from announcements.models import Announcement class AnnouncementAdminForm(forms.ModelForm): """ A custom form for the admin of the Announcment model. Has an extra field called send_now that when checked will send out the announcment allowing the user to decide when that happens. """ send_now = forms.BooleanField(required=False, help_text=_("Send out this announcement now.")) class Meta: model = Announcement def save(self, commit=True): """ Checks the send_now field in the form and when True sends out the announcement through notification if present. """ announcement = super(AnnouncementAdminForm, self).save(commit) if self.cleaned_data["send_now"]: if notification: users = User.objects.all() notification.send(users, "announcement", { "announcement": announcement, }, on_site=False, queue=True) return announcement
from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ try: from notification import models as notification except ImportError: notification = None from announcements.models import Announcement class AnnouncementAdminForm(forms.ModelForm): """ A custom form for the admin of the Announcment model. Has an extra field called send_now that when checked will send out the announcment allowing the user to decide when that happens. """ send_now = forms.BooleanField(required=False, help_text=_("Send out this announcement now.")) class Meta: model = Announcement def save(self, commit=True): """ Checks the send_now field in the form and when True sends out the announcement through notification if present. """ announcement = super(AnnouncementAdminForm, self).save(commit) if self.cleaned_data["send_now"]: if notification: users = User.objects.all() notification.queue(users, "announcement", { "announcement": announcement, }, on_site=False) return announcement
Add attribute for 'contact' in person shortcode
<?php # Member template for the 'medlem' shortcode function # The $meta includes member info # Uses a $content variable if available, otherwise the meta description of the actual member. $year = $meta['it_year']; $userdata = get_userdata($id); $description = ($content != null) ? $content : $meta['description']; $avatar_size = ($args != null) ? $args['avatar_size'] : 96; # Shown email may be overriden in the shortcode attribute 'contact' $user_contact = ($contact != null) ? $contact : $userdata->data->user_email; ?> <section class="member row"> <figure class="three columns"> <?php echo get_avatar($id, $avatar_size); ?> </figure> <div class="member-details nine columns"> <?php if($role) : ?> <hgroup> <h2><?php user_fullname($userdata);?></h2> <h3 class="sub"><?php echo $role;?></h3> </hgroup> <?php else : ?> <h2><?php user_fullname($userdata);?></h2> <?php endif;?> <p class="description"> <?php echo strip_tags($description);?> </p> <footer> <?php if($user_contact) : ?> <strong>Kontakt:</strong> <a href="mailto:<?php echo $user_contact;?>"><?php echo $user_contact;?></a> <?php endif;?> </footer> </div> </section>
<?php # Member template for the 'medlem' shortcode function # The $meta includes member info # Uses a $content variable if available, otherwise the meta description of the actual member. $year = $meta['it_year']; $description = ($content != null) ? $content : $meta['description']; $avatar_size = ($args != null) ? $args['avatar_size'] : 96; ?> <section class="member row"> <figure class="three columns"> <?php echo get_avatar($id, $avatar_size); ?> </figure> <div class="member-details nine columns"> <?php if($role) : ?> <hgroup> <h2><?php user_fullname(get_userdata($id));?></h2> <h3 class="sub"><?php echo $role;?></h3> </hgroup> <?php else : ?> <h2><?php user_fullname(get_userdata($id));?></h2> <?php endif;?> <p class="description"> <?php echo strip_tags($description);?> </p> </div> </section>
Fix argument order of tile item message ctor call Rearrange the arguments passed to the SendTileItemUpdateMessage constructor when recording a ground item RegionUpdate. Fixes #316.
package org.apollo.game.model.area.update; import org.apollo.game.message.impl.RegionUpdateMessage; import org.apollo.game.message.impl.RemoveTileItemMessage; import org.apollo.game.message.impl.SendPublicTileItemMessage; import org.apollo.game.model.area.EntityUpdateType; import org.apollo.game.model.area.Region; import org.apollo.game.model.entity.GroundItem; /** * A {@link UpdateOperation} for {@link GroundItem}s. * * @author Major */ public final class ItemUpdateOperation extends UpdateOperation<GroundItem> { /** * Creates the ItemUpdateOperation. * * @param region The {@link Region} the type occurred in. Must not be {@code null}. * @param type The {@link EntityUpdateType}. Must not be {@code null}. * @param item The modified {@link GroundItem}. Must not be {@code null}. */ public ItemUpdateOperation(Region region, EntityUpdateType type, GroundItem item) { super(region, type, item); } @Override protected RegionUpdateMessage add(int offset) { return new SendPublicTileItemMessage(entity.getItem(), entity.getOwnerIndex(), offset); } @Override protected RegionUpdateMessage remove(int offset) { return new RemoveTileItemMessage(entity.getItem(), offset); } }
package org.apollo.game.model.area.update; import org.apollo.game.message.impl.RegionUpdateMessage; import org.apollo.game.message.impl.RemoveTileItemMessage; import org.apollo.game.message.impl.SendPublicTileItemMessage; import org.apollo.game.model.area.EntityUpdateType; import org.apollo.game.model.area.Region; import org.apollo.game.model.entity.GroundItem; /** * A {@link UpdateOperation} for {@link GroundItem}s. * * @author Major */ public final class ItemUpdateOperation extends UpdateOperation<GroundItem> { /** * Creates the ItemUpdateOperation. * * @param region The {@link Region} the type occurred in. Must not be {@code null}. * @param type The {@link EntityUpdateType}. Must not be {@code null}. * @param item The modified {@link GroundItem}. Must not be {@code null}. */ public ItemUpdateOperation(Region region, EntityUpdateType type, GroundItem item) { super(region, type, item); } @Override protected RegionUpdateMessage add(int offset) { return new SendPublicTileItemMessage(entity.getItem(), offset, entity.getOwnerIndex()); } @Override protected RegionUpdateMessage remove(int offset) { return new RemoveTileItemMessage(entity.getItem(), offset); } }
Add missing setup in class.
const { BadRequest } = require('@feathersjs/errors'); const userDataFilter = user => ({ userId: user._id, email: user.email, firstName: user.firstName, lastName: user.lastName, importHash: user.importHash, schoolId: user.schoolId, birthday: user.birthday, }); class UserLinkImportService { constructor(userService) { this.userService = userService; this.docs = {}; } get(hash) { // can not use get becouse the hash can have / that mapped to non existing routes return this.userService.find({ query: { importHash: hash } }) .then((users) => { if (users.data.length !== 1) { throw new BadRequest('Can not match the hash.'); } return userDataFilter(users.data[0]); }).catch(err => err); } setup(app) { this.app = app; } } module.exports = UserLinkImportService;
const { BadRequest } = require('@feathersjs/errors'); const userDataFilter = user => ({ userId: user._id, email: user.email, firstName: user.firstName, lastName: user.lastName, importHash: user.importHash, schoolId: user.schoolId, birthday: user.birthday, }); class UserLinkImportService { constructor(userService) { this.userService = userService; this.docs = {}; } get(hash) { // can not use get becouse the hash can have / that mapped to non existing routes return this.userService.find({ query: { importHash: hash } }) .then((users) => { if (users.data.length !== 1) { throw new BadRequest('Can not match the hash.'); } return userDataFilter(users.data[0]); }).catch(err => err); } } module.exports = UserLinkImportService;
Add Unknown to ‘completed’ list
package com.sixsq.slipstream.statemachine; import java.util.Arrays; import java.util.List; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * 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. * -=================================================================- */ public enum States { Inactive, Initializing, Running, SendingFinalReport, Disconnected, Finalizing, Terminal, Unknown, Done, Cancelled, Aborting, Aborted, Failing, Failed; public static List<States> completed() { return Arrays.asList(States.Cancelled, States.Terminal, States.Aborted, States.Unknown, States.Done); } }
package com.sixsq.slipstream.statemachine; import java.util.Arrays; import java.util.List; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * 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. * -=================================================================- */ public enum States { Inactive, Initializing, Running, SendingFinalReport, Disconnected, Finalizing, Terminal, Unknown, Done, Cancelled, Aborting, Aborted, Failing, Failed; public static List<States> completed() { return Arrays.asList(States.Cancelled, States.Terminal, States.Aborted, States.Done); } }
Update Number of tasks listed in Find command
package seedu.address.logic.commands; import java.util.Set; /** * Finds and lists all persons in address book whose name contains any of the argument keywords. * Keyword matching is case sensitive. */ public class FindCommand extends Command { public static final String COMMAND_WORD = "find"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of " + "the specified keywords (case-sensitive) and displays them as a list with index numbers.\n" + "Parameters: KEYWORD [MORE_KEYWORDS]...\n" + "Example: " + COMMAND_WORD + " CS2103"; private final Set<String> keywords; public FindCommand(Set<String> keywords) { this.keywords = keywords; } @Override public CommandResult execute() { model.updateFilteredPersonList(keywords); return new CommandResult(getMessageForPersonListShownSummary(model.getFilteredPersonList().size()+model.getFilteredUndatedTaskList().size())); } }
package seedu.address.logic.commands; import java.util.Set; /** * Finds and lists all persons in address book whose name contains any of the argument keywords. * Keyword matching is case sensitive. */ public class FindCommand extends Command { public static final String COMMAND_WORD = "find"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of " + "the specified keywords (case-sensitive) and displays them as a list with index numbers.\n" + "Parameters: KEYWORD [MORE_KEYWORDS]...\n" + "Example: " + COMMAND_WORD + " CS2103"; private final Set<String> keywords; public FindCommand(Set<String> keywords) { this.keywords = keywords; } @Override public CommandResult execute() { model.updateFilteredPersonList(keywords); return new CommandResult(getMessageForPersonListShownSummary(model.getFilteredPersonList().size())); } }
Add (failing) test for ADHD query. Returns results on site, not through API. Needs investigation
from django.test import TestCase from api import PubMed from sysrev.models import Review class PubmedQueryTestCase(TestCase): def test_query(self): result = PubMed.query("smoking") self.assertGreater(result[u'Count'], 25000, "Expected >25000 results for smoking") def test_paper(self): result = PubMed.read_papers_from_ids([25929677]) self.assertEquals(len(result[0][u'MedlineCitation'][u'Article'][u'AuthorList']), 7, "25929677 should have 7 authors") def test_create_papers_from_ids(self): review = Review.objects.get_or_create(title="Investigating the effects of acupuncture on children with ADHD")[0] result = PubMed.create_papers_from_ids([26502548], review)[0] print result.title self.assertEquals("[A Meta-analysis on Acupuncture Treatment of Attention Deficit/Hyperactivity Disorder].", result.title) def test_adhd_query(self): query = """(adhd OR adhs OR addh) AND (child OR adolescent) AND acupuncture""" result = PubMed.get_ids_from_query(query) self.assertGreater(len(result), 0, "Expected some results for ADHD query")
from django.test import TestCase from api import PubMed from sysrev.models import Review class PubmedQueryTestCase(TestCase): def test_query(self): result = PubMed.query("smoking") self.assertGreater(result[u'Count'], 25000, "Expected >25000 results for smoking") def test_paper(self): result = PubMed.read_papers_from_ids([25929677]) self.assertEquals(len(result[0][u'MedlineCitation'][u'Article'][u'AuthorList']), 7, "25929677 should have 7 authors") def test_create_papers_from_ids(self): review = Review.objects.get_or_create(title="Investigating the effects of acupuncture on children with ADHD")[0] result = PubMed.create_papers_from_ids([26502548], review)[0] print result.title self.assertEquals("[A Meta-analysis on Acupuncture Treatment of Attention Deficit/Hyperactivity Disorder].", result.title)
Make limit a command-line parameter too.
from sys import argv from axiom.store import Store from entropy.store import ImmutableObject from entropy.util import getAppStore def moveObjects(appStore, start, limit): obj = None for obj in appStore.query( ImmutableObject, ImmutableObject.storeID >= start, limit=limit): oldPath = obj.content bucket = obj.contentDigest[:4] newPath = appStore.newFilePath( 'objects', 'immutable', bucket, '%s:%s' % (obj.hash, obj.contentDigest)) if not newPath.parent().exists(): newPath.parent().makedirs() oldPath.moveTo(newPath) obj.content = newPath if obj is None: print 'No objects selected' else: print 'Last object seen: %s' % (obj.storeID,) siteStore = Store(argv[1]) appStore = getAppStore(siteStore) limit = int(argv[3]) appStore.transact(moveObjects, appStore, int(argv[2]), int(argv[3]))
from sys import argv from axiom.store import Store from entropy.store import ImmutableObject from entropy.util import getAppStore def moveObjects(appStore, start, limit=1000): obj = None for obj in appStore.query( ImmutableObject, ImmutableObject.storeID >= start, limit=limit): oldPath = obj.content bucket = obj.contentDigest[:4] newPath = appStore.newFilePath( 'objects', 'immutable', bucket, '%s:%s' % (obj.hash, obj.contentDigest)) if not newPath.parent().exists(): newPath.parent().makedirs() oldPath.moveTo(newPath) obj.content = newPath if obj is None: print 'No objects selected' else: print 'Last object seen: %s' % (obj.storeID,) siteStore = Store(argv[1]) appStore = getAppStore(siteStore) appStore.transact(moveObjects, appStore, int(argv[2]))
Fix broken UMD filename definition
import resolve from 'rollup-plugin-node-resolve' import babel from 'rollup-plugin-babel' import commonjs from 'rollup-plugin-commonjs' import replace from 'rollup-plugin-replace' import pkg from './package.json' const input = 'src/index' const exclude = 'node_modules/**' export default [ // browser-friendly UMD build { input, output: { name: 'redux-starter-kit', file: pkg.unpkg, format: 'umd' }, plugins: [ babel({ exclude: 'node_modules/**' }), resolve(), replace({ 'process.env.NODE_ENV': JSON.stringify('development') }), commonjs({ namedExports: { 'node_modules/curriable/dist/curriable.js': ['curry', '__'] } }) ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // the `targets` option which can specify `dest` and `format`) { input, output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ], external: Object.keys(pkg.dependencies), plugins: babel({ exclude }) } ]
import resolve from 'rollup-plugin-node-resolve' import babel from 'rollup-plugin-babel' import commonjs from 'rollup-plugin-commonjs' import replace from 'rollup-plugin-replace' import pkg from './package.json' const input = 'src/index' const exclude = 'node_modules/**' export default [ // browser-friendly UMD build { input, output: { name: 'redux-starter-kit', file: pkg.browser, format: 'umd' }, plugins: [ babel({ exclude: 'node_modules/**' }), resolve(), replace({ 'process.env.NODE_ENV': JSON.stringify('development') }), commonjs({ namedExports: { 'node_modules/curriable/dist/curriable.js': ['curry', '__'] } }) ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // the `targets` option which can specify `dest` and `format`) { input, output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ], external: Object.keys(pkg.dependencies), plugins: babel({ exclude }) } ]
Allow downloading objectives & phone
const ALLOWED_CSV_FIELD_PATHS = [ 'ids.GB-CHC', 'ids.charityId', 'name', 'contact.address', 'contact.email', 'contact.geo.latitude', 'contact.geo.longitude', 'contact.person', 'contact.phone', 'contact.postcode', 'people.volunteers', 'people.employees', 'people.trustees', 'activities', 'website', 'income.annual', 'areaOfBenefit', 'causes', 'beneficiaries', 'operations', 'objectives', ] const FY_END_YEARS = [ 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, ] module.exports = { ALLOWED_CSV_FIELD_PATHS, FY_END_YEARS, }
const ALLOWED_CSV_FIELD_PATHS = [ 'ids.GB-CHC', 'ids.charityId', 'name', 'contact.email', 'contact.person', 'contact.postcode', 'contact.address', 'contact.geo.longitude', 'contact.geo.latitude', 'people.volunteers', 'people.employees', 'people.trustees', 'activities', 'website', 'income.annual', 'areaOfBenefit', 'causes', 'beneficiaries', 'operations', ] const FY_END_YEARS = [ 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, ] module.exports = { ALLOWED_CSV_FIELD_PATHS, FY_END_YEARS, }
Implement ACL for call url creation
from pyramid.security import Allow, Authenticated, authenticated_userid from cornice import Service from tokenlib.errors import Error as TokenError callurl = Service(name='callurl', path='/call-url') call = Service(name='call', path='/call/{token}') def acl(request): return [(Allow, Authenticated, 'create-callurl')] def is_token_valid(request): token = request.matchdict['token'] try: token = request.token_manager.parse_token(token.encode()) request.validated['token'] = token except TokenError as e: request.errors.add('querystring', 'token', e.message) @callurl.post(permission='create-callurl', acl=acl) def generate_callurl(request): """ Generate a callurl based on user ID. """ userid = authenticated_userid(request) token = request.token_manager.make_token({"userid": userid}) call_url = '{root}/call/{token}'.format(root=request.application_url, token=token) return {'call-url': call_url} @call.get(validators=[is_token_valid], renderer='templates/call.jinja2') def display_app(request): return request.validated['token']
from cornice import Service from tokenlib.errors import Error as TokenError callurl = Service(name='callurl', path='/call-url') call = Service(name='call', path='/call/{token}') def is_authenticated(request): """Validates that an user is authenticated and extracts its userid""" request.validated['userid'] = 'n1k0'; def is_token_valid(request): token = request.matchdict['token'] try: token = request.token_manager.parse_token(token.encode()) request.validated['token'] = token except TokenError as e: request.errors.add('querystring', 'token', e.message) @callurl.post(permission='create') def generate_callurl(request): """ Generate a callurl based on user ID. """ token = request.token_manager.make_token({ "userid": request.validated['userid'], }) call_url = '{root}/call/{token}'.format(root=request.application_url, token=token) return {'call-url': call_url} @call.get(validators=[is_token_valid], renderer='templates/call.jinja2') def display_app(request): return request.validated['token']
Fix ref on downshift element
import React from 'react'; import PropTypes from 'prop-types'; import Popper from '../Popper'; const OptionsListWrapper = React.forwardRef(({ useLegacy, children, controlRef, isOpen, renderToOverlay, menuPropGetter, modifiers, ...props }, ref) => { if (useLegacy) { return <div {...menuPropGetter({ ref })} {...props} hidden={!isOpen}>{children}</div>; } const { overlayRef, ...menuRest } = menuPropGetter({ ref, refKey: 'overlayRef' }); let portal; if (renderToOverlay) { portal = document.getElementById('OverlayContainer'); } return ( <Popper anchorRef={controlRef} overlayProps={{ ...menuRest, ...props }} overlayRef={overlayRef} isOpen={isOpen} portal={portal} placement="bottom-start" modifiers={modifiers} hideIfClosed > {children} </Popper> ); }); OptionsListWrapper.displayName = 'OptionsListWrapper'; OptionsListWrapper.propTypes = { children: PropTypes.node, controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), isOpen: PropTypes.bool, menuPropGetter: PropTypes.func, modifiers: PropTypes.object, renderToOverlay: PropTypes.bool, useLegacy: PropTypes.bool, }; export default OptionsListWrapper;
import React from 'react'; import PropTypes from 'prop-types'; import Popper from '../Popper'; const OptionsListWrapper = React.forwardRef(({ useLegacy, children, controlRef, isOpen, renderToOverlay, menuPropGetter, modifiers, ...props }, ref) => { if (useLegacy) { return <div {...menuPropGetter()} {...props} ref={ref} hidden={!isOpen}>{children}</div>; } const { overlayRef, ...menuRest } = menuPropGetter({ ref, refKey: 'overlayRef' }); let portal; if (renderToOverlay) { portal = document.getElementById('OverlayContainer'); } return ( <Popper anchorRef={controlRef} overlayProps={{ ...menuRest, ...props }} overlayRef={overlayRef} isOpen={isOpen} portal={portal} placement="bottom-start" modifiers={modifiers} hideIfClosed > {children} </Popper> ); }); OptionsListWrapper.displayName = 'OptionsListWrapper'; OptionsListWrapper.propTypes = { children: PropTypes.node, controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), isOpen: PropTypes.bool, menuPropGetter: PropTypes.func, modifiers: PropTypes.object, renderToOverlay: PropTypes.bool, useLegacy: PropTypes.bool, }; export default OptionsListWrapper;
Fix another weird logger instantiation
import {logging} from "./react-server"; const logger = logging.getLogger(__LOGGER__); // takes in the err and stats object returned by a webpack compilation and returns // an error object if something serious happened, or null if things are ok. export default function handleCompilationErrors (err, stats){ if (err) { logger.error("Error during webpack build."); logger.error(err); return new Error(err); // TODO: inspect stats to see if there are errors -sra. } else if (stats.hasErrors()) { console.error("There were errors in the JavaScript compilation."); stats.toJson().errors.forEach((error) => { console.error(error); }); return new Error("There were errors in the JavaScript compilation."); } else if (stats.hasWarnings()) { logger.warning("There were warnings in the JavaScript compilation. Note that this is normal if you are minifying your code."); // for now, don't enumerate warnings; they are absolutely useless in minification mode. // TODO: handle this more intelligently, perhaps with a --reportwarnings flag or with different // behavior based on whether or not --minify is set. } return null; }
import reactServer from "./react-server"; const logger = reactServer.logging.getLogger(__LOGGER__); // takes in the err and stats object returned by a webpack compilation and returns // an error object if something serious happened, or null if things are ok. export default function handleCompilationErrors (err, stats){ if (err) { logger.error("Error during webpack build."); logger.error(err); return new Error(err); // TODO: inspect stats to see if there are errors -sra. } else if (stats.hasErrors()) { console.error("There were errors in the JavaScript compilation."); stats.toJson().errors.forEach((error) => { console.error(error); }); return new Error("There were errors in the JavaScript compilation."); } else if (stats.hasWarnings()) { logger.warning("There were warnings in the JavaScript compilation. Note that this is normal if you are minifying your code."); // for now, don't enumerate warnings; they are absolutely useless in minification mode. // TODO: handle this more intelligently, perhaps with a --reportwarnings flag or with different // behavior based on whether or not --minify is set. } return null; }
Add pytimeparse as an install dependency
from setuptools import setup, find_packages from bot import project_info setup( name=project_info.name, use_scm_version=True, description=project_info.description, long_description=project_info.description, url=project_info.url, author=project_info.author_name, author_email=project_info.author_email, license=project_info.license_name, packages=find_packages(), setup_requires=[ 'setuptools_scm' ], install_requires=[ 'sqlite-framework', 'requests', 'pytz', 'psutil', 'pytimeparse' ], python_requires='>=3', # for pypi: keywords='telegram bot api framework', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
from setuptools import setup, find_packages from bot import project_info setup( name=project_info.name, use_scm_version=True, description=project_info.description, long_description=project_info.description, url=project_info.url, author=project_info.author_name, author_email=project_info.author_email, license=project_info.license_name, packages=find_packages(), setup_requires=[ 'setuptools_scm' ], install_requires=[ 'sqlite-framework', 'requests', 'pytz', 'psutil' ], python_requires='>=3', # for pypi: keywords='telegram bot api framework', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
Use codecs.open for py2/py3-compatible utf8 reading Fixes gh-6
from setuptools import setup, find_packages import sys import os.path import numpy as np # Must be one line or PyPI will cut it off DESC = ("A powerful, accurate, and easy-to-use Python library for " "doing colorspace conversions") import codecs LONG_DESC = codecs.open("README.rst", encoding="utf-8").read() # defines __version__ exec(open("colorspacious/version.py").read()) setup( name="colorspacious", version=__version__, description=DESC, long_description=LONG_DESC, author="Nathaniel J. Smith", author_email="njs@pobox.com", url="https://github.com/njsmith/colorspacious", license="MIT", classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], packages=find_packages(), install_requires=["numpy"], )
from setuptools import setup, find_packages import sys import os.path import numpy as np # Must be one line or PyPI will cut it off DESC = ("A powerful, accurate, and easy-to-use Python library for " "doing colorspace conversions") LONG_DESC = open("README.rst").read() # defines __version__ exec(open("colorspacious/version.py").read()) setup( name="colorspacious", version=__version__, description=DESC, long_description=LONG_DESC, author="Nathaniel J. Smith", author_email="njs@pobox.com", url="https://github.com/njsmith/colorspacious", license="MIT", classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], packages=find_packages(), install_requires=["numpy"], )
REFACTOR : Import YAMLError so it is usable as a generic exception.
# The all important loader from strictyaml.parser import load # Validators from strictyaml.validators import Optional from strictyaml.validators import Validator from strictyaml.validators import OrValidator from strictyaml.validators import Any from strictyaml.validators import Scalar from strictyaml.validators import Enum from strictyaml.validators import Str from strictyaml.validators import Int from strictyaml.validators import Bool from strictyaml.validators import Float from strictyaml.validators import Decimal from strictyaml.validators import Map from strictyaml.validators import MapPattern from strictyaml.validators import Seq from strictyaml.validators import UniqueSeq # Exceptions from strictyaml.exceptions import YAMLError from strictyaml.exceptions import StrictYAMLError from strictyaml.exceptions import YAMLValidationError # Disallowed token exceptions from strictyaml.exceptions import DisallowedToken from strictyaml.exceptions import TagTokenDisallowed from strictyaml.exceptions import FlowMappingDisallowed from strictyaml.exceptions import AnchorTokenDisallowed
# The all important loader from strictyaml.parser import load # Validators from strictyaml.validators import Optional from strictyaml.validators import Validator from strictyaml.validators import OrValidator from strictyaml.validators import Any from strictyaml.validators import Scalar from strictyaml.validators import Enum from strictyaml.validators import Str from strictyaml.validators import Int from strictyaml.validators import Bool from strictyaml.validators import Float from strictyaml.validators import Decimal from strictyaml.validators import Map from strictyaml.validators import MapPattern from strictyaml.validators import Seq from strictyaml.validators import UniqueSeq # Exceptions from strictyaml.exceptions import StrictYAMLError # Validaton from strictyaml.exceptions import YAMLValidationError # Disallowed token exceptions from strictyaml.exceptions import DisallowedToken from strictyaml.exceptions import TagTokenDisallowed from strictyaml.exceptions import FlowMappingDisallowed from strictyaml.exceptions import AnchorTokenDisallowed
Use router to navigate to buildset
zeus.simpleModule('apps.projects.views', function (views, Marionette, $) { views.ProjectLayout = Marionette.Layout.extend({ template: "#project-layout-template", regions: { contentRegion: "#project-content-region" } }); views.ProjectDetails = zeus.views.View.extend({ template: "#project-details-template", modelContextName: "project", events: { "click .show-buildset": "showBuildset" }, showBuildset: function (event) { event.preventDefault(); event.stopPropagation(); var url = $(event.target).attr('href'); zeus.navigate(url, {trigger: true}); } }); views.BuildsetDetails = zeus.views.View.extend({ template: "#buildset-details-template", modelContextName: "buildset" }); }, Marionette, $);
zeus.simpleModule('apps.projects.views', function (views, Marionette, $) { views.ProjectLayout = Marionette.Layout.extend({ template: "#project-layout-template", regions: { contentRegion: "#project-content-region" } }); views.ProjectDetails = zeus.views.View.extend({ template: "#project-details-template", modelContextName: "project", events: { "click .show-buildset": "showBuildset" }, showBuildset: function (event) { event.preventDefault(); event.stopPropagation(); var number = this.getBuildsetNumber(event); zeus.trigger('show:buildset', this.model.get('name'), number) }, getBuildsetNumber: function (event) { var el = $(event.target); return el.attr('buildsetNumber'); } }); views.BuildsetDetails = zeus.views.View.extend({ template: "#buildset-details-template", modelContextName: "buildset" }); }, Marionette, $);
Allow loading without a callback
/*global _, Backbone, lumbarLoader */ (function() { lumbarLoader.initEvents = function() { // Needs to be defered until we know that backbone has been loaded _.extend(lumbarLoader, Backbone.Events); }; if (window.Backbone) { lumbarLoader.initEvents(); } var baseLoadModule = lumbarLoader.loadModule; lumbarLoader.loadModule = function(moduleName, callback, options) { options = options || {}; var loaded = lumbarLoader.isLoaded(moduleName); if (!options.silent && !loaded) { lumbarLoader.trigger && lumbarLoader.trigger('load:start', moduleName, undefined, lumbarLoader); } baseLoadModule(moduleName, function(error) { if (!options.silent && !loaded) { lumbarLoader.trigger && lumbarLoader.trigger('load:end', lumbarLoader); } callback && callback(error); }, options); }; }());
/*global _, Backbone, lumbarLoader */ (function() { lumbarLoader.initEvents = function() { // Needs to be defered until we know that backbone has been loaded _.extend(lumbarLoader, Backbone.Events); }; if (window.Backbone) { lumbarLoader.initEvents(); } var baseLoadModule = lumbarLoader.loadModule; lumbarLoader.loadModule = function(moduleName, callback, options) { options = options || {}; var loaded = lumbarLoader.isLoaded(moduleName); if (!options.silent && !loaded) { lumbarLoader.trigger && lumbarLoader.trigger('load:start', moduleName, undefined, lumbarLoader); } baseLoadModule(moduleName, function(error) { if (!options.silent && !loaded) { lumbarLoader.trigger && lumbarLoader.trigger('load:end', lumbarLoader); } callback(error); }, options); }; }());
Increment version number for added ELT combiner tool
from codecs import open from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: readme = f.read() with open(path.join(here, 'requirements', 'install.txt'), encoding='utf-8') as f: install_requires = f.read().splitlines() setup( name='analyzere_extras', version='0.2.0', description='Python extras to support visualization', long_description=readme, url='https://github.com/analyzere/analyzere-python-extras', author='Analyze Re', author_email='support@analyzere.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=[ 'analyzere_extras', ], install_requires=install_requires )
from codecs import open from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: readme = f.read() with open(path.join(here, 'requirements', 'install.txt'), encoding='utf-8') as f: install_requires = f.read().splitlines() setup( name='analyzere_extras', version='0.1.10', description='Python extras to support visualization', long_description=readme, url='https://github.com/analyzere/analyzere-python-extras', author='Analyze Re', author_email='support@analyzere.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=[ 'analyzere_extras', ], install_requires=install_requires )
Update "Colleges Roomies from Hell" after site change
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Colleges Roomies from Hell" language = "en" url = "http://www.crfh.net/" start_date = "1999-01-01" rights = "Maritza Campos" class Crawler(CrawlerBase): history_capable_date = "1999-01-01" time_zone = "America/Merida" def crawl(self, pub_date): page_url = "http://www.crfh.net/d/%s.html" % ( pub_date.strftime("%Y%m%d"), ) page = self.parse_page(page_url) url = page.src('img[src*="crfh%s"]' % pub_date.strftime("%Y%m%d")) url = url.replace("\n", "") return CrawlerImage(url)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Colleges Roomies from Hell" language = "en" url = "http://www.crfh.net/" start_date = "1999-01-01" rights = "Maritza Campos" class Crawler(CrawlerBase): history_capable_date = "1999-01-01" time_zone = "America/Merida" def crawl(self, pub_date): page_url = "http://www.crfh.net/d2/%s.html" % ( pub_date.strftime("%Y%m%d"), ) page = self.parse_page(page_url) url = page.src('img[src*="crfh%s"]' % pub_date.strftime("%Y%m%d")) url = url.replace("\n", "") return CrawlerImage(url)
Use 'escapeValue' to escape the new line character We need to escape the new line character as well as per RFC : http://tools.ietf.org/html/rfc5545#section-3.3.11
<?php namespace Eluceo\iCal\Property\Event; use Eluceo\iCal\Property\ValueInterface; use Eluceo\iCal\Util\PropertyValueUtil; /** * Class Description * Alows new line charectars to be in the description * * @package Eluceo\iCal\Property */ class Description implements ValueInterface { /** * The value. * * @var string */ protected $value; public function __construct($value) { $this->value = $value; } /** * Return the value of the Property as an escaped string. * * Escape values as per RFC 2445. See http://www.kanzaki.com/docs/ical/text.html * * @return string */ public function getEscapedValue() { return PropertyValueUtil::escapeValue((string) $this->value); } /** * @param string $value * * @return $this */ public function setValue($value) { $this->value = $value; return $this; } /** * @return string */ public function getValue() { return $this->value; } }
<?php namespace Eluceo\iCal\Property\Event; use Eluceo\iCal\Property\ValueInterface; use Eluceo\iCal\Util\PropertyValueUtil; /** * Class Description * Alows new line charectars to be in the description * * @package Eluceo\iCal\Property */ class Description implements ValueInterface { /** * The value. * * @var string */ protected $value; public function __construct($value) { $this->value = $value; } /** * Return the value of the Property as an escaped string. * * Escape values as per RFC 2445. See http://www.kanzaki.com/docs/ical/text.html * * @return string */ public function getEscapedValue() { return PropertyValueUtil::escapeValueAllowNewLine((string) $this->value); } /** * @param string $value * * @return $this */ public function setValue($value) { $this->value = $value; return $this; } /** * @return string */ public function getValue() { return $this->value; } }
Fix login if activation enabled
<?php namespace Laravolt\Auth; use Illuminate\Http\Request; use Laravolt\Auth\Contracts\Login; class DefaultLogin implements Login { public function rules(Request $request) { $rules = [ $this->identifier() => 'required', 'password' => 'required', ]; if (config('laravolt.auth.captcha')) { $rules['g-recaptcha-response'] = 'required|captcha'; } return $rules; } public function credentials(Request $request) { $credential = $request->only($this->identifier(), 'password'); if (config('laravolt.auth.activation.enable')) { $credential['status'] = config('laravolt.auth.activation.status_after'); } return $credential; } public function loggedOut(Request $request) { return redirect()->to(config('laravolt.auth.redirect.after_logout', '/')); } protected function identifier() { return config('laravolt.auth.identifier'); } }
<?php namespace Laravolt\Auth; use Illuminate\Http\Request; use Laravolt\Auth\Contracts\Login; class DefaultLogin implements Login { public function rules(Request $request) { $rules = [ $this->identifier() => 'required', 'password' => 'required', ]; if (config('laravolt.auth.captcha')) { $rules['g-recaptcha-response'] = 'required|captcha'; } return $rules; } public function credentials(Request $request) { return $request->only($this->identifier(), 'password'); } public function loggedOut(Request $request) { return redirect()->to(config('laravolt.auth.redirect.after_logout', '/')); } protected function identifier() { return config('laravolt.auth.identifier'); } }
Update 11ty config to use imports
import minifyHtml from './eleventy/utilities/minifyHtml.js'; import addHeaderCredit from './eleventy/utilities/addHeaderCredit.js'; import absoluteUrl from './eleventy/filters/absoluteUrl.js'; import cacheBust from './eleventy/filters/cacheBust.js'; module.exports = function(config) { // If prod or stage, minify the html if (process.env.NODE_ENV !== 'development') { config.addTransform('minifyHtml', minifyHtml); } // Add header credit to html config.addTransform('addHeaderCredit', addHeaderCredit); // Filters config.addFilter('absoluteUrl', absoluteUrl); config.addFilter('cacheBust', cacheBust); return { dir: { input: 'src/site', output: 'dist' }, htmlTemplateEngine: 'njk', markdownTemplateEngine: 'njk', dataTemplateEngine: 'njk' }; };
module.exports = function(config) { // If prod or stage, minify the html if (process.env.NODE_ENV !== 'development') { config.addTransform('minifyHtml', require('./eleventy/utilities/minifyHtml.js')); } // Add header credit to html config.addTransform('addHeaderCredit', require('./eleventy/utilities/addHeaderCredit.js')); // Filters config.addFilter('absoluteUrl', require('./eleventy/filters/absoluteUrl.js')); config.addFilter('cacheBust', require('./eleventy/filters/cacheBust.js')); return { dir: { input: 'src/site', output: 'dist' }, htmlTemplateEngine: 'njk', markdownTemplateEngine: 'njk', dataTemplateEngine: 'njk' }; };
[native] Use hook instead of connect functions and HOC in Timestamp Test Plan: Flow Reviewers: ashoat, palys-swm Reviewed By: ashoat Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D481
// @flow import { longAbsoluteDate } from 'lib/utils/date-utils'; import * as React from 'react'; import { SingleLine } from '../components/single-line.react'; import { useStyles } from '../themes/colors'; export type DisplayType = 'lowContrast' | 'modal'; type Props = {| +time: number, +display: DisplayType, |}; function Timestamp(props: Props) { const styles = useStyles(unboundStyles); const style = [styles.timestamp]; if (props.display === 'modal') { style.push(styles.modal); } return ( <SingleLine style={style}> {longAbsoluteDate(props.time).toUpperCase()} </SingleLine> ); } const timestampHeight = 26; const unboundStyles = { modal: { // high contrast framed against OverlayNavigator-dimmed background color: 'white', }, timestamp: { alignSelf: 'center', bottom: 0, color: 'listBackgroundTernaryLabel', fontSize: 14, height: timestampHeight, paddingVertical: 3, }, }; export { Timestamp, timestampHeight };
// @flow import { longAbsoluteDate } from 'lib/utils/date-utils'; import { connect } from 'lib/utils/redux-utils'; import * as React from 'react'; import { SingleLine } from '../components/single-line.react'; import type { AppState } from '../redux/redux-setup'; import { styleSelector } from '../themes/colors'; export type DisplayType = 'lowContrast' | 'modal'; type Props = {| time: number, display: DisplayType, // Redux state styles: typeof styles, |}; function Timestamp(props: Props) { const style = [props.styles.timestamp]; if (props.display === 'modal') { style.push(props.styles.modal); } return ( <SingleLine style={style}> {longAbsoluteDate(props.time).toUpperCase()} </SingleLine> ); } const timestampHeight = 26; const styles = { modal: { // high contrast framed against OverlayNavigator-dimmed background color: 'white', }, timestamp: { alignSelf: 'center', bottom: 0, color: 'listBackgroundTernaryLabel', fontSize: 14, height: timestampHeight, paddingVertical: 3, }, }; const stylesSelector = styleSelector(styles); const WrappedTimestamp = connect((state: AppState) => ({ styles: stylesSelector(state), }))(Timestamp); export { WrappedTimestamp as Timestamp, timestampHeight };
Remove behave_pytest from general_itests too
# Copyright 2015-2016 Yelp Inc. # # 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 shutil from paasta_tools.utils import get_docker_client def after_scenario(context, scenario): if getattr(context, "tmpdir", None): shutil.rmtree(context.tmpdir) if getattr(context, "running_container_id", None): docker_client = get_docker_client() docker_client.stop(container=context.running_container_id) docker_client.remove_container(container=context.running_container_id) if getattr(context, "fake_http_server", None): context.fake_http_server.shutdown() context.fake_http_server = None
# Copyright 2015-2016 Yelp Inc. # # 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 shutil from behave_pytest.hook import install_pytest_asserts from paasta_tools.utils import get_docker_client def before_all(context): install_pytest_asserts() def after_scenario(context, scenario): if getattr(context, "tmpdir", None): shutil.rmtree(context.tmpdir) if getattr(context, "running_container_id", None): docker_client = get_docker_client() docker_client.stop(container=context.running_container_id) docker_client.remove_container(container=context.running_container_id) if getattr(context, "fake_http_server", None): context.fake_http_server.shutdown() context.fake_http_server = None
tests.http: Test creation of HTTP credentials
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) def test_client_init_sets_credentials(self): domain = '' expected_credentials = [(domain, 'guest', 'guest')] self.assertEqual( self.c.client.credentials.credentials, expected_credentials) def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5)
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5)
Fix LOCI common utils compilation.
// // XsltProc.java // import java.io.FileReader; import java.io.IOException; import loci.common.xml.XMLTools; import java.io.StringWriter; import javax.xml.transform.Templates; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; /** * Transforms an XML document according to the given stylesheet, * similar to the xsltproc command line tool. */ public class XsltProc { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: java XsltProc stylesheet.xsl document.xml"); System.exit(1); } String xsl = args[0]; String xml = args[1]; StreamSource xmlSource = new StreamSource(new FileReader(xml)); StringWriter xmlWriter = new StringWriter(); StreamResult xmlResult = new StreamResult(xmlWriter); // transform from source to result Templates stylesheet = XMLTools.getStylesheet(xsl, null); XMLTools.transformXML(xmlSource, stylesheet); String output = xmlWriter.toString(); System.out.println(output); } }
// // XsltProc.java // import java.io.FileReader; import java.io.IOException; import loci.common.XMLTools; import java.io.StringWriter; import javax.xml.transform.Templates; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; /** * Transforms an XML document according to the given stylesheet, * similar to the xsltproc command line tool. */ public class XsltProc { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: java XsltProc stylesheet.xsl document.xml"); System.exit(1); } String xsl = args[0]; String xml = args[1]; StreamSource xmlSource = new StreamSource(new FileReader(xml)); StringWriter xmlWriter = new StringWriter(); StreamResult xmlResult = new StreamResult(xmlWriter); // transform from source to result Templates stylesheet = XMLTools.getStylesheet(xsl, null); XMLTools.transformXML(xmlSource, stylesheet); String output = xmlWriter.toString(); System.out.println(output); } }
Fix regexp for validation Instagram URL
<?php namespace Codenetix\SocialMediaImporter\Importers; use Codenetix\SocialMediaImporter\Exceptions\ImportException; use Codenetix\SocialMediaImporter\Exceptions\RequestedDataNotFoundException; use Codenetix\SocialMediaImporter\Exceptions\WrongInputURLException; use Codenetix\SocialMediaImporter\FactoryMethods\InstagramMediaAdapterFactoryMethod; use Codenetix\SocialMediaImporter\Scrapers\InstagramScraper; /** * @author Andrey Vorobiov<andrew.sprw@gmail.com> */ class InstagramSingleMediaImporter extends AInstagramMediaImporter { private function checkURL($url) { if (!preg_match('/^https?:\/\/(?:www\.)?instagram\.com\/p\/[a-zA-Z0-9_-]+\/?/', $url)) { throw new WrongInputURLException("Wrong URL format"); } } public function importByURL($url) { $this->checkURL($url); $item = $this->instagramClient->getMedia((new InstagramScraper($url))->id()); if(!$item){ throw new RequestedDataNotFoundException("Requested media was not found"); } if($item->meta->code != 200){ throw new ImportException($item->meta->error_message); } return (new InstagramMediaAdapterFactoryMethod())->make($item->data->type, $item->data)->transform($this->mediaFactoryMethod); } }
<?php namespace Codenetix\SocialMediaImporter\Importers; use Codenetix\SocialMediaImporter\Exceptions\ImportException; use Codenetix\SocialMediaImporter\Exceptions\RequestedDataNotFoundException; use Codenetix\SocialMediaImporter\Exceptions\WrongInputURLException; use Codenetix\SocialMediaImporter\FactoryMethods\InstagramMediaAdapterFactoryMethod; use Codenetix\SocialMediaImporter\Scrapers\InstagramScraper; /** * @author Andrey Vorobiov<andrew.sprw@gmail.com> */ class InstagramSingleMediaImporter extends AInstagramMediaImporter { private function checkURL($url) { if (!preg_match('/^https?:\/\/(?:www\.)?instagram\.com\/p\/[a-zA-Z0-9_-]+\/?$/', $url)) { throw new WrongInputURLException(); } } public function importByURL($url) { $this->checkURL($url); $item = $this->instagramClient->getMedia((new InstagramScraper($url))->id()); if(!$item){ throw new RequestedDataNotFoundException("Requested media was not found"); } if($item->meta->code != 200){ throw new ImportException($item->meta->error_message); } return (new InstagramMediaAdapterFactoryMethod())->make($item->data->type, $item->data)->transform($this->mediaFactoryMethod); } }
Update connection protocol for Login success
package response import ( "github.com/Vladimiroff/vec2d" "warcluster/entities" ) type Fraction struct { Id uint16 Color entities.Color Name string } type LoginSuccess struct { baseResponse Username string Position *vec2d.Vector Fraction Fraction HomePlanet struct { Name string Position *vec2d.Vector } } type LoginFailed struct { baseResponse } type LoginInformation struct { baseResponse } func NewLoginSuccess(player *entities.Player, homePlanet *entities.Planet) *LoginSuccess { r := new(LoginSuccess) r.Command = "login_success" r.Username = player.Username r.Fraction = Fraction{player.Race.ID, player.Race.Color(), player.Race.Name()} r.Position = player.ScreenPosition r.HomePlanet.Name = homePlanet.Name r.HomePlanet.Position = homePlanet.Position return r } func NewLoginFailed() *LoginFailed { r := new(LoginFailed) r.Command = "login_failed" return r } func NewLoginInformation() *LoginInformation { r := new(LoginInformation) r.Command = "request_setup_params" return r } func (l *LoginSuccess) Sanitize(*entities.Player) {} func (l *LoginFailed) Sanitize(*entities.Player) {} func (l *LoginInformation) Sanitize(*entities.Player) {}
package response import ( "github.com/Vladimiroff/vec2d" "warcluster/entities" ) type LoginSuccess struct { baseResponse Username string Position *vec2d.Vector HomePlanet struct { Name string Position *vec2d.Vector } } type LoginFailed struct { baseResponse } type LoginInformation struct { baseResponse } func NewLoginSuccess(player *entities.Player, homePlanet *entities.Planet) *LoginSuccess { r := new(LoginSuccess) r.Command = "login_success" r.Username = player.Username r.Position = player.ScreenPosition r.HomePlanet.Name = homePlanet.Name r.HomePlanet.Position = homePlanet.Position return r } func NewLoginFailed() *LoginFailed { r := new(LoginFailed) r.Command = "login_failed" return r } func NewLoginInformation() *LoginInformation { r := new(LoginInformation) r.Command = "request_setup_params" return r } func (l *LoginSuccess) Sanitize(*entities.Player) {} func (l *LoginFailed) Sanitize(*entities.Player) {} func (l *LoginInformation) Sanitize(*entities.Player) {}
Remove space before function parenthesis
var ng = require('angular2/core'); var ngHttp = require('angular2/http'); var Tech = require('./tech'); require('rxjs/Rx'); module.exports = ng.Component({ selector: 'Techs', template: '<div class="techs-container">' + '<h2 class="techs-h2">' + 'Cooked with all these awesome technologies:' + '</h2>' + '<div class="techs">' + '<Tech *ngFor="#tech of techs" [tech]="tech"></Tech>' + '</div>' + '</div>', directives: [Tech], providers: [ngHttp.HTTP_PROVIDERS] }) .Class({ constructor: [ngHttp.Http, function TechsController(http) { // https://github.com/angular/angular/issues/7507 var vm = this; this.http = http; vm.getTechs().subscribe(function (result) { vm.techs = result; }); }], getTechs: function getTechs() { // http://stackoverflow.com/questions/33458481/angular-2-how-to-use-http-in-es5 return this.http .get('app/techs/techs.json') .map(function (response) { return response.json(); }); } });
var ng = require('angular2/core'); var ngHttp = require('angular2/http'); var Tech = require('./tech'); require('rxjs/Rx'); module.exports = ng.Component({ selector: 'Techs', template: '<div class="techs-container">' + '<h2 class="techs-h2">' + 'Cooked with all these awesome technologies:' + '</h2>' + '<div class="techs">' + '<Tech *ngFor="#tech of techs" [tech]="tech"></Tech>' + '</div>' + '</div>', directives: [Tech], providers: [ngHttp.HTTP_PROVIDERS] }) .Class({ constructor: [ngHttp.Http, function TechsController(http) { // https://github.com/angular/angular/issues/7507 var vm = this; this.http = http; vm.getTechs().subscribe(function (result) { vm.techs = result; }); }], getTechs: function getTechs () { // http://stackoverflow.com/questions/33458481/angular-2-how-to-use-http-in-es5 return this.http .get('app/techs/techs.json') .map(function (response) { return response.json(); }); } });
Fix invalid arguments value issue
<?php namespace AMQPy; use AMQPExchange; use AMQPy\Client\Properties; use AMQPy\Serializers\SerializersPool; class Publisher { private $exchange; private $serializers; public function __construct(AMQPExchange $exchange, SerializersPool $serializers_pool) { $this->exchange = $exchange; $this->serializers = $serializers_pool; } public function getExchange() { return $this->exchange; } public function getSerializers() { return $this->serializers; } public function publish($message, $routing_key, Properties $properties = null, $flags = AMQP_NOPARAM) { $content_type = 'text/plain'; $attributes = []; if ($properties) { if ($properties->getContentType()) { $content_type = $properties->getContentType(); } $attributes = $properties->toArray(); } $message = $this->serializers->get($content_type)->serialize($message); $attributes['content_type'] = $content_type; $attributes = array_filter($attributes); $this->exchange->publish($message, $routing_key, $flags, $attributes); } }
<?php namespace AMQPy; use AMQPExchange; use AMQPy\Client\Properties; use AMQPy\Serializers\SerializersPool; class Publisher { private $exchange; private $serializers; public function __construct(AMQPExchange $exchange, SerializersPool $serializers_pool) { $this->exchange = $exchange; $this->serializers = $serializers_pool; } public function getExchange() { return $this->exchange; } public function getSerializers() { return $this->serializers; } public function publish($message, $routing_key, Properties $properties = null, $flags = AMQP_NOPARAM) { $content_type = 'text/plain'; $attributes = []; if ($properties) { if ($properties->getContentType()) { $content_type = $properties->getContentType(); } $attributes = $properties->toArray(); } $message = $this->serializers->get($content_type)->serialize($message); $attributes['content_type'] = $content_type; $this->exchange->publish($message, $routing_key, $flags, $attributes); } }
Remove invocation level teardown from FIX tags benchmark
package org.jvirtanen.philadelphia.perf; import static java.nio.charset.StandardCharsets.*; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import org.jvirtanen.philadelphia.FIXTags; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; @State(Scope.Thread) @OutputTimeUnit(TimeUnit.NANOSECONDS) public class FIXTagsBenchmark { private ByteBuffer buffer; @Setup(Level.Iteration) public void prepare() { buffer = ByteBuffer.wrap("123=".getBytes(US_ASCII)); } @Benchmark @BenchmarkMode(Mode.SampleTime) public long get() { long tag = FIXTags.get(buffer); buffer.flip(); return tag; } @Benchmark @BenchmarkMode(Mode.SampleTime) public void put() { FIXTags.put(buffer, 123); buffer.flip(); } }
package org.jvirtanen.philadelphia.perf; import static java.nio.charset.StandardCharsets.*; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import org.jvirtanen.philadelphia.FIXTags; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; @State(Scope.Thread) @OutputTimeUnit(TimeUnit.NANOSECONDS) public class FIXTagsBenchmark { private ByteBuffer buffer; @Setup(Level.Iteration) public void prepare() { buffer = ByteBuffer.wrap("123=".getBytes(US_ASCII)); } @TearDown(Level.Invocation) public void tearDown() { buffer.flip(); } @Benchmark @BenchmarkMode(Mode.SampleTime) public long get() { return FIXTags.get(buffer); } @Benchmark @BenchmarkMode(Mode.SampleTime) public void put() { FIXTags.put(buffer, 123); } }
Fix for submit for approval button not always showing. Ensure event lookup uses consistent uri format. Former-commit-id: 4c388aa2dc9c2b167231283ce4be3f3cfb4b6d92
function getLastEditedEvent(collection, page) { var uri = page; if (uri.charAt(0) !== '/') { uri = "/" + uri; } var pageEvents = collection.eventsByUri[uri]; var lastEditedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'EDITED' }) .sortBy(function (event) { return event.date; }) .last() .value(); return lastEditedEvent; } function getLastCompletedEvent(collection, page) { var uri = page; if (uri.charAt(0) !== '/') { uri = "/" + uri; } var lastCompletedEvent; if (collection.eventsByUri) { var pageEvents = collection.eventsByUri[uri]; if (pageEvents) { lastCompletedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'COMPLETED' }) .sortBy(function (event) { return event.date; }) .last() .value(); } } return lastCompletedEvent; }
function getLastEditedEvent(collection, page) { var pageEvents = collection.eventsByUri[page]; var lastEditedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'EDITED' }) .sortBy(function (event) { return event.date; }) .last() .value(); return lastEditedEvent; } function getLastCompletedEvent(collection, page) { var lastCompletedEvent; if (collection.eventsByUri) { var pageEvents = collection.eventsByUri[page]; if (pageEvents) { lastCompletedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'COMPLETED' }) .sortBy(function (event) { return event.date; }) .last() .value(); } } return lastCompletedEvent; }
peas-demo: Add a configure dialog to the python plugin.
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: import gobject from gi.repository import Peas from gi.repository import PeasUI from gi.repository import Gtk LABEL_STRING="Python Says Hello!" class PythonHelloPlugin(gobject.GObject, Peas.Activatable): __gtype_name__ = 'PythonHelloPlugin' def do_activate(self, window): print "PythonHelloPlugin.do_activate", repr(window) window._pythonhello_label = Gtk.Label() window._pythonhello_label.set_text(LABEL_STRING) window._pythonhello_label.show() window.get_child().pack_start(window._pythonhello_label, True, True, 0) def do_deactivate(self, window): print "PythonHelloPlugin.do_deactivate", repr(window) window.get_child().remove(window._pythonhello_label) window._pythonhello_label.destroy() def do_update_state(self, window): print "PythonHelloPlugin.do_update_state", repr(window) class PythonHelloConfigurable(gobject.GObject, PeasUI.Configurable): __gtype_name__ = 'PythonHelloConfigurable' def do_create_configure_widget(self): return Gtk.Label.new("Python Hello configure widget")
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: import gobject from gi.repository import Peas from gi.repository import Gtk LABEL_STRING="Python Says Hello!" class PythonHelloPlugin(gobject.GObject, Peas.Activatable): __gtype_name__ = 'PythonHelloPlugin' def do_activate(self, window): print "PythonHelloPlugin.do_activate", repr(window) window._pythonhello_label = Gtk.Label() window._pythonhello_label.set_text(LABEL_STRING) window._pythonhello_label.show() window.get_child().pack_start(window._pythonhello_label, True, True, 0) def do_deactivate(self, window): print "PythonHelloPlugin.do_deactivate", repr(window) window.get_child().remove(window._pythonhello_label) window._pythonhello_label.destroy() def do_update_state(self, window): print "PythonHelloPlugin.do_update_state", repr(window)
scripts: Allow to override the JSON loading and dumping parameters.
#!/usr/bin/env python3 # Touhou Community Reliant Automatic Patcher # Scripts # # ---- # """Utility functions shared among all the scripts.""" from collections import OrderedDict import json import os json_load_params = { 'object_pairs_hook': OrderedDict } def patch_files_filter(files): """Filters all file names that can not be among the content of a patch.""" for i in files: if i != 'files.js': yield i json_dump_params = { 'ensure_ascii': False, 'indent': '\t', 'separators': (',', ': '), 'sort_keys': True } # Default parameters for JSON input and output def json_load(fn, json_kwargs=json_load_params): with open(fn, 'r', encoding='utf-8') as file: return json.load(file, **json_kwargs) def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params): """Saves the JSON object [obj] to [fn], creating all necessary directories in the process. If [dirs] is given, the function is executed for every root directory in the array.""" for i in dirs: full_fn = os.path.join(i, fn) os.makedirs(os.path.dirname(full_fn), exist_ok=True) with open(full_fn, 'w', encoding='utf-8') as file: json.dump(obj, file, **json_kwargs) file.write('\n')
#!/usr/bin/env python3 # Touhou Community Reliant Automatic Patcher # Scripts # # ---- # """Utility functions shared among all the scripts.""" from collections import OrderedDict import json import os json_load_params = { 'object_pairs_hook': OrderedDict } def patch_files_filter(files): """Filters all file names that can not be among the content of a patch.""" for i in files: if i != 'files.js': yield i json_dump_params = { 'ensure_ascii': False, 'indent': '\t', 'separators': (',', ': '), 'sort_keys': True } # Default parameters for JSON input and output def json_load(fn): with open(fn, 'r', encoding='utf-8') as file: return json.load(file, **json_load_params) def json_store(fn, obj, dirs=['']): """Saves the JSON object [obj] to [fn], creating all necessary directories in the process. If [dirs] is given, the function is executed for every root directory in the array.""" for i in dirs: full_fn = os.path.join(i, fn) os.makedirs(os.path.dirname(full_fn), exist_ok=True) with open(full_fn, 'w', encoding='utf-8') as file: json.dump(obj, file, **json_dump_params) file.write('\n')
Add name to EnumType in test since pgsql needs it.
import enum from sqlalchemy.schema import Column from sqlalchemy.types import Integer from cliche.sqltypes import EnumType from cliche.orm import Base class Color(enum.Enum): red = 1 green = 2 blue = 3 class ColorTable(Base): __tablename__ = 'color_table' id = Column(Integer, primary_key=True) color = Column(EnumType(Color, name='color')) def test_enum_type(fx_session): red_obj = ColorTable(color=Color.red) green_obj = ColorTable(color=Color.green) blue_obj = ColorTable(color=Color.blue) fx_session.add(red_obj) fx_session.add(green_obj) fx_session.add(blue_obj) fx_session.flush() result_obj = fx_session.query(ColorTable) \ .filter(ColorTable.color == Color.green) \ .one() assert green_obj is result_obj
import enum from sqlalchemy.schema import Column from sqlalchemy.types import Integer from cliche.sqltypes import EnumType from cliche.orm import Base class Color(enum.Enum): red = 1 green = 2 blue = 3 class ColorTable(Base): __tablename__ = 'color_table' id = Column(Integer, primary_key=True) test_col = Column(EnumType(Color)) def test_enum_type(fx_session): red_obj = ColorTable(test_col=Color.red) green_obj = ColorTable(test_col=Color.green) blue_obj = ColorTable(test_col=Color.blue) fx_session.add(red_obj) fx_session.add(green_obj) fx_session.add(blue_obj) fx_session.flush() result_obj = fx_session.query(ColorTable) \ .filter(ColorTable.test_col == Color.green) \ .one() assert green_obj is result_obj
Replace relative links with absolute links
import re import setuptools with open("README.md", "r") as fin: long_description = fin.read() long_description = re.sub( "^(!\[.*\]\()(.*\))", lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2), long_description, flags=re.MULTILINE ) setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
import setuptools with open("README.md", "r") as fin: long_description = fin.read() setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
Use modulePaths instead of moduleDirectories
import Metalsmith from 'metalsmith'; import common from '@rollup/plugin-commonjs'; import inPlace from '@metalsmith/in-place'; import layouts from '@metalsmith/layouts'; import markdown from '@metalsmith/markdown'; import {dirname, resolve} from 'node:path'; import {env} from 'node:process'; import {fileURLToPath} from 'node:url'; import {nodeResolve} from '@rollup/plugin-node-resolve'; import {rollup} from 'rollup'; import {terser} from 'rollup-plugin-terser'; const baseDir = dirname(fileURLToPath(import.meta.url)); const builder = Metalsmith(baseDir) .source('./src') .destination('./build') .clean(true) .metadata({ version: env.OL_VERSION || 'dev', }) .use(inPlace()) .use(markdown()) .use(layouts()); builder.build(async (err) => { if (err) { throw err; } await bundleMain(); }); async function bundleMain() { const inputOptions = { plugins: [ common(), nodeResolve({ modulePaths: [ resolve(baseDir, '../src'), resolve(baseDir, '../node_modules'), ], }), terser(), ], input: resolve(baseDir, './build/main.js'), }; const outputOptions = { dir: resolve(baseDir, './build'), format: 'iife', }; const bundle = await rollup(inputOptions); await bundle.write(outputOptions); bundle.close(); }
import Metalsmith from 'metalsmith'; import common from '@rollup/plugin-commonjs'; import inPlace from '@metalsmith/in-place'; import layouts from '@metalsmith/layouts'; import markdown from '@metalsmith/markdown'; import {dirname, resolve} from 'node:path'; import {env} from 'node:process'; import {fileURLToPath} from 'node:url'; import {nodeResolve} from '@rollup/plugin-node-resolve'; import {rollup} from 'rollup'; import {terser} from 'rollup-plugin-terser'; const baseDir = dirname(fileURLToPath(import.meta.url)); const builder = Metalsmith(baseDir) .source('./src') .destination('./build') .clean(true) .metadata({ version: env.OL_VERSION || 'dev', }) .use(inPlace()) .use(markdown()) .use(layouts()); builder.build(async (err) => { if (err) { throw err; } await bundleMain(); }); async function bundleMain() { const inputOptions = { plugins: [ common(), nodeResolve({ moduleDirectories: [ resolve(baseDir, '../src'), resolve(baseDir, '../node_modules'), ], }), terser(), ], input: resolve(baseDir, './build/main.js'), }; const outputOptions = { dir: resolve(baseDir, './build'), format: 'iife', }; const bundle = await rollup(inputOptions); await bundle.write(outputOptions); bundle.close(); }
Fix migration when no existing team.user field at fresh start
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-12-19 11:53 from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team # def generate_slugs(apps, schema_editor): # teams = Team.objects.all() # for team in teams: # team.save() class Migration(migrations.Migration): dependencies = [ ('organization-network', '0117_merge_20181204_1801'), ] operations = [ migrations.AddField( model_name='team', name='slug', field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'), ), # migrations.RunPython(generate_slugs), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-12-19 11:53 from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team def generate_slugs(apps, schema_editor): teams = Team.objects.all() for team in teams: team.save() class Migration(migrations.Migration): dependencies = [ ('organization-network', '0117_merge_20181204_1801'), ] operations = [ migrations.AddField( model_name='team', name='slug', field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'), ), migrations.RunPython(generate_slugs), ]
Rename `next` to `dispatcher` to avoid confusion from JS source.
package redux.api.enhancer; import redux.api.Dispatcher; import redux.api.StateProvider; /** * A middleware is an interface that composes a {@link Dispatcher} to return a new dispatch function. It often turns * async actions into actions. * * @see <a href="http://redux.js.org/docs/advanced/Middleware.html">http://redux.js.org/docs/advanced/Middleware.html</a> * * @param <S> The store type */ interface Middleware<S> { /** * Dispatches an action. This is the only way to trigger a state change. * * @see <a href="http://redux.js.org/docs/Glossary.html#middleware">http://redux.js.org/docs/Glossary.html#middleware</a> * * @param stateProvider An interface to return the current state of the store. * @param action The action * @param dispatcher The next dispatcher in the chain * @return The action */ Object dispatch(StateProvider<S> stateProvider, Object action, Dispatcher dispatcher); }
package redux.api.enhancer; import redux.api.Dispatcher; import redux.api.StateProvider; /** * A middleware is an interface that composes a {@link Dispatcher} to return a new dispatch function. It often turns * async actions into actions. * * @see <a href="http://redux.js.org/docs/advanced/Middleware.html">http://redux.js.org/docs/advanced/Middleware.html</a> * * @param <S> The store type */ interface Middleware<S> { /** * Dispatches an action. This is the only way to trigger a state change. * * @see <a href="http://redux.js.org/docs/Glossary.html#middleware">http://redux.js.org/docs/Glossary.html#middleware</a> * * @param stateProvider An interface to return the current state of the store. * @param action The action * @param next The next dispatcher in the chain * @return The action */ Object dispatch(StateProvider<S> stateProvider, Object action, Dispatcher next); }
Create sample using new process create method.
(function (module) { module.controller("SamplesController", SamplesController); SamplesController.$inject = ["$state", "project", "$filter", "samples"]; function SamplesController($state, project, $filter, samples) { var ctrl = this; ctrl.project = project; ctrl.viewSample = viewSample; ctrl.samples = samples; ctrl.createSample = createSample; if (ctrl.samples.length !== 0) { var sortedSamples = $filter('orderBy')(ctrl.samples, 'name'); ctrl.current = sortedSamples[0]; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } ////////////////// function viewSample(sample) { ctrl.current = sample; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } function createSample() { $state.go('projects.project.processes.create', {process: 'As Received', process_id: ''}); } } }(angular.module('materialscommons')));
(function (module) { module.controller("SamplesController", SamplesController); SamplesController.$inject = ["$state", "project", "$filter", "samples", "processTemplates"]; function SamplesController($state, project, $filter, samples, processTemplates) { var ctrl = this; ctrl.project = project; ctrl.viewSample = viewSample; ctrl.samples = samples; ctrl.createSample = createSample; if (ctrl.samples.length !== 0) { var sortedSamples = $filter('orderBy')(ctrl.samples, 'name'); ctrl.current = sortedSamples[0]; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } ////////////////// function viewSample(sample) { ctrl.current = sample; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } function createSample() { var template = processTemplates.getTemplateByName('As Received'); processTemplates.setActiveTemplate(template); $state.go('projects.project.processes.create'); } } }(angular.module('materialscommons')));
Use middleware as generated by express-generator.
require('dotenv').config(); var express = require('express'); var passport = require('passport'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var authRouter = require('./routes/auth'); var app = express(); require('./boot/auth')(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // session setup // // This sequence of middleware is necessary for login sessions. The first // middleware loads session data and makes it available at `req.session`. The // next lines initialize Passport and authenticate the request based on session // data. If session data contains an authenticated user, the user is set at // `req.user`. app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); // Define routes. app.get('/', function(req, res) { res.render('home', { user: req.user }); }); app.use('/', authRouter); app.get('/profile', require('connect-ensure-login').ensureLoggedIn(), function(req, res){ res.render('profile', { user: req.user }); }); module.exports = app;
require('dotenv').config(); var path = require('path'); var express = require('express'); var passport = require('passport'); var authRouter = require('./routes/auth'); // Create a new Express application. var app = express(); require('./boot/auth')(); // Configure view engine to render EJS templates. app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); // Use application-level middleware for common functionality, including // logging, parsing, and session handling. app.use(require('morgan')('combined')); app.use(express.static(path.join(__dirname, 'public'))); app.use(require('cookie-parser')()); app.use(require('body-parser').urlencoded({ extended: true })); app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true })); // Initialize Passport and restore authentication state, if any, from the // session. app.use(passport.initialize()); app.use(passport.session()); // Define routes. app.get('/', function(req, res) { res.render('home', { user: req.user }); }); app.use('/', authRouter); app.get('/profile', require('connect-ensure-login').ensureLoggedIn(), function(req, res){ res.render('profile', { user: req.user }); }); module.exports = app;
Implement container blocks dropping their contents. Fixes containers losing their contents and dropping incorrect blocks when broken.
package net.glowstone.block.blocktype; import net.glowstone.block.GlowBlock; import net.glowstone.block.entity.TEContainer; import net.glowstone.block.entity.TileEntity; import net.glowstone.entity.GlowPlayer; import org.bukkit.block.BlockFace; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.util.Collection; import java.util.LinkedList; /** * Base BlockType for containers. */ public class BlockContainer extends BlockType { @Override public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) { TileEntity te = block.getTileEntity(); if (te instanceof TEContainer) { // todo: animation? player.openInventory(((TEContainer) te).getInventory()); return true; } return false; } @Override public Collection<ItemStack> getDrops(GlowBlock block) { LinkedList<ItemStack> list = new LinkedList<ItemStack>(); list.add(new ItemStack(block.getType(), 1)); for (ItemStack i : ((TEContainer) block.getTileEntity()).getInventory().getContents()) { if (i != null) { list.add(i); } } return list; } }
package net.glowstone.block.blocktype; import net.glowstone.block.GlowBlock; import net.glowstone.block.entity.TEContainer; import net.glowstone.block.entity.TileEntity; import net.glowstone.entity.GlowPlayer; import org.bukkit.block.BlockFace; import org.bukkit.util.Vector; /** * Base BlockType for containers. */ public class BlockContainer extends BlockType { @Override public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) { TileEntity te = block.getTileEntity(); if (te instanceof TEContainer) { // todo: animation? player.openInventory(((TEContainer) te).getInventory()); return true; } return false; } }
Test again when TestudocParser is recreated
import gulp from 'gulp'; import {build} from './build'; import {test} from './test'; import {makeParser, fixParser} from './parse'; const allSrcGlob = [ 'src/**/*.js', '!src/static/antlr4/parsers/**/*.js', 'test/**/*.js', ]; const allBuildGlob = [ 'build/src/*.js', 'build/test/**/*.js', ]; const grammarGlob = [ 'src/static/antlr4/grammars/**/*.g4', 'build/src/static/antlr4/Translator.js', ]; const dataGlob = [ 'src/static/data/**/*.*', 'src/static/antlr4/parsers/TestudocParser.js', ]; export const watch = done => { gulp.watch(allSrcGlob, build); gulp.watch(allBuildGlob, test); gulp.watch(grammarGlob, gulp.series(makeParser, fixParser)); gulp.watch(dataGlob, test); done(); }; gulp.task('watch', watch);
import gulp from 'gulp'; import {build} from './build'; import {test} from './test'; import {makeParser, fixParser} from './parse'; const allSrcGlob = [ 'src/**/*.js', '!src/static/antlr4/parsers/**/*.js', 'test/**/*.js', ]; const allBuildGlob = [ 'build/src/*.js', 'build/test/**/*.js', ]; const grammarGlob = [ 'src/static/antlr4/grammars/**/*.g4', 'build/src/static/antlr4/Translator.js', ]; const dataGlob = [ 'src/static/data/**/*.*', ]; export const watch = done => { gulp.watch(allSrcGlob, build); gulp.watch(allBuildGlob, test); gulp.watch(grammarGlob, gulp.series(makeParser, fixParser)); gulp.watch(dataGlob, test); done(); }; gulp.task('watch', watch);
Add 12 hour option and make it default
Defaults = {}; Defaults.Tweets = function () { return { userId: null, defaultText: '', date: new Date().getTime(), variations: Helpers.getVariations(null, Defaults.Settings()) }; }; Defaults.Variations = function () { return { text: null, time: null, enabled: true } } Defaults.Settings = function () { return { repeatCount: 2, repeatCountOptions: range(1, 5), intervalValue: 12, intervalValueOptions: range(1, 13), intervalUnit: 'Hours', hasVariations: false, intervalUnitOptions: [ {title: 'Hours', millis: 1000*60*60}, {title: 'Days', millis: 1000*60*60*24}, {title: 'Weeks', millis: 1000*60*60*24*7} ] }; }; function range (start, end) { var array = new Array(end-start); for( var i=0; i<array.length; ++i) array[i] = start + i; return array; }
Defaults = {}; Defaults.Tweets = function () { return { userId: null, defaultText: '', date: new Date().getTime(), variations: Helpers.getVariations(null, Defaults.Settings()) }; }; Defaults.Variations = function () { return { text: null, time: null, enabled: true } } Defaults.Settings = function () { return { repeatCount: 4, repeatCountOptions: range(1, 5), intervalValue: 8, intervalValueOptions: range(1, 12), intervalUnit: 'Hours', hasVariations: false, intervalUnitOptions: [ {title: 'Hours', millis: 1000*60*60}, {title: 'Days', millis: 1000*60*60*24}, {title: 'Weeks', millis: 1000*60*60*24*7} ] }; }; function range (start, end) { var array = new Array(end-start); for( var i=0; i<array.length; ++i) array[i] = start + i; return array; }
Add callback for image upload
<!DOCTYPE html> <html> <head> <title>MissAtomicBomb</title> <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="/assets/font-awesome/css/font-awesome.css"> <link rel="stylesheet" href="/assets/summernote/dist/summernote.css"> </head> <body> <h1>editor</h1> <div id="summernote">You gonna miss me when I am gone</div> <script src="/assets/jquery/dist/jquery.js"></script> <script src="/assets/bootstrap/dist/js/bootstrap.js"></script> <script src="/assets/angular/angular.js"></script> <script src="/assets/summernote/dist/summernote.js"></script> <script src="/assets/summernote/lang/summernote-zh-CN.js"></script> <script> $(document).ready(function () { $('#summernote').summernote({ lang: 'zh-CN', onImageUpload: function (files) { console.log('need to upload '); // so the image won't got inserted } }); }); </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>MissAtomicBomb</title> <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="/assets/font-awesome/css/font-awesome.css"> <link rel="stylesheet" href="/assets/summernote/dist/summernote.css"> </head> <body> <h1>editor</h1> <div id="summernote">You gonna miss me when I am gone</div> <script src="/assets/jquery/dist/jquery.js"></script> <script src="/assets/bootstrap/dist/js/bootstrap.js"></script> <script src="/assets/angular/angular.js"></script> <script src="/assets/summernote/dist/summernote.js"></script> <script src="/assets/summernote/lang/summernote-zh-CN.js"></script> <script> $(document).ready(function() { $('#summernote').summernote({ lang: 'zh-CN' }); }); </script> </body> </html>
Make sure the PaxLevel.toString() returns something meaningful
/* * Copyright 2006 Niclas Hedhman. * * 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.ops4j.pax.logging.internal; import org.ops4j.pax.logging.spi.PaxLevel; import org.apache.log4j.Level; public class PaxLevelImpl implements PaxLevel { private Level m_delegate; public PaxLevelImpl( Level delegate ) { m_delegate = delegate; } public boolean isGreaterOrEqual( PaxLevel r ) { PaxLevelImpl impl = (PaxLevelImpl) r; return m_delegate.isGreaterOrEqual( impl.m_delegate ); } public int toInt() { return m_delegate.toInt(); } public int getSyslogEquivalent() { return m_delegate.getSyslogEquivalent(); } public String toString() { return m_delegate.toString(); } }
/* * Copyright 2006 Niclas Hedhman. * * 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.ops4j.pax.logging.internal; import org.ops4j.pax.logging.spi.PaxLevel; import org.apache.log4j.Level; public class PaxLevelImpl implements PaxLevel { private Level m_delegate; public PaxLevelImpl( Level delegate ) { m_delegate = delegate; } public boolean isGreaterOrEqual( PaxLevel r ) { PaxLevelImpl impl = (PaxLevelImpl) r; return m_delegate.isGreaterOrEqual( impl.m_delegate ); } public int toInt() { return m_delegate.toInt(); } public int getSyslogEquivalent() { return m_delegate.getSyslogEquivalent(); } }
Update preview logic after content refactoring As we removed the two column layout in favour of the 1 column stream, the related preview logic has to be updated.
const parseUrl = require('parseurl'); const get = require('lodash/get'); const crypto = require('crypto'); const timingSafeCompare = require('tsscmp'); const contentStore = require('../../lib/content-store'); /* eslint-disable no-param-reassign */ module.exports = (req, res, next) => { const pathName = get(parseUrl.original(req), 'pathname', ''); const [, givenSignature, pageId, revisionId] = pathName.match(/\/preview\/(.*=)\/(\d+)\/(\d+)/); const message = `${pageId}/${revisionId}/`; const hmacSha1 = crypto.createHmac('sha1', process.env.PREVIEW_SIGNATURE_KEY).update(message).digest('base64'); const expectedSignature = hmacSha1.replace(/\+/g, '-').replace(/\//g, '_'); // Ensure the signature is valid if (!timingSafeCompare(expectedSignature, givenSignature)) { const err = new Error('Page not found'); err.status = 404; return next(err); } return contentStore.getPreview(`${pageId}/?revision-id=${revisionId}`) .then((response) => { const record = response; const layout = record.layout || 'content-simple'; req.layout = `_layouts/${layout}`; req.pageData = record; req.pageData.previewRevisionId = revisionId; next(); }) .catch((err) => { err.status = 404; next(err); }); };
const parseUrl = require('parseurl'); const get = require('lodash/get'); const crypto = require('crypto'); const timingSafeCompare = require('tsscmp'); const contentStore = require('../../lib/content-store'); /* eslint-disable no-param-reassign */ module.exports = (req, res, next) => { const pathName = get(parseUrl.original(req), 'pathname', ''); const [, givenSignature, pageId, revisionId] = pathName.match(/\/preview\/(.*=)\/(\d+)\/(\d+)/); const message = `${pageId}/${revisionId}/`; const hmacSha1 = crypto.createHmac('sha1', process.env.PREVIEW_SIGNATURE_KEY).update(message).digest('base64'); const expectedSignature = hmacSha1.replace(/\+/g, '-').replace(/\//g, '_'); // Ensure the signature is valid if (!timingSafeCompare(expectedSignature, givenSignature)) { const err = new Error('Page not found'); err.status = 404; return next(err); } return contentStore.getPreview(`${pageId}/?revision-id=${revisionId}`) .then((response) => { req.layout = `_layouts/${response.layout}`; req.pageData = response; req.pageData.previewRevisionId = revisionId; next(); }) .catch((err) => { err.status = 404; next(err); }); };
Update a string with the latest formatting approach
from abc import ABCMeta import logging logger = logging.getLogger(__name__) class SubclassRegisteringABCMeta(ABCMeta): def __init__(cls, name, bases, dct): super(SubclassRegisteringABCMeta, cls).__init__(name, bases, dct) if not hasattr(cls, '_registry'): cls._registry = {} registry_keys = getattr(cls, '_registry_keys', []) if registry_keys: for key in registry_keys: if key in cls._registry and cls.__name__ != cls._registry[key].__name__: logger.info(f"Ignoring attempt by class `{cls.__name__}` to register key '{key}', " f"which is already registered for class `{cls._registry[key].__name__}`.") else: cls._registry[key] = cls def _get_subclass_for(cls, key): return cls._registry[key]
from abc import ABCMeta import logging logger = logging.getLogger(__name__) class SubclassRegisteringABCMeta(ABCMeta): def __init__(cls, name, bases, dct): super(SubclassRegisteringABCMeta, cls).__init__(name, bases, dct) if not hasattr(cls, '_registry'): cls._registry = {} registry_keys = getattr(cls, '_registry_keys', []) if registry_keys: for key in registry_keys: if key in cls._registry and cls.__name__ != cls._registry[key].__name__: logger.info("Ignoring attempt by class `{}` to register key '{}', which is already registered for class `{}`.".format(cls.__name__, key, cls._registry[key].__name__)) else: cls._registry[key] = cls def _get_subclass_for(cls, key): return cls._registry[key]
Use unicode for ical description
from django_ical.views import ICalFeed from .models import Meeting from datetime import timedelta class MeetingFeed(ICalFeed): """ A iCal feed for meetings """ product_id = '-//chipy.org//Meeting//EN' timezone = 'CST' def items(self): return Meeting.objects.order_by('-when').all() def item_description(self, item): description = 'RSVP at http://chipy.org\n\n' for topic in item.topics.all(): description += u'{title} by {speaker}\n{description}\n\n'.format( title=topic.title, speaker=topic.presentors.all()[0].name, description=topic.description) return description def item_link(self, item): return '' def item_location(self, item): return item.where.address def item_start_datetime(self, item): return item.when def item_end_datetime(self, item): return item.when + timedelta(hours=1) def item_title(self, item): return 'ChiPy Meeting'
from django_ical.views import ICalFeed from .models import Meeting from datetime import timedelta class MeetingFeed(ICalFeed): """ A iCal feed for meetings """ product_id = '-//chipy.org//Meeting//EN' timezone = 'CST' def items(self): return Meeting.objects.order_by('-when').all() def item_description(self, item): description = 'RSVP at http://chipy.org\n\n' for topic in item.topics.all(): description += '{title} by {speaker}\n{description}\n\n'.format( title=topic.title, speaker=topic.presentors.all()[0].name, description=topic.description) return description def item_link(self, item): return '' def item_location(self, item): return item.where.address def item_start_datetime(self, item): return item.when def item_end_datetime(self, item): return item.when + timedelta(hours=1) def item_title(self, item): return 'ChiPy Meeting'
Remove useless comment about returning a null mouse. Access mouse through ForPlay.mouse().
/** * Copyright 2010 The ForPlay Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package forplay.core; /** * Generic platform interface. New platforms are defined as implementations of this interface. */ public interface Platform { Audio audio(); Graphics graphics(); AssetManager assetManager(); Json json(); Keyboard keyboard(); Log log(); Net net(); Pointer pointer(); Mouse mouse(); Storage storage(); Analytics analytics(); float random(); void run(Game game); double time(); RegularExpression regularExpression(); void openURL(String url); }
/** * Copyright 2010 The ForPlay Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package forplay.core; /** * Generic platform interface. New platforms are defined as implementations of this interface. */ public interface Platform { Audio audio(); Graphics graphics(); AssetManager assetManager(); Json json(); Keyboard keyboard(); Log log(); Net net(); Pointer pointer(); /** * Return the mouse if it is supported, or null otherwise. * * @return the mouse if it is supported, or null otherwise. */ Mouse mouse(); Storage storage(); Analytics analytics(); float random(); void run(Game game); double time(); RegularExpression regularExpression(); void openURL(String url); }
[skip ci] Fix arrayconstructor for empty arrays
import Expression from '../Expression'; import Specificity from '../Specificity'; import ArrayValue from '../dataTypes/ArrayValue'; import Sequence from '../dataTypes/Sequence'; /** * @extends {Expression} */ class CurlyArrayConstructor extends Expression { /** * @param {!Array<!Expression>} members The expressions for the values */ constructor (members) { super( new Specificity({ [Specificity.EXTERNAL_KIND]: 1 }), members, { canBeStaticallyEvaluated: members.every(member => member.canBeStaticallyEvaluated) }); this._members = members; } evaluate (dynamicContext, executionParameters) { if (this._members.length === 0) { return Sequence.singleton(new ArrayValue([])); } return this._members[0].evaluateMaybeStatically(dynamicContext, executionParameters) .mapAll(allValues => Sequence.singleton(new ArrayValue(allValues.map(Sequence.singleton)))); } } export default CurlyArrayConstructor;
import Expression from '../Expression'; import Specificity from '../Specificity'; import ArrayValue from '../dataTypes/ArrayValue'; import Sequence from '../dataTypes/Sequence'; /** * @extends {Expression} */ class CurlyArrayConstructor extends Expression { /** * @param {!Array<!Expression>} members The expressions for the values */ constructor (members) { super( new Specificity({ [Specificity.EXTERNAL_KIND]: 1 }), members, { canBeStaticallyEvaluated: members.every(member => member.canBeStaticallyEvaluated) }); this._members = members; } evaluate (dynamicContext, executionParameters) { return this._members[0].evaluateMaybeStatically(dynamicContext, executionParameters) .mapAll(allValues => Sequence.singleton(new ArrayValue(allValues.map(Sequence.singleton)))); } } export default CurlyArrayConstructor;
Use Object and not array. Instead of using `info = []`. To which if we try to assign properties, doesn't seem to work well. Hence, try to use object representation, which allows us to use `info.name` or assign it another object.
const execute = require('../lib/executeCommand'); module.exports = (vm) => { return new Promise((resolve, reject) => { execute(['showvminfo', '"' + vm + '"']).then(stdout => { let info = {}; let regex = /^(.*?):\s+(.*)$/gim; let match; while (match = regex.exec(stdout)) { if (match.index === regex.lastIndex) { regex.lastIndex++; } // Trim let varname = match[1].trim().toLowerCase().replace(/ /g, '_'); let value = match[2].trim(); info[varname] = value; } resolve(info); }).catch(reject); }); };
const execute = require('../lib/executeCommand'); module.exports = (vm) => { return new Promise((resolve, reject) => { execute(['showvminfo', '"' + vm + '"']).then(stdout => { let info = []; let regex = /^(.*?):\s+(.*)$/gim; let match; while (match = regex.exec(stdout)) { if (match.index === regex.lastIndex) { regex.lastIndex++; } // Trim let varname = match[1].trim().toLowerCase().replace(/ /g, '_'); let value = match[2].trim(); info[varname] = value; } resolve(info); }).catch(reject); }); };
Change button text for closed applications
<?hh class FrontpageController extends BaseController { public static function getPath(): string { return '/'; } public static function get(): :xhp { # If a user is logged in, redirect them to where they belong if(Session::isActive()) { header('Location: /dashboard'); } $registration = "Registration now open"; $button = "APPLY NOW"; if (!Settings::get('applications_open')) { $registration = "Registration is now closed"; $button = "CHECK MY STATUS"; } return <div class="col-md-6 col-md-offset-3 masthead"> <h3 class="hero-info">Austin, TX | Sept. 26-27</h3> <p class="prompt-open">{$registration}</p> <p><a id="signin" class="btn btn-default col-xs-12" role="button" href="/login">{$button}</a></p> <p class="info">Applications are acccepted on a first come first serve basis. If accepted, you will receive a confirmation email in ~7 days.</p> <div class="footer"> <p class="footer-prompt">Already Have An Account? <a href={LoginController::getPath()}>Log in Here</a></p> <p class="footer-prompt">Having Trouble? Email Us <a href="mailto:hello@hacktx.com">hello@hacktx.com</a></p> </div> </div>; } }
<?hh class FrontpageController extends BaseController { public static function getPath(): string { return '/'; } public static function get(): :xhp { # If a user is logged in, redirect them to where they belong if(Session::isActive()) { header('Location: /dashboard'); } return <div class="col-md-6 col-md-offset-3 masthead"> <h3 class="hero-info">Austin, TX | Sept. 26-27</h3> <p class="prompt-open">Registration now open</p> <p><a id="signin" class="btn btn-default col-xs-12" role="button" href="/login">APPLY NOW</a></p> <p class="info">Applications are acccepted on a first come first serve basis. If accepted, you will receive a confirmation email in ~7 days.</p> <div class="footer"> <p class="footer-prompt">Already Have An Account? <a href={LoginController::getPath()}>Log in Here</a></p> <p class="footer-prompt">Having Trouble? Email Us <a href="mailto:hello@hacktx.com">hello@hacktx.com</a></p> </div> </div>; } }
Clean up imports after expirements with signals for quitting
import subprocess from os import path, mkdir from tympeg.util import renameFile class StreamSaver: def __init__(self, input_stream, output_file_path_ts, verbosity=24): self.file_writer = None self.analyzeduration = 5000000 # ffmpeg default value (milliseconds must be integer) self.probesize = 5000000 # ffmpeg default value (bytes must be > 32 and integer) directory, file_name = path.split(output_file_path_ts) # make sure output is .ts file for stable writing file_name, ext = file_name.split('.') file_name += '.ts' if not path.isdir(directory): mkdir(directory) if path.isfile(output_file_path_ts): file_name = renameFile(file_name) output_file_path_ts = path.join(directory, file_name) self.args = ['ffmpeg', '-v', str(verbosity), '-analyzeduration', str(self.analyzeduration), '-probesize', str(self.probesize), '-i', str(input_stream), '-c', 'copy', output_file_path_ts] def run(self): self.file_writer = subprocess.Popen(self.args) def quit(self): self.file_writer.terminate()
import subprocess from os import path, mkdir from tympeg.util import renameFile import platform import signal import sys class StreamSaver: def __init__(self, input_stream, output_file_path_ts, verbosity=24): self.file_writer = None self.analyzeduration = 5000000 # ffmpeg default value (milliseconds must be integer) self.probesize = 5000000 # ffmpeg default value (bytes must be > 32 and integer) directory, file_name = path.split(output_file_path_ts) # make sure output is .ts file for stable writing file_name, ext = file_name.split('.') file_name += '.ts' if not path.isdir(directory): mkdir(directory) if path.isfile(output_file_path_ts): file_name = renameFile(file_name) output_file_path_ts = path.join(directory, file_name) self.args = ['ffmpeg', '-v', str(verbosity), '-analyzeduration', str(self.analyzeduration), '-probesize', str(self.probesize), '-i', str(input_stream), '-c', 'copy', output_file_path_ts] def run(self): self.file_writer = subprocess.Popen(self.args) def quit(self): self.file_writer.terminate()
tour: Rename mux -> mu to follow convention Nearly all sync.Mutex members in the standard library are named mu, or use "mu" as part of the name. While this isn't a documented recommendation anywhere that I can find, it would seem nice to start new users with this same convention. Change-Id: I67cbe2a0052b81d8bb57d5ece0cefd2f3838f298 GitHub-Last-Rev: 31ef869d9b72e7eb08b9be9340242b0e535a175f GitHub-Pull-Request: golang/tour#813 Reviewed-on: https://go-review.googlesource.com/c/tour/+/192725 Reviewed-by: Brad Fitzpatrick <ae9783c0b0efc69cd85ab025ddd17aa44cdc4aa5@golang.org>
// +build OMIT package main import ( "fmt" "sync" "time" ) // SafeCounter is safe to use concurrently. type SafeCounter struct { mu sync.Mutex v map[string]int } // Inc increments the counter for the given key. func (c *SafeCounter) Inc(key string) { c.mu.Lock() // Lock so only one goroutine at a time can access the map c.v. c.v[key]++ c.mu.Unlock() } // Value returns the current value of the counter for the given key. func (c *SafeCounter) Value(key string) int { c.mu.Lock() // Lock so only one goroutine at a time can access the map c.v. defer c.mu.Unlock() return c.v[key] } func main() { c := SafeCounter{v: make(map[string]int)} for i := 0; i < 1000; i++ { go c.Inc("somekey") } time.Sleep(time.Second) fmt.Println(c.Value("somekey")) }
// +build OMIT package main import ( "fmt" "sync" "time" ) // SafeCounter is safe to use concurrently. type SafeCounter struct { v map[string]int mux sync.Mutex } // Inc increments the counter for the given key. func (c *SafeCounter) Inc(key string) { c.mux.Lock() // Lock so only one goroutine at a time can access the map c.v. c.v[key]++ c.mux.Unlock() } // Value returns the current value of the counter for the given key. func (c *SafeCounter) Value(key string) int { c.mux.Lock() // Lock so only one goroutine at a time can access the map c.v. defer c.mux.Unlock() return c.v[key] } func main() { c := SafeCounter{v: make(map[string]int)} for i := 0; i < 1000; i++ { go c.Inc("somekey") } time.Sleep(time.Second) fmt.Println(c.Value("somekey")) }
Fix small issue with ember dropzone
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['draggable-dropzone'], classNameBindings: ['dragClass'], dragClass: 'deactivated', dragLeave: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); }, dragOver: function(event) { event.preventDefault(); this.set('dragClass', 'activated'); }, drop: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); var data = event.dataTransfer.getData('text/data'); // default drop action - change with {{draggable-dropzone dropped=xyz}} this.sendAction('dropped', data); } });
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['draggable-dropzone'], classNameBindings: ['dragClass'], dragClass: 'deactivated', dragLeave: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); }, dragOver: function(event) { event.preventDefault(); this.set('dragClass', 'activated'); }, drop: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); data = event.dataTransfer.getData('text/data'); // default drop action - change with {{draggable-dropzone dropped=xyz}} this.sendAction('dropped', data); } });
Fix linebreaks only for string values
jsio('from shared.javascript import Class, bind') jsio('import ui.Component') exports = Class(ui.Component, function(supr){ this._domTag = 'span' this._className = 'Value' this.init = function(jsArgs, viewArgs) { supr(this, 'init') this._itemIds = jsArgs[0] this._property = viewArgs[0] } this._createContent = function() { this.setDependant(this._itemIds, this._property) } this.setDependant = function(itemIds, property) { if (this._item) { logger.warn("TODO unsubscribe from old item") } this._propertyChain = property.split('.') var itemId = (typeof itemIds == 'string' ? itemIds : itemIds.getId ? itemIds.getId() : itemIds[this._propertyChain.shift()]) this._item = fin.getItem(itemId) this._item.addDependant(this._propertyChain, bind(this, '_onItemMutation')) } this._onItemMutation = function(mutation, newValue) { this.setValue(newValue) } this.setValue = function(value) { if (typeof value == 'undefined') { return } if (typeof value == 'string') { value = value.replace(/\n/g, '<br />') value = value.replace(/ $/, '&nbsp;') } this._element.innerHTML = value } })
jsio('from shared.javascript import Class, bind') jsio('import ui.Component') exports = Class(ui.Component, function(supr){ this._domTag = 'span' this._className = 'Value' this.init = function(jsArgs, viewArgs) { supr(this, 'init') this._itemIds = jsArgs[0] this._property = viewArgs[0] } this._createContent = function() { this.setDependant(this._itemIds, this._property) } this.setDependant = function(itemIds, property) { if (this._item) { logger.warn("TODO unsubscribe from old item") } this._propertyChain = property.split('.') var itemId = (typeof itemIds == 'string' ? itemIds : itemIds.getId ? itemIds.getId() : itemIds[this._propertyChain.shift()]) this._item = fin.getItem(itemId) this._item.addDependant(this._propertyChain, bind(this, '_onItemMutation')) } this._onItemMutation = function(mutation, newValue) { this.setValue(newValue) } this.setValue = function(value) { if (typeof value == 'undefined') { return } value = value.replace(/\n/g, '<br />') value = value.replace(/ $/, '&nbsp;') this._element.innerHTML = value } })
Use regexp to match end of html; let local test function to return bool status
package urlfetch import "testing" import "regexp" // Local helper functions func parse(output string) bool { test, err := regexp.MatchString("</html>", output) if err != nil { return false } return test } func test_getdata4urls(urls []string) bool { ch := make(chan []byte) for _, url := range urls { go Getdata(url, ch) } for i := 0; i<len(urls); i++ { res := string(<-ch) if ! parse(res) { return false } } return true } func test_getdata(url string) bool { ch := make(chan []byte) go Getdata(url, ch) res := string(<-ch) return parse(res) } // Test function func TestGetdata(t *testing.T) { url1 := "http://www.google.com" url2 := "http://www.golang.org" urls := []string{url1, url2} var test bool test = test_getdata(url1) if ! test { t.Log("test getdata call", url1) t.Fail() } test = test_getdata4urls(urls) if ! test { t.Log("test getdata call with multiple urls", urls) t.Fail() } }
package urlfetch import "testing" import "fmt" // Local helper functions func test_getdata4urls(urls []string) { // create HTTP client client := HttpClient() ch := make(chan []byte) n := 0 for _, url := range urls { n++ go Getdata(client, url, ch) } for i:=0; i<n; i++ { fmt.Println(string(<-ch)) } } func test_getdata(url string) { // create HTTP client client := HttpClient() ch := make(chan []byte) go Getdata(client, url, ch) fmt.Println(string(<-ch)) } // Test function func TestGetdata(t *testing.T) { url1 := "http://www.google.com" url2 := "http://www.golang.org" urls := []string{url1, url2} t.Log("test getdata call") test_getdata(url1) t.Log("test getdata call with multiple urls") test_getdata4urls(urls) }
Add caching to HGNC client
import urllib2 from functools32 import lru_cache import xml.etree.ElementTree as et hgnc_url = 'http://rest.genenames.org/fetch/' @lru_cache(maxsize=1000) def get_hgnc_name(hgnc_id): xml_tree = get_hgnc_entry(hgnc_id) if xml_tree is None: return None hgnc_name_tag =\ xml_tree.find("result/doc/str[@name='symbol']") if hgnc_name_tag is None: return None return hgnc_name_tag.text.strip() def get_hgnc_entry(hgnc_id): url = hgnc_url + 'hgnc_id/%s' % hgnc_id headers = {'Accept': '*/*'} req = urllib2.Request(url, headers=headers) try: res = urllib2.urlopen(req) except urllib2.HTTPError: return None xml_tree = et.parse(res) return xml_tree
import urllib2 import xml.etree.ElementTree as et hgnc_url = 'http://rest.genenames.org/fetch/' def get_hgnc_name(hgnc_id): xml_tree = get_hgnc_entry(hgnc_id) if xml_tree is None: return None hgnc_name_tag =\ xml_tree.find("result/doc/str[@name='symbol']") if hgnc_name_tag is None: return None return hgnc_name_tag.text.strip() def get_hgnc_entry(hgnc_id): url = hgnc_url + 'hgnc_id/%s' % hgnc_id headers = {'Accept': '*/*'} req = urllib2.Request(url, headers=headers) try: res = urllib2.urlopen(req) except urllib2.HTTPError: return None xml_tree = et.parse(res) return xml_tree
Use environment variable to detect Windows systems.
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = sys.platform.startswith('win') PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
Slack: Add a space onto the end of italic text (prevent merging the _ with links)
var plugin; var slack; var config; var events = {} events.onLoad = function(plugin) { // dependency injection, any better methods for Node? this.plugin = plugin; config = plugin.getConfig(); // https://www.npmjs.com/package/slack-node var Slack = require('slack-node'); slack = new Slack(); slack.setWebhook(config.webhookuri); } events.onUnload = function() { } events.plug_join = function(user) { } events.plug_chat = function(message) { var content = message.message; var parts = content.split(" "); if (parts[0] == "/me") { parts.shift(); content = "_" + parts.join(" ") + " _"; } slack.webhook({ channel : config.channel, username : message.from.username, text : content }, function(err, response) { if (response.status != "ok") { console.log(response); } }); } module.exports = { "events" : events };
var plugin; var slack; var config; var events = {} events.onLoad = function(plugin) { // dependency injection, any better methods for Node? this.plugin = plugin; config = plugin.getConfig(); // https://www.npmjs.com/package/slack-node var Slack = require('slack-node'); slack = new Slack(); slack.setWebhook(config.webhookuri); } events.onUnload = function() { } events.plug_join = function(user) { } events.plug_chat = function(message) { var content = message.message; var parts = content.split(" "); if (parts[0] == "/me") { parts.shift(); content = "_" + parts.join(" ") + "_"; } slack.webhook({ channel : config.channel, username : message.from.username, text : content }, function(err, response) { if (response.status != "ok") { console.log(response); } }); } module.exports = { "events" : events };
IVIS-56: Fix package name in argument resolver.
package imcode.services.argumentresolver; import com.imcode.services.GenericService; import imcode.services.IvisServiceFactory; import imcode.services.utils.IvisOAuth2Utils; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebArgumentResolver; import org.springframework.web.context.request.NativeWebRequest; import javax.servlet.http.HttpServletRequest; /** * Created by ruslan on 06.12.16. */ public class IvisServiceArgumentResolver implements WebArgumentResolver { @Override public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { Class<?> type = methodParameter.getParameterType(); Object nativeRequest = webRequest.getNativeRequest(); if (!GenericService.class.isAssignableFrom(type) && !(nativeRequest instanceof HttpServletRequest)) { return UNRESOLVED; } HttpServletRequest request = (HttpServletRequest) nativeRequest; IvisServiceFactory ivisServiceFactory = IvisOAuth2Utils.getServiceFactory(request); return ivisServiceFactory.getService((Class<? extends GenericService>) type); } }
package com.imcode.configuration; import com.imcode.services.GenericService; import imcode.services.IvisServiceFactory; import imcode.services.utils.IvisOAuth2Utils; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebArgumentResolver; import org.springframework.web.context.request.NativeWebRequest; import javax.servlet.http.HttpServletRequest; /** * Created by ruslan on 06.12.16. */ public class IvisServiceArgumentResolver implements WebArgumentResolver { @Override public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { Class<?> type = methodParameter.getParameterType(); Object nativeRequest = webRequest.getNativeRequest(); if (!GenericService.class.isAssignableFrom(type) && !(nativeRequest instanceof HttpServletRequest)) { return UNRESOLVED; } HttpServletRequest request = (HttpServletRequest) nativeRequest; IvisServiceFactory ivisServiceFactory = IvisOAuth2Utils.getServiceFactory(request); return ivisServiceFactory.getService((Class<? extends GenericService>) type); } }
Handle spans in large contenteditable divs.
(function() { "use strict"; var ContentEditableUtils = function() { }; ContentEditableUtils.prototype.getTextFromContentEditable = function(contentEditable) { var pre = $("<pre/>").html(contentEditable.html()); pre.find("div").replaceWith(function() { return "\n" + this.innerHTML; }); pre.find("p").replaceWith(function() { return this.innerHTML + "<br>"; }); pre.find("br").replaceWith("\n"); pre.find("span").replaceWith(function() { return "\n" + this.innerHTML; }); var tempParagraphs = pre.text().trim().split("\n"); var resultParagraphs = []; $.each(tempParagraphs, function(index, value) { value = value.trim(); if (value !== "") { resultParagraphs.push("<p>" + value + "</p>"); } }); return resultParagraphs.join(""); }; // Export window.hikeio.ContentEditableUtils = ContentEditableUtils; } )();
(function() { "use strict"; var ContentEditableUtils = function() { }; ContentEditableUtils.prototype.getTextFromContentEditable = function(contentEditable) { var pre = $("<pre/>").html(contentEditable.html()); pre.find("div").replaceWith(function() { return "\n" + this.innerHTML; }); pre.find("p").replaceWith(function() { return this.innerHTML + "<br>"; }); pre.find("br").replaceWith("\n"); var tempParagraphs = pre.text().trim().split("\n"); var resultParagraphs = []; $.each(tempParagraphs, function(index, value) { value = value.trim(); if (value !== "") { resultParagraphs.push("<p>" + value + "</p>"); } }); return resultParagraphs.join(""); }; // Export window.hikeio.ContentEditableUtils = ContentEditableUtils; } )();
Fix a typo that make the setup fail for localfs
<?php /** * Interface for the file system models. * * This defines the interface for any model that wants to interact with a remote file system. * @author Jaisen Mathai <jaisen@jmathai.com> */ interface FileSystemInterface { public function deletePhoto($id); public function getPhoto($filename); public function putPhoto($localFile, $remoteFile); public function putPhotos($files); public function getHost(); public function initialize(); } /** * The public interface for instantiating a file system obect. * This returns the appropriate type of object by reading the config. * Accepts a set of params that must include a type and targetType * * @param string $type Optional type parameter which defines the type of file system. * @return object A file system object that implements FileSystemInterface */ function getFs(/*$type*/) { static $filesystem, $type; if($filesystem) return $filesystem; if(func_num_args() == 1) $type = func_get_arg(0); // load configs only once if(!$type) $type = getConfig()->get('systems')->fileSystem; switch($type) { case 'S3': $filesystem = new FileSystemS3(); break; case 'LocalFs': $filesystem = new FileSystemLocal(); break; } if($filesystem) return $filesystem; throw new Exception("FileSystem Provider {$type} does not exist", 404); }
<?php /** * Interface for the file system models. * * This defines the interface for any model that wants to interact with a remote file system. * @author Jaisen Mathai <jaisen@jmathai.com> */ interface FileSystemInterface { public function deletePhoto($id); public function getPhoto($filename); public function putPhoto($localFile, $remoteFile); public function putPhotos($files); public function getHost(); public function initialize(); } /** * The public interface for instantiating a file system obect. * This returns the appropriate type of object by reading the config. * Accepts a set of params that must include a type and targetType * * @param string $type Optional type parameter which defines the type of file system. * @return object A file system object that implements FileSystemInterface */ function getFs(/*$type*/) { static $filesystem, $type; if($filesystem) return $filesystem; if(func_num_args() == 1) $type = func_get_arg(0); // load configs only once if(!$type) $type = getConfig()->get('systems')->fileSystem; switch($type) { case 'S3': $filesystem = new FileSystemS3(); break; case 'localfs': $filesystem = new FileSystemLocal(); break; } if($filesystem) return $filesystem; throw new Exception("FileSystem Provider {$type} does not exist", 404); }
Add PermissionsLogging for log files.
#!/usr/bin/env python from distutils.core import setup setup(name='SpaceScout-Web', version='1.0', description='Web frontend for SpaceScout', install_requires=[ 'Django>=1.4,<1.5', 'oauth2', 'oauth_provider', 'django-compressor<2.0', 'django-mobility', 'django-templatetag-handlebars', 'simplejson', 'python-ldap', 'mock<=1.0.1', 'PermissionsLogging', ], )
#!/usr/bin/env python from distutils.core import setup setup(name='SpaceScout-Web', version='1.0', description='Web frontend for SpaceScout', install_requires=[ 'Django>=1.4,<1.5', 'oauth2', 'oauth_provider', 'django-compressor<2.0', 'django-mobility', 'django-templatetag-handlebars', 'simplejson', 'python-ldap', 'mock<=1.0.1', ], )
Add shadow to application title
package org.genericsystem.reactor.gs; import org.genericsystem.reactor.Tag; import org.genericsystem.reactor.gs.GSSubcellDisplayer.TagConstructor; public class GSHeader extends GSDiv { public GSHeader(Tag parent, String string, TagConstructor tag1, String string1, TagConstructor tag2, String string2) { super(parent, FlexDirection.ROW); addStyle("justify-content", "space-around"); addStyle("padding", "10px"); if (tag1 != null) { Tag leftTag = tag1.build(this); leftTag.setText(string1); leftTag.addStyle("flex", "1"); } else { Tag leftTag = new GSDiv(this, FlexDirection.COLUMN); leftTag.addStyle("flex", "1"); } new GenericH2Section(this, string) { { addStyle("flex", "3"); addStyle("align-items", "center"); addStyle("color", "White"); addStyle("text-shadow", "1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue"); } }; if (tag2 != null) { Tag rightTag = tag2.build(this); rightTag.setText(string2); rightTag.addStyle("flex", "1"); } else { Tag rightTag = new GSDiv(this, FlexDirection.COLUMN); rightTag.addStyle("flex", "1"); } }; }
package org.genericsystem.reactor.gs; import org.genericsystem.reactor.Tag; import org.genericsystem.reactor.gs.GSSubcellDisplayer.TagConstructor; public class GSHeader extends GSDiv { public GSHeader(Tag parent, String string, TagConstructor tag1, String string1, TagConstructor tag2, String string2) { super(parent, FlexDirection.ROW); addStyle("justify-content", "space-around"); addStyle("padding", "10px"); if (tag1 != null) { Tag leftTag = tag1.build(this); leftTag.setText(string1); leftTag.addStyle("flex", "1"); } else { Tag leftTag = new GSDiv(this, FlexDirection.COLUMN); leftTag.addStyle("flex", "1"); } new GenericH2Section(this, string) { { addStyle("flex", "3"); addStyle("align-items", "center"); addStyle("color", "White"); } }; if (tag2 != null) { Tag rightTag = tag2.build(this); rightTag.setText(string2); rightTag.addStyle("flex", "1"); } else { Tag rightTag = new GSDiv(this, FlexDirection.COLUMN); rightTag.addStyle("flex", "1"); } }; }
Fix in output to help command. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
# The client of DDuplicated tool. from os import path as opath, getcwd from pprint import pprint from sys import argv from dduplicated import commands def get_paths(params): paths = [] for param in params: path = opath.join(getcwd(), param) if opath.exists(path) and opath.isdir(path) and not opath.islink(path): paths.append(path) return paths def main(): params = argv processed_files = [] # Remove the command name del params[0] if len(params) == 0 or "help" in params: commands.help() exit() elif "detect" in params: processed_files = commands.detect(get_paths(params)) elif "delete" in params: processed_files = commands.delete(commands.detect(get_paths(params))) elif "link" in params: processed_files = commands.link(commands.detect(get_paths(params))) else: commands.help() exit() if len(processed_files) > 0: pprint(processed_files) else: print("No duplicates found") print("Great! Bye!") exit(0)
# The client of DDuplicated tool. from os import path as opath, getcwd from pprint import pprint from sys import argv from dduplicated import commands def get_paths(params): paths = [] for param in params: path = opath.join(getcwd(), param) if opath.exists(path) and opath.isdir(path) and not opath.islink(path): paths.append(path) return paths def main(): params = argv processed_files = [] # Remove the command name del params[0] if len(params) == 0 or "help" in params: commands.help() elif "detect" in params: processed_files = commands.detect(get_paths(params)) elif "delete" in params: processed_files = commands.delete(commands.detect(get_paths(params))) elif "link" in params: processed_files = commands.link(commands.detect(get_paths(params))) else: commands.help() exit() if len(processed_files) > 0: pprint(processed_files) else: print("No duplicates found") print("Great! Bye!") exit(0)
Use django.get_version in prerequisite checker
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") sys.exit(1) # Check that we have installed Django try: import django except ImportError: print("It doesn't look like Django is installed.") print("Are you in an activated virtual environment?") print("Did you pip install from requirements.txt?") sys.exit(1) # Check that we have the expected version of Django expected_version = '1.7.1' installed_version = django.get_version() try: assert installed_version == expected_version except AssertionError: print("It doesn't look like you have the expected version " "of Django installed.") print("You have {0}.".format(installed_version)) sys.exit(1) # All good, have fun! print("Everything looks okay to me... Have fun!")
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") sys.exit(1) # Check that we have installed Django try: import django except ImportError: print("It doesn't look like Django is installed.") print("Are you in an activated virtual environment?") print("Did you pip install from requirements.txt?") sys.exit(1) # Check that we have the expected version of Django expected_version = (1, 7, 1) try: assert django.VERSION[:3] == expected_version except AssertionError: print("It doesn't look like you have the expected version " "of Django installed.") print("You have {0}".format('.'.join([str(i) for i in django.VERSION][:3]))) sys.exit(1) # All good, have fun! print("Everything looks okay to me... Have fun!")
build: Exclude .json files in the build
import gulp from 'gulp'; import sourceMaps from 'gulp-sourcemaps'; import babel from 'gulp-babel'; import path from 'path'; import del from 'del'; const paths = { es6Path: './src/**/*.*', es6: [ './src/**/*.js', '!./src/**/*.json' ], es5: './dist', // Must be absolute or relative to source map sourceRoot: path.join( __dirname, 'src' ) }; gulp.task( 'clean:dist', () => { return del( [ './dist/**/*' ] ); } ); gulp.task( 'build', [ 'clean:dist', 'copy:nonJs' ], () => { return gulp.src( paths.es6 ) .pipe( sourceMaps.init() ) .pipe( babel( { presets: [ 'es2015' ] } ) ) .pipe( sourceMaps.write( '.', { sourceRoot: paths.sourceRoot } ) ) .pipe( gulp.dest( paths.es5 ) ); } ); // Copy all the non JavaScript files to the ./dist folder gulp.task( 'copy:nonJs', () => { return gulp.src( [ paths.es6Path, '!' + paths.es6 ] ) .pipe( gulp.dest( paths.es5 ) ) } ); gulp.task( 'watch', [ 'build' ], () => { gulp.watch( paths.es6, [ 'build' ] ); } ); gulp.task( 'default', [ 'watch' ] );
import gulp from 'gulp'; import sourceMaps from 'gulp-sourcemaps'; import babel from 'gulp-babel'; import path from 'path'; import del from 'del'; const paths = { es6Path: './src/**/*.*', es6: [ './src/**/*.js', './src/**/*.json' ], es5: './dist', // Must be absolute or relative to source map sourceRoot: path.join( __dirname, 'src' ) }; gulp.task( 'clean:dist', () => { return del( [ './dist/**/*' ] ); } ); gulp.task( 'build', [ 'clean:dist', 'copy:nonJs' ], () => { return gulp.src( paths.es6 ) .pipe( sourceMaps.init() ) .pipe( babel( { presets: [ 'es2015' ] } ) ) .pipe( sourceMaps.write( '.', { sourceRoot: paths.sourceRoot } ) ) .pipe( gulp.dest( paths.es5 ) ); } ); // Copy all the non JavaScript files to the ./dist folder gulp.task( 'copy:nonJs', () => { return gulp.src( [ paths.es6Path, '!' + paths.es6 ] ) .pipe( gulp.dest( paths.es5 ) ) } ); gulp.task( 'watch', [ 'build' ], () => { gulp.watch( paths.es6, [ 'build' ] ); } ); gulp.task( 'default', [ 'watch' ] );
Align easing float classes API
package com.haxademic.core.math.easing; public class LinearFloat implements IEasingValue { public float _val, _target, _inc; public int _delay; public LinearFloat( float value, float inc ) { _val = value; _target = value; _inc = inc; _delay = 0; } public float value() { return _val; } public float target() { return _target; } public void setCurrent( float value ) { _val = value; } public void setTarget( float value ) { _target = value; } public void setInc( float value ) { _inc = value; } public void setDelay( int frames ) { _delay = frames; } // mask to be swappable with EasingFloat public void update(boolean bool) { update(); } public void update() { if( _delay > 0 ) { _delay--; return; } if( _val != _target ) { boolean switchedSides = false; if( _val < _target ) { _val += _inc; if( _val > _target ) switchedSides = true; } else { _val -= _inc; if( _val < _target ) switchedSides = true; } if( switchedSides == true ) { _val = _target; } } } }
package com.haxademic.core.math.easing; public class LinearFloat implements IEasingValue { public float _val, _target, _inc; public int _delay; public LinearFloat( float value, float inc ) { _val = value; _target = value; _inc = inc; _delay = 0; } public float value() { return _val; } public float target() { return _target; } public void setCurrent( float value ) { _val = value; } public void setTarget( float value ) { _target = value; } public void setInc( float value ) { _inc = value; } public void setDelay( int frames ) { _delay = frames; } public void update() { if( _delay > 0 ) { _delay--; return; } if( _val != _target ) { boolean switchedSides = false; if( _val < _target ) { _val += _inc; if( _val > _target ) switchedSides = true; } else { _val -= _inc; if( _val < _target ) switchedSides = true; } if( switchedSides == true ) { _val = _target; } } } }
Clean up and code style
<?php namespace App\Http\Controllers; use \Redirect; use App\Models\Domain; use App\Models\Hit; class DomainsController extends Controller { public function index() { $domain = Domain::matching($_SERVER['SERVER_NAME'])->first(); if (!$domain || !$domain->active) { abort(404); } // log hit $data = [ 'domain_id' => $domain->id, 'server_values' => json_encode($_SERVER), 'path' => $_SERVER['REQUEST_URI'], ]; if (isset($_SERVER['HTTP_REFERER'])) { $data['referer'] = $_SERVER['HTTP_REFERER']; } Hit::create($data); // redirect to destination return Redirect::to($domain->redirect_url, $domain->status); } }
<?php namespace App\Http\Controllers; use \Redirect; use App\Models\Domain; use App\Models\Hit; class DomainsController extends Controller { public function index() { $domain = Domain::matching($_SERVER['SERVER_NAME']) ->first(); if (!$domain || !$domain->active) { abort(404); } // log hit $data = array( 'domain_id' => $domain->id, 'server_values' => json_encode($_SERVER), 'path' => $_SERVER['REQUEST_URI'], ); if (isset($_SERVER['HTTP_REFERER'])) { $data['referer'] = $_SERVER['HTTP_REFERER']; } Hit::create($data); // redirect to destination return Redirect::to( $domain->redirect_url, $domain->status ); } }
Make live reloading work again
const gulp = require('gulp'), sass = require('gulp-sass'), babel = require('gulp-babel'), sourcemaps = require('gulp-sourcemaps'), gls = require('gulp-live-server'), server = gls.new('index.js'); gulp.task( 'js', () => { return gulp.src( 'src/**/*.js' ) .pipe(sourcemaps.init()) .pipe(babel({ presets: ['es2015'], compact: true })) .pipe(sourcemaps.write('.')) .pipe( gulp.dest( 'public' ) ); }); gulp.task( 'scss', () => { return gulp.src( 'src/**/*.scss' ) .pipe(sourcemaps.init()) .pipe( sass({ outputStyle: 'compressed' }).on( 'error', sass.logError ) ) .pipe(sourcemaps.write('.')) .pipe( gulp.dest('public') ); }); gulp.task( 'watch', () => { server.start(); function notifyServer(file) { var ext = file.path.split('.').pop(); if(ext == 'scss' || ext == 'js') { gulp.run( ext ); } server.notify.apply( server, [file] ); } gulp.watch('src/index.html', notifyServer); gulp.watch('src/*.scss', notifyServer); gulp.watch('src/*.js', notifyServer); gulp.watch('index.js', function() { server.start.bind(server)() }); }); gulp.task( 'default', ['js', 'scss', 'watch'] );
const gulp = require('gulp'), sass = require('gulp-sass'), babel = require('gulp-babel'), sourcemaps = require('gulp-sourcemaps'), gls = require('gulp-live-server'), server = gls.new('index.js'); gulp.task( 'es6', () => { return gulp.src( 'src/**/*.js' ) .pipe(sourcemaps.init()) .pipe(babel({ presets: ['es2015'], compact: true })) .pipe(sourcemaps.write('.')) .pipe( gulp.dest( 'public' ) ); }); gulp.task( 'sass', () => { return gulp.src( 'src/**/*.scss' ) .pipe(sourcemaps.init()) .pipe( sass({ outputStyle: 'compressed' }).on( 'error', sass.logError ) ) .pipe(sourcemaps.write('.')) .pipe( gulp.dest('public') ); }); gulp.task( 'watch', () => { function notifyServer(file) { server.notify.apply( server, [file] ); } server.start(); gulp.watch( 'src/index.html', notifyServer ); gulp.watch( 'src/*.scss', ['sass'], notifyServer ); gulp.watch( 'src/*.js', ['es6'], notifyServer ); gulp.watch( 'index.js', server.start.bind(server) ); }); gulp.task( 'default', ['es6', 'sass', 'watch'] );
Send page pathname rather than whole URL
(function (GOVUK) { "use strict"; var sendVirtualPageView = function() { var $element = $(this); var url = $element.data('url'); if (GOVUK.analytics && url){ GOVUK.analytics.trackPageview(url); } }; GOVUK.GDM.analytics.virtualPageViews = function() { var $messageSent; $('[data-analytics=trackPageView]').each(sendVirtualPageView); if (GOVUK.GDM.analytics.location.pathname().match(/^\/suppliers\/opportunities\/\d+\/ask-a-question/) !== null) { $messageSent = $('#content form').attr('data-message-sent') === 'true'; if ($messageSent) { GOVUK.analytics.trackPageview(GOVUK.GDM.analytics.location.pathname() + '?submitted=true'); } } }; })(window.GOVUK);
(function (GOVUK) { "use strict"; var sendVirtualPageView = function() { var $element = $(this); var url = $element.data('url'); if (GOVUK.analytics && url){ GOVUK.analytics.trackPageview(url); } }; GOVUK.GDM.analytics.virtualPageViews = function() { var $messageSent; $('[data-analytics=trackPageView]').each(sendVirtualPageView); if (GOVUK.GDM.analytics.location.pathname().match(/^\/suppliers\/opportunities\/\d+\/ask-a-question/) !== null) { $messageSent = $('#content form').attr('data-message-sent') === 'true'; if ($messageSent) { GOVUK.analytics.trackPageview(GOVUK.GDM.analytics.location.href() + '?submitted=true'); } } }; })(window.GOVUK);
Make shared static path OS-agnostic
from os.path import join from datetime import datetime import alabaster # Alabaster theme + mini-extension html_theme_path = [alabaster.get_path()] extensions = ['alabaster'] # Paths relative to invoking conf.py - not this shared file html_static_path = [join('..', '_shared_static')] html_theme = 'alabaster' html_theme_options = { 'description': "Pythonic remote execution", 'github_user': 'fabric', 'github_repo': 'fabric', 'gittip_user': 'bitprophet', 'analytics_id': 'UA-18486793-1', } html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html', 'donate.html', ] } # Regular settings project = 'Fabric' year = datetime.now().year copyright = '%d Jeff Forcier' % year master_doc = 'index' templates_path = ['_templates'] exclude_trees = ['_build'] source_suffix = '.rst' default_role = 'obj'
from datetime import datetime import alabaster # Alabaster theme + mini-extension html_theme_path = [alabaster.get_path()] extensions = ['alabaster'] # Paths relative to invoking conf.py - not this shared file html_static_path = ['../_shared_static'] html_theme = 'alabaster' html_theme_options = { 'description': "Pythonic remote execution", 'github_user': 'fabric', 'github_repo': 'fabric', 'gittip_user': 'bitprophet', 'analytics_id': 'UA-18486793-1', } html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html', 'donate.html', ] } # Regular settings project = 'Fabric' year = datetime.now().year copyright = '%d Jeff Forcier' % year master_doc = 'index' templates_path = ['_templates'] exclude_trees = ['_build'] source_suffix = '.rst' default_role = 'obj'
Remove handleOpen function. because it is unnecessary.
import React, { Component } from 'react'; import Dialog from 'material-ui/lib/dialog'; import FlatButton from 'material-ui/lib/flat-button'; import RaisedButton from 'material-ui/lib/raised-button'; // NOTE: For emit `onTouchTap` event. import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); export default class PromoteModal extends Component { constructor(props) { super(props); this.state = { open: false }; } handleClose() { this.props.onHidePromoteModal(); this.setState({ open: this.props.open }); } render() { const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose.bind(this)} />, <FlatButton label="Submit" primary={true} onTouchTap={this.handleClose.bind(this)} /> ]; return ( <div> <Dialog title="" actions={actions} modal={true} open={this.props.open} /> </div> ); } }
import React, { Component } from 'react'; import Dialog from 'material-ui/lib/dialog'; import FlatButton from 'material-ui/lib/flat-button'; import RaisedButton from 'material-ui/lib/raised-button'; // NOTE: For emit `onTouchTap` event. import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); export default class PromoteModal extends Component { constructor(props) { super(props); this.state = { open: false }; } handleOpen() { this.setState({ open: true }); } handleClose() { this.props.onHidePromoteModal(); this.setState({ open: this.props.open }); } render() { const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose.bind(this)} />, <FlatButton label="Submit" primary={true} onTouchTap={this.handleClose.bind(this)} /> ]; return ( <div> <Dialog title="" actions={actions} modal={true} open={this.props.open} /> </div> ); } }
Switch to es5 to match the rest of the lib
function Sites( api ) { this.api = api; } Sites.prototype.query = function( args ) { return new Promise( function( resolve, reject ) { this.api .get( '/sites' ) .query( args ) .end( function( err, res ) { if ( err ) { return reject( err ); } return resolve( res.body ); }); }); } Sites.prototype.getMeta = function( site_id, meta_key ) { var self = this; return new Promise( function( resolve, reject ) { self.api .get( '/sites/' + site_id + '/meta/' + meta_key ) .end( function( err, res ) { if ( err ) { return reject( err ); } return resolve( res.body ); }); }); } module.exports = Sites;
function Sites( api ) { this.api = api; } Sites.prototype.query = function( args ) { return new Promise( function( resolve, reject ) { this.api .get( '/sites' ) .query( args ) .end( function( err, res ) { if ( err ) { return reject( err ); } return resolve( res.body ); }); }); } Sites.prototype.getMeta = function( site_id, meta_key ) { var self = this; return new Promise( ( resolve, reject ) => { self.api .get( '/sites/' + site_id + '/meta/' + meta_key ) .end( ( err, res ) => { if ( err ) { return reject( err ); } return resolve( res.body ); }); }); } module.exports = Sites;
Remove dead code, os.path.mkdir does not even exist
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass try: os.path.mkdir('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
Fix error when output closes before end (e.g., head -n 1)
#!/usr/bin/env node var fs = require('fs') var path = require('path') var minimist = require('minimist') var fasta = require('./') var argv = minimist(process.argv.slice(2), { boolean: ['path', 'file'], alias: { file: 'f', path: 'p' } }) if (argv.help) { return console.log( 'Usage: bionode-ncbi <options> <fasta file [required]> <output file>\n\n' + 'You can also use fasta files compressed with gzip\n' + 'If no output is provided, the result will be printed to stdout\n\n' + 'Options: -p, --path: Includes the path of the original file as a property of the output objects\n\n' ) } var options = { includePath: argv.path, filenameMode: argv.file && !argv.write } var output = argv._[1] ? fs.createWriteStream(argv._[1]) : process.stdout var parser = argv.write ? fasta.write() : fasta(options, argv._[0]) parser.pipe(output) process.stdin.setEncoding('utf8'); if (!process.stdin.isTTY) { process.stdin.on('data', function(data) { if (data.trim() === '') { return } parser.write(data.trim()) }) } process.stdout.on('error', function (err) { if (err.code === 'EPIPE') { process.exit(0) } })
#!/usr/bin/env node var fs = require('fs') var path = require('path') var minimist = require('minimist') var fasta = require('./') var argv = minimist(process.argv.slice(2), { boolean: ['path', 'file'], alias: { file: 'f', path: 'p' } }) if (argv.help) { return console.log( 'Usage: bionode-ncbi <options> <fasta file [required]> <output file>\n\n' + 'You can also use fasta files compressed with gzip\n' + 'If no output is provided, the result will be printed to stdout\n\n' + 'Options: -p, --path: Includes the path of the original file as a property of the output objects\n\n' ) } var options = { includePath: argv.path, filenameMode: argv.file && !argv.write } var output = argv._[1] ? fs.createWriteStream(argv._[1]) : process.stdout var parser = argv.write ? fasta.write() : fasta(options, argv._[0]) parser.pipe(output) process.stdin.setEncoding('utf8'); if (!process.stdin.isTTY) { process.stdin.on('data', function(data) { if (data.trim() === '') { return } parser.write(data.trim()) }) }
Remove sqlalchemy 0.7 warning (Binary => LargeBinary)
#-*-*- encoding: utf-8 -*-*- # # Copyright (C) 2005-2009 University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # listed below: # # Author: Pablo Orduña <pablo@ordunya.com> # from sqlalchemy import Column, String, DateTime, LargeBinary from sqlalchemy.ext.declarative import declarative_base SessionBase = declarative_base() class Session(SessionBase): __tablename__ = 'Sessions' sess_id = Column(String(100), primary_key = True) session_pool_id = Column(String(100), nullable = False) start_date = Column(DateTime(), nullable = False) latest_access = Column(DateTime()) latest_change = Column(DateTime()) session_obj = Column(LargeBinary(), nullable = False) def __init__(self, sess_id, session_pool_id, start_date, session_obj): self.sess_id = sess_id self.session_pool_id = session_pool_id self.start_date = start_date self.session_obj = session_obj
#-*-*- encoding: utf-8 -*-*- # # Copyright (C) 2005-2009 University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # listed below: # # Author: Pablo Orduña <pablo@ordunya.com> # from sqlalchemy import Column, String, DateTime, Binary from sqlalchemy.ext.declarative import declarative_base SessionBase = declarative_base() class Session(SessionBase): __tablename__ = 'Sessions' sess_id = Column(String(100), primary_key = True) session_pool_id = Column(String(100), nullable = False) start_date = Column(DateTime(), nullable = False) latest_access = Column(DateTime()) latest_change = Column(DateTime()) session_obj = Column(Binary(), nullable = False) def __init__(self, sess_id, session_pool_id, start_date, session_obj): self.sess_id = sess_id self.session_pool_id = session_pool_id self.start_date = start_date self.session_obj = session_obj
Use map instead of for loop
import React, { Component, PropTypes } from 'react'; import EventImage from '../components/EventImage'; import CompanyPropTypes from '../proptypes/CompanyPropTypes'; import ImagePropTypes from '../proptypes/ImagePropTypes'; class EventImageContainer extends Component { mergeImages() { const { image, company_event } = this.props; const eventImages = []; // Event images if (image) { eventImages.push(image); } // Company images const companyImages = company_event.map(company => ( company.company.image )); return [...eventImages, ...companyImages]; } render() { return <EventImage {...this.props} images={this.mergeImages()} />; } } EventImageContainer.propTypes = { company_event: PropTypes.arrayOf(PropTypes.shape({ company: PropTypes.shape(CompanyPropTypes), event: PropTypes.number, })), image: PropTypes.shape(ImagePropTypes), }; export default EventImageContainer;
import React, { Component, PropTypes } from 'react'; import EventImage from '../components/EventImage'; import CompanyPropTypes from '../proptypes/CompanyPropTypes'; import ImagePropTypes from '../proptypes/ImagePropTypes'; class EventImageContainer extends Component { mergeImages() { const images = []; // Event images if (this.props.image) { images.push(this.props.image); } // Company images for (const company of this.props.company_event) { images.push(company.company.image); } return images; } render() { return <EventImage {...this.props} images={this.mergeImages()} />; } } EventImageContainer.propTypes = { company_event: PropTypes.arrayOf(PropTypes.shape({ company: PropTypes.shape(CompanyPropTypes), event: PropTypes.number, })), image: PropTypes.shape(ImagePropTypes), }; export default EventImageContainer;
Make travis happy & make my need for semicolons happy ;)
var util = require("util") , EventEmitter = require("events").EventEmitter; module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; } util.inherits(CustomEventEmitter, EventEmitter); CustomEventEmitter.prototype.run = function() { var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); return this; } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct); return this; } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct); return this; } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }); return this; } return CustomEventEmitter; })();
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); return this; } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
[r] Make import compatible with python 2.6
from unittest import TestCase from mock import Mock from robber import expect from robber.matchers.called import Called class TestCalled(TestCase): def test_matches(self): mock = Mock() mock() expect(Called(mock).matches()) == True def test_failure_message(self): mock = Mock() called = Called(mock) message = called.failure_message() expect(message) == 'Expected {function} to be called'.format(function=mock) def test_register(self): expect(expect.matcher('called')) == Called expect(expect.matcher('__called__')) == Called def test_not_a_mock(self): with self.assertRaises(TypeError): expect(Called("a").matches()) == True with self.assertRaises(TypeError): expect(Called(1).matches()) == True
from unittest.case import TestCase from mock import Mock from robber import expect from robber.matchers.called import Called class TestCalled(TestCase): def test_matches(self): mock = Mock() mock() expect(Called(mock).matches()) == True def test_failure_message(self): mock = Mock() called = Called(mock) message = called.failure_message() expect(message) == 'Expected {function} to be called'.format(function=mock) def test_register(self): expect(expect.matcher('called')) == Called expect(expect.matcher('__called__')) == Called def test_not_a_mock(self): with self.assertRaises(TypeError): expect(Called("a").matches()) == True with self.assertRaises(TypeError): expect(Called(1).matches()) == True
state/remote: Switch to statemgr interfaces in test These statemgr interfaces are the new names for the older interfaces in the "state" package. These types alias each other so it doesn't really matter which we use, but the "state" package is deprecated and we intend to eventually remove it, so this is a further step in that direction.
package remote import ( "sync" "testing" "github.com/hashicorp/terraform/states/statemgr" ) func TestState_impl(t *testing.T) { var _ statemgr.Reader = new(State) var _ statemgr.Writer = new(State) var _ statemgr.Persister = new(State) var _ statemgr.Refresher = new(State) var _ statemgr.Locker = new(State) } func TestStateRace(t *testing.T) { s := &State{ Client: nilClient{}, } current := state.TestStateInitial() var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() s.WriteState(current) s.PersistState() s.RefreshState() }() } wg.Wait() }
package remote import ( "sync" "testing" "github.com/hashicorp/terraform/state" ) func TestState_impl(t *testing.T) { var _ state.StateReader = new(State) var _ state.StateWriter = new(State) var _ state.StatePersister = new(State) var _ state.StateRefresher = new(State) var _ state.Locker = new(State) } func TestStateRace(t *testing.T) { s := &State{ Client: nilClient{}, } current := state.TestStateInitial() var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() s.WriteState(current) s.PersistState() s.RefreshState() }() } wg.Wait() }
NXP-11577: Fix Sonar Major violations: Hide Utility Class Constructor
/* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Olivier Grisel <ogrisel@nuxeo.com> * Antoine Taillefer <ataillefer@nuxeo.com> */ package org.nuxeo.drive.service; import java.io.Serializable; public final class NuxeoDriveEvents { private NuxeoDriveEvents() { // Utility class } public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot"; public static final String ROOT_REGISTERED = "rootRegistered"; public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot"; public static final String ROOT_UNREGISTERED = "rootUnregistered"; public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName"; public static final Serializable EVENT_CATEGORY = "NuxeoDrive"; public static final String DELETED_EVENT = "deleted"; }
/* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Olivier Grisel <ogrisel@nuxeo.com> * Antoine Taillefer <ataillefer@nuxeo.com> */ package org.nuxeo.drive.service; import java.io.Serializable; public final class NuxeoDriveEvents { public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot"; public static final String ROOT_REGISTERED = "rootRegistered"; public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot"; public static final String ROOT_UNREGISTERED = "rootUnregistered"; public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName"; public static final Serializable EVENT_CATEGORY = "NuxeoDrive"; public static final String DELETED_EVENT = "deleted"; }
Add file name parsing helper
package com.github.sormuras.bach.internal; import java.net.URI; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; public interface StringSupport { static String join(List<String> strings) { return strings.stream().map(StringSupport::firstLine).collect(Collectors.joining(" ")); } static String firstLine(String string) { var lines = string.lines().toList(); var size = lines.size(); return size <= 1 ? string : lines.get(0) + "[...%d lines]".formatted(size); } static String parseFileName(String string) { var path = string.indexOf(':') > 0 ? URI.create(string).getPath() : string; return Path.of(path).getFileName().toString(); } record Property(String key, String value) {} static Property parseProperty(String string) { return StringSupport.parseProperty(string, '='); } static Property parseProperty(String string, char separator) { int index = string.indexOf(separator); if (index < 0) { var message = "Expected a `KEY%sVALUE` string, but got: %s".formatted(separator, string); throw new IllegalArgumentException(message); } var key = string.substring(0, index); var value = string.substring(index + 1); return new Property(key, value); } }
package com.github.sormuras.bach.internal; import java.util.List; import java.util.stream.Collectors; public interface StringSupport { static String join(List<String> strings) { return strings.stream().map(StringSupport::firstLine).collect(Collectors.joining(" ")); } static String firstLine(String string) { var lines = string.lines().toList(); var size = lines.size(); return size <= 1 ? string : lines.get(0) + "[...%d lines]".formatted(size); } record Property(String key, String value) {} static Property parseProperty(String string) { return StringSupport.parseProperty(string, '='); } static Property parseProperty(String string, char separator) { int index = string.indexOf(separator); if (index < 0) { var message = "Expected a `KEY%sVALUE` string, but got: %s".formatted(separator, string); throw new IllegalArgumentException(message); } var key = string.substring(0, index); var value = string.substring(index + 1); return new Property(key, value); } }
Add indexes to inventoryitem migration
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Inventoryitem extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('inventoryitem', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number'); $table->string('name'); $table->string('version'); $table->string('bundleid'); $table->string('bundlename'); $table->text('path'); $table->index(['name', 'version']); $table->index('serial_number'); $table->index('bundleid'); $table->index('bundlename'); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('inventoryitem'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Inventoryitem extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('inventoryitem', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number'); $table->string('name'); $table->string('version'); $table->string('bundleid'); $table->string('bundlename'); $table->text('path'); $table->index(['name', 'version']); $table->index('serial_number'); // $table->timestamps(); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('inventoryitem'); } }
Fix another import in test
from __future__ import print_function from metatlas.mzml_loader import mzml_to_hdf, get_test_data from metatlas.h5_query import get_XIC, get_data def rmse(target, predictions): target = target / target.max() predictions = predictions / predictions.max() return np.sqrt(((predictions - targets) ** 2).mean()) def test_xicof(): return fid = tables.open_file('140808_1_RCH2_neg.h5') x, y = get_XICof(fid, 1, 1000, 1, 0) xicof_scidb = np.load('xicof_scidb.npy') assert rmse(y, xicof_scidb[:, 1]) < 0.01 data = get_data(fid, 1, 0, mz_min=1, mz_max=1000) assert x.sum() == data['i'].sum() assert y[0] == data['rt'][0] assert y[-1] == data['rt'][-1]
from __future__ import print_function from metatlas.mzml_loader import mzml_to_hdf, get_test_data from metatlas.h5_query import get_XICof, get_data def rmse(target, predictions): target = target / target.max() predictions = predictions / predictions.max() return np.sqrt(((predictions - targets) ** 2).mean()) def test_xicof(): return fid = tables.open_file('140808_1_RCH2_neg.h5') x, y = get_XICof(fid, 1, 1000, 1, 0) xicof_scidb = np.load('xicof_scidb.npy') assert rmse(y, xicof_scidb[:, 1]) < 0.01 data = get_data(fid, 1, 0, mz_min=1, mz_max=1000) assert x.sum() == data['i'].sum() assert y[0] == data['rt'][0] assert y[-1] == data['rt'][-1]
Fix random instanciation with milliseconds as seeds
package net.f4fs.util; import java.util.Random; /** * RandomDevice for global usage of pseudo-random numbers. * * Usage: * * RandomDevice.INSTANCE.nextLong * * Created by samuel on 31.03.15. */ public enum RandomDevice { // To provide reproducible outcomes. INSTANCE(new Random(System.currentTimeMillis())); private Random rand; private RandomDevice(Random rand) { this.rand = rand; } /** * Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) * and the specified value (exclusive), drawn from this random number generator's sequence. * * @param n Bound * @return 0 <= value < n */ public synchronized int nextInt(int n) { return rand.nextInt(n); } /** * Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) * and the specified value (exclusive), drawn from this random number generator's sequence. * * @param n Bound * @return 0 <= value < n */ public synchronized long nextLong(long n) { return rand.nextLong(); } public Random getRand() { return rand; } }
package net.f4fs.util; import java.util.Random; /** * RandomDevice for global usage of pseudo-random numbers. * * Usage: * * RandomDevice.INSTANCE.nextLong * * Created by samuel on 31.03.15. */ public enum RandomDevice { // To provide reproducible outcomes. INSTANCE(new Random(4568321548855l)); private Random rand; private RandomDevice(Random rand) { this.rand = rand; } /** * Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) * and the specified value (exclusive), drawn from this random number generator's sequence. * * @param n Bound * @return 0 <= value < n */ public synchronized int nextInt(int n) { return rand.nextInt(n); } /** * Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) * and the specified value (exclusive), drawn from this random number generator's sequence. * * @param n Bound * @return 0 <= value < n */ public synchronized long nextLong(long n) { return rand.nextLong(); } public Random getRand() { return rand; } }
Remove obsolete import (removed in Django 1.10)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \ DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^formset$', DefaultFormsetView.as_view(), name='formset_default'), url(r'^form$', DefaultFormView.as_view(), name='form_default'), url(r'^form_by_field$', DefaultFormByFieldView.as_view(), name='form_by_field'), url(r'^form_horizontal$', FormHorizontalView.as_view(), name='form_horizontal'), url(r'^form_inline$', FormInlineView.as_view(), name='form_inline'), url(r'^form_with_files$', FormWithFilesView.as_view(), name='form_with_files'), url(r'^pagination$', PaginationView.as_view(), name='pagination'), url(r'^misc$', MiscView.as_view(), name='misc'), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import patterns, url from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \ DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^formset$', DefaultFormsetView.as_view(), name='formset_default'), url(r'^form$', DefaultFormView.as_view(), name='form_default'), url(r'^form_by_field$', DefaultFormByFieldView.as_view(), name='form_by_field'), url(r'^form_horizontal$', FormHorizontalView.as_view(), name='form_horizontal'), url(r'^form_inline$', FormInlineView.as_view(), name='form_inline'), url(r'^form_with_files$', FormWithFilesView.as_view(), name='form_with_files'), url(r'^pagination$', PaginationView.as_view(), name='pagination'), url(r'^misc$', MiscView.as_view(), name='misc'), ]
Fix a field lookup to be compatible with all versions of Django. Recent versions of Django removed Meta.get_field_by_name(), which our built-in evolutions were trying to use. Fortunately, all supported versions have Meta.get_field(), which works just as well. This change switches over to that. We'll want to revisit the built-in evolutions before release in order to prevent possible conflicts with Django's migrations.
from django.contrib.sessions.models import Session BUILTIN_SEQUENCES = { 'django.contrib.auth': [], 'django.contrib.contenttypes': [], 'django.contrib.sessions': [], } # Starting in Django 1.3 alpha, Session.expire_date has a db_index set. # This needs to be reflected in the evolutions. Rather than hard-coding # a specific version to check for, we check the actual value in the field. if Session._meta.get_field('expire_date').db_index: BUILTIN_SEQUENCES['django.contrib.sessions'].append( 'session_expire_date_db_index') # Starting in Django 1.4 alpha, the Message model was deleted. try: from django.contrib.auth.models import Message except ImportError: BUILTIN_SEQUENCES['django.contrib.auth'].append('auth_delete_message') # Starting with Django Evolution 0.7.0, we explicitly need ChangeMetas for # unique_together. BUILTIN_SEQUENCES['django.contrib.auth'].append( 'auth_unique_together_baseline') BUILTIN_SEQUENCES['django.contrib.contenttypes'].append( 'contenttypes_unique_together_baseline')
from django.contrib.sessions.models import Session BUILTIN_SEQUENCES = { 'django.contrib.auth': [], 'django.contrib.contenttypes': [], 'django.contrib.sessions': [], } # Starting in Django 1.3 alpha, Session.expire_date has a db_index set. # This needs to be reflected in the evolutions. Rather than hard-coding # a specific version to check for, we check the actual value in the field. if Session._meta.get_field_by_name('expire_date')[0].db_index: BUILTIN_SEQUENCES['django.contrib.sessions'].append( 'session_expire_date_db_index') # Starting in Django 1.4 alpha, the Message model was deleted. try: from django.contrib.auth.models import Message except ImportError: BUILTIN_SEQUENCES['django.contrib.auth'].append('auth_delete_message') # Starting with Django Evolution 0.7.0, we explicitly need ChangeMetas for # unique_together. BUILTIN_SEQUENCES['django.contrib.auth'].append( 'auth_unique_together_baseline') BUILTIN_SEQUENCES['django.contrib.contenttypes'].append( 'contenttypes_unique_together_baseline')