text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Remove unneded (copied for reference) code
import React from 'react'; class ImputationResults extends React.Component { static propTypes = { imputation_data: React.PropTypes.object, biobank: React.PropTypes.string, } render() { if (!this.props.imputation_data) { return <div />; } const data = this.props.imputation_data; const biobankLetter = this.props.biobank && this.props.biobank[0].toUpperCase(); let analysisLetter = ''; let rsq = ''; if (data.genotyped) { rsq = data.rsq; analysisLetter = 'g'; } else if (data.imputed) { rsq = data.rsq; analysisLetter = 'i'; } else { analysisLetter = 't'; } return ( <div> <span style={{ fontWeight: 'bold' }}>{biobankLetter}</span> <span style={{ fontStyle: 'italic' }}>{analysisLetter}</span> {" "} {data.maf} <br /> {data.ref} {" "} {data.alt} {rsq ? ` ${rsq}` : ''} </div> ); } } export default ImputationResults;
import React from 'react'; class ImputationResults extends React.Component { static propTypes = { imputation_data: React.PropTypes.object, biobank: React.PropTypes.string, } let analysis; if ( hunt && hunt.length && hunt[0].genotyped || tromso && tromso.length && tromso[0].genotyped ) { analysis = 'Genotyped'; } else if ( hunt && hunt.length && hunt[0].imputed || tromso && tromso.length && tromso[0].imputed ) { analysis = 'Imputed'; } else if (hunt && hunt.length || tromso && tromso.length) { analysis = 'Typed_Only'; } render() { if (!this.props.imputation_data) { return <div />; } const data = this.props.imputation_data; const biobankLetter = this.props.biobank && this.props.biobank[0].toUTCString(); let analysisLetter = ''; let rsq = ''; if (data.genotyped) { rsq = data.rsq; analysisLetter = 'g'; } else if (data.imputed) { rsq = data.rsq; analysisLetter = 'i'; } else { analysisLetter = 't'; } return ( <div> <span style={{ fontWeight: 'bold' }}>{biobankLetter}</span> <span style={{ fontStyle: 'italic' }}>{analysisLetter}</span> {" "} {data.maf} <br /> {data.ref} {" "} {data.alt} {rsq ? ` ${rsq}` : ''} </div> ); } } export default ImputationResults;
Add shutil dependency to get the terminal size
# -*- coding: utf-8 -*- """Utilities for Halo library. """ import platform import six import codecs import shutil from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating system supports main symbols or not """ os_arch = platform.system() if os_arch != 'Windows': return True return False def colored_frame(frame, color): """Color the frame with given color and returns. Parameters ---------- frame : str Frame to be colored color : str Color to be applied Returns ------- str Colored frame """ return colored(frame, color, attrs=['bold']) def is_text_type(text): """Check if given parameter is a string or not Parameters ---------- text : * Parameter to be checked for text type Returns ------- bool Whether parameter is a string or not """ if isinstance(text, six.text_type) or isinstance(text, six.string_types): return True return False def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except: return text def get_terminal_size(): return shutil.get_terminal_size()
# -*- coding: utf-8 -*- """Utilities for Halo library. """ import platform import six import codecs from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating system supports main symbols or not """ os_arch = platform.system() if os_arch != 'Windows': return True return False def colored_frame(frame, color): """Color the frame with given color and returns. Parameters ---------- frame : str Frame to be colored color : str Color to be applied Returns ------- str Colored frame """ return colored(frame, color, attrs=['bold']) def is_text_type(text): """Check if given parameter is a string or not Parameters ---------- text : * Parameter to be checked for text type Returns ------- bool Whether parameter is a string or not """ if isinstance(text, six.text_type) or isinstance(text, six.string_types): return True return False def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except: return text
Use bigger image for user picture
import React, { PropTypes, Component } from 'react'; import { Link } from 'react-router'; import shouldPureComponentUpdate from 'react-pure-render/function'; import selectn from 'selectn'; export default class User extends Component { static propTypes = { user: PropTypes.object.isRequired }; shouldComponentUpdate = shouldPureComponentUpdate; render() { const { user } = this.props; let imgSrc = user.picture ? `https://dev.nekuno.com/media/cache/user_avatar_180x180/user/images/${user.picture}` : 'https://dev.nekuno.com/media/cache/user_avatar_180x180/bundles/qnoowweb/images/user-no-img.jpg'; return ( <div className="User"> <div className="content-block user-block"> <div className="user-image"> <img src={imgSrc} /> </div> <div className="user-data"> <div className="user-username"> {user.username} </div> <div className="user-location"> <span className="icon-marker"></span> {selectn('location.address', user) ? user.location.address : 'Madrid'} </div> </div> </div> </div> ); } }
import React, { PropTypes, Component } from 'react'; import { Link } from 'react-router'; import shouldPureComponentUpdate from 'react-pure-render/function'; import selectn from 'selectn'; export default class User extends Component { static propTypes = { user: PropTypes.object.isRequired }; shouldComponentUpdate = shouldPureComponentUpdate; render() { const { user } = this.props; let imgSrc = user.picture ? `https://dev.nekuno.com/media/cache/resolve/profile_picture/user/images/${user.picture}` : 'https://dev.nekuno.com/media/cache/user_avatar_180x180/bundles/qnoowweb/images/user-no-img.jpg'; return ( <div className="User"> <div className="content-block user-block"> <div className="user-image"> <img src={imgSrc} /> </div> <div className="user-data"> <div className="user-username"> {user.username} </div> <div className="user-location"> <span className="icon-marker"></span> {selectn('location.address', user) ? user.location.address : 'Madrid'} </div> </div> </div> </div> ); } }
Set request user resolver when authentication is available. Signed-off-by: Mior Muhammad Zaki <[email protected]>
<?php namespace Laravel\Lumen\Auth\Providers; use Dingo\Api\Routing\Route; use Illuminate\Http\Request; use Illuminate\Auth\AuthManager; use Dingo\Api\Auth\Provider\Authorization; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; class Guard extends Authorization { /** * Illuminate authentication manager. * * @var \Illuminate\Contracts\Auth\Guard */ protected $auth; /** * The guard driver name. * * @var string */ protected $guard = 'api'; /** * Create a new basic provider instance. * * @param \Illuminate\Auth\AuthManager $auth */ public function __construct(AuthManager $auth) { $this->auth = $auth->guard($this->guard); } /** * Authenticate request with a Illuminate Guard. * * @param \Illuminate\Http\Request $request * @param \Dingo\Api\Routing\Route $route * * @return mixed */ public function authenticate(Request $request, Route $route) { if (! $user = $this->auth->user()) { throw new UnauthorizedHttpException( get_class($this), 'Unable to authenticate with invalid API key and token.' ); } else { $request->setUserResolver(static function () use ($user) { return $user; }); } return $user; } /** * Get the providers authorization method. * * Note: Not used directly, added just for contract requirement. * * @return string */ public function getAuthorizationMethod() { return 'API_TOKEN'; } }
<?php namespace Laravel\Lumen\Auth\Providers; use Dingo\Api\Routing\Route; use Illuminate\Http\Request; use Illuminate\Auth\AuthManager; use Dingo\Api\Auth\Provider\Authorization; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; class Guard extends Authorization { /** * Illuminate authentication manager. * * @var \Illuminate\Contracts\Auth\Guard */ protected $auth; /** * The guard driver name. * * @var string */ protected $guard = 'api'; /** * Create a new basic provider instance. * * @param \Illuminate\Auth\AuthManager $auth */ public function __construct(AuthManager $auth) { $this->auth = $auth->guard($this->guard); } /** * Authenticate request with a Illuminate Guard. * * @param \Illuminate\Http\Request $request * @param \Dingo\Api\Routing\Route $route * * @return mixed */ public function authenticate(Request $request, Route $route) { if (! $user = $this->auth->user()) { throw new UnauthorizedHttpException( get_class($this), 'Unable to authenticate with invalid API key and token.' ); } return $user; } /** * Get the providers authorization method. * * Note: Not used directly, added just for contract requirement. * * @return string */ public function getAuthorizationMethod() { return 'API_TOKEN'; } }
Fix for broken zeroconf publishing.
import zeroconf import socket class Bonjour(object): """ """ def __init__(self): """ """ self.zeroconf = zeroconf.Zeroconf() self.servers = {} def publish(self, server): """ """ if server in self.servers: self.unpublish(server) ip = "127.0.0.1" if server.ip == "0.0.0.0" else server.ip description = { "txtvers": 1, "Password": int(bool(server.password)), "Machine Name": server.server_name } self.servers[server] = zeroconf.ServiceInfo( "_daap._tcp.local.", server.server_name + "._daap._tcp.local.", socket.inet_aton(ip), server.port, 0, 0, description) self.zeroconf.register_service(self.servers[server]) def unpublish(self, server): """ """ if server not in self.servers: return self.zeroconf.unregister_service(self.servers[server]) del self.servers[server] def close(self): """ """ self.zeroconf.close()
import zeroconf import socket class Bonjour(object): """ """ def __init__(self): """ """ self.zeroconf = zeroconf.Zeroconf() self.servers = {} def publish(self, server): """ """ if server in self.servers: self.unpublish(server) ip = "127.0.0.1" if server.ip == "0.0.0.0" else server.ip description = { "txtvers": 1, "Password": server.password is not None, "Machine Name": server.server_name } self.servers[server] = zeroconf.ServiceInfo( "_daap._tcp.local.", server.server_name + ".daap._tcp.local.", socket.inet_aton(ip), server.port, 0, 0, description) self.zeroconf.register_service(self.servers[server]) def unpublish(self, server): """ """ if server not in self.servers: return self.zeroconf.unregister_service(self.servers[server]) del self.servers[server] def close(self): """ """ self.zeroconf.close()
refactor: Declare now as a string
const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const nowString = new Date().toISOString(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = { ...notification, read_at: nowString }; context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications;
const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const now = new Date(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = { ...notification, read_at: now.toISOString() }; context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications;
Use doxx.template instead of default
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'lib/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, tape: { options: { pretty: true, output: 'console' }, //files: ['test/**/*.js'] files: ['test/test.js'] }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] }, doxx: { all: { src: 'lib', target: 'docs', options: { title: 'LineRate Node.js REST API module', template: 'doxx.jade' } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-doxx'); grunt.loadNpmTasks('grunt-tape'); grunt.registerTask('test', ['jshint', 'tape']); grunt.registerTask('default', ['jshint', 'tape', 'doxx']); };
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'lib/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, tape: { options: { pretty: true, output: 'console' }, //files: ['test/**/*.js'] files: ['test/test.js'] }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] }, doxx: { all: { src: 'lib', target: 'docs', options: { title: 'LineRate Node.js REST API module' } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-doxx'); grunt.loadNpmTasks('grunt-tape'); grunt.registerTask('test', ['jshint', 'tape']); grunt.registerTask('default', ['jshint', 'tape', 'doxx']); };
Reduce log level to avoid log polution
package org.pitest.cucumber; import org.pitest.junit.CompoundTestUnitFinder; import org.pitest.junit.JUnitCompatibleConfiguration; import org.pitest.testapi.TestGroupConfig; import org.pitest.testapi.TestUnitFinder; import org.pitest.util.Log; import java.util.List; import static java.util.Arrays.asList; public class CucumberJUnitCompatibleConfiguration extends JUnitCompatibleConfiguration { public CucumberJUnitCompatibleConfiguration(TestGroupConfig config) { super(config); } @Override public TestUnitFinder testUnitFinder() { final TestUnitFinder finder; if (isCucumberUsed()) { Log.getLogger().fine("Cucumber detected, scenarios will be used"); List<TestUnitFinder> finders = asList(new CucumberTestUnitFinder(), super.testUnitFinder()); finder = new CompoundTestUnitFinder(finders); } else { Log.getLogger().fine("Cucumber not used in this project"); finder = super.testUnitFinder(); } return finder; } private boolean isCucumberUsed() { boolean result = false; try { Class.forName("cucumber.api.junit.Cucumber"); result = true; } catch (ClassNotFoundException e) { } return result; } }
package org.pitest.cucumber; import org.pitest.junit.CompoundTestUnitFinder; import org.pitest.junit.JUnitCompatibleConfiguration; import org.pitest.testapi.TestGroupConfig; import org.pitest.testapi.TestUnitFinder; import org.pitest.util.Log; import java.util.List; import static java.util.Arrays.asList; public class CucumberJUnitCompatibleConfiguration extends JUnitCompatibleConfiguration { public CucumberJUnitCompatibleConfiguration(TestGroupConfig config) { super(config); } @Override public TestUnitFinder testUnitFinder() { final TestUnitFinder finder; if (isCucumberUsed()) { Log.getLogger().info("Cucumber detected, scenarios will be used"); List<TestUnitFinder> finders = asList(new CucumberTestUnitFinder(), super.testUnitFinder()); finder = new CompoundTestUnitFinder(finders); } else { Log.getLogger().info("Cucumber not used in this project"); finder = super.testUnitFinder(); } return finder; } private boolean isCucumberUsed() { boolean result = false; try { Class.forName("cucumber.api.junit.Cucumber"); result = true; } catch (ClassNotFoundException e) { } return result; } }
Set java_home correctly for each OS
module.exports = (function() { var path = require('path'); var ReadLine = require('readline'); var spawn = require('child_process').spawn; var events = require('events'); var os = require('os'); return { startNew: function() { var url; var hash; var eventEmitter = new events.EventEmitter(); var osName = os.type(); if (osName.startsWith('Windows')){ process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jre'); backend = spawn(path.resolve(__dirname + '/../dist/beaker.command.bat'), ['--open-browser', 'false']); } else if (osName.startsWith('Darwin')) { process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jre/Contents/Home'); backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']); } var rl = ReadLine.createInterface({ input: backend.stdout }); rl.on('line', function(line) { console.log(line); // Pipe backend's stdout to electron's stdout if (line.startsWith('Beaker hash')){ backend.hash = line.split(' ')[2]; } else if (line.startsWith('Beaker listening on')){ backend.url = line.split(' ')[3]; backend.local = true; eventEmitter.emit('ready', backend); } }); return eventEmitter; } } })();
module.exports = (function() { var path = require('path'); // var java_home = path.resolve(__dirname + '/../jre/Contents/Home'); // var java_home = path.resolve(__dirname + '/../jre'); var ReadLine = require('readline'); var spawn = require('child_process').spawn; var events = require('events'); var os = require('os'); return { startNew: function() { var url; var hash; var eventEmitter = new events.EventEmitter(); var osName = os.type(); if (osName.startsWith('Windows')){ backend = spawn(path.resolve(__dirname + '/../dist/beaker.command.bat'), ['--open-browser', 'false']); } else { backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']); } // process.env['JAVA_HOME'] = java_home; // backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']); var rl = ReadLine.createInterface({ input: backend.stdout }); rl.on('line', function(line) { console.log(line); // Pipe backend's stdout to electron's stdout if (line.startsWith('Beaker hash')){ backend.hash = line.split(' ')[2]; } else if (line.startsWith('Beaker listening on')){ backend.url = line.split(' ')[3]; backend.local = true; eventEmitter.emit('ready', backend); } }); return eventEmitter; } } })();
FIX BUILD: Unit test assumed polycom authid was first visible on page git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@7583 a612230a-c5fa-0310-af8b-88eea846685b
/* * * * Copyright (C) 2004 SIPfoundry Inc. * Licensed by SIPfoundry under the LGPL license. * * Copyright (C) 2004 Pingtel Corp. * Licensed to SIPfoundry under a Contributor Agreement. * * $ */ package org.sipfoundry.sipxconfig.site.phone.polycom; import junit.framework.Test; import net.sourceforge.jwebunit.WebTestCase; import org.sipfoundry.sipxconfig.site.SiteTestHelper; import org.sipfoundry.sipxconfig.site.phone.PhoneTestHelper; import org.w3c.dom.Element; public class PasswordSettingTestUi extends WebTestCase { private PhoneTestHelper m_helper; public static Test suite() throws Exception { return SiteTestHelper.webTestSuite(PasswordSettingTestUi.class); } protected void setUp() throws Exception { super.setUp(); getTestContext().setBaseUrl(SiteTestHelper.getBaseUrl()); m_helper = new PhoneTestHelper(tester); m_helper.reset(); } protected void tearDown() throws Exception { super.tearDown(); } public void testEditSipSetttings() { m_helper.seedLine(1); SiteTestHelper.setScriptingEnabled(true); clickLink("ManagePhones"); clickLinkWithText(SiteTestHelper.TEST_USER); clickLinkWithText("Registration"); clickLink("setting:toggle"); Element passwordField = getDialog().getElement("setting:auth.password"); assertEquals("password", passwordField.getAttribute("type")); } }
/* * * * Copyright (C) 2004 SIPfoundry Inc. * Licensed by SIPfoundry under the LGPL license. * * Copyright (C) 2004 Pingtel Corp. * Licensed to SIPfoundry under a Contributor Agreement. * * $ */ package org.sipfoundry.sipxconfig.site.phone.polycom; import junit.framework.Test; import net.sourceforge.jwebunit.WebTestCase; import org.sipfoundry.sipxconfig.site.SiteTestHelper; import org.sipfoundry.sipxconfig.site.phone.PhoneTestHelper; import org.w3c.dom.Element; public class PasswordSettingTestUi extends WebTestCase { private PhoneTestHelper m_helper; public static Test suite() throws Exception { return SiteTestHelper.webTestSuite(PasswordSettingTestUi.class); } protected void setUp() throws Exception { super.setUp(); getTestContext().setBaseUrl(SiteTestHelper.getBaseUrl()); m_helper = new PhoneTestHelper(tester); m_helper.reset(); } protected void tearDown() throws Exception { super.tearDown(); } public void testEditSipSetttings() { m_helper.seedLine(1); clickLink("ManagePhones"); clickLinkWithText(SiteTestHelper.TEST_USER); clickLinkWithText("Registration"); Element passwordField = getDialog().getElement("setting:auth.password"); assertEquals("password", passwordField.getAttribute("type")); } }
Update gulp dev task to no longer build scripts
var gulp = require('gulp'); var browserify = require('gulp-browserify'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); var uglify = require('gulp-uglify'); var size = require('gulp-size'); var rename = require('gulp-rename'); gulp.task('scripts', function() { gulp.src('index.js') .pipe(browserify()) .pipe(jshint()) .pipe(rename('grex.js')) .pipe(gulp.dest('./build')) .pipe(size({ showFiles: true })) // Minified version .pipe(uglify()) .pipe(rename('grex.min.js')) .pipe(gulp.dest('./build')) .pipe(size({ showFiles: true })); }); gulp.task('test', function() { require('should'); gulp.src('test/**/*') .pipe(mocha({ reporter: 'spec', })) .on('error', function(error) { console.error('\nError:', error.plugin); console.error(error.message); }); }); gulp.task('watch', function() { function onChange(event) { console.log('File', event.type +':', event.path); } gulp.watch('src/**/*', ['test']).on('change', onChange); gulp.watch('test/**/*', ['test']).on('change', onChange); }); gulp.task('default', ['dev']); gulp.task('dev', ['test', 'watch']); gulp.task('build', ['test', 'scripts']);
var gulp = require('gulp'); var browserify = require('gulp-browserify'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); var uglify = require('gulp-uglify'); var size = require('gulp-size'); var rename = require('gulp-rename'); gulp.task('scripts', function() { gulp.src('index.js') .pipe(browserify()) .pipe(jshint()) .pipe(rename('grex.js')) .pipe(gulp.dest('./build')) .pipe(size({ showFiles: true })) // Minified version .pipe(uglify()) .pipe(rename('grex.min.js')) .pipe(gulp.dest('./build')) .pipe(size({ showFiles: true })); }); gulp.task('test', function() { require('should'); gulp.src('test/**/*') .pipe(mocha({ reporter: 'spec', })) .on('error', function(error) { console.error('\nError:', error.plugin); console.error(error.message); }); }); gulp.task('watch', function() { function onChange(event) { console.log('File', event.type +':', event.path); } gulp.watch('src/**/*', ['test']).on('change', onChange); gulp.watch('test/**/*', ['test']).on('change', onChange); }); gulp.task('default', ['dev']); gulp.task('dev', ['build', 'test', 'watch']); gulp.task('build', ['test', 'scripts']);
Update migration to fetch domains with applications using old location fixture
import json from django.core.management.base import BaseCommand from toggle.models import Toggle from corehq.apps.locations.models import SQLLocation from corehq.apps.domain.models import Domain from corehq.toggles import HIERARCHICAL_LOCATION_FIXTURE, NAMESPACE_DOMAIN class Command(BaseCommand): help = """ To migrate to new flat fixture for locations. Enable FF HIERARCHICAL_LOCATION_FIXTURE for apps with locations and having commtrack:enabled in app files The Feature Flag FLAT_LOCATION_FIXTURE should be removed after this """ def handle(self, *args, **options): domains_having_locations = ( SQLLocation.objects.order_by('domain').distinct('domain') .values_list('domain', flat=True) ) domains_with_hierarchical_fixture = find_applications_with_hierarchical_fixture( domains_having_locations ) toggle = Toggle.get(HIERARCHICAL_LOCATION_FIXTURE.slug) for domain in domains_with_hierarchical_fixture: toggle.add(domain, True, NAMESPACE_DOMAIN) def find_applications_with_hierarchical_fixture(domains): search_string = 'commtrack:enabled' domain_with_application = {} for domain in domains: domain_obj = Domain.get_by_name(domain) for application in domain_obj.applications(): raw_doc = json.dumps(application.get_db().get(application.id)) if search_string in raw_doc: search_string[domain] = application.id continue return domain_with_application
from django.core.management.base import BaseCommand from toggle.models import Toggle from corehq.apps.locations.models import LocationFixtureConfiguration, SQLLocation from corehq.toggles import FLAT_LOCATION_FIXTURE class Command(BaseCommand): help = """ To migrate to new flat fixture for locations. Update apps with locations and not having FLAT_LOCATION_FIXTURE enabled to have LocationFixtureConfiguration with sync_hierarchical_fixture True and sync_flat_fixture False to have old fixtures enabled. The Feature Flag should be removed after this """ def handle(self, *args, **options): domains_having_locations = set(SQLLocation.objects.values_list('domain', flat=True)) toggle = Toggle.get(FLAT_LOCATION_FIXTURE.slug) enabled_users = toggle.enabled_users enabled_domains = [user.split('domain:')[1] for user in enabled_users] for domain_name in domains_having_locations: if domain_name not in enabled_domains: domain_config = LocationFixtureConfiguration.for_domain(domain_name) # update configs that had not been changed which means both values are at default True if domain_config.sync_hierarchical_fixture and domain_config.sync_flat_fixture: # update them to use hierarchical fixture domain_config.sync_flat_fixture = False domain_config.sync_hierarchical_fixture = True domain_config.save()
Add header to stats table.
import { ToastsComponent } from "../toasts/toasts.component.js"; export class StatsTemplate { static update(render, { symbol = "" } = {}) { if (!symbol) { render` <h2>Last Asset Stats</h2> No stats available for last asset. `; return; } workway("node://finance.js").then(async({ namespace: finance }) => { /* eslint-disable indent */ render` <h2>Last Asset Stats ${symbol}</h2> ${{ any: finance.getKeyStatistics({ symbol }).then(data => { const labels = Object.keys(data); const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-black-10 tr"; const trClasses = "pv1 pr1 bb b--black-20 tr"; return hyperHTML.wire()` <table class="f7 mw8 center pa2"> <thead> <th class="${headerClasses}">Label</th> <th class="${headerClasses}">Value</th> </thead> <tbody>${labels.map(label => { const value = data[label] && data[label].fmt; if (!value) { return hyperHTML.wire()`<tr></tr>`; } return hyperHTML.wire()`<tr> <td class="${trClasses}">${label}</td> <td class="${trClasses}">${value}</td> </tr>`; }) }</tbody> </table> `; }).catch(err => { ToastsComponent.update({ message: `${symbol} Stats ${err.message || err}` }); return "Fundamental data not available for the asset."; }), placeholder: "Loading..." }} `; /* eslint-enable indent */ }); } }
import { ToastsComponent } from "../toasts/toasts.component.js"; export class StatsTemplate { static update(render, { symbol = "" } = {}) { if (!symbol) { render` <h2>Last Asset Stats</h2> No stats available for last asset. `; return; } workway("node://finance.js").then(async({ namespace: finance }) => { /* eslint-disable indent */ render` <h2>Last Asset Stats ${symbol}</h2> ${{ any: finance.getKeyStatistics({ symbol }).then(data => { const labels = Object.keys(data); const trClasses = "pv1 pr1 bb b--black-20 tr"; return hyperHTML.wire()` <table class="f7 mw8 center pa2"> <tbody>${labels.map(label => { const value = data[label] && data[label].fmt; if (!value) { return hyperHTML.wire()`<tr></tr>`; } return hyperHTML.wire()`<tr> <td class="${trClasses}">${label}</td> <td class="${trClasses}">${value}</td> </tr>`; }) }</tbody> </table> `; }).catch(err => { ToastsComponent.update({ message: `${symbol} Stats ${err.message || err}` }); return "Fundamental data not available for the asset."; }), placeholder: "Loading..." }} `; /* eslint-enable indent */ }); } }
Make the initial shared secret less obnoxiously long
var bcrypt = require('bcrypt'); var crypto = require('crypto'); var passport = require('passport'); var request = require('request'); var SALT = process.env.SALT; var SIGNUP_URL = process.env.LANDLINE_API + '/teams'; module.exports = function(router) { router.get('/signup', function(req, res) { res.render('signup', { title: 'Landline | Signup' }); }); router.post('/signup', function(req, res) { if (!req.body.email || !req.body.password || !req.body.name || !req.body.url) { return res.render('signup', { title: 'Landline | Signup', error: 'All fields are required' }); } var password = req.body.password; req.body.name = req.body.name.toLowerCase(); req.body.password = bcrypt.hashSync(password, SALT); req.body.secret = crypto.randomBytes(24).toString('hex'); request.post({ url: SIGNUP_URL, json: true, body: req.body }, function(err, response) { if (err) { return res.render('signup', { title: 'Landline | Signup', error: err.message }); } req.session.teamName = req.body.name; req.session.jwt = response.body.token; passport.authenticate('local')(req, res, function () { res.redirect('/settings'); }); }); }); };
var bcrypt = require('bcrypt'); var crypto = require('crypto'); var passport = require('passport'); var request = require('request'); var SALT = process.env.SALT; var SIGNUP_URL = process.env.LANDLINE_API + '/teams'; module.exports = function(router) { router.get('/signup', function(req, res) { res.render('signup', { title: 'Landline | Signup' }); }); router.post('/signup', function(req, res) { if (!req.body.email || !req.body.password || !req.body.name || !req.body.url) { return res.render('signup', { title: 'Landline | Signup', error: 'All fields are required' }); } var password = req.body.password; req.body.name = req.body.name.toLowerCase(); req.body.password = bcrypt.hashSync(password, SALT); req.body.secret = crypto.randomBytes(48).toString('hex'); request.post({ url: SIGNUP_URL, json: true, body: req.body }, function(err, response) { if (err) { return res.render('signup', { title: 'Landline | Signup', error: err.message }); } req.session.teamName = req.body.name; req.session.jwt = response.body.token; passport.authenticate('local')(req, res, function () { res.redirect('/settings'); }); }); }); };
Revert "update Guam to not show at zoom 2" This reverts commit b12f1560f6b6284c9d26dab96a6c09eac1942424.
# -*- encoding: utf-8 -*- from . import FixtureTest class LowZoomPlacesTest(FixtureTest): def test_zoom_1(self): import dsl z, x, y = (3, 7, 3) self.generate_fixtures( dsl.way(607976629, dsl.tile_centre_shape(z, x, y), { "min_zoom": 1, "__ne_max_zoom": 10, "__ne_min_zoom": 3, "area": 0, "place": "country", "name": "Guam", "population": 185427, "source": "openstreetmap.org", }), ) # should exist at zoom 3 (the min zoom from NE) self.assert_has_feature( z, x, y, 'places', { 'id': 607976629, 'kind': 'country', 'name': 'Guam', }) # should exist at zoom 2 (one past the min zoom) self.assert_has_feature( z-1, x//2, y//2, 'places', { 'id': 607976629, 'kind': 'country', 'name': 'Guam', }) # should not exist at zoom 1 self.assert_no_matching_feature( z-2, x//4, y//4, 'places', { 'id': 607976629, })
# -*- encoding: utf-8 -*- from . import FixtureTest class LowZoomPlacesTest(FixtureTest): def test_zoom_1(self): import dsl z, x, y = (3, 7, 3) self.generate_fixtures( dsl.way(607976629, dsl.tile_centre_shape(z, x, y), { "min_zoom": 1, "__ne_max_zoom": 10, "__ne_min_zoom": 3, "area": 0, "place": "country", "name": "Guam", "population": 185427, "source": "openstreetmap.org", }), ) # should exist at zoom 3 (the min zoom from NE) self.assert_has_feature( z, x, y, 'places', { 'id': 607976629, 'kind': 'country', 'name': 'Guam', }) # should not exist at zoom 2 (one less than the min zoom) self.assert_no_matching_feature( z-1, x//2, y//2, 'places', { 'id': 607976629, }) # should not exist at zoom 1 self.assert_no_matching_feature( z-2, x//4, y//4, 'places', { 'id': 607976629, })
Fix style issues in python test plugin https://bugzilla.gnome.org/show_bug.cgi?id=678339
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: from gi.repository import GObject, Introspection, Peas class ExtensionPythonPlugin(GObject.Object, Peas.Activatable, Introspection.Base, Introspection.Callable, Introspection.PropertiesPrerequisite, Introspection.Properties, Introspection.HasPrerequisite): object = GObject.property(type=GObject.Object) construct_only = GObject.property(type=str) read_only = GObject.property(type=str, default="read-only") write_only = GObject.property(type=str) readwrite = GObject.property(type=str, default="readwrite") prerequisite = GObject.property(type=str) def do_activate(self): pass def do_deactivate(self): pass def do_update_state(self): pass def do_get_plugin_info(self): return self.plugin_info def do_get_settings(self): return self.plugin_info.get_settings(None) def do_call_with_return(self): return "Hello, World!" def do_call_no_args(self): pass def do_call_single_arg(self): return True def do_call_multi_args(self, in_, inout): return (inout, in_)
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: from gi.repository import GObject, Introspection, Peas class ExtensionPythonPlugin(GObject.Object, Peas.Activatable, Introspection.Base, Introspection.Callable, Introspection.PropertiesPrerequisite, Introspection.Properties, Introspection.HasPrerequisite): object = GObject.property(type=GObject.Object) construct_only = GObject.property(type=str) read_only = GObject.property(type=str, default="read-only") write_only = GObject.property(type=str) readwrite = GObject.property(type=str, default="readwrite") prerequisite = GObject.property(type=str) def do_activate(self): pass def do_deactivate(self): pass def do_update_state(self): pass def do_get_plugin_info(self): return self.plugin_info def do_get_settings(self): return self.plugin_info.get_settings(None) def do_call_with_return(self): return "Hello, World!"; def do_call_no_args(self): pass def do_call_single_arg(self): return True def do_call_multi_args(self, in_, inout): return (inout, in_)
Improve handling of not found interfaces
package com.telerik.metadata.parsing; import com.telerik.metadata.ClassRepo; import com.telerik.metadata.desc.ClassDescriptor; import com.telerik.metadata.desc.MethodDescriptor; import java.util.HashSet; import java.util.Set; public final class ClassParser { private final ClassDescriptor clazz; private ClassParser(ClassDescriptor clazz) { this.clazz = clazz; } public static ClassParser forClassDescriptor(ClassDescriptor clazz) { return new ClassParser(clazz); } public Set<MethodDescriptor> getAllDefaultMethodsFromImplementedInterfaces() { return getAllDefaultMethodsFromImplementedInterfacesRecursively(clazz, new HashSet<MethodDescriptor>()); } private HashSet<MethodDescriptor> getAllDefaultMethodsFromImplementedInterfacesRecursively(ClassDescriptor clazz, HashSet<MethodDescriptor> collectedDefaultMethods) { String[] implementedInterfacesNames = clazz.getInterfaceNames(); for (String implementedInterfaceName : implementedInterfacesNames) { ClassDescriptor interfaceClass = ClassRepo.findClass(implementedInterfaceName); if (interfaceClass == null) { System.out.println(String.format("WARNING: Skipping interface %s implemented in %s as it cannot be resolved", implementedInterfaceName, clazz.getClassName())); continue; } for (MethodDescriptor md : interfaceClass.getMethods()) { if (!md.isStatic() && !md.isAbstract()) { collectedDefaultMethods.add(md); } } collectedDefaultMethods.addAll(getAllDefaultMethodsFromImplementedInterfacesRecursively(interfaceClass, new HashSet<MethodDescriptor>())); } return collectedDefaultMethods; } }
package com.telerik.metadata.parsing; import com.telerik.metadata.ClassRepo; import com.telerik.metadata.desc.ClassDescriptor; import com.telerik.metadata.desc.MethodDescriptor; import java.util.HashSet; import java.util.Set; public final class ClassParser { private final ClassDescriptor clazz; private ClassParser(ClassDescriptor clazz) { this.clazz = clazz; } public static ClassParser forClassDescriptor(ClassDescriptor clazz) { return new ClassParser(clazz); } public Set<MethodDescriptor> getAllDefaultMethodsFromImplementedInterfaces() { return getAllDefaultMethodsFromImplementedInterfacesRecursively(clazz, new HashSet<MethodDescriptor>()); } private HashSet<MethodDescriptor> getAllDefaultMethodsFromImplementedInterfacesRecursively(ClassDescriptor clazz, HashSet<MethodDescriptor> collectedDefaultMethods) { String[] implementedInterfacesNames = clazz.getInterfaceNames(); for (String implementedInterfaceName : implementedInterfacesNames) { ClassDescriptor interfaceClass = ClassRepo.findClass(implementedInterfaceName); for (MethodDescriptor md : interfaceClass.getMethods()) { if (!md.isStatic() && !md.isAbstract()) { collectedDefaultMethods.add(md); } } collectedDefaultMethods.addAll(getAllDefaultMethodsFromImplementedInterfacesRecursively(interfaceClass, new HashSet<MethodDescriptor>())); } return collectedDefaultMethods; } }
Hide pinning controls when embedded js-ipfs is active - there's no pinning in js-ipfs yet - closes #380
'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') const navItem = require('./nav-item') module.exports = function contextActions ({ ipfsNodeType, isIpfsContext, isPinning, isUnPinning, isPinned, isIpfsOnline, onCopyIpfsAddr, onCopyPublicGwAddr, onPin, onUnPin }) { if (!isIpfsContext) return null const isPinningSupported = (ipfsNodeType !== 'embedded') return html` <div class="bb b--black-20 mv2 pb2"> ${navItem({ text: browser.i18n.getMessage('panelCopy_currentIpfsAddress'), onClick: onCopyIpfsAddr })} ${navItem({ text: browser.i18n.getMessage('panel_copyCurrentPublicGwUrl'), onClick: onCopyPublicGwAddr })} ${isIpfsOnline && isPinningSupported && !isPinned ? ( navItem({ text: browser.i18n.getMessage('panel_pinCurrentIpfsAddress'), disabled: isPinning, onClick: onPin }) ) : null} ${isIpfsOnline && isPinningSupported && isPinned ? ( navItem({ text: browser.i18n.getMessage('panel_unpinCurrentIpfsAddress'), disabled: isUnPinning, onClick: onUnPin }) ) : null} </div> ` }
'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') const navItem = require('./nav-item') module.exports = function contextActions ({ isIpfsContext, isPinning, isUnPinning, isPinned, isIpfsOnline, onCopyIpfsAddr, onCopyPublicGwAddr, onPin, onUnPin }) { if (!isIpfsContext) return null return html` <div class="bb b--black-20 mv2 pb2"> ${navItem({ text: browser.i18n.getMessage('panelCopy_currentIpfsAddress'), onClick: onCopyIpfsAddr })} ${navItem({ text: browser.i18n.getMessage('panel_copyCurrentPublicGwUrl'), onClick: onCopyPublicGwAddr })} ${isIpfsOnline && isPinned ? null : ( navItem({ text: browser.i18n.getMessage('panel_pinCurrentIpfsAddress'), disabled: isPinning, onClick: onPin }) )} ${isIpfsOnline && isPinned ? ( navItem({ text: browser.i18n.getMessage('panel_unpinCurrentIpfsAddress'), disabled: isUnPinning, onClick: onUnPin }) ) : null} </div> ` }
Allow using redis-py 2.7.4 (lowest revision with set keyword arguments).
# -*- encoding: utf8 -*- from setuptools import setup, find_packages import os setup( name = "python-redis-lock", version = "0.1.1", url = 'https://github.com/ionelmc/python-redis-lock', download_url = '', license = 'BSD', description = "Lock context manager implemented via redis SETNX/BLPOP.", long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), author = 'Ionel Cristian Mărieș', author_email = '[email protected]', packages = find_packages('src'), package_dir = {'':'src'}, include_package_data = True, zip_safe = False, classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Utilities', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], install_requires=[ 'redis>=2.7.4', ], extras_require={ 'django': [ 'django-redis>=3.3', ] } )
# -*- encoding: utf8 -*- from setuptools import setup, find_packages import os setup( name = "python-redis-lock", version = "0.1.1", url = 'https://github.com/ionelmc/python-redis-lock', download_url = '', license = 'BSD', description = "Lock context manager implemented via redis SETNX/BLPOP.", long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), author = 'Ionel Cristian Mărieș', author_email = '[email protected]', packages = find_packages('src'), package_dir = {'':'src'}, include_package_data = True, zip_safe = False, classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Utilities', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], install_requires=[ 'redis>=2.8.0', ], extras_require={ 'django': [ 'django-redis>=3.3', ] } )
Remove unreachable code. Use functools.wraps. - Remove code that was unreachable. Thanks Jaskirat (http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/#c24691) - Use functools.wraps to make the retry decorator "well behaved" - Fix typo
import time from functools import wraps def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of exceptions to check :type ExceptionToCheck: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: logger to use. If None, print :type logger: logging.Logger instance """ def deco_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 1: try: return f(*args, **kwargs) except ExceptionToCheck, e: msg = "%s, Retrying in %d seconds..." % (str(e), mdelay) if logger: logger.warning(msg) else: print msg time.sleep(mdelay) mtries -= 1 mdelay *= backoff return f(*args, **kwargs) return f_retry # true decorator return deco_retry
import time def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of excpetions to check :type ExceptionToCheck: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: logger to use. If None, print :type logger: logging.Logger instance """ def deco_retry(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay try_one_last_time = True while mtries > 1: try: return f(*args, **kwargs) try_one_last_time = False break except ExceptionToCheck, e: msg = "%s, Retrying in %d seconds..." % (str(e), mdelay) if logger: logger.warning(msg) else: print msg time.sleep(mdelay) mtries -= 1 mdelay *= backoff if try_one_last_time: return f(*args, **kwargs) return return f_retry # true decorator return deco_retry
Add missing alias for webpack-test
var path = require("path"); var tests = path.resolve(__dirname, "frontend/tests"); var js = path.resolve(__dirname, "frontend"); module.exports = { entry: { testsuite: path.resolve(tests, "testsuite.js") }, output: { path: path.resolve(tests, "dist"), filename: "[name].js" }, resolve: { extensions: ["*", ".js", ".vue"], alias: { jquery: "admin-lte/plugins/jQuery/jquery-2.2.3.min", vue: "vue/dist/vue", "vue-router": "vue-router/dist/vue-router", "user-resources": path.resolve(tests, "tests/user/mock_jsapi"), gamodule: path.resolve(js, "gamodule"), urlutils: path.resolve(js, "urlutils"), utils: path.resolve(js, "utils"), toolkit: path.resolve(js, "toolkit/toolkit"), helpers: path.resolve(tests, "helpers"), admin: path.resolve(js, "admin"), user: path.resolve(js, "user"), } }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader' } }, { test: /\.vue$/, use: { loader: 'vue-loader' } } ] } };
var path = require("path"); var tests = path.resolve(__dirname, "frontend/tests"); var js = path.resolve(__dirname, "frontend"); module.exports = { entry: { testsuite: path.resolve(tests, "testsuite.js") }, output: { path: path.resolve(tests, "dist"), filename: "[name].js" }, resolve: { extensions: ["*", ".js", ".vue"], alias: { vue: "vue/dist/vue", "vue-router": "vue-router/dist/vue-router", "user-resources": path.resolve(tests, "tests/user/mock_jsapi"), gamodule: path.resolve(js, "gamodule"), urlutils: path.resolve(js, "urlutils"), utils: path.resolve(js, "utils"), toolkit: path.resolve(js, "toolkit/toolkit"), helpers: path.resolve(tests, "helpers"), admin: path.resolve(js, "admin"), user: path.resolve(js, "user"), } }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader' } }, { test: /\.vue$/, use: { loader: 'vue-loader' } } ] } };
Handle the case when result is undefined
export default class RocExportPlugin { constructor(resolveRequest) { this.resolveRequest = resolveRequest; } apply(compiler) { // We assume that loaders will be managed in Webpack-land, that is we will not manage them in exports compiler.plugin('normal-module-factory', (normalModuleFactory) => { normalModuleFactory.plugin('before-resolve', (result, callback) => { // We do not want to process Webpack special paths if (!result || result.request.match(/(\?|!)/)) { return callback(null, result); } // Try to resolve the dependency against the roc dependency context result.request = this.resolveRequest(result.request, result.context); // eslint-disable-line // Test to see if we can resolve the dependency return compiler.resolvers.normal.resolve(result.context, result.request, (err) => { if (err) { // We got an error and will try again with fallback enabled result.request = this.resolveRequest(result.request, result.context, true); // eslint-disable-line return callback(null, result); } return callback(null, result); }); }); }); } }
export default class RocExportPlugin { constructor(resolveRequest) { this.resolveRequest = resolveRequest; } apply(compiler) { // We assume that loaders will be managed in Webpack-land, that is we will not manage them in exports compiler.plugin('normal-module-factory', (normalModuleFactory) => { normalModuleFactory.plugin('before-resolve', (result, callback) => { // We do not want to process Webpack special paths if (result.request.match(/(\?|!)/)) { return callback(null, result); } // Try to resolve the dependency against the roc dependency context result.request = this.resolveRequest(result.request, result.context); // eslint-disable-line // Test to see if we can resolve the dependency return compiler.resolvers.normal.resolve(result.context, result.request, (err) => { if (err) { // We got an error and will try again with fallback enabled result.request = this.resolveRequest(result.request, result.context, true); // eslint-disable-line return callback(null, result); } return callback(null, result); }); }); }); } }
Work with array of NSE values
import React, { Component } from 'react'; import request from 'ajax-request'; export default class StockComponent extends Component { constructor(props) { super(props); this.state = { stocks: [] } } componentDidMount() { //Not sure how we're going to pass the stock info here var nseArray = ["GOOG", "AAPL", "YHOO", "AMZN", "MSFT"]; for (var i = 0; i < nseArray.length; i++) { this.makeRequest(nseArray[i]); } } makeRequest(nse) { request({ url: `stock/${nse}`, method: 'GET', headers: { 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' } }, (error, response, body) => { const stockJson = JSON.parse(body); var stockObj = { lastPrice: stockJson.LastPrice, dayLow: stockJson.Low, dayHigh: stockJson.High, dayOpen: stockJson.Open, change: stockJson.Change }; this.setStockState(stockObj); }); } setStockState(stockObj) { var stocks = this.state.stocks; stocks.push(stockObj); this.setState({ stocks: stocks }); } render() { //Do what you need to make it look nice return ( <div> Current Price: {this.state.stocks[0].lastPrice} </div> ) } }
import React, { Component } from 'react'; import request from 'ajax-request'; export default class StockComponent extends Component { constructor(props) { super(props); this.state = { lastPrice: null, dayLow: null, dayHigh: null, dayOpen: null, change: null } } componentDidMount() { //Not sure how we're going to pass the stock info here var nse = "GOOG"; this.makeRequest(nse); } makeRequest(nse) { request({ url: `stock/${nse}`, method: 'GET', headers: { 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' } }, (error, response, body) => { const stockObj = JSON.parse(body); this.setStockState(stockObj); }); } setStockState(stockObj) { this.setState({ lastPrice:stockObj.LastPrice, dayLow:stockObj.Low, dayHigh:stockObj.High, dayOpen:stockObj.Open, change:stockObj.Change }); } render() { //Not sure relaly how to pass proper HTML into here return ( <div> Current Price: {this.state.lastPrice} {this.state.change} </div> ) } }
Fix assert for python 2.6 compatibility
from __future__ import unicode_literals from unittest import TestCase from wtforms import TextField, validators from wtforms.ext.i18n.utils import get_translations from wtforms.ext.i18n import form as i18n_form class I18NTest(TestCase): def test_failure(self): self.assertRaises(IOError, get_translations, []) def test_us_translation(self): translations = get_translations(['en_US']) self.assertEqual(translations.gettext('Invalid Mac address.'), 'Invalid MAC address.') class FormTest(TestCase): class F(i18n_form.Form): LANGUAGES = ['en_US', 'en'] a = TextField(validators=[validators.Required()]) def test_form(self): tcache = i18n_form.translations_cache tcache.clear() form = self.F() assert ('en_US', 'en') in tcache assert form._get_translations() is tcache[('en_US', 'en')] assert not form.validate() self.assertEqual(form.a.errors[0], 'This field is required.') form = self.F(LANGUAGES=['es']) assert len(tcache) == 2 assert ('es', ) in tcache assert not form.validate() self.assertEqual(form.a.errors[0], 'Este campo es obligatorio.') if __name__ == '__main__': from unittest import main main()
from __future__ import unicode_literals from unittest import TestCase from wtforms import TextField, validators from wtforms.ext.i18n.utils import get_translations from wtforms.ext.i18n import form as i18n_form class I18NTest(TestCase): def test_failure(self): self.assertRaises(IOError, get_translations, []) def test_us_translation(self): translations = get_translations(['en_US']) self.assertEqual(translations.gettext('Invalid Mac address.'), 'Invalid MAC address.') class FormTest(TestCase): class F(i18n_form.Form): LANGUAGES = ['en_US', 'en'] a = TextField(validators=[validators.Required()]) def test_form(self): tcache = i18n_form.translations_cache tcache.clear() form = self.F() assert ('en_US', 'en') in tcache self.assertIs(form._get_translations(), tcache[('en_US', 'en')]) assert not form.validate() self.assertEqual(form.a.errors[0], 'This field is required.') form = self.F(LANGUAGES=['es']) assert len(tcache) == 2 assert ('es', ) in tcache assert not form.validate() self.assertEqual(form.a.errors[0], 'Este campo es obligatorio.') if __name__ == '__main__': from unittest import main main()
Drop "useAllScheme" option (no implementation)
<?php namespace Mapbender\DigitizerBundle\Element\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class DigitizerAdminType extends AbstractType { public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'application' => null )); } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array( 'element_class' => 'Mapbender\CoreBundle\Element\Map', 'application' => $options['application'], 'required' => false, // dummy property path required for compatibility for TargetElementType // on Mapbender <=3.0.8.4 (no longer required on 3.0.8.5 RC and higher) 'property_path' => '[target]', )) ->add('displayOnInactive','checkbox',array('required' => false, 'label' => 'mb.digitizer.displayOnInactive')) ->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array( 'required' => false, 'attr' => array( 'class' => 'code-yaml', ), )) ; } }
<?php namespace Mapbender\DigitizerBundle\Element\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class DigitizerAdminType extends AbstractType { public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'application' => null )); } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array( 'element_class' => 'Mapbender\CoreBundle\Element\Map', 'application' => $options['application'], 'required' => false, // dummy property path required for compatibility for TargetElementType // on Mapbender <=3.0.8.4 (no longer required on 3.0.8.5 RC and higher) 'property_path' => '[target]', )) ->add('useAllScheme','checkbox',array('required' => false, 'label' => 'mb.digitizer.useAllScheme')) ->add('displayOnInactive','checkbox',array('required' => false, 'label' => 'mb.digitizer.displayOnInactive')) ->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array( 'required' => false, 'attr' => array( 'class' => 'code-yaml', ), )) ; } }
Correct container name to data
'use strict' var pubsubangular = angular.module('pubsub.angular', []); pubsubangular.factory('ps', function () { var ps = window.PubSub; if(!!ps===false){ throw new Error('Pubsub-js is a required dependency.'); } return ps; }); pubsubangular .directive('psSubscribe', function (ps) { return { template: '<div ng-transclude></div>', transclude: true, link: function postLink(scope, element, attrs) { var attr = (attrs.psSubscribe || "").split('|'); var context = { event: 'broadcast', data: 'data' }; if (attr.length == 1) { context.event = attr[0].trim(); } else if (attr.length == 2) { context.event = attr[0].trim(); context.data = attr[1].trim(); } ps.subscribe(context.event, function (label, d) { scope.label = label; scope[context.data] = d; scope.$digest(); }); } }; });
'use strict' var pubsubangular = angular.module('pubsub.angular', []); pubsubangular.factory('ps', function () { var ps = window.PubSub; if(!!ps===false){ throw new Error('Pubsub-js is a required dependency.'); } return ps; }); pubsubangular .directive('psSubscribe', function (ps) { return { template: '<div ng-transclude></div>', transclude: true, link: function postLink(scope, element, attrs) { var attr = (attrs.psSubscribe || "").split('|'); var context = { event: 'broadcast', data: 'data' }; if (attr.length == 1) { context.event = attr[0].trim(); } else if (attr.length == 2) { context.event = attr[0].trim(); context.container = attr[1].trim(); } ps.subscribe(context.event, function (label, d) { scope.label = label; scope[context.data] = d; scope.$digest(); }); } }; });
Simplify equals and hashCode given @NonNull
package mcjty.xnet.api.keys; import mcjty.lib.varia.BlockPosTools; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; public class SidedPos { private final BlockPos pos; private final EnumFacing side; /** * A position of a connected block and the side relative * from this block where the connection is. Basically * pos.offset(side) will be the consumer/connector */ public SidedPos(@Nonnull BlockPos pos, @Nonnull EnumFacing side) { this.pos = pos; this.side = side; } @Nonnull public BlockPos getPos() { return pos; } /** * Get the side relative to this position for the connector. */ @Nonnull public EnumFacing getSide() { return side; } @Override public String toString() { return "SidedPos{" + BlockPosTools.toString(pos) + "/" + side.getName() + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SidedPos sidedPos = (SidedPos) o; return side == sidedPos.side && pos.equals(sidedPos.pos); } @Override public int hashCode() { return 31 * pos.hashCode() + side.hashCode(); } }
package mcjty.xnet.api.keys; import mcjty.lib.varia.BlockPosTools; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; public class SidedPos { private final BlockPos pos; private final EnumFacing side; /** * A position of a connected block and the side relative * from this block where the connection is. Basically * pos.offset(side) will be the consumer/connector */ public SidedPos(@Nonnull BlockPos pos, @Nonnull EnumFacing side) { this.pos = pos; this.side = side; } @Nonnull public BlockPos getPos() { return pos; } /** * Get the side relative to this position for the connector. */ @Nonnull public EnumFacing getSide() { return side; } @Override public String toString() { return "SidedPos{" + BlockPosTools.toString(pos) + "/" + side.getName() + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SidedPos sidedPos = (SidedPos) o; if (pos != null ? !pos.equals(sidedPos.pos) : sidedPos.pos != null) return false; if (side != sidedPos.side) return false; return true; } @Override public int hashCode() { int result = pos != null ? pos.hashCode() : 0; result = 31 * result + (side != null ? side.hashCode() : 0); return result; } }
Fix attachments state update when thesis is saved
const reducer = (state = [], action) => { switch (action.type) { case 'AGREEMENT_GET_ALL_SUCCESS': // Attachments are attachments to agreement, so fetch them all. return action.response.attachments case 'THESIS_SAVE_ONE_SUCCESS': // Saving thesis response has multiple fields. // Whilst saving a new thesis there shouldn't exist any old attachments return [...state, ...action.response.attachments] case 'AGREEMENT_SAVE_ONE_SUCCESS': // TODO update attachments when agreement is saved return state case 'ATTACHMENT_DOWNLOAD_SUCCESS': { // TODO: refactor const blob = new Blob([action.response], { type: 'application/pdf' }) const url = URL.createObjectURL(blob) const show = true if (show) { // Display window.location.href = url } else { // Download const a = document.createElement('a') a.href = url a.download = 'theses.pdf' a.target = '_blank' document.body.appendChild(a) a.click() document.body.removeChild(a) } return state } case 'ATTACHMENT_SAVE_ONE_SUCCESS': return [...state, ...action.response] case 'ATTACHMENT_DELETE_ONE_SUCCESS': return state.filter(attachment => attachment.attachmentId !== action.response) default: return state } } export default reducer
const reducer = (state = [], action) => { switch (action.type) { case 'AGREEMENT_GET_ALL_SUCCESS': // Attachments are attachments to agreement, so fetch them all. return action.response.attachments case 'THESIS_SAVE_ONE_SUCCESS': // Saving thesis response has multiple fields. // Whilst saving a new thesis there shouldn't exist any old attachments return [...state, action.response.attachments] case 'AGREEMENT_SAVE_ONE_SUCCESS': // TODO update attachments when agreement is saved return state case 'ATTACHMENT_DOWNLOAD_SUCCESS': { // TODO: refactor const blob = new Blob([action.response], { type: 'application/pdf' }) const url = URL.createObjectURL(blob) const show = true if (show) { // Display window.location.href = url } else { // Download const a = document.createElement('a') a.href = url a.download = 'theses.pdf' a.target = '_blank' document.body.appendChild(a) a.click() document.body.removeChild(a) } return state } case 'ATTACHMENT_SAVE_ONE_SUCCESS': return [...state, ...action.response] case 'ATTACHMENT_DELETE_ONE_SUCCESS': return state.filter(attachment => attachment.attachmentId !== action.response) default: return state } } export default reducer
Allow code spans across newlines.
<?php namespace FluxBB\Markdown\Parser\Inline; use FluxBB\Markdown\Common\Text; use FluxBB\Markdown\Node\Code; use FluxBB\Markdown\Node\InlineNodeAcceptorInterface; use FluxBB\Markdown\Parser\AbstractInlineParser; class CodeSpanParser extends AbstractInlineParser { /** * Parse the given content. * * Any newly created nodes should be appended to the given target. Any remaining content should be passed to the * next parser in the chain. * * @param Text $content * @param InlineNodeAcceptorInterface $target * @return void */ public function parseInline(Text $content, InlineNodeAcceptorInterface $target) { if ($content->contains('`')) { $this->parseCodeSpan($content, $target); } else { $this->next->parseInline($content, $target); } } protected function parseCodeSpan(Text $content, InlineNodeAcceptorInterface $target) { $content->handle( '{ (`+) # $1 = Opening run of ` (.+?) # $2 = The code block (?<!`) \1 # Matching closer (?!`) }sx', function (Text $whole, Text $b, Text $code) use ($target) { $target->addInline(new Code($code->trim()->escapeHtml())); }, function (Text $part) use ($target) { $this->next->parseInline($part, $target); } ); } }
<?php namespace FluxBB\Markdown\Parser\Inline; use FluxBB\Markdown\Common\Text; use FluxBB\Markdown\Node\Code; use FluxBB\Markdown\Node\InlineNodeAcceptorInterface; use FluxBB\Markdown\Parser\AbstractInlineParser; class CodeSpanParser extends AbstractInlineParser { /** * Parse the given content. * * Any newly created nodes should be appended to the given target. Any remaining content should be passed to the * next parser in the chain. * * @param Text $content * @param InlineNodeAcceptorInterface $target * @return void */ public function parseInline(Text $content, InlineNodeAcceptorInterface $target) { if ($content->contains('`')) { $this->parseCodeSpan($content, $target); } else { $this->next->parseInline($content, $target); } } protected function parseCodeSpan(Text $content, InlineNodeAcceptorInterface $target) { $content->handle( '{ (`+) # $1 = Opening run of ` (.+?) # $2 = The code block (?<!`) \1 # Matching closer (?!`) }x', function (Text $whole, Text $b, Text $code) use ($target) { $target->addInline(new Code($code->trim()->escapeHtml())); }, function (Text $part) use ($target) { $this->next->parseInline($part, $target); } ); } }
Add form validator for icon_emoji
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms __all__ = ['LabelForm', 'LabelOptionForm'] class LabelForm(forms.Form): name = forms.StringField( "", widget=forms.HiddenInput(), validators=[forms.validators.Optional()] ) title = forms.StringField( __("Label"), validators=[ forms.validators.DataRequired(__(u"This can’t be empty")), forms.validators.Length(max=250), ], filters=[forms.filters.strip()], ) icon_emoji = forms.StringField( "", validators=[forms.validators.IsEmoji()] ) required = forms.BooleanField( __("Make this label mandatory in proposal forms"), default=False, description=__("If checked, proposers must select one of the options"), ) restricted = forms.BooleanField( __("Restrict use of this label to editors"), default=False, description=__( "If checked, only editors and reviewers can apply this label on proposals" ), ) class LabelOptionForm(forms.Form): name = forms.StringField( "", widget=forms.HiddenInput(), validators=[forms.validators.Optional()] ) title = forms.StringField( __("Option"), validators=[ forms.validators.DataRequired(__(u"This can’t be empty")), forms.validators.Length(max=250), ], filters=[forms.filters.strip()], ) icon_emoji = forms.StringField( "", validators=[forms.validators.IsEmoji()] ) seq = forms.IntegerField("", widget=forms.HiddenInput())
# -*- coding: utf-8 -*- from baseframe import __ import baseframe.forms as forms __all__ = ['LabelForm', 'LabelOptionForm'] class LabelForm(forms.Form): name = forms.StringField( "", widget=forms.HiddenInput(), validators=[forms.validators.Optional()] ) title = forms.StringField( __("Label"), validators=[ forms.validators.DataRequired(__(u"This can’t be empty")), forms.validators.Length(max=250), ], filters=[forms.filters.strip()], ) icon_emoji = forms.StringField("") required = forms.BooleanField( __("Make this label mandatory in proposal forms"), default=False, description=__("If checked, proposers must select one of the options"), ) restricted = forms.BooleanField( __("Restrict use of this label to editors"), default=False, description=__( "If checked, only editors and reviewers can apply this label on proposals" ), ) class LabelOptionForm(forms.Form): name = forms.StringField( "", widget=forms.HiddenInput(), validators=[forms.validators.Optional()] ) title = forms.StringField( __("Option"), validators=[ forms.validators.DataRequired(__(u"This can’t be empty")), forms.validators.Length(max=250), ], filters=[forms.filters.strip()], ) icon_emoji = forms.StringField("") seq = forms.IntegerField("", widget=forms.HiddenInput())
Join threads or else the number of running threads increments by 5 at each request and will never stop until main process is killed
from multiprocessing.pool import ThreadPool from django.shortcuts import render from .forms import SearchForm from source import view_models def index(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): title = request.GET.__getitem__('movie_title').__str__() pool = ThreadPool(processes=5) async_rt_rating = pool.apply_async(view_models.get_rt_rating, (title,)) async_bluray_rating = pool.apply_async(view_models.get_bluray_rating, (title,)) async_tech_specs = pool.apply_async(view_models.get_tech_spec, (title,)) async_price = pool.apply_async(view_models.get_price, (title,)) async_artwork = pool.apply_async(view_models.get_artwork, (title,)) pool.close() rt_rating = async_rt_rating.get() bluray_rating = async_bluray_rating.get() tech_specs = async_tech_specs.get() price = async_price.get() artwork = async_artwork.get() pool.join() return render(request, 'index.html', {'form': form, 'rt_rating': rt_rating, 'bluray_rating': bluray_rating, 'tech_specs': tech_specs, 'price': price, 'artwork': artwork}) else: form = SearchForm() return render(request, 'index.html', {'form': form})
from multiprocessing.pool import ThreadPool from django.shortcuts import render from .forms import SearchForm from source import view_models def index(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): title = request.GET.__getitem__('movie_title').__str__() pool = ThreadPool(processes=5) async_rt_rating = pool.apply_async(view_models.get_rt_rating, (title,)) async_bluray_rating = pool.apply_async(view_models.get_bluray_rating, (title,)) async_tech_specs = pool.apply_async(view_models.get_tech_spec, (title,)) async_price = pool.apply_async(view_models.get_price, (title,)) async_artwork = pool.apply_async(view_models.get_artwork, (title,)) rt_rating = async_rt_rating.get() bluray_rating = async_bluray_rating.get() tech_specs = async_tech_specs.get() price = async_price.get() artwork = async_artwork.get() return render(request, 'index.html', {'form': form, 'rt_rating': rt_rating, 'bluray_rating': bluray_rating, 'tech_specs': tech_specs, 'price': price, 'artwork': artwork}) else: form = SearchForm() return render(request, 'index.html', {'form': form})
Add support for arguments in request() in tests
import os import tempfile from flask import json import tsserver # If set to True, each time the test is run, new database is created as a # temporary file. If the value is equal to False, tests will be using SQLite # in-memory database. USE_DB_TEMP_FILE = False def before_scenario(context, scenario): if USE_DB_TEMP_FILE: context.db_fd, context.db_url = tempfile.mkstemp() db_url = 'sqlite:///' + context.db_url else: db_url = 'sqlite://' tsserver.app.config['SQLALCHEMY_DATABASE_URI'] = db_url # Ensure the tests are actually run in temporary database assert str(tsserver.db.engine.url) == db_url tsserver.app.config['TESTING'] = True tsserver.db.create_all() context.app = tsserver.app.test_client() def request(url, method='GET', *args, **kwargs): """ Wrapper over Flask.open function that parses returned data as JSON :param method: HTTP method to be used. GET is used by default :param url: URL to retrieve :return: Response object """ rv = context.app.open(url, method=method, *args, **kwargs) rv.json_data = json.loads(rv.data) return rv context.request = request def after_scenario(context, scenario): if USE_DB_TEMP_FILE: os.close(context.db_fd) os.unlink(context.db_url)
import os import tempfile from flask import json import tsserver # If set to True, each time the test is run, new database is created as a # temporary file. If the value is equal to False, tests will be using SQLite # in-memory database. USE_DB_TEMP_FILE = False def before_scenario(context, scenario): if USE_DB_TEMP_FILE: context.db_fd, context.db_url = tempfile.mkstemp() db_url = 'sqlite:///' + context.db_url else: db_url = 'sqlite://' tsserver.app.config['SQLALCHEMY_DATABASE_URI'] = db_url # Ensure the tests are actually run in temporary database assert str(tsserver.db.engine.url) == db_url tsserver.app.config['TESTING'] = True tsserver.db.create_all() context.app = tsserver.app.test_client() def request(url, method='GET'): """ Wrapper over Flask.open function that parses returned data as JSON :param method: HTTP method to be used. GET is used by default :param url: URL to retrieve :return: Response object """ rv = context.app.open(url, method=method) rv.json_data = json.loads(rv.data) return rv context.request = request def after_scenario(context, scenario): if USE_DB_TEMP_FILE: os.close(context.db_fd) os.unlink(context.db_url)
Add a proper exception type for failed conversion
package icepick.annotation; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; class IcicleField { public final String name; public final String typeCast; public final String command; IcicleField(String name, String typeCast, String command) { this.name = name; this.command = command; this.typeCast = typeCast; } static class Factory { private final Types typeUtils; private final IcicleConversionMap conversionMap; Factory(Elements elementUtils, Types typeUtils) { this.typeUtils = typeUtils; this.conversionMap = new IcicleConversionMap(elementUtils, typeUtils); } public IcicleField from(Element element) { TypeMirror typeMirror = element.asType(); String command = convert(typeMirror); String typeCast = IcicleConversionMap.TYPE_CAST_COMMANDS.contains(command) ? "(" + typeMirror.toString() + ")" : ""; String name = element.getSimpleName().toString(); return new IcicleField(name, typeCast, command); } private String convert(TypeMirror typeMirror) { for (TypeMirror other : conversionMap.keySet()) { if (typeUtils.isAssignable(typeMirror, other)) { return conversionMap.get(other); } } throw new UnableToSerializeException(typeMirror); } } public static class UnableToSerializeException extends RuntimeException { UnableToSerializeException(TypeMirror fieldType) { super("Don't know how to put a " + fieldType + " into a Bundle"); } } }
package icepick.annotation; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; class IcicleField { public final String name; public final String typeCast; public final String command; IcicleField(String name, String typeCast, String command) { this.name = name; this.command = command; this.typeCast = typeCast; } static class Factory { private final Types typeUtils; private final IcicleConversionMap conversionMap; Factory(Elements elementUtils, Types typeUtils) { this.typeUtils = typeUtils; this.conversionMap = new IcicleConversionMap(elementUtils, typeUtils); } public IcicleField from(Element element) { TypeMirror typeMirror = element.asType(); String command = convert(typeMirror); String typeCast = IcicleConversionMap.TYPE_CAST_COMMANDS.contains(command) ? "(" + typeMirror.toString() + ")" : ""; String name = element.getSimpleName().toString(); return new IcicleField(name, typeCast, command); } public String convert(TypeMirror typeMirror) { for (TypeMirror other : conversionMap.keySet()) { if (typeUtils.isAssignable(typeMirror, other)) { return conversionMap.get(other); } } throw new AssertionError("Cannot insert a " + typeMirror + " into a Bundle"); } } }
Add some links for STS
// -------------------------------------------------------------------------------------------------------------------- // // sts-config.js - config for AWS Security Token Service // // Copyright (c) 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <[email protected]> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- // From: http://docs.amazonwebservices.com/STS/latest/APIReference/API_Operations.html // // * http://docs.amazonwebservices.com/STS/latest/APIReference/API_GetFederationToken.html // * http://docs.amazonwebservices.com/STS/latest/APIReference/API_GetSessionToken.html module.exports = { GetFederationToken : { defaults : { Action : 'GetFederationToken', }, args : { Action : { required : true, type : 'param', }, DurationSeconds : { required : false, type : 'param', }, Name : { required : true, type : 'param', }, Policy : { required : false, type : 'param', }, }, }, GetSessionToken : { defaults : { Action : 'GetSessionToken', }, args : { Action : { required : true, type : 'param', }, DurationSeconds : { required : false, type : 'param', }, }, }, }; // --------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------- // // sts-config.js - config for AWS Security Token Service // // Copyright (c) 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <[email protected]> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- module.exports = { GetSessionToken : { defaults : { Action : 'GetSessionToken', }, args : { Action : { required : true, type : 'param', }, DurationSeconds : { required : false, type : 'param', }, }, }, GetFederationToken : { defaults : { Action : 'GetFederationToken', }, args : { Action : { required : true, type : 'param', }, DurationSeconds : { required : false, type : 'param', }, Name : { required : true, type : 'param', }, Policy : { required : false, type : 'param', }, }, }, }; // --------------------------------------------------------------------------------------------------------------------
Allow set loadItems and onBeforeRequest with component props
import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import collectListInitialState from './collectListInitialState'; import * as actions from './actions'; export default function reduxFilterlist(ReduxFilterlistWrapper, { listId, ...decoratorParams }) { if (!listId) { throw new Error('listId is required'); } return (WrappedComponent) => { const mapStateToProps = ({ reduxFilterlist: { [listId]: listState, }, }, componentProps) => { const reduxFilterlistParams = { ...decoratorParams, ...componentProps, }; const { loadItems, onBeforeRequest, } = reduxFilterlistParams; if (!loadItems) { throw new Error('loadItems is required'); } if (typeof loadItems !== 'function') { throw new Error('loadItems should be a function'); } if (typeof onBeforeRequest !== 'undefined' && typeof onBeforeRequest !== 'function') { throw new Error('onBeforeRequest should be a function'); } return { listState: listState || collectListInitialState(reduxFilterlistParams), componentProps, listId, loadItems, onBeforeRequest, reduxFilterlistParams, WrappedComponent, }; }; const mapDispatchToProps = dispatch => ({ listActions: bindActionCreators(actions, dispatch), }); return connect(mapStateToProps, mapDispatchToProps)(ReduxFilterlistWrapper); }; }
import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import collectListInitialState from './collectListInitialState'; import * as actions from './actions'; export default function reduxFilterlist(ReduxFilterlistWrapper, { listId, loadItems, onBeforeRequest, ...decoratorParams }) { if (!listId) { throw new Error('listId is required'); } if (!loadItems) { throw new Error('loadItems is required'); } if (typeof loadItems !== 'function') { throw new Error('loadItems should be a function'); } if (typeof onBeforeRequest !== 'undefined' && typeof onBeforeRequest !== 'function') { throw new Error('onBeforeRequest should be a function'); } return (WrappedComponent) => { const mapStateToProps = ({ reduxFilterlist: { [listId]: listState, }, }, componentProps) => { const reduxFilterlistParams = { ...decoratorParams, ...componentProps, }; return { listState: listState || collectListInitialState(reduxFilterlistParams), componentProps, listId, loadItems, onBeforeRequest, reduxFilterlistParams, WrappedComponent, }; }; const mapDispatchToProps = dispatch => ({ listActions: bindActionCreators(actions, dispatch), }); return connect(mapStateToProps, mapDispatchToProps)(ReduxFilterlistWrapper); }; }
Remove checking of null in compareTo method
package org.zanata.webtrans.shared.model; import java.io.Serializable; import com.google.gwt.user.client.rpc.IsSerializable; //@Immutable public class DocumentId implements Identifier<Long>, Comparable, IsSerializable, Serializable { private static final long serialVersionUID = 1L; private Long id; private String docId; // for GWT @SuppressWarnings("unused") private DocumentId() { } public DocumentId(Long id, String docId) { this.id = id; this.docId = docId; } @Override public String toString() { return String.valueOf(id); } @Override public int hashCode() { return id.intValue(); } @Override public Long getValue() { return id; } public Long getId() { return id; } public String getDocId() { return docId; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } return obj instanceof DocumentId && ((DocumentId) obj).id.equals(id); } @Override public int compareTo(Object o) { DocumentId compareTo = (DocumentId) o; return this.getDocId().compareTo(compareTo.getDocId()); } }
package org.zanata.webtrans.shared.model; import java.io.Serializable; import com.google.gwt.user.client.rpc.IsSerializable; //@Immutable public class DocumentId implements Identifier<Long>, Comparable, IsSerializable, Serializable { private static final long serialVersionUID = 1L; private Long id; private String docId; // for GWT @SuppressWarnings("unused") private DocumentId() { } public DocumentId(Long id, String docId) { this.id = id; this.docId = docId; } @Override public String toString() { return String.valueOf(id); } @Override public int hashCode() { return id.intValue(); } @Override public Long getValue() { return id; } public Long getId() { return id; } public String getDocId() { return docId; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } return obj instanceof DocumentId && ((DocumentId) obj).id.equals(id); } @Override public int compareTo(Object o) { if (o == this) { return 0; } if (o == null) { return -1; } DocumentId compareTo = (DocumentId) o; return this.getDocId().compareTo(compareTo.getDocId()); } }
Fix a bug in load_tags function
import os import json from dtags.utils import halt, expand_path TAGS = os.path.expanduser('~/.dtags') def load_tags(): """Load the tags from disk.""" if not os.path.exists(TAGS): try: with open(TAGS, "w") as config_file: json.dump({}, config_file) except (IOError, OSError) as e: halt("Failed to init {}: {}".format(TAGS, e.strerror), e.errno) else: try: with open(TAGS, "r") as config_file: json_str = config_file.read().strip() if not json_str: return {} tag_data = json.loads(json_str) if not tag_data: return {} return { tag: {expand_path(path): path for path in paths} for tag, paths in tag_data.items() } except ValueError as e: halt("Failed to load {}: {}".format(TAGS, e)) except (IOError, OSError) as e: halt("Failed to load {}: {}".format(TAGS, e.strerror), e.errno) def save_tags(tags): """Save the tags to disk. :param tags: tags to save """ try: with open(TAGS, "w") as config_file: json.dump( {tag: sorted(paths.values()) for tag, paths in tags.items()}, config_file, indent=4, sort_keys=True ) except IOError as e: halt("Failed to save {}: {}".format(TAGS, e.strerror))
import os import json from dtags.utils import halt, expand_path TAGS = os.path.expanduser('~/.dtags') def load_tags(): """Load the tags from disk.""" if not os.path.exists(TAGS): try: with open(TAGS, "w") as config_file: json.dump({}, config_file) except (IOError, OSError) as e: halt("Failed to init {}: {}".format(TAGS, e.strerror), e.errno) else: try: with open(TAGS, "r") as config_file: json_str = config_file.read().strip() tag_data = {} if not json_str else json.loads(json_str) return { tag: {expand_path(path): path for path in paths} for tag, paths in tag_data.items() } except ValueError as e: halt("Failed to load {}: {}".format(TAGS, e)) except (IOError, OSError) as e: halt("Failed to load {}: {}".format(TAGS, e.strerror), e.errno) def save_tags(tags): """Save the tags to disk. :param tags: tags to save """ try: with open(TAGS, "w") as config_file: json.dump( {tag: sorted(paths.values()) for tag, paths in tags.items()}, config_file, indent=4, sort_keys=True ) except IOError as e: halt("Failed to save {}: {}".format(TAGS, e.strerror))
Return proper reponse in JSON layer
<?php namespace Aztech\Layers\Elements; use Aztech\Layers\Responses\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpException; class JsonRenderingLayer { private $callable; public function __construct(callable $callable) { $this->callable = $callable; } public function __invoke(Request $request = null) { if (! $request) { $request = Request::createFromGlobals(); } $callable = $this->callable; try { $response = $callable($request); } catch (HttpException $exception) { return (new JsonResponse([ 'success' => false, 'message' => $exception->getMessage() ], $exception->getStatusCode()))->getResponse(); } if ($response instanceof Response) { return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse(); } if (! $response) { $response = []; } return (new JsonResponse($response, 200))->getResponse(); } }
<?php namespace Aztech\Layers\Elements; use Aztech\Layers\Responses\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpException; class JsonRenderingLayer { private $callable; public function __construct(callable $callable) { $this->callable = $callable; } public function __invoke(Request $request = null) { if (! $request) { $request = Request::createFromGlobals(); } $callable = $this->callable; try { $response = $callable($request); } catch (HttpException $exception) { $response = new JsonResponse([ 'success' => false, 'message' => $exception->getMessage() ], $exception->getStatusCode()); } if ($response instanceof Response) { return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse(); } if (! $response) { $response = []; } return (new JsonResponse($response, 200))->getResponse(); } }
Revert "revert data and layout role to be object" This reverts commit 655508a7309da2bd89265c1ab469bae7034a56a4.
/** * Copyright 2012-2021, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = { _isLinkedToArray: 'frames_entry', group: { valType: 'string', description: [ 'An identifier that specifies the group to which the frame belongs,', 'used by animate to select a subset of frames.' ].join(' ') }, name: { valType: 'string', description: 'A label by which to identify the frame' }, traces: { valType: 'any', description: [ 'A list of trace indices that identify the respective traces in the', 'data attribute' ].join(' ') }, baseframe: { valType: 'string', description: [ 'The name of the frame into which this frame\'s properties are merged', 'before applying. This is used to unify properties and avoid needing', 'to specify the same values for the same properties in multiple frames.' ].join(' ') }, data: { valType: 'any', description: [ 'A list of traces this frame modifies. The format is identical to the', 'normal trace definition.' ].join(' ') }, layout: { valType: 'any', description: [ 'Layout properties which this frame modifies. The format is identical', 'to the normal layout definition.' ].join(' ') } };
/** * Copyright 2012-2021, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = { _isLinkedToArray: 'frames_entry', group: { valType: 'string', description: [ 'An identifier that specifies the group to which the frame belongs,', 'used by animate to select a subset of frames.' ].join(' ') }, name: { valType: 'string', description: 'A label by which to identify the frame' }, traces: { valType: 'any', description: [ 'A list of trace indices that identify the respective traces in the', 'data attribute' ].join(' ') }, baseframe: { valType: 'string', description: [ 'The name of the frame into which this frame\'s properties are merged', 'before applying. This is used to unify properties and avoid needing', 'to specify the same values for the same properties in multiple frames.' ].join(' ') }, data: { valType: 'any', role: 'object', description: [ 'A list of traces this frame modifies. The format is identical to the', 'normal trace definition.' ].join(' ') }, layout: { valType: 'any', role: 'object', description: [ 'Layout properties which this frame modifies. The format is identical', 'to the normal layout definition.' ].join(' ') } };
Fix to the mapper related entities when null
<?php namespace FS\SolrBundle\Doctrine\Mapper\Mapping; use FS\SolrBundle\Doctrine\Annotation\Field; use FS\SolrBundle\Doctrine\Mapper\MetaInformationInterface; use Doctrine\Common\Collections\Collection; /** * command maps all fields of the entity * * uses parent method for mapping of document_name and id */ class MapAllFieldsCommand extends AbstractDocumentCommand { /** * @param MetaInformationInterface $meta * * @return null|\Solarium\QueryType\Update\Query\Document\Document */ public function createDocument(MetaInformationInterface $meta) { $fields = $meta->getFields(); if (count($fields) == 0) { return null; } $document = parent::createDocument($meta); foreach ($fields as $field) { if (!$field instanceof Field) { continue; } $value = $field->getValue(); $getter = $field->getGetterName(); if (!empty($getter)) { if ($value instanceof Collection) { $values = array(); foreach ($value as $relatedObj) { $values[] = $relatedObj->{$getter}(); } $document->addField($field->getNameWithAlias(), $values, $field->getBoost()); } elseif (is_object($value) && method_exists($value, $getter)) { $document->addField($field->getNameWithAlias(), $value->{$getter}(), $field->getBoost()); } } else { $document->addField($field->getNameWithAlias(), $field->getValue(), $field->getBoost()); } } return $document; } }
<?php namespace FS\SolrBundle\Doctrine\Mapper\Mapping; use FS\SolrBundle\Doctrine\Annotation\Field; use FS\SolrBundle\Doctrine\Mapper\MetaInformationInterface; use Doctrine\Common\Collections\Collection; /** * command maps all fields of the entity * * uses parent method for mapping of document_name and id */ class MapAllFieldsCommand extends AbstractDocumentCommand { /** * @param MetaInformationInterface $meta * * @return null|\Solarium\QueryType\Update\Query\Document\Document */ public function createDocument(MetaInformationInterface $meta) { $fields = $meta->getFields(); if (count($fields) == 0) { return null; } $document = parent::createDocument($meta); foreach ($fields as $field) { if (!$field instanceof Field) { continue; } $value = $field->getValue(); $getter = $field->getGetterName(); if (!empty($getter)) { if ($value instanceof Collection) { $values = array(); foreach ($value as $relatedObj) { $values[] = $relatedObj->{$getter}(); } $document->addField($field->getNameWithAlias(), $values, $field->getBoost()); } else { $document->addField($field->getNameWithAlias(), $value->{$getter}(), $field->getBoost()); } } else { $document->addField($field->getNameWithAlias(), $field->getValue(), $field->getBoost()); } } return $document; } }
Set the timezone right after it gets activated.
from django.conf import settings from django.utils import timezone from pytz import UnknownTimeZoneError from .models import TimezoneStore class TimezonesMiddleware(object): def process_request(self, request): """ Attempts to activate a timezone from a cookie or session """ if getattr(settings, 'USE_TZ'): # check the cookie and the session tz = request.COOKIES.get('timezone') session_tz = request.session.get('timezone') tz = tz or session_tz if tz: try: # attempt to activate the timezone. This might be an invalid # timezone or none, so the rest of the logic following is coniditional # on getting a valid timezone timezone.activate(tz) # caching the timezone inside the user instance request.user._timezone = tz_store # check to see if the session needs to be updated if request.user.is_authenticated() and session_tz != tz: request.session['timezone'] = tz request.session.save() # the session had to change, lets update the users database entry # to be safe tz_store, created = TimezoneStore.objects.get_or_create(user = request.user) tz_store.timezone = tz tz_store.save() except UnknownTimeZoneError: pass else: timezone.deactivate()
from django.conf import settings from django.utils import timezone from pytz import UnknownTimeZoneError from .models import TimezoneStore class TimezonesMiddleware(object): def process_request(self, request): """ Attempts to activate a timezone from a cookie or session """ if getattr(settings, 'USE_TZ'): # check the cookie and the session tz = request.COOKIES.get('timezone') session_tz = request.session.get('timezone') tz = tz or session_tz if tz: try: # attempt to activate the timezone. This might be an invalid # timezone or none, so the rest of the logic following is coniditional # on getting a valid timezone timezone.activate(tz) # check to see if the session needs to be updated if request.user.is_authenticated() and session_tz != tz: request.session['timezone'] = tz request.session.save() # the session had to change, lets update the users database entry # to be safe tz_store, created = TimezoneStore.objects.get_or_create(user = request.user) tz_store.timezone = tz tz_store.save() request.user._timezone = tz_store except UnknownTimeZoneError: pass else: timezone.deactivate()
Allow spaces in path for project create
var ProjectList, Project = require("../models/project"), server = require("../server"), storage = require("../storage"); ProjectList = Backbone.Collection.extend({ model: Project, initialize: function () { var collection = this, projects = storage.readProjects(), projectId; for (projectId in projects) { if (projects.hasOwnProperty(projectId)) { this.create(projects[projectId]); } } }, sync: function (method, model, options) { }, deleteProjectModel: function (modelCid) { // Remove from collection and destroy model var modelToDelete = this.get(modelCid); this.remove(modelToDelete); modelToDelete.sync("delete", modelToDelete); }, createProjectOnDisk: function (values, callback) { var collection = this; server.create({ args: [ "\"" + values.location + "\"", values.name ].join(" ") }, function (response) { var model = collection.create(values); callback(response, model); }); }, deleteProjectFromDisk: function (modelCid, callback) { var collection = this, model = this.get(modelCid); server.delete({ projectPath: model.get("location") }, function (response) { collection.deleteProjectModel(modelCid); callback(response); }); }, getDefaultProjectPath: function (callback) { server.defaultProjectPath({}, function (response) { callback(response); }); } }); module.exports = ProjectList;
var ProjectList, Project = require("../models/project"), server = require("../server"), storage = require("../storage"); ProjectList = Backbone.Collection.extend({ model: Project, initialize: function () { var collection = this, projects = storage.readProjects(), projectId; for (projectId in projects) { if (projects.hasOwnProperty(projectId)) { this.create(projects[projectId]); } } }, sync: function (method, model, options) { }, deleteProjectModel: function (modelCid) { // Remove from collection and destroy model var modelToDelete = this.get(modelCid); this.remove(modelToDelete); modelToDelete.sync("delete", modelToDelete); }, createProjectOnDisk: function (values, callback) { var collection = this; server.create({ args: [ values.location, values.name ].join(" ") }, function (response) { var model = collection.create(values); callback(response, model); }); }, deleteProjectFromDisk: function (modelCid, callback) { var collection = this, model = this.get(modelCid); server.delete({ projectPath: model.get("location") }, function (response) { collection.deleteProjectModel(modelCid); callback(response); }); }, getDefaultProjectPath: function (callback) { server.defaultProjectPath({}, function (response) { callback(response); }); } }); module.exports = ProjectList;
Fix object class assertion bug
<?php /** * This file is part of the Axstrad library. * * (c) Dan Kempster <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Dan Kempster <[email protected]> * @package Axstrad\DoctineExtensions */ namespace Axstrad\DoctrineExtensions\Activatable; use Doctrine\Common\EventArgs; use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs; use Gedmo\Mapping\MappedEventSubscriber; use Axstrad\DoctrineExtensions\Exception\InvalidArgumentException; /** * Axstrad\DoctrineExtensions\Activatable\ActivatableListener */ class ActivatableListener extends MappedEventSubscriber { /** */ public function getSubscribedEvents() { return array( 'loadClassMetadata', ); } /** * Mapps additional metadata * * @param EventArgs $eventArgs * @return void */ public function loadClassMetadata(EventArgs $eventArgs) { if (!$eventArgs instanceof LoadClassMetadataEventArgs) { throw InvalidArgumentException::create( 'Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs', $eventArgs ); } $ea = $this->getEventAdapter($eventArgs); $this->loadMetadataForObjectClass($ea->getObjectManager(), $eventArgs->getClassMetadata()); } /** * {@inheritDoc} */ public function getNamespace() { return __NAMESPACE__; } }
<?php /** * This file is part of the Axstrad library. * * (c) Dan Kempster <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Dan Kempster <[email protected]> * @package Axstrad\DoctineExtensions */ namespace Axstrad\DoctrineExtensions\Activatable; use Doctrine\Common\EventArgs; use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs; use Gedmo\Mapping\MappedEventSubscriber; use Axstrad\DoctrineExtensions\Exception\InvalidArgumentException; /** * Axstrad\DoctrineExtensions\Activatable\ActivatableListener */ class ActivatableListener extends MappedEventSubscriber { /** */ public function getSubscribedEvents() { return array( 'loadClassMetadata', ); } /** * Mapps additional metadata * * @param EventArgs $eventArgs * @return void */ public function loadClassMetadata(EventArgs $eventArgs) { if ($eventArgs instanceof LoadClassMetadataEventArgs) { throw InvalidArgumentException::create( 'Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs', $eventArgs ); } $ea = $this->getEventAdapter($eventArgs); $this->loadMetadataForObjectClass($ea->getObjectManager(), $eventArgs->getClassMetadata()); } /** * {@inheritDoc} */ public function getNamespace() { return __NAMESPACE__; } }
Add UI for unknow exception
import React from 'react'; import { connect } from 'react-redux'; import Grid from 'react-bootstrap/lib/Grid'; import Errors from '../../constants/Errors'; import { removeError } from '../../actions/errorActions'; let ErrorList = ({ errors, dispatch }) => ( <Grid> {errors.map((error) => ( <div key={error.id} className="alert alert-danger alert-dismissible" role="alert" > <button type="button" className="close" data-dismiss="alert" aria-label="Close" onClick={() => dispatch(removeError(error.id))} > <span aria-hidden="true">&times;</span> </button> <strong>{error.title}</strong> {' ' + error.detail} {error.meta && [( <p key="0"> {error.code === Errors.STATE_PRE_FETCHING_FAIL.code && ( <span>{error.meta.detail}</span> )} </p> ), ( <p key="1"> {error.meta.path && `(at path '${error.meta.path}')`} </p> ), ( <p key="2"> {error.code === Errors.UNKNOWN_EXCEPTION.code && ( <span>{error.meta.toString()}</span> )} </p> )]} </div> ))} </Grid> ); export default connect(state => ({ errors: state.errors, }))(ErrorList);
import React from 'react'; import { connect } from 'react-redux'; import Grid from 'react-bootstrap/lib/Grid'; import Errors from '../../constants/Errors'; import { removeError } from '../../actions/errorActions'; let ErrorList = ({ errors, dispatch }) => ( <Grid> {errors.map((error) => ( <div key={error.id} className="alert alert-danger alert-dismissible" role="alert" > <button type="button" className="close" data-dismiss="alert" aria-label="Close" onClick={() => dispatch(removeError(error.id))} > <span aria-hidden="true">&times;</span> </button> <strong>{error.title}</strong> {' ' + error.detail} {error.meta && [( <p key="0"> {error.code === Errors.STATE_PRE_FETCHING_FAIL.code && ( <span>{error.meta.detail}</span> )} </p> ), ( <p key="1"> {error.meta.path && `(at path '${error.meta.path}')`} </p> )]} </div> ))} </Grid> ); export default connect(state => ({ errors: state.errors, }))(ErrorList);
Add missing null-checks for Neo4j session factory instantiation
package org.atlasapi.neo4j; import org.neo4j.driver.v1.AuthToken; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Session; import static com.google.common.base.Preconditions.checkNotNull; public class Neo4jSessionFactory { private final Driver driver; private Neo4jSessionFactory(Driver driver) { this.driver = checkNotNull(driver); } public static Neo4jSessionFactory create( String host, int port, AuthToken authToken, int maxIdleSessions ) { return new Neo4jSessionFactory(GraphDatabase .driver( "bolt://" + checkNotNull(host) + ":" + port, checkNotNull(authToken), Config.build() .withMaxIdleSessions(maxIdleSessions) .withEncryptionLevel(Config.EncryptionLevel.NONE) .toConfig() )); } public Session getSession() { return driver.session(); } public void close() { driver.close(); } }
package org.atlasapi.neo4j; import org.neo4j.driver.v1.AuthToken; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Session; import static com.google.common.base.Preconditions.checkNotNull; public class Neo4jSessionFactory { private final Driver driver; private Neo4jSessionFactory(Driver driver) { this.driver = checkNotNull(driver); } public static Neo4jSessionFactory create( String host, int port, AuthToken authToken, int maxIdleSessions ) { return new Neo4jSessionFactory(GraphDatabase .driver( "bolt://" + host + ":" + port, authToken, Config.build() .withMaxIdleSessions(maxIdleSessions) .withEncryptionLevel(Config.EncryptionLevel.NONE) .toConfig() )); } public Session getSession() { return driver.session(); } public void close() { driver.close(); } }
Add trailing slash for INVITE_ENDPOINT
package co.phoenixlab.discord.api; /** * Contains various useful API URLs and paths */ public class ApiConst { /** * Utility class */ private ApiConst() { } /** * The base URL from which Discord runs */ public static final String BASE_URL = "https://discordapp.com/"; /** * Base API path */ public static final String API_BASE_PATH = BASE_URL + "api"; /** * WebSocket gateway */ public static final String WEBSOCKET_GATEWAY = API_BASE_PATH + "/gateway"; /** * The endpoint for accessing user information */ public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/"; /** * The endpoint for logging in */ public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login"; /** * The endpoint for logging out */ public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout"; /** * The endpoint for accessing server information */ public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/"; /** * The endpoint for accessing channel information */ public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/"; /** * The endpoint for accepting invites */ public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite/"; /** * The format string for avatar URLs */ public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg"; }
package co.phoenixlab.discord.api; /** * Contains various useful API URLs and paths */ public class ApiConst { /** * Utility class */ private ApiConst() { } /** * The base URL from which Discord runs */ public static final String BASE_URL = "https://discordapp.com/"; /** * Base API path */ public static final String API_BASE_PATH = BASE_URL + "api"; /** * WebSocket gateway */ public static final String WEBSOCKET_GATEWAY = API_BASE_PATH + "/gateway"; /** * The endpoint for accessing user information */ public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/"; /** * The endpoint for logging in */ public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login"; /** * The endpoint for logging out */ public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout"; /** * The endpoint for accessing server information */ public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/"; /** * The endpoint for accessing channel information */ public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/"; /** * The endpoint for accepting invites */ public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite"; /** * The format string for avatar URLs */ public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg"; }
Update webservice to use array of ids
<?php namespace fennecweb\ajax\details; use \PDO as PDO; /** * Web Service. * Returns a project according to the project ID. */ class Projects extends \fennecweb\WebService { /** * @param $querydata[] * @returns Array $result * <code> * array('project_id': {biomfile}); * </code> */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $result = array(); $ids = $querydata['ids']; $placeholders = implode(',', array_fill(0, count($ids), '?')); if (!isset($_SESSION)) { session_start(); } $query_get_project_details = <<<EOF SELECT webuser_data_id, project FROM full_webuser_data WHERE provider = ? AND oauth_id = ? AND webuser_data_id IN ($placeholders) EOF; $stm_get_project_details = $db->prepare($query_get_project_details); $stm_get_project_details->execute( array_merge(array($_SESSION['user']['provider'], $_SESSION['user']['id']), $ids) ); while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) { $result[$row['webuser_data_id']] = $row['project']; } return $result; } }
<?php namespace fennecweb\ajax\details; use \PDO as PDO; /** * Web Service. * Returns a project according to the project ID. */ class Projects extends \fennecweb\WebService { /** * @param $querydata[] * @returns Array $result * <code> * array('project_id': {biomfile}); * </code> */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $result = array(); $project_id = $querydata['id']; if (!isset($_SESSION)) { session_start(); } $query_get_project_details = <<<EOF SELECT project FROM full_webuser_data WHERE webuser_data_id = :project_id AND provider = :provider AND oauth_id = :oauth_id EOF; $stm_get_project_details = $db->prepare($query_get_project_details); $stm_get_project_details->bindValue('project_id', $project_id); $stm_get_project_details->bindValue('provider', $_SESSION['user']['provider']); $stm_get_project_details->bindValue('oauth_id', $_SESSION['user']['id']); $stm_get_project_details->execute(); while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) { $result[$project_id] = $row['project']; } return $result; } }
Fix static and private combination
<?php /** * Part of CI PHPUnit Test * * @author Kenji Suzuki <https://github.com/kenjis> * @license MIT License * @copyright 2015 Kenji Suzuki * @link https://github.com/kenjis/ci-phpunit-test */ $installer = new Installer(); $installer->install(); class Installer { public static function install() { $test_folder = 'application/tests'; self::recursiveCopy( 'vendor/kenjis/ci-phpunit-test/application/tests', $test_folder ); } /** * Recursive Copy * * @param string $src * @param string $dst */ private static function recursiveCopy($src, $dst) { @mkdir($dst, 0755); $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $file) { if ($file->isDir()) { @mkdir($dst . '/' . $iterator->getSubPathName()); } else { $success = copy($file, $dst . '/' . $iterator->getSubPathName()); if ($success) { echo 'copied: ' . $dst . '/' . $iterator->getSubPathName() . PHP_EOL; } } } } }
<?php /** * Part of CI PHPUnit Test * * @author Kenji Suzuki <https://github.com/kenjis> * @license MIT License * @copyright 2015 Kenji Suzuki * @link https://github.com/kenjis/ci-phpunit-test */ $installer = new Installer(); $installer->install(); class Installer { public static function install() { $test_folder = 'application/tests'; static::recursiveCopy( 'vendor/kenjis/ci-phpunit-test/application/tests', $test_folder ); } /** * Recursive Copy * * @param string $src * @param string $dst */ private static function recursiveCopy($src, $dst) { @mkdir($dst, 0755); $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $file) { if ($file->isDir()) { @mkdir($dst . '/' . $iterator->getSubPathName()); } else { $success = copy($file, $dst . '/' . $iterator->getSubPathName()); if ($success) { echo 'copied: ' . $dst . '/' . $iterator->getSubPathName() . PHP_EOL; } } } } }
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) tmp_member.seek(0) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False return func def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
Work around combobox not getting detected correctly TODO: find proper solution
Ext2.namespace('Kwc.TextImage.ImageEnlarge'); Kwc.TextImage.ImageEnlarge.ImageUploadField = Ext2.extend(Kwc.Basic.ImageEnlarge.ImageUploadField, { afterRender: function() { Kwc.TextImage.ImageEnlarge.ImageUploadField.superclass.afterRender.call(this); var actionField = this._findActionCombobox(); actionField.on('changevalue', function (combo, value, index) { this._checkForImageTooSmall(); }, this); }, _findActionCombobox: function () { var actionSelectFields = this.findParentBy(function (component, container){ if (component.identifier == 'kwc-basic-imageenlarge-form') { return true; } return false; }, this).findBy(function (component, container) { //TODO why isn't the first one not enough? Kwc.Basic.LinkTag.ComboBox inherits Kwc.Abstract.Cards.ComboBox! if (component instanceof Kwc.Abstract.Cards.ComboBox || component instanceof Kwc.Basic.LinkTag.ComboBox) { return true; } return false; }, this); return actionSelectFields[0]; }, _isValidateImageTooSmallUsingImageEnlargeDimensions: function () { // check if dropdown has selected imageenlarge var actionField = this._findActionCombobox(); var action = actionField.defaultValue; if (actionField.getValue()) { action = actionField.getValue(); } return action == 'enlarge'; } }); Ext2.reg('kwc.textimage.imageenlarge.imageuploadfield', Kwc.TextImage.ImageEnlarge.ImageUploadField);
Ext2.namespace('Kwc.TextImage.ImageEnlarge'); Kwc.TextImage.ImageEnlarge.ImageUploadField = Ext2.extend(Kwc.Basic.ImageEnlarge.ImageUploadField, { afterRender: function() { Kwc.TextImage.ImageEnlarge.ImageUploadField.superclass.afterRender.call(this); var actionField = this._findActionCombobox(); actionField.on('changevalue', function (combo, value, index) { this._checkForImageTooSmall(); }, this); }, _findActionCombobox: function () { var actionSelectFields = this.findParentBy(function (component, container){ if (component.identifier == 'kwc-basic-imageenlarge-form') { return true; } return false; }, this).findBy(function (component, container) { if (component instanceof Kwc.Abstract.Cards.ComboBox) { return true; } return false; }, this); return actionSelectFields[0]; }, _isValidateImageTooSmallUsingImageEnlargeDimensions: function () { // check if dropdown has selected imageenlarge var actionField = this._findActionCombobox(); var action = actionField.defaultValue; if (actionField.getValue()) { action = actionField.getValue(); } return action == 'enlarge'; } }); Ext2.reg('kwc.textimage.imageenlarge.imageuploadfield', Kwc.TextImage.ImageEnlarge.ImageUploadField);
Use startActivityForResult when creating the first Timetable
package com.satsumasoftware.timetable.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.satsumasoftware.timetable.R; import com.satsumasoftware.timetable.TimetableApplication; import com.satsumasoftware.timetable.framework.Timetable; public class SplashActivity extends AppCompatActivity { private static final int REQUEST_CODE_TIMETABLE_EDIT = 1; private static final int SLEEP_TIME = 1000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Thread timer = new Thread() { public void run() { try { sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } finally { Timetable currentTimetable = ((TimetableApplication) getApplication()).getCurrentTimetable(); Intent intent; if (currentTimetable == null) { intent = new Intent(getBaseContext(), TimetableEditActivity.class); startActivityForResult(intent, REQUEST_CODE_TIMETABLE_EDIT); } else { intent = new Intent(getBaseContext(), MainActivity.class); startActivity(intent); finish(); } } } }; timer.start(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_TIMETABLE_EDIT) { if (resultCode == Activity.RESULT_OK) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } } } }
package com.satsumasoftware.timetable.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.satsumasoftware.timetable.R; import com.satsumasoftware.timetable.TimetableApplication; import com.satsumasoftware.timetable.framework.Timetable; public class SplashActivity extends AppCompatActivity { private static final int SLEEP_TIME = 1000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Thread timer = new Thread() { public void run() { try { sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } finally { Timetable currentTimetable = ((TimetableApplication) getApplication()).getCurrentTimetable(); Intent intent; if (currentTimetable == null) { intent = new Intent(getBaseContext(), TimetableEditActivity.class); } else { intent = new Intent(getBaseContext(), MainActivity.class); } startActivity(intent); } } }; timer.start(); } @Override protected void onPause() { super.onPause(); finish(); } }
Change ping result error handling to return values instead of raise exception
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <[email protected]> """ from __future__ import absolute_import from __future__ import unicode_literals from collections import namedtuple import platform import dataproperty PingResult = namedtuple("PingResult", "stdout stderr returncode") class PingTransmitter(object): def __init__(self): self.destination_host = "" self.waittime = 1 self.ping_option = "" def ping(self): import subprocess self.__validate_ping_param() command_list = [ "ping", self.destination_host, ] if dataproperty.is_not_empty_string(self.ping_option): command_list.append(self.ping_option) if platform.system() == "Windows": command_list.append("-n {:d}".format(self.waittime)) else: command_list.append("-q -w {:d}".format(self.waittime)) ping_proc = subprocess.Popen( " ".join(command_list), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = ping_proc.communicate() return PingResult(stdout, stderr, ping_proc.returncode) def __validate_ping_param(self): if dataproperty.is_empty_string(self.destination_host): raise ValueError("destination_host host is empty") if self.waittime <= 0: raise ValueError( "wait time expected to be greater than or equal to zero")
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <[email protected]> """ from __future__ import absolute_import from __future__ import unicode_literals import platform import dataproperty class PingTransmitter(object): def __init__(self): self.destination_host = "" self.waittime = 1 self.ping_option = "" def ping(self): import subprocess self.__validate_ping_param() command_list = [ "ping", self.destination_host, ] if dataproperty.is_not_empty_string(self.ping_option): command_list.append(self.ping_option) if platform.system() == "Windows": command_list.append("-n {:d}".format(self.waittime)) else: command_list.append("-q -w {:d}".format(self.waittime)) ping_proc = subprocess.Popen( " ".join(command_list), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = ping_proc.communicate() if ping_proc.returncode != 0: raise RuntimeError(stderr) return stdout def __validate_ping_param(self): if dataproperty.is_empty_string(self.destination_host): raise ValueError("destination_host host is empty") if self.waittime <= 0: raise ValueError( "waittime expected to be greater than or equal to zero")
Update DUA requirement to support Django 1.9
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="Pinax Team", author_email="[email protected]", description="a user to user join invitations app", name="pinax-invitations", long_description=read("README.rst"), version="3.0.0", url="http://github.com/pinax/pinax-invitations/", license="MIT", packages=find_packages(), package_data={ "invitations": [] }, test_suite="runtests.runtests", install_requires=[ "django-appconf>=1.0.1", "django-user-accounts>=1.3" ], tests_require=[ ], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="Pinax Team", author_email="[email protected]", description="a user to user join invitations app", name="pinax-invitations", long_description=read("README.rst"), version="3.0.0", url="http://github.com/pinax/pinax-invitations/", license="MIT", packages=find_packages(), package_data={ "invitations": [] }, test_suite="runtests.runtests", install_requires=[ "django-appconf>=1.0.1", "django-user-accounts>=1.2" ], tests_require=[ ], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
Support import was throwing exceptions
import React from 'react'; import { View, Text, } from 'react-native'; // import { Actions } from 'react-native-router-flux'; import RoomView from './RoomView'; import { AppStyles, AppSizes } from '../../../theme/'; import Network from '../../../network'; import t from '../../../i18n'; export default class SupportGroup extends React.Component { constructor(props) { super(props); this.supportGroup = null; } componentWillMount() { const net = new Network(); this.supportGroup = net.db.groups.findByName('support'); } render() { return ( <View style={[AppStyles.container, { marginTop: -(AppSizes.navbarHeight), paddingBottom: 5, }]} > { this.supportGroup && <RoomView obj={this.supportGroup} /> } { !this.supportGroup && <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', }} > <Text style={{ fontSize: 16, fontFamily: 'OpenSans-Regular', fontWeight: '500', }} >{t('txt_CS')}</Text> </View> } </View> ); } } SupportGroup.defaultProps = { }; SupportGroup.propTypes = { };
import React from 'react'; import { View, Text, } from 'react-native'; // import { Actions } from 'react-native-router-flux'; import { RoomView } from './RoomView'; import { AppStyles, AppSizes } from '../../../theme/'; import Network from '../../../network'; import t from '../../../i18n'; export default class SupportGroup extends React.Component { constructor(props) { super(props); this.supportGroup = null; } componentWillMount() { const net = new Network(); this.supportGroup = net.db.groups.findByName('support'); } render() { return ( <View style={[AppStyles.container, { marginTop: -(AppSizes.navbarHeight), paddingBottom: 5, }]} > { this.supportGroup && <RoomView obj={this.supportGroup} /> } { !this.supportGroup && <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', }} > <Text style={{ fontSize: 16, fontFamily: 'OpenSans-Regular', fontWeight: '500', }} >{t('txt_CS')}</Text> </View> } </View> ); } } SupportGroup.defaultProps = { }; SupportGroup.propTypes = { };
Update clear cache to electron promise APIs
import { ipcRenderer, remote } from 'electron'; import du from 'du'; import { getServicePartitionsDirectory } from '../../helpers/service-helpers.js'; const debug = require('debug')('Franz:LocalApi'); const { session } = remote; export default class LocalApi { // Settings getAppSettings(type) { return new Promise((resolve) => { ipcRenderer.once('appSettings', (event, resp) => { debug('LocalApi::getAppSettings resolves', resp.type, resp.data); resolve(resp); }); ipcRenderer.send('getAppSettings', type); }); } async updateAppSettings(type, data) { debug('LocalApi::updateAppSettings resolves', type, data); ipcRenderer.send('updateAppSettings', { type, data, }); } // Services async getAppCacheSize() { const partitionsDir = getServicePartitionsDirectory(); return new Promise((resolve, reject) => { du(partitionsDir, (err, size) => { if (err) reject(err); debug('LocalApi::getAppCacheSize resolves', size); resolve(size); }); }); } async clearCache(serviceId) { const s = session.fromPartition(`persist:service-${serviceId}`); debug('LocalApi::clearCache resolves', serviceId); return s.clearCache(); } async clearAppCache() { const s = session.defaultSession; debug('LocalApi::clearCache clearAppCache'); return s.clearCache(); } }
import { ipcRenderer, remote } from 'electron'; import du from 'du'; import { getServicePartitionsDirectory } from '../../helpers/service-helpers.js'; const debug = require('debug')('Franz:LocalApi'); const { session } = remote; export default class LocalApi { // Settings getAppSettings(type) { return new Promise((resolve) => { ipcRenderer.once('appSettings', (event, resp) => { debug('LocalApi::getAppSettings resolves', resp.type, resp.data); resolve(resp); }); ipcRenderer.send('getAppSettings', type); }); } async updateAppSettings(type, data) { debug('LocalApi::updateAppSettings resolves', type, data); ipcRenderer.send('updateAppSettings', { type, data, }); } // Services async getAppCacheSize() { const partitionsDir = getServicePartitionsDirectory(); return new Promise((resolve, reject) => { du(partitionsDir, (err, size) => { if (err) reject(err); debug('LocalApi::getAppCacheSize resolves', size); resolve(size); }); }); } async clearCache(serviceId) { const s = session.fromPartition(`persist:service-${serviceId}`); debug('LocalApi::clearCache resolves', serviceId); return new Promise(resolve => s.clearCache(resolve)); } async clearAppCache() { const s = session.defaultSession; debug('LocalApi::clearCache clearAppCache'); return new Promise(resolve => s.clearCache(resolve)); } }
WebRTC: Switch chromium.webrtc Linux builders to chromium recipe. With https://codereview.chromium.org/1406253003/ landed this is the first CL in a series of careful rollout to the new recipe. BUG=538259 [email protected] Review URL: https://codereview.chromium.org/1508933002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@297884 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factory m_annotator = annotator_factory.AnnotatorFactory() def Update(c): c['schedulers'].append( SingleBranchScheduler(name='chromium_scheduler', change_filter=ChangeFilter(project='chromium', branch='master'), treeStableTimer=60, builderNames=[ 'Win Builder', 'Mac Builder', 'Linux Builder', ]), ) specs = [ {'name': 'Win Builder', 'category': 'win'}, {'name': 'WinXP Tester', 'category': 'win'}, {'name': 'Win7 Tester', 'category': 'win'}, {'name': 'Win8 Tester', 'category': 'win'}, {'name': 'Win10 Tester', 'category': 'win'}, {'name': 'Mac Builder', 'category': 'mac'}, {'name': 'Mac Tester', 'category': 'mac'}, {'name': 'Linux Builder', 'recipe': 'chromium', 'category': 'linux'}, {'name': 'Linux Tester', 'recipe': 'chromium', 'category': 'linux'}, ] c['builders'].extend([ { 'name': spec['name'], 'factory': m_annotator.BaseFactory(spec.get('recipe', 'webrtc/chromium')), 'category': spec['category'], 'notify_on_missing': True, } for spec in specs ])
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factory m_annotator = annotator_factory.AnnotatorFactory() def Update(c): c['schedulers'].append( SingleBranchScheduler(name='chromium_scheduler', change_filter=ChangeFilter(project='chromium', branch='master'), treeStableTimer=60, builderNames=[ 'Win Builder', 'Mac Builder', 'Linux Builder', ]), ) specs = [ {'name': 'Win Builder', 'category': 'win'}, {'name': 'WinXP Tester', 'category': 'win'}, {'name': 'Win7 Tester', 'category': 'win'}, {'name': 'Win8 Tester', 'category': 'win'}, {'name': 'Win10 Tester', 'category': 'win'}, {'name': 'Mac Builder', 'category': 'mac'}, {'name': 'Mac Tester', 'category': 'mac'}, {'name': 'Linux Builder', 'category': 'linux'}, {'name': 'Linux Tester', 'category': 'linux'}, ] c['builders'].extend([ { 'name': spec['name'], 'factory': m_annotator.BaseFactory('webrtc/chromium'), 'category': spec['category'], 'notify_on_missing': True, } for spec in specs ])
Revert "eos and UNK will be overwritten if they occur in the corpus, should always be 0 and 1" Actually fine if there are weird values, as Nematus does not really use them. This reverts commit 09eb3594fb395d43dd3f6c2a4dec85af683cbb30.
#!/usr/bin/python import numpy import json import sys import fileinput from collections import OrderedDict def main(): for filename in sys.argv[1:]: print 'Processing', filename word_freqs = OrderedDict() with open(filename, 'r') as f: for line in f: words_in = line.strip().split(' ') for w in words_in: if w not in word_freqs: word_freqs[w] = 0 word_freqs[w] += 1 words = word_freqs.keys() freqs = word_freqs.values() sorted_idx = numpy.argsort(freqs) sorted_words = [words[ii] for ii in sorted_idx[::-1]] worddict = OrderedDict() worddict['eos'] = 0 worddict['UNK'] = 1 for ii, ww in enumerate(sorted_words): worddict[ww] = ii+2 with open('%s.json'%filename, 'wb') as f: json.dump(worddict, f, indent=2, ensure_ascii=False) print 'Done' if __name__ == '__main__': main()
#!/usr/bin/python import numpy import json import sys import fileinput from collections import OrderedDict def main(): for filename in sys.argv[1:]: print 'Processing', filename word_freqs = OrderedDict() with open(filename, 'r') as f: for line in f: words_in = line.strip().split(' ') for w in words_in: if w not in word_freqs: word_freqs[w] = 0 word_freqs[w] += 1 words = word_freqs.keys() freqs = word_freqs.values() sorted_idx = numpy.argsort(freqs) sorted_words = [words[ii] for ii in sorted_idx[::-1]] worddict = OrderedDict() for ii, ww in enumerate(sorted_words): worddict[ww] = ii+2 worddict['eos'] = 0 worddict['UNK'] = 1 with open('%s.json'%filename, 'wb') as f: json.dump(worddict, f, indent=2, ensure_ascii=False) print 'Done' if __name__ == '__main__': main()
Include Assinaturas ebook in Edit Start Page
import m from 'mithril'; import h from '../h'; import userVM from '../vms/user-vm'; import projectVM from '../vms/project-vm'; import youtubeLightbox from '../c/youtube-lightbox'; const I18nScope = _.partial(h.i18nScope, 'projects.dashboard_start'); const projectEditStart = { controller(args) { }, view(ctrl, args) { return m('.dashboard-header.min-height-70.u-text-center', m('.w-container', m('.u-marginbottom-40.w-row', [ m('.w-col.w-col-8.w-col-push-2', [ m('.fontsize-larger.fontweight-semibold.lineheight-looser.u-marginbottom-10', I18n.t('title', I18nScope()) ), m('.fontsize-small.lineheight-loose.u-marginbottom-40', I18n.t('description', I18nScope({ name: args.project().user.name || '' })) ), m('.card.card-terciary.u-radius', m(`iframe[allowfullscreen="true"][frameborder="0"][scrolling="no"][mozallowfullscreen="true"][webkitallowfullscreen="true"][src=${I18n.t('video_src', I18nScope())}]`) ) ] ) ] ) ) ); } }; export default projectEditStart;
import m from 'mithril'; import h from '../h'; import userVM from '../vms/user-vm'; import projectVM from '../vms/project-vm'; import youtubeLightbox from '../c/youtube-lightbox'; const I18nScope = _.partial(h.i18nScope, 'projects.dashboard_start'); const projectEditStart = { controller(args) { }, view(ctrl, args) { return m('.dashboard-header.min-height-70.u-text-center', m('.w-container', m('.u-marginbottom-40.w-row', [ m('.w-col.w-col-8.w-col-push-2', [ m('.fontsize-larger.fontweight-semibold.lineheight-looser.u-marginbottom-10', I18n.t('title', I18nScope()) ), m('.fontsize-small.lineheight-loose.u-marginbottom-40', I18n.t('description', I18nScope({ name: args.project().user.name || '' })) ), m('.card.card-terciary.u-radius', m('.w-embed.w-video', { style: { 'padding-top': '56.17021276595745%' } }, m(`iframe.embedly-embed[allowfullscreen="true"][frameborder="0"][scrolling="no"][src=${I18n.t('video_src', I18nScope())}]`) ) ) ] ) ] ) ) ); } }; export default projectEditStart;
Apply site controller to the root state in embedded mode
'use strict'; (function() { angular .module('app') .config(['$stateProvider', '$urlRouterProvider', 'grEmbeddingParamsProvider', function($stateProvider, $urlRouterProvider, grEmbeddingParamsProvider) { $stateProvider .state('site', { abstract: true, templateUrl: '/templates/site.html', controller: grEmbeddingParamsProvider.getParams().isEmbeddedMode ? 'SiteController' : undefined }).state('site.laws', { url: '/', templateUrl: '/templates/law/index.html', controller: 'LawIndexController' }).state('site.404', { params: { message: undefined }, templateUrl: '/templates/site/404.html', controller: 'StaticPageController' }).state('site.message', { params: { title: undefined, message: undefined }, templateUrl: '/templates/site/message.html', controller: 'StaticPageController' }); $urlRouterProvider.otherwise( function($injector, $location) { if ($location.path() === '') { $location.replace().path('/'); } else { console.error($location.path(), '404: route not found!'); $injector.get('grMessage').error404(); } }); } ]); })();
'use strict'; (function() { angular .module('app') .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('site', { abstract: true, templateUrl: '/templates/site.html' }).state('site.laws', { url: '/', templateUrl: '/templates/law/index.html', controller: 'LawIndexController' }).state('site.404', { params: { message: undefined }, templateUrl: '/templates/site/404.html', controller: 'StaticPageController' }).state('site.message', { params: { title: undefined, message: undefined }, templateUrl: '/templates/site/message.html', controller: 'StaticPageController' }); $urlRouterProvider.otherwise( function($injector, $location) { if ($location.path() === '') { $location.replace().path('/'); } else { console.error($location.path(), '404: route not found!'); $injector.get('grMessage').error404(); } }); } ]); })();
Remove the task only once
define([ 'Backbone', //Templates 'text!templates/project-page/closeGameTemplate.html' ], function( Backbone, //Template closeGameTemplate ){ var GameController = Backbone.View.extend({ template: _.template(closeGameTemplate), close: function(event){ var task = this.selectedTask.get('id'); socket.emit('close game', task); }, killTask: function(){ var task = this.selectedTask.get('id'); var kill = _.once(function(){ socket.emit('kill task', task); }); kill(); }, render: function(){ var estimations = this.selectedTask.get('estimated') || []; var time = this.selectedTask.get('time'); var total = _.countBy(estimations, function(estimation){ return estimation.card; }); var max = _.max(total, function(point){return point;}); var result = _.compact(_.map(total, function(count, point){ return count === max ? point : false; })).pop(); if(!estimations[0]){ estimations.push({ player: 'No one estimated', card: '?' }); } if(time === '0'){ this.killTask(); } this.selectedTask.set({result: result}, {silent: true}); this.$el.html(this.template({ estimations: estimations, time: time, result: result })); } }); return GameController; });
define([ 'Backbone', //Templates 'text!templates/project-page/closeGameTemplate.html' ], function( Backbone, //Template closeGameTemplate ){ var GameController = Backbone.View.extend({ template: _.template(closeGameTemplate), close: function(event){ var task = this.selectedTask.get('id'); socket.emit('close game', task); }, killTask: function(){ var result = this.selectedTask.get('result'); this.selectedTask.destroy({data: 'result='+result}); }, render: function(){ var estimations = this.selectedTask.get('estimated') || []; var time = this.selectedTask.get('time'); var total = _.countBy(estimations, function(estimation){ return estimation.card; }); var max = _.max(total, function(point){return point;}); var result = _.compact(_.map(total, function(count, point){ return count === max ? point : false; })).pop(); if(!estimations[0]){ estimations.push({ player: 'No one estimated', card: '?' }); } if(time === '0'){ this.killTask(); } this.selectedTask.set({result: result}, {silent: true}); this.$el.html(this.template({ estimations: estimations, time: time, result: result })); } }); return GameController; });
Nick: Add working search function v1
#!/usr/bin/env python from __future__ import print_function class Node(object): def __init__(self, value): self._val = value self._next = None @property def next(self): return self._next @next.setter def next(self, value): self._next = value @property def val(self): return self._val class LinkedList(object): def __init__(self): self._head = None @property def head(self): return self._head def insert(self, val): if not self._head: self._head = Node(val) self._head.next = None else: b = self._head self._head = Node(val) self._head.next = b def pop(self): self._head = self._head.next def size(self): i = 0 if not self._head: return i else: i = 1 if not self._head.next: return i else: i = 2 z = 1 a = self._head.next while z: if not a.next: z = 0 return i else: a = a.next i += 1 def search(self, value): z = 1 a = self._head.next while z: if a.val == value: z = 0 return a elif not a.next: z = 0 return None else: a = a.next l = LinkedList() l.insert('Nick') l.insert('Constantine') l.insert('Maria') l.insert('Bob') print(l.size()) print(l.search("Constantine"))
#!/usr/bin/env python from __future__ import print_function class Node(object): def __init__(self, value): self._val = value self._next = None @property def next(self): return self._next @next.setter def next(self, value): self._next = value @property def val(self): return self._val class LinkedList(object): def __init__(self): self._head = None @property def head(self): return self._head def insert(self, val): if not self._head: self._head = Node(val) self._head.next = None else: b = self._head self._head = Node(val) self._head.next = b def pop(self): self._head = self._head.next def size(self): i = 0 if not self._head: return i else: i = 1 if not self._head.next: return i else: i = 2 z = 1 a = self._head.next while z: if not a.next: z = 0 return i else: a = a.next i += 1 # def search l = LinkedList() # l.insert('Nick') # l.insert('Constantine') # l.insert('Maria') # l.insert('Bob') print(l.size())
Add option to start server passing lib path
#!/usr/bin/env python """ This is an example snap7 server. It doesn't do much, but accepts connection. Usefull for running the python-snap7 test suite. """ import time import logging import snap7 def mainloop(): server = snap7.server.Server() size = 100 data = (snap7.types.wordlen_to_ctypes[snap7.types.S7WLByte] * size)() server.register_area(snap7.types.srvAreaDB, 1, data) server.start() while True: #logger.info("server: %s cpu: %s users: %s" % server.get_status()) while True: event = server.pick_event() if event: logger.info(server.event_text(event)) else: break time.sleep(1) def check_root(): """ check if uid of this process is root """ import os import platform if platform.system() == 'Windows': # We don't need root on Windows to use port 102 return True if os.getuid() == 0: return True root_msg = "it sucks, but you need to run this as root. The snap7 library is" \ " hardcoded run on port 102, which requires root privileges." if __name__ == '__main__': import sys if len(sys.argv) > 1: snap7.common.load_library(sys.argv[1]) logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) if not check_root(): logging.error(root_msg) mainloop()
#!/usr/bin/env python """ This is an example snap7 server. It doesn't do much, but accepts connection. Usefull for running the python-snap7 test suite. """ import time import logging import snap7 def mainloop(): server = snap7.server.Server() size = 100 data = (snap7.types.wordlen_to_ctypes[snap7.types.S7WLByte] * size)() server.register_area(snap7.types.srvAreaDB, 1, data) server.start() while True: #logger.info("server: %s cpu: %s users: %s" % server.get_status()) while True: event = server.pick_event() if event: logger.info(server.event_text(event)) else: break time.sleep(1) def check_root(): """ check if uid of this process is root """ import os import platform if platform.system() == 'Windows': # We don't need root on Windows to use port 102 return True if os.getuid() == 0: return True root_msg = "it sucks, but you need to run this as root. The snap7 library is" \ " hardcoded run on port 102, which requires root privileges." if __name__ == '__main__': logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) if not check_root(): logging.error(root_msg) mainloop()
QS-1001: Access translated components by ref
import { default as React } from 'react'; import en from './en'; import es from './es'; const locales = {en, es}; export default function translate(key) { return Component => { class TranslationComponent extends React.Component { componentWillMount() { let strings = locales[this.context.locale]['Framework7']; nekunoApp.params.modalTitle = strings.modalTitle; nekunoApp.params.modalButtonOk = strings.modalButtonOk; nekunoApp.params.modalButtonCancel = strings.modalButtonCancel; } // TranslationComponent receives ref from parent, so this is a wrapper to use children methods. getSelectedFilter() { let filter = null; Object.keys(this.refs).forEach(function(value){ if (typeof this.refs[value].getSelectedFilter === 'function'){ filter = this.refs[value].getSelectedFilter(); } }, this); return filter; } selectedFilterContains(a) { let contains = null; Object.keys(this.refs).forEach(function(value){ if (typeof this.refs[value].selectedFilterContains === 'function'){ contains = this.refs[value].selectedFilterContains(a); } }, this); return contains; } render() { var strings = locales[this.context.locale][key]; const merged = { ...this.props.strings, ...strings }; if (strings) { return <Component {...this.props} ref={Date.now()} strings={merged} locale={this.context.locale}/>; } else { return <Component {...this.props} ref={Date.now()} locale={this.context.locale}/>; } } } TranslationComponent.contextTypes = { locale: React.PropTypes.string }; return TranslationComponent; }; }
import { default as React } from 'react'; import en from './en'; import es from './es'; const locales = {en, es}; export default function translate(key) { return Component => { class TranslationComponent extends React.Component { componentWillMount() { let strings = locales[this.context.locale]['Framework7']; nekunoApp.params.modalTitle = strings.modalTitle; nekunoApp.params.modalButtonOk = strings.modalButtonOk; nekunoApp.params.modalButtonCancel = strings.modalButtonCancel; } render() { var strings = locales[this.context.locale][key]; const merged = { ...this.props.strings, ...strings }; if (strings) { return <Component {...this.props} strings={merged} locale={this.context.locale}/>; } else { return <Component {...this.props} locale={this.context.locale}/>; } } } TranslationComponent.contextTypes = { locale: React.PropTypes.string }; return TranslationComponent; }; }
[fix] Add missing viewport tag. Responsive styles were setup, but weren't taking effect.
const React = require('react'); const ReactGA = require('react-ga'); const Component = React.createClass({ render: function () { return ( <html> <head> <meta name="description" content="Web application design, development, enterprise architecture, hiring, and training for Node.js and React.js" /> <meta httpEquiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="author" href="https://plus.google.com/108812193853051708628" /> <link ref="publisher" href="https://plus.google.com/108812193853051708628" /> <title>Langa | Enterprise Web Development and Design</title> <link rel="stylesheet" href="/assets/styles/prod.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" /> </head> <body> <div id="app-mount" dangerouslySetInnerHTML={{ __html: this.props.children }}> </div> <script id="app-state" dangerouslySetInnerHTML={{ __html: this.props.state }}> </script> <script src="/assets/client.js"></script> </body> </html> ); } }); module.exports = Component;
const React = require('react'); const ReactGA = require('react-ga'); const Component = React.createClass({ render: function () { return ( <html> <head> <meta name="description" content="Web application design, development, enterprise architecture, hiring, and training for Node.js and React.js" /> <meta httpEquiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="author" href="https://plus.google.com/108812193853051708628" /> <link ref="publisher" href="https://plus.google.com/108812193853051708628" /> <title>Langa | Enterprise Web Development and Design</title> <link rel="stylesheet" href="/assets/styles/prod.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" /> </head> <body> <div id="app-mount" dangerouslySetInnerHTML={{ __html: this.props.children }}> </div> <script id="app-state" dangerouslySetInnerHTML={{ __html: this.props.state }}> </script> <script src="/assets/client.js"></script> </body> </html> ); } }); module.exports = Component;
CRM-7032: Configure form extension for Customer entities - Add Account column to customers grids - Add Account column to customers views
<?php namespace Oro\Bundle\DataGridBundle\Tools; use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration; use Oro\Bundle\EntityBundle\ORM\EntityClassResolver; class GridConfigurationHelper { /** @var EntityClassResolver */ protected $entityClassResolver; /** * @param EntityClassResolver $entityClassResolver */ public function __construct(EntityClassResolver $entityClassResolver) { $this->entityClassResolver = $entityClassResolver; } /** * @param DatagridConfiguration $config * * @return string|null */ public function getEntity(DatagridConfiguration $config) { $entityClassName = $config->offsetGetOr('extended_entity_name'); if ($entityClassName) { return $entityClassName; } $from = $config->offsetGetByPath('[source][query][from]'); if (!$from) { return null; } return $this->entityClassResolver->getEntityClass($from[0]['table']); } /** * @param DatagridConfiguration $config * * @return null */ public function getEntityRootAlias(DatagridConfiguration $config) { $from = $config->offsetGetByPath('[source][query][from]'); if ($from) { return $from[0]['alias']; } return null; } }
<?php namespace Oro\Bundle\DataGridBundle\Tools; use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration; use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource; use Oro\Bundle\EntityBundle\ORM\EntityClassResolver; use Oro\Bundle\SearchBundle\Datagrid\Datasource\SearchDatasource; use Oro\Bundle\SearchBundle\Provider\AbstractSearchMappingProvider; class GridConfigurationHelper { /** @var EntityClassResolver */ protected $entityClassResolver; /** * @param EntityClassResolver $entityClassResolver */ public function __construct(EntityClassResolver $entityClassResolver) { $this->entityClassResolver = $entityClassResolver; } /** * @param DatagridConfiguration $config * * @return string|null */ public function getEntity(DatagridConfiguration $config) { $entityClassName = $config->offsetGetOr('extended_entity_name'); if ($entityClassName) { return $entityClassName; } $from = $config->offsetGetByPath('[source][query][from]'); if (!$from) { return null; } return $this->entityClassResolver->getEntityClass($from[0]['table']); } /** * @param DatagridConfiguration $config * * @return null */ public function getEntityRootAlias(DatagridConfiguration $config) { $from = $config->offsetGetByPath('[source][query][from]'); if ($from) { return $from[0]['alias']; } return null; } }
Update validation-rules prop to accept Array in addition to String
import Validator from 'validatorjs'; export default { props: { valid: { type: Boolean, default: true, twoWay: true }, dirty: { type: Boolean, default: false, twoWay: true }, hideValidationErrors: { type: Boolean, default: false }, validationRules: [String, Array], validationMessages: Object }, data() { return { validationError: '' }; }, events: { 'ui-input::set-validity': function(valid, error, id) { // Abort if event isn't meant for this component if (!this.eventTargetsComponent(id)) { return; } this.setValidity(valid, error); } }, methods: { validate() { if (!this.validationRules || !this.dirty) { return; } let data = { value: this.value }; let rules = { value: this.validationRules }; let validation = new Validator(data, rules, this.validationMessages); validation.setAttributeNames({ value: this.name.replace(/_/g, ' ') }); this.setValidity(validation.passes(), validation.errors.first('value')); }, setValidity(valid, error) { this.valid = valid; if (!valid && error && error.length) { this.validationError = error; } } } };
import Validator from 'validatorjs'; export default { props: { valid: { type: Boolean, default: true, twoWay: true }, dirty: { type: Boolean, default: false, twoWay: true }, hideValidationErrors: { type: Boolean, default: false }, validationRules: String, validationMessages: Object }, data() { return { validationError: '' }; }, events: { 'ui-input::set-validity': function(valid, error, id) { // Abort if event isn't meant for this component if (!this.eventTargetsComponent(id)) { return; } this.setValidity(valid, error); } }, methods: { validate() { if (!this.validationRules || !this.dirty) { return; } let data = { value: this.value }; let rules = { value: this.validationRules }; let validation = new Validator(data, rules, this.validationMessages); validation.setAttributeNames({ value: this.name.replace(/_/g, ' ') }); this.setValidity(validation.passes(), validation.errors.first('value')); }, setValidity(valid, error) { this.valid = valid; if (!valid && error && error.length) { this.validationError = error; } } } };
Use barbe to render dynamic fields.
"use strict"; const typpy = require("typpy") , iterateObject = require("iterate-object") , barbe = require("barbe") ; /** * Err * Create a custom error object. * * @name Err * @function * @param {String|Error|Object} error The error message or an existing `Error` * instance or the `data` object where the `message` is the error message. * @param {String|Object} code The error code or the data object. * @param {Object} data The data object (its fields will be appended to the * `Error` object). * @return {Error} The custom `Error` instance. */ module.exports = class Err extends Error { constructor (error, code, data) { // Err({ message: "...", code: "...", ... }); if (typpy(error, Object)) { data = error; error = data.message; delete data.message; code = data.code; } // Err(message, code, data); // Err(message, data); if (typpy(data, Object)) { data.code = code; } else if (typpy(code, Object)) { data = code; code = undefined; } else if (!typpy(code, undefined)) { data = { code: code }; } if (typeof error === "string") { error = barbe(error, ["<", ">"], data); } // Create the error super(error); if (data) { iterateObject(data, (v, n) => { this[n] = v; }); } } };
"use strict"; const typpy = require("typpy") , iterateObject = require("iterate-object") ; /** * Err * Create a custom error object. * * @name Err * @function * @param {String|Error|Object} error The error message or an existing `Error` * instance or the `data` object where the `message` is the error message. * @param {String|Object} code The error code or the data object. * @param {Object} data The data object (its fields will be appended to the * `Error` object). * @return {Error} The custom `Error` instance. */ module.exports = class Err extends Error { constructor (error, code, data) { // Err({ message: "...", code: "...", ... }); if (typpy(error, Object)) { data = error; error = data.message; delete data.message; code = data.code; } // Err(message, code, data); // Err(message, data); if (typpy(data, Object)) { data.code = code; } else if (typpy(code, Object)) { data = code; code = undefined; } else if (!typpy(code, undefined)) { data = { code: code }; } // Create the error super(error); if (data) { iterateObject(data, (v, n) => { this[n] = v; }); } } };
Remove recording wait, works better
import io import picamera class Camera(object): def __init__(self): self.camera = picamera.PiCamera() self.camera.resolution = (640, 480) self.camera.rotation = 180 self.camera.led = False self.recording = False self.loopStream = picamera.PiCameraCircularIO(self.camera, seconds=600) def captureStream(self): stream = io.BytesIO() self.camera.capture(stream, format='jpeg', use_video_port=True, resize=(320, 240)) stream.seek(0) return stream def startRecording(self): self.camera.start_recording(self.loopStream, format='h264') self.recording = True def stopRecording(self): self.camera.stop_recording() self.recording = False def writeStream(self, filename): if not self.recording: return with io.open(filename, 'wb') as output: for frame in self.loopStream.frames: if frame.header: self.loopStream.seek(frame.position) break while True: buf = self.loopStream.read1() if not buf: break output.write(buf) self.loopStream.seek(0) self.loopStream.truncate()
import io import picamera class Camera(object): def __init__(self): self.camera = picamera.PiCamera() self.camera.resolution = (800, 600) self.camera.framerate = 30 self.camera.rotation = 180 self.camera.led = False self.recording = False self.loopStream = picamera.PiCameraCircularIO(self.camera, seconds=600) def captureStream(self): if self.recording: self.camera.wait_recording() stream = io.BytesIO() self.camera.capture(stream, format='jpeg', use_video_port=True, resize=(320, 240)) stream.seek(0) return stream def startRecording(self): self.camera.start_recording(self.loopStream, format='h264') self.recording = True def stopRecording(self): self.camera.stop_recording() self.recording = False def writeStream(self, filename): if not self.recording: return with io.open(filename, 'wb') as output: for frame in self.loopStream.frames: if frame.header: self.loopStream.seek(frame.position) break while True: buf = stream.read1() if not buf: break output.write(buf) self.loopStream.seek(0) self.loopStream.truncate()
Add timestamp when none present
<?php /* * This file is part of Raven. * * (c) Sentry Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Raven Breadcrumbs * * @package raven */ class Raven_Breadcrumbs { public function __construct($size = 100) { $this->count = 0; $this->pos = 0; $this->size = $size; $this->buffer = array(); } public function record($crumb) { if (empty($crumb['timestamp'])) { $crumb['timestamp'] = microtime(true); } $this->buffer[$this->pos] = $crumb; $this->pos = ($this->pos + 1) % $this->size; $this->count++; } public function fetch() { $results = array(); for ($i = 0; $i <= ($this->size - 1); $i++) { $node = @$this->buffer[($this->pos + $i) % $this->size]; if (isset($node)) { $results[] = $node; } } return $results; } public function is_empty() { return $this->count === 0; } public function to_json() { return array( 'values' => $this->fetch(), ); } }
<?php /* * This file is part of Raven. * * (c) Sentry Team * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Raven Breadcrumbs * * @package raven */ class Raven_Breadcrumbs { public function __construct($size = 100) { $this->count = 0; $this->pos = 0; $this->size = $size; $this->buffer = array(); } public function record($crumb) { $this->buffer[$this->pos] = $crumb; $this->pos = ($this->pos + 1) % $this->size; $this->count++; } public function fetch() { $results = array(); for ($i = 0; $i <= ($this->size - 1); $i++) { $node = @$this->buffer[($this->pos + $i) % $this->size]; if (isset($node)) { $results[] = $node; } } return $results; } public function is_empty() { return $this->count === 0; } public function to_json() { return array( 'values' => $this->fetch(), ); } }
Fix sessionStorage name to retrieve token.
angular.module('MovnThereUI').factory('AuthFactory', function($http, $window, ServerUrl) { 'use strict'; var login = function(credentials) { return $http .post(ServerUrl + 'login', credentials) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var signup = function(credentials) { var params = { user: credentials }; return $http .post(ServerUrl + 'signup', params) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var logout = function(credentials) { return $http .post(ServerUrl + '/logout') .success(function(response) { $window.sessionStorage.removeItem('movnThereUI.user'); }); }; var isAuthenticated = function() { return !!$window.sessionStorage.getItem('movnThereUI.user'); }; return { login: login, signup: signup, logout: logout, isAuthenticated: isAuthenticated }; });
angular.module('MovnThereUI').factory('AuthFactory', function($http, $window, ServerUrl) { 'use strict'; var login = function(credentials) { return $http .post(ServerUrl + 'login', credentials) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUIUI.user'); }); }; var signup = function(credentials) { var params = { user: credentials }; return $http .post(ServerUrl + 'signup', params) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var logout = function(credentials) { return $http .post(ServerUrl + '/logout') .success(function(response) { $window.sessionStorage.removeItem('movnThereUI.user'); }); }; var isAuthenticated = function() { return !!$window.sessionStorage.getItem('movnThereUI.user'); }; return { login: login, signup: signup, logout: logout, isAuthenticated: isAuthenticated }; });
Change Widget tag on SimultaneousAxes to TEXTINPUT
from annotypes import Anno, Array, Union, Sequence, add_call_types from malcolm.core import Part, StringArrayMeta, Widget, config_tag, \ PartRegistrar, APartName from ..hooks import ValidateHook, AAxesToMove with Anno("Initial value for set of axes that can be moved at the same time"): ASimultaneousAxes = Array[str] USimultaneousAxes = Union[ASimultaneousAxes, Sequence[str], str] class SimultaneousAxesPart(Part): def __init__(self, name="simultaneousAxes", value=None): # type: (APartName, USimultaneousAxes) -> None super(SimultaneousAxesPart, self).__init__(name) self.attr = StringArrayMeta( "Set of axes that can be specified in axesToMove at configure", tags=[Widget.TEXTINPUT.tag(), config_tag()] ).create_attribute_model(value) # Hooks self.register_hooked(ValidateHook, self.validate) # This will be serialized, so maintain camelCase for axesToMove # noinspection PyPep8Naming @add_call_types def validate(self, axesToMove): # type: (AAxesToMove) -> None assert not set(axesToMove) - set(self.attr.value), \ "Can only move %s simultaneously, requested %s" % ( list(self.attr.value), axesToMove) def setup(self, registrar): # type: (PartRegistrar) -> None registrar.add_attribute_model( "simultaneousAxes", self.attr, self.attr.set_value)
from annotypes import Anno, Array, Union, Sequence, add_call_types from malcolm.core import Part, StringArrayMeta, Widget, config_tag, \ PartRegistrar, APartName from ..hooks import ValidateHook, AAxesToMove with Anno("Initial value for set of axes that can be moved at the same time"): ASimultaneousAxes = Array[str] USimultaneousAxes = Union[ASimultaneousAxes, Sequence[str], str] class SimultaneousAxesPart(Part): def __init__(self, name="simultaneousAxes", value=None): # type: (APartName, USimultaneousAxes) -> None super(SimultaneousAxesPart, self).__init__(name) self.attr = StringArrayMeta( "Set of axes that can be specified in axesToMove at configure", tags=[Widget.TABLE.tag(), config_tag()] ).create_attribute_model(value) # Hooks self.register_hooked(ValidateHook, self.validate) # This will be serialized, so maintain camelCase for axesToMove # noinspection PyPep8Naming @add_call_types def validate(self, axesToMove): # type: (AAxesToMove) -> None assert not set(axesToMove) - set(self.attr.value), \ "Can only move %s simultaneously, requested %s" % ( list(self.attr.value), axesToMove) def setup(self, registrar): # type: (PartRegistrar) -> None registrar.add_attribute_model( "simultaneousAxes", self.attr, self.attr.set_value)
Fix swapped dates on invoices
from django.core.management import BaseCommand from spiff.membership.utils import monthRange from spiff.membership.models import Member, RankLineItem from spiff.payment.models import Invoice class Command(BaseCommand): help = 'Bills active members for the month' def handle(self, *args, **options): for member in Member.objects.all(): if not member.billedForMonth(): if member.highestRank is not None and member.highestRank.monthlyDues > 0: print "Billing", member, "for the month" startOfMonth, endOfMonth = monthRange() invoice = Invoice.objects.create( user=member.user, dueDate=endOfMonth, ) for group in member.user.groups.all(): if group.rank.monthlyDues > 0: lineItem = RankLineItem.objects.create( rank = group.rank, member = member, activeFromDate=startOfMonth, activeToDate=endOfMonth, invoice=invoice ) print "\tCreated", lineItem invoice.draft = False invoice.open = True invoice.save() print "\tInvoice saved!" else: print "%s has outstanding balance of $%s"%( member, member.outstandingBalance )
from django.core.management import BaseCommand from spiff.membership.utils import monthRange from spiff.membership.models import Member, RankLineItem from spiff.payment.models import Invoice class Command(BaseCommand): help = 'Bills active members for the month' def handle(self, *args, **options): for member in Member.objects.all(): if not member.billedForMonth(): if member.highestRank is not None and member.highestRank.monthlyDues > 0: print "Billing", member, "for the month" endOfMonth, startOfMonth = monthRange() invoice = Invoice.objects.create( user=member.user, dueDate=endOfMonth, ) for group in member.user.groups.all(): if group.rank.monthlyDues > 0: lineItem = RankLineItem.objects.create( rank = group.rank, member = member, activeFromDate=startOfMonth, activeToDate=endOfMonth, invoice=invoice ) print "\tCreated", lineItem invoice.draft = False invoice.open = True invoice.save() print "\tInvoice saved!" else: print "%s has outstanding balance of $%s"%( member, member.outstandingBalance )
Make it clear that the user must implement generate_from_int
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class CheckDigitNumber: def __init__ (self, number = None): self.__set_number(number) def generate_from_int (self, n): raise NotImplementedError def get_check_digit (self): if self: return self.generate_from_int(self.number) else: return None def has_valid_check_digit (self): if self: digit = self.number % 10 static = self.number // 10 return digit == self.generate_from_int(static) else: return False def __bool__ (self): return self.number is not None def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.number)) def __set_number (self, number): if isinstance(number, int): self.number = number elif isinstance(number, str): self.__try_to_extract_number_from_str(number) else: self.number = None def __try_to_extract_number_from_str (self, number): try: self.number = int(number) except ValueError: self.number = None
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class CheckDigitNumber: def __init__ (self, number = None): self.__set_number(number) def get_check_digit (self): if self: return self.generate_from_int(self.number) else: return None def has_valid_check_digit (self): if self: digit = self.number % 10 static = self.number // 10 return digit == self.generate_from_int(static) else: return False def __bool__ (self): return self.number is not None def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.number)) def __set_number (self, number): if isinstance(number, int): self.number = number elif isinstance(number, str): self.__try_to_extract_number_from_str(number) else: self.number = None def __try_to_extract_number_from_str (self, number): try: self.number = int(number) except ValueError: self.number = None
examples: Update to use v_normals for color
FamousFramework.scene('famous-tests:webgl:custom-shader:fragment', { behaviors: { '.sphere': { 'size': [200, 200], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'base-color': { 'name': 'sphereFragment', 'glsl': 'vec4((v_normal + 1.0) * 0.5, 1.0);', 'output': 4, }, 'geometry': { 'shape': 'GeodesicSphere', 'options': { 'detail': 3 } } }, '.light': { 'size': [200, 200], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'position-z': 500, 'light': { 'type': 'point', 'color': 'white' } }, '.background': { 'size': [undefined, undefined], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'geometry': { 'shape': 'Plane' } } }, events: {}, states: {}, tree: ` <node class="background"></node> <node class="sphere"></node> <node class="light"></node> ` });
FamousFramework.scene('famous-tests:webgl:custom-shader:fragment', { behaviors: { '.sphere': { 'size': [200, 200], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'base-color': { 'name': 'sphereFragment', 'glsl': 'vec4(0.0, 1.0, 1.0, 1.0);', 'output': 4, }, 'geometry': { 'shape': 'GeodesicSphere', 'options': { 'detail': 3 } } }, '.light': { 'size': [200, 200], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'position-z': 50, 'light': { 'type': 'point', 'color': 'white' } }, '.background': { 'size': [undefined, undefined], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'geometry': { 'shape': 'Plane' } } }, events: {}, states: {}, tree: ` <node class="background"></node> <node class="sphere"></node> <node class="light"></node> ` });
Fix command to show parse logs and tail output
// Requires var _ = require('underscore'); function setup(options, imports, register) { var deploy = imports.deploy; var shells = imports.shells; /* Documentation about parse command lien tool can be found at: https://parse.com/docs/cloud_code_guide */ deploy.add({ id: "parse", name: "Parse", settings: { app: { label: "Application", type: "text", help: "(optional) Name of your Parse Cloud Code application." } }, actions: [ { id: "deploy", name: "Deploy", action: function(config) { var shellId = "parse:deploy"; return shells.createShellCommand( shellId, ["parse", "deploy", config.app] ).then(function(shell) { return { 'shellId': shellId }; }); } }, { id: "logs", name: "Show Logs", action: function(config) { var shellId = "parse:logs"; return shells.createShellCommand( shellId, ["parse", "log", config.app, "-f"] ).then(function(shell) { return { 'shellId': shellId, 'title': "Parse Logs" }; }); } } ] }); // Register register(null, {}); } // Exports module.exports = setup;
// Requires var _ = require('underscore'); function setup(options, imports, register) { var deploy = imports.deploy; var shells = imports.shells; /* Documentation about parse command lien tool can be found at: https://parse.com/docs/cloud_code_guide */ deploy.add({ id: "parse", name: "Parse", settings: { app: { label: "Application", type: "text", help: "(optional) Name of your Parse Cloud Code application." } }, actions: [ { id: "deploy", name: "Deploy", action: function(config) { var shellId = "parse:deploy"; return shells.createShellCommand( shellId, ["parse", "deploy", config.app] ).then(function(shell) { return { 'shellId': shellId }; }); } }, { id: "logs", name: "Show Logs", action: function(config) { var shellId = "parse:logs"; return shells.createShellCommand( shellId, ["parse", "logs", config.app] ).then(function(shell) { return { 'shellId': shellId, 'title': "Parse Logs" }; }); } } ] }); // Register register(null, {}); } // Exports module.exports = setup;
Remove nullable() from wifi migration
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Wifi extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('wifi', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number')->unique(); $table->integer('agrctlrssi'); $table->integer('agrextrssi'); $table->integer('agrctlnoise'); $table->integer('agrextnoise'); $table->string('state'); $table->string('op_mode'); $table->integer('lasttxrate'); $table->string('lastassocstatus'); $table->integer('maxrate'); $table->string('x802_11_auth'); $table->string('link_auth'); $table->string('bssid'); $table->string('ssid'); $table->integer('mcs'); $table->string('channel'); $table->index('bssid'); $table->index('ssid'); $table->index('state'); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('wifi'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Wifi extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('wifi', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number')->unique()->nullable(); $table->integer('agrctlrssi')->nullable(); $table->integer('agrextrssi')->nullable(); $table->integer('agrctlnoise')->nullable(); $table->integer('agrextnoise')->nullable(); $table->string('state')->nullable(); $table->string('op_mode')->nullable(); $table->integer('lasttxrate')->nullable(); $table->string('lastassocstatus')->nullable(); $table->integer('maxrate')->nullable(); $table->string('x802_11_auth')->nullable(); $table->string('link_auth')->nullable(); $table->string('bssid')->nullable(); $table->string('ssid')->nullable(); $table->integer('mcs')->nullable(); $table->string('channel')->nullable(); // $table->timestamps(); $table->index('bssid'); $table->index('ssid'); $table->index('state'); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('wifi'); } }
Use repr for assert failure
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %r != %r after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
Clean up the model a bit
var Q = require('Q'); var request = Q.denodeify(require('request')); var _ = require('underscore'); function CampaignModel(name) { // @todo Can probably clean this up? _.bindAll.apply(_, [this].concat(_.functions(this))); this.name = name; this._request = null; } CampaignModel.get = function(name) { return new CampaignModel(name); }; _.extend(CampaignModel.prototype, { _getRequestUrl: function() { return 'http://my.charitywater.org/' + this.name; }, _getRequest: function() { if (!this.name || typeof this.name !== 'string') { return Q.reject(new Error('Empty campaign name')); } if (!this._request) { var url = this._getRequestUrl(); this._request = request(url).then(function(arr) { if (Math.floor(arr[0].statusCode / 100) !== 2) { throw new Error('Invalid campaign name'); } return arr[0]; }); } return this._request; }, _getBody: function() { if (!this._body) { this._body = this._getRequest().then(function(req) { return req.body; }); } return this._body; }, id: function() { return this._getBody().then(function(body) { return Number(body.match(/campaign_id\s*=\s*(\d+)/)[1]); }); } }); module.exports = CampaignModel;
var Q = require('Q'); var request = Q.denodeify(require('request')); var _ = require('underscore'); function CampaignModel(name) { // @todo Can probably clean this up? _.bindAll.apply(_, [this].concat(_.functions(this))); this.name = name; this._request = null; } CampaignModel.get = function(name) { return new CampaignModel(name); }; _.extend(CampaignModel.prototype, { _getRequestUrl: function() { return 'http://my.charitywater.org/' + this.name; }, _getRequest: function _getRequest() { if (!this.name || typeof this.name !== 'string') { return Q.reject(new Error('Empty campaign name')); } if (!this._request) { var url = this._getRequestUrl(); this._request = request(url).then(function _getRequestInner(arr) { if (Math.floor(arr[0].statusCode / 100) !== 2) { throw new Error('Invalid campaign name'); } return arr[0]; }); } return this._request; }, _getBody: function _getBody() { if (!this._body) { this._body = this._getRequest().then(function _getBodyInner(req) { return req.body; }); } return this._body; }, id: function() { return this._getBody().then(function(body) { return Number(body.match(/campaign_id\s*=\s*(\d+)/)[1]); }); } }); module.exports = CampaignModel;
Return null on parse errors as per specification; Do not throw Exception
package org.crygier.graphql; import java.math.BigInteger; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import graphql.language.IntValue; import graphql.language.StringValue; import graphql.schema.Coercing; import graphql.schema.GraphQLScalarType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JavaScalars { static final Logger log = LoggerFactory.getLogger(JavaScalars.class); public static GraphQLScalarType GraphQLDate = new GraphQLScalarType("Date", "Date type", new Coercing() { @Override public Object serialize(Object input) { if (input instanceof String) { return parseStringToDate((String) input); } else if (input instanceof Date) { return input; } else if (input instanceof Long) { return new Date(((Long) input).longValue()); } else if (input instanceof Integer) { return new Date(((Integer) input).longValue()); } return null; } @Override public Object parseValue(Object input) { return serialize(input); } @Override public Object parseLiteral(Object input) { if (input instanceof StringValue) { return parseStringToDate(((StringValue) input).getValue()); } else if (input instanceof IntValue) { BigInteger value = ((IntValue) input).getValue(); return new Date(value.longValue()); } return null; } private Date parseStringToDate(String input) { try { return DateFormat.getInstance().parse(input); } catch (ParseException e) { log.warn("Failed to parse Date from input: " + input, e); return null; } } }); }
package org.crygier.graphql; import java.math.BigInteger; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import graphql.language.IntValue; import graphql.language.StringValue; import graphql.schema.Coercing; import graphql.schema.GraphQLScalarType; public class JavaScalars { public static GraphQLScalarType GraphQLDate = new GraphQLScalarType("Date", "Date type", new Coercing() { @Override public Object serialize(Object input) { if (input instanceof String) { try { return DateFormat.getInstance().parse((String)input); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } } else if (input instanceof Date) { return input; } else if (input instanceof Long) { return new Date(((Long) input)); } else if (input instanceof Integer) { return new Date(((Integer) input).longValue()); } else { return null; } } @Override public Object parseValue(Object input) { return serialize(input); } @Override public Object parseLiteral(Object input) { if (input instanceof StringValue) { try { return DateFormat.getInstance().parse(((StringValue) input).getValue()); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } } else if (input instanceof IntValue) { BigInteger value = ((IntValue) input).getValue(); return new Date(value.longValue()); } return null; } }); }
Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.
""" Summary Footnotes ------------- Fix handling of footnote links inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
""" Summary Footnotes ------------- Fix handling of footnotes inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes)
Handle protocol errors and disconnect client
<?php namespace Clue\Redis\React; use Evenement\EventEmitter; use React\Stream\Stream; use Clue\Redis\Protocol\ProtocolInterface; use Clue\Redis\Protocol\ParserException; use React\Promise\Deferred; class Client extends EventEmitter { private $stream; private $protocol; public function __construct(Stream $stream, ProtocolInterface $protocol) { $that = $this; $stream->on('data', function($chunk) use ($protocol, $that) { try { $protocol->pushIncoming($chunk); } catch (ParserException $error) { $that->emit('error', array($error)); $that->close(); return; } while ($protocol->hasIncoming()) { $that->emit('message', array($protocol->popIncoming(), $that)); } }); $stream->on('close', function () use ($that) { $that->close(); }); $stream->resume(); $this->stream = $stream; $this->protocol = $protocol; } public function __call($name, $args) { /* Build the Redis unified protocol command */ array_unshift($args, strtoupper($name)); $this->stream->write($this->protocol->createMessage($args)); return new Deferred(); } public function end() { $this->stream->end(); } public function close() { $this->stream->close(); } }
<?php namespace Clue\Redis\React; use Evenement\EventEmitter; use React\Stream\Stream; use Clue\Redis\Protocol\ProtocolInterface; use React\Promise\Deferred; class Client extends EventEmitter { private $stream; private $protocol; public function __construct(Stream $stream, ProtocolInterface $protocol) { $that = $this; $stream->on('data', function($chunk) use ($protocol, $that) { $protocol->pushIncoming($chunk); while ($protocol->hasIncoming()) { $that->emit('message', array($protocol->popIncoming(), $that)); } }); $stream->on('close', function () use ($that) { $that->close(); }); $stream->resume(); $this->stream = $stream; $this->protocol = $protocol; } public function __call($name, $args) { /* Build the Redis unified protocol command */ array_unshift($args, strtoupper($name)); $this->stream->write($this->protocol->createMessage($args)); return new Deferred(); } public function end() { $this->stream->end(); } public function close() { $this->stream->close(); } }
Add return type declaration (TreeBuilder)
<?php /** * User: Simon Libaud * Date: 12/03/2017 * Email: [email protected]. */ namespace Sil\RouteSecurityBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Class Configuration. */ class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder(): TreeBuilder { $tree = new TreeBuilder('sil_route_security'); // Keep compatibility with symfony/config < 4.2 if (false === method_exists($tree, 'getRootNode')) { $root = $tree->root('sil_route_security'); } else { $root = $tree->getRootNode(); } $root ->children() ->booleanNode('enable_access_control')->defaultFalse()->end() ->scalarNode('secured_routes_format')->defaultNull()->end() ->scalarNode('ignored_routes_format')->defaultNull()->end() ->arrayNode('ignored_routes')->prototype('scalar')->end()->end() ->arrayNode('secured_routes')->prototype('scalar')->end()->end() ->scalarNode('naming_strategy')->defaultNull()->end() ; return $tree; } }
<?php /** * User: Simon Libaud * Date: 12/03/2017 * Email: [email protected]. */ namespace Sil\RouteSecurityBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Class Configuration. */ class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $tree = new TreeBuilder('sil_route_security'); // Keep compatibility with symfony/config < 4.2 if (false === method_exists($tree, 'getRootNode')) { $root = $tree->root('sil_route_security'); } else { $root = $tree->getRootNode(); } $root ->children() ->booleanNode('enable_access_control')->defaultFalse()->end() ->scalarNode('secured_routes_format')->defaultNull()->end() ->scalarNode('ignored_routes_format')->defaultNull()->end() ->arrayNode('ignored_routes')->prototype('scalar')->end()->end() ->arrayNode('secured_routes')->prototype('scalar')->end()->end() ->scalarNode('naming_strategy')->defaultNull()->end() ; return $tree; } }
Deal with exceptions more cleanly.
"use strict"; var t0 = Date.now(); var express = require("express"), xhub = require('express-x-hub'); if (process.env.NODE_ENV === "dev") { // Load local env variables require("./env"); } function logArgs() { var args = arguments; process.nextTick(function() { console.log.apply(console, args); }); } var app = express(); app.use(xhub({ algorithm: 'sha1', secret: process.env.GITHUB_SECRET })); app.post('/github-hook', function (req, res, next) { if (process.env.NODE_ENV != 'production' || req.isXHubValid()) { res.send(new Date().toISOString()); var payload = req.body; switch(payload.action) { case "opened": case "edited": case "reopened": case "synchronize": require("./lib/comment")(payload.pull_request).then(logArgs, logArgs); break; default: logArgs("Unknown request", JSON.stringify(payload, null, 4)); } } else { logArgs("Unverified request", req); } next(); }); var port = process.env.PORT || 5000; app.listen(port, function() { console.log("Express server listening on port %d in %s mode", port, app.settings.env); console.log("App started in", (Date.now() - t0) + "ms."); });
"use strict"; var t0 = Date.now(); var express = require("express"), xhub = require('express-x-hub'); if (process.env.NODE_ENV === "dev") { // Load local env variables require("./env"); } function logArgs() { var args = arguments; process.nextTick(function() { console.log.apply(console, args); }); } var app = express(); app.use(xhub({ algorithm: 'sha1', secret: process.env.GITHUB_SECRET })); app.post('/github-hook', function (req, res, next) { if (process.env.NODE_ENV != 'production' || req.isXHubValid()) { res.send(new Date().toISOString()); var payload = req.body; switch(payload.action) { case "opened": case "edited": case "reopened": case "synchronize": require("./lib/comment")(payload.pull_request).then(logArgs, logArgs); break; default: logArgs("Unused request", payload.action, payload.pull_request.base.repo.full_name, payload.number); } } else { logArgs("Unverified request", req); } next(); }); var port = process.env.PORT || 5000; app.listen(port, function() { console.log("Express server listening on port %d in %s mode", port, app.settings.env); console.log("App started in", (Date.now() - t0) + "ms."); });
Remove use of mocks since we can use functions on their own now
<?php namespace Lily\Test\Application; use Lily\Application\MiddlewareApplication; use Lily\Util\Response; class MiddlewareApplicationTest extends \PHPUnit_Framework_TestCase { public function testMiddlewareOrder() { $expectedCalledOrder = array(1, 2, 3); $calledOrder = array(); $handler = new MiddlewareApplication(array( function ($request) use (& $calledOrder) { $calledOrder[] = 3; return Response::ok(); }, function ($handler) use (& $calledOrder) { return function ($request) use ($handler, & $calledOrder) { $calledOrder[] = 2; return $handler($request); }; }, function ($handler) use (& $calledOrder) { return function ($request) use ($handler, & $calledOrder) { $calledOrder[] = 1; return $handler($request); }; }, )); $handler(array()); $this->assertSame($expectedCalledOrder, $calledOrder); } public function testWithoutMiddleware() { $called = FALSE; $handler = new MiddlewareApplication(array( function () use (& $called) { $called = TRUE; }, )); $handler(array()); $this->assertTrue($called); } }
<?php namespace Lily\Test\Application; use Lily\Application\MiddlewareApplication; use Lily\Mock\Application; use Lily\Mock\Middleware; class MiddlewareApplicationTest extends \PHPUnit_Framework_TestCase { public function testMiddlewareOrder() { $expectedCalledOrder = array(1, 2, 3); $calledOrder = array(); $handler = new MiddlewareApplication(array( new Application(function () use (& $calledOrder) { $calledOrder[] = 3; }), new Middleware(function () use (& $calledOrder) { $calledOrder[] = 2; }), new Middleware(function () use (& $calledOrder) { $calledOrder[] = 1; }), )); $handler(array()); $this->assertSame($expectedCalledOrder, $calledOrder); } public function testWithoutMiddleware() { $called = FALSE; $handler = new MiddlewareApplication(array( new Application(function () use (& $called) { $called = TRUE; }), )); $handler(array()); $this->assertTrue($called); } }
Add rarely, mostly and other alias
import random in_percentage = lambda x: random.randint(1,100) <= x """ They've done studies, you know. 50% of the time, it works every time. """ def sometimes(fn): def wrapped(*args, **kwargs): wrapped.x += 1 if wrapped.x % 2 == 1: return fn(*args, **kwargs) wrapped.x = 0 return wrapped half_the_time = sometimes """ Has a 50/50 chance of calling a function """ def sometimesish(fn): def wrapped(*args, **kwargs): if random.randint(1,2) == 1: return fn(*args, **kwargs) return wrapped """ Function has a X percentage chance of running """ def percent_of_the_time(p): def decorator(fn): def wrapped(*args, **kwargs): if in_percentage(p): fn(*args, **kwargs) return wrapped return decorator """ Only 5% chance of happening """ def rarely(fn): def wrapped(*args, **kwargs): if in_percentage(5): fn(*args, **kwargs) return wrapped """ 95% chance of happening """ def mostly(fn): def wrapped(*args, **kwargs): if in_percentage(95): fn(*args, **kwargs) return wrapped """ Do something a random amount of times between x & y """ def times(x,y): def decorator(fn): def wrapped(*args, **kwargs): while wrapped.min <= wrapped.max: wrapped.min += 1 fn(*args, **kwargs) wrapped.min = x wrapped.max = random.randint(x,y) return wrapped return decorator
import random in_percentage = lambda x: random.randint(1,100) <= x """ They've done studies, you know. 50% of the time, it works every time. """ def sometimes(fn): def wrapped(*args, **kwargs): wrapped.x += 1 if wrapped.x % 2 == 1: return fn(*args, **kwargs) return wrapped.x = 0 return wrapped """ Has a 50/50 chance of calling a function """ def sometimesish(fn): def wrapped(*args, **kwargs): if random.randint(1,2) == 1: return fn(*args, **kwargs) return return wrapped """ Function has a X percentage chance of running """ def percent_of_the_time(p): def decorator(fn): def wrapped(*args, **kwargs): if in_percentage(p): fn(*args, **kwargs) return return wrapped return decorator """ Do something a random amount of times between x & y """ def times(x,y): def decorator(fn): def wrapped(*args, **kwargs): while wrapped.min <= wrapped.max: wrapped.min += 1 fn(*args, **kwargs) return wrapped.min = x wrapped.max = random.randint(x,y) return wrapped return decorator
PIG-4268: Enable unit test "TestStreamingUDF" in spark (liyunzhang via praveen) git-svn-id: d317905e1b1233abb7022f5914f79c3119e04b87@1645891 13f79535-47bb-0310-9956-ffa450edef68
package org.apache.pig.test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.pig.ExecType; import org.apache.pig.backend.hadoop.executionengine.spark.SparkExecType; public class SparkMiniCluster extends MiniGenericCluster { private static final File CONF_DIR = new File("build/classes"); private static final File CONF_FILE = new File(CONF_DIR, "hadoop-site.xml"); private ExecType spark = new SparkExecType(); SparkMiniCluster() { } @Override public ExecType getExecType() { return spark; } @Override protected void setupMiniDfsAndMrClusters() { try { CONF_DIR.mkdirs(); if (CONF_FILE.exists()) { CONF_FILE.delete(); } m_conf = new Configuration(); m_conf.set("io.sort.mb", "1"); m_conf.writeXml(new FileOutputStream(CONF_FILE)); int dataNodes = 4; m_dfs = new MiniDFSCluster(m_conf, dataNodes, true, null); m_fileSys = m_dfs.getFileSystem(); m_fileSys.mkdirs(m_fileSys.getWorkingDirectory()); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void shutdownMiniMrClusters() { if (CONF_FILE.exists()) { CONF_FILE.delete(); } } }
package org.apache.pig.test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.pig.ExecType; import org.apache.pig.backend.hadoop.executionengine.spark.SparkExecType; public class SparkMiniCluster extends MiniGenericCluster { private static final File CONF_DIR = new File("build/classes"); private static final File CONF_FILE = new File(CONF_DIR, "hadoop-site.xml"); private ExecType spark = new SparkExecType(); SparkMiniCluster() { } @Override public ExecType getExecType() { return spark; } @Override protected void setupMiniDfsAndMrClusters() { try { CONF_DIR.mkdirs(); if (CONF_FILE.exists()) { CONF_FILE.delete(); } m_conf = new Configuration(); m_conf.set("io.sort.mb", "1"); m_conf.writeXml(new FileOutputStream(CONF_FILE)); int dataNodes = 4; m_dfs = new MiniDFSCluster(m_conf, dataNodes, true, null); m_fileSys = m_dfs.getFileSystem(); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void shutdownMiniMrClusters() { if (CONF_FILE.exists()) { CONF_FILE.delete(); } } }
Use template for postlinks to allow easy changes
<?php /** * Default template for displaying post content * * @package ZnWP Bootstrap Theme */ global $znwp_theme; ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="post-title"> <?php if (is_single()): ?> <?php the_title(); ?> <?php else: ?> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endif; ?> </h1> <time><span class="glyphicon glyphicon-time"></span> <?php the_date(); ?></time> <hr class="title-divider" /> <?php if (is_single()): ?> <?php the_content(); get_template_part('postlinks'); ?> <?php else: ?> <?php the_excerpt(); ?> <?php endif; ?> </article>
<?php /** * Default template for displaying post content * * @package ZnWP Bootstrap Theme */ global $znwp_theme; ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="post-title"> <?php if (is_single()): ?> <?php the_title(); ?> <?php else: ?> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endif; ?> </h1> <time><span class="glyphicon glyphicon-time"></span> <?php the_date(); ?></time> <hr class="title-divider" /> <?php if (is_single()): ?> <?php the_content(); ?> <br /> <div class="post-links"> <?php previous_post_link( '<div class="link-block post-prev">%link</div>', '<span class="glyphicon glyphicon-chevron-left"></span> %title' ); next_post_link( '<div class="link-block post-next">%link</div>', '%title <span class="glyphicon glyphicon-chevron-right"></span>' ); ?> </div> <?php else: ?> <?php the_excerpt(); ?> <?php endif; ?> </article>
Define the public methods in the private space
var Gificiency = (function() { 'use strict'; var searchField = $('.search'), items = $('li'), links = $('a'); var search = function(filter) { links.each(function() { var elem = $(this); if (elem.text().search( new RegExp(filter, 'i') ) < 0) { elem.hide(); } else { elem.show(); } }); }; var getHash = function() { var filter; if (window.location.hash != '') { filter = window.location.hash.substring(1); } else { filter = false; } return filter; }; var clearImages = function() { $('img').each(function() { $(this).remove(); }); }; var popup = function(image) { return $('<img src="'+ image +'" />'); }; var init = function() { if ( getHash() ) { search( getHash() ); } events(); }; var events = function() { searchField.on('keyup', function() { search( $(this).val() ); }); items.on('mouseover', function() { var elem = $(this).find('a'), image = elem.attr('href'); elem.parent().append( popup(image) ); }).on('mouseout', function() { clearImages(); }); }; var Gificiency = { init: init, events: events }; return Gificiency; })();
var Gificiency = (function() { 'use strict'; var searchField = $('.search'); var items = $('li'); var links = $('a'); var search = function(filter) { links.each(function() { var elem = $(this); if (elem.text().search( new RegExp(filter, 'i') ) < 0) { elem.hide(); } else { elem.show(); } }); }; var getHash = function() { var filter; if (window.location.hash != '') { filter = window.location.hash.substring(1); } else { filter = false; } return filter; }; var clearImages = function() { $('img').each(function() { $(this).remove(); }); }; var popup = function(image) { return $('<img src="'+ image +'" />'); }; var Gificiency = { init: function() { if ( getHash() ) { search( getHash() ); } Gificiency.events(); }, events: function() { searchField.on('keyup', function() { search( $(this).val() ); }); items.on('mouseover', function() { var elem = $(this).find('a'), image = elem.attr('href'); elem.parent().append( popup(image) ); }).on('mouseout', function() { clearImages(); }); } }; return Gificiency; })();
Rewrite to use mousewheel functions for detecting scroll direction, turning scroll on/off
var direction; $(function(){ $('body').css('overflow', 'hidden'); $(document).on('mousewheel DOMMouseScroll MozMousePixelScroll', scrollFunctions); }); $(window).load(function(){ $(window).scrollTop(0); }); function scrollFunctions() { getScrollDirection(); scrollOnScroll(); } function scrollOnScroll() { if ( direction != undefined ) { var activeScrollSection = $('.scroll-target.active'); if ( !activeScrollSection.hasClass('animating') ) { if ( direction == 'down' ) { var scrollTarget = activeScrollSection.next('.scroll-target'); } else { var scrollTarget = activeScrollSection.prev('.scroll-target'); } if ( scrollTarget.length != 0 ) { var scrollTargetTop = scrollTarget.offset().top; } console.log("Not animating"); console.log("Target: " + scrollTarget.text()); activeScrollSection.addClass('animating'); $('html, body').animate({ scrollTop: scrollTargetTop}, 1400, function() { scrollTarget.addClass('active'); activeScrollSection.removeClass('active').removeClass('animating'); $(document).off('mousewheel DOMMouseScroll MozMousePixelScroll', scrollFunctions); setTimeout(function(){ $(document).on('mousewheel DOMMouseScroll MozMousePixelScroll', scrollFunctions); }, 500); }); } } } function getScrollDirection() { $('body').bind('mousewheel', function(e){ if(e.originalEvent.wheelDelta / 120 > 0) { direction = 'up'; } else{ direction = 'down'; } }); } function preventScroll(event) { event.preventDefault(); }
var lastScrollTop; $(function(){ var direction = 'down'; lastScrollTop = 0; $(window).on('scroll', scrollOnScroll); }); function scrollOnScroll() { var windowTop = $(window).scrollTop(); var activeScrollSection = $('.scroll-target.active'); var scrollTarget = activeScrollSection.next('.scroll-target'); if ( scrollTarget.length != 0 ) { var scrollTargetTop = scrollTarget.offset().top; } direction = getScrollDirection(); if ( !activeScrollSection.hasClass('animating') ) { $(window).off('scroll', scrollOnScroll); if ( windowTop < scrollTargetTop && direction == 'down' ) { activeScrollSection.addClass('animating'); $('html, body').stop().animate({ scrollTop: scrollTargetTop}, 1000, function() { scrollTarget.addClass('active'); activeScrollSection.removeClass('active').removeClass('animating'); // Clear/wait for residual scroll functions $(window).clearQueue(); setTimeout(function(){ $(window).on('scroll', scrollOnScroll); }, 100); }); } } } function getScrollDirection() { var currentScrollTop = $(this).scrollTop(); var direction; if ( currentScrollTop > lastScrollTop ) { direction = 'down'; } else { direction = 'up'; } lastScrollTop = currentScrollTop; return direction; }
[Codeception] Move mailer hack to `loadApp` method to ensure it's always applied.
<?php namespace Codeception\Module; use Codeception\TestInterface; use Symfony\Component\BrowserKit\CookieJar; use Symfony\Component\HttpKernel\Client; /** * Change client to follow redirects and keep cookie jar between tests. * * @author Carson Full <[email protected]> */ class WorkingSilex extends Silex { /** @var CookieJar */ protected $cookieJar; public function _initialize() { $this->cookieJar = new CookieJar(); parent::_initialize(); } public function _before(TestInterface $test) { $this->reloadApp(); } protected function loadApp() { parent::loadApp(); $this->app->finish(function () { if ($this->app['mailer.initialized'] && $this->app['swiftmailer.use_spool'] && $this->app['swiftmailer.spooltransport'] instanceof \Swift_Transport_SpoolTransport) { $spool = $this->app['swiftmailer.spooltransport']->getSpool(); $r = new \ReflectionClass($spool); $p = $r->getProperty('messages'); $p->setAccessible(true); $p->setValue($spool, []); } }, 512); } public function reloadApp() { $this->loadApp(); $this->client = new Client($this->app, [], null, $this->cookieJar); $this->client->followRedirects(); } }
<?php namespace Codeception\Module; use Codeception\TestInterface; use Symfony\Component\BrowserKit\CookieJar; use Symfony\Component\HttpKernel\Client; /** * Change client to follow redirects and keep cookie jar between tests. * * @author Carson Full <[email protected]> */ class WorkingSilex extends Silex { /** @var CookieJar */ protected $cookieJar; public function _initialize() { $this->cookieJar = new CookieJar(); parent::_initialize(); } public function _before(TestInterface $test) { $this->reloadApp(); $this->app->finish(function () { if ($this->app['mailer.initialized'] && $this->app['swiftmailer.use_spool'] && $this->app['swiftmailer.spooltransport'] instanceof \Swift_Transport_SpoolTransport) { $spool = $this->app['swiftmailer.spooltransport']->getSpool(); $r = new \ReflectionClass($spool); $p = $r->getProperty('messages'); $p->setAccessible(true); $p->setValue($spool, []); } }, 512); } public function reloadApp() { $this->loadApp(); $this->client = new Client($this->app, [], null, $this->cookieJar); $this->client->followRedirects(); } }
Add metadata and resource distinction in DataManager
import logging from collections import OrderedDict from egpackager.datasources import GspreadDataSource, RasterDataSource class DataManager(object): def __init__(self, debug=False): # Set up logging if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger(__name__) self.logger.debug("Initializing new registry manager") self._data = OrderedDict() def add_datasource(self, *args, **kwargs): if 'type' not in kwargs: raise TypeError("Missing require keyword argument: 'type") if kwargs['type'] == 'gspread': # Remove keyword argument 'type' as it us not needed anymore del kwargs['type'] self.logger.debug('Adding Google Sheets data source') self._data['metadata'] = GspreadDataSource(*args, **kwargs) elif kwargs['type'] == 'raster': del kwargs['type'] self.logger.debug('Adding raster data source') self._data['resource'] = RasterDataSource(*args, **kwargs) else: raise TypeError("Unknown data source type: {0}".format(kwargs['type'])) self._data['uri'] = kwargs['uri'] @property def data(self): return self._data def get_metadata_value(self, key, value): return self.data['metadata'].get_value(key, value) def get_resource_value(self, key, value): return self.data['resource'].get_value(key, value) @property def metadata(self): return self.data['metadata'].data @property def resource_metadata(self): return self.data['resource'].data
import logging from collections import OrderedDict from egpackager.datasources import GspreadDataSource, RasterDataSource class DataManager(object): def __init__(self, debug=False): # Set up logging if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger(__name__) self.logger.debug("Initializing new registry manager") self._data = OrderedDict() def add_datasource(self, *args, **kwargs): if 'type' not in kwargs: raise TypeError("Missing require keyword argument: 'type") if kwargs['type'] == 'gspread': # Remove keyword argument 'type' as it us not needed anymore del kwargs['type'] self.logger.debug('Adding Google Sheets data source') self._data[kwargs['uri']] = GspreadDataSource(*args, **kwargs) elif kwargs['type'] == 'raster': del kwargs['type'] self.logger.debug('Adding raster data source') self._data[kwargs['uri']] = RasterDataSource(*args, **kwargs) else: raise TypeError("Unknown data source type: {0}".format(kwargs['type'])) @property def data(self): return self._data
:new: Add forecast dimensions to the dashboard
'use strict'; angular .module('report-editor') .config(function ($stateProvider) { $stateProvider .state('dashboard.concepts.concept', { url: '/:concepts/:label', templateUrl: '/dashboard/concepts/concept/concept.html', controller: 'DashboardConceptCtrl', resolve: { facts: ['$stateParams', 'API', 'Session', function($stateParams, API, Session){ $stateParams.concepts = $stateParams.concepts.split(','); return API.Queries.listFacts({ token: Session.getToken(), edinetcode: $stateParams.edinetcode, concept: $stateParams.concepts, fiscalYear: 'ALL', fiscalPeriod: 'FY', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis': 'ALL', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis::default': 'jppfs-cor:NonConsolidatedMember', "tse-ed-t:ResultForecastAxis": ["tse-ed-t:ForecastMember", "xbrl28:EDINETReportedValue"], "tse-ed-t:ResultForecastAxis::default": "xbrl28:EDINETReportedValue", "tse-ed-t:ConsolidatedNonconsolidatedAxis": "ALL", "tse-ed-t:PreviousCurrentAxis": "ALL", "tse-ed-t:ConsolidatedNonconsolidatedAxis::default": "NONE", "tse-ed-t:PreviousCurrentAxis::default": "NONE", "fsa:ArchiveFiscalPeriod": "ALL", "fsa:ArchiveFiscalYear": "ALL" }).then(function(response){ console.log(response.FactTable); return response.FactTable; }); }] } }); }) ;
'use strict'; angular .module('report-editor') .config(function ($stateProvider) { $stateProvider .state('dashboard.concepts.concept', { url: '/:concepts/:label', templateUrl: '/dashboard/concepts/concept/concept.html', controller: 'DashboardConceptCtrl', resolve: { facts: ['$stateParams', 'API', 'Session', function($stateParams, API, Session){ $stateParams.concepts = $stateParams.concepts.split(','); return API.Queries.listFacts({ token: Session.getToken(), edinetcode: $stateParams.edinetcode, concept: $stateParams.concepts, fiscalYear: 'ALL', fiscalPeriod: 'FY', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis': 'ALL', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis::default': 'jppfs-cor:NonConsolidatedMember' }).then(function(response){ return response.FactTable; }); }] } }); }) ;
Print "Geschaeftsprozessmodelle" when 'l' has been pressed
package rogue.creature; import java.util.Collection; import jade.fov.RayCaster; import jade.fov.ViewField; import jade.ui.Camera; import jade.ui.Terminal; import jade.util.datatype.ColoredChar; import jade.util.datatype.Coordinate; import jade.util.datatype.Direction; public class Player extends Creature implements Camera { private Terminal term; private ViewField fov; public Player(Terminal term) { super(ColoredChar.create('@')); this.term = term; fov = new RayCaster(); } @Override public void act() { try { char key; key = term.getKey(); switch(key) { case 'q': expire(); break; case 'l': System.out.println("Geschaeftsprozessmodelle"); // Do not break; here, otherwise we can't move left! default: Direction dir = Direction.keyToDir(key); if(dir != null) move(dir); break; } } catch(InterruptedException e) { e.printStackTrace(); } } @Override public Collection<Coordinate> getViewField() { return fov.getViewField(world(), pos(), 5); } }
package rogue.creature; import java.util.Collection; import jade.fov.RayCaster; import jade.fov.ViewField; import jade.ui.Camera; import jade.ui.Terminal; import jade.util.datatype.ColoredChar; import jade.util.datatype.Coordinate; import jade.util.datatype.Direction; public class Player extends Creature implements Camera { private Terminal term; private ViewField fov; public Player(Terminal term) { super(ColoredChar.create('@')); this.term = term; fov = new RayCaster(); } @Override public void act() { try { char key; key = term.getKey(); switch(key) { case 'q': expire(); break; default: Direction dir = Direction.keyToDir(key); if(dir != null) move(dir); break; } } catch(InterruptedException e) { e.printStackTrace(); } } @Override public Collection<Coordinate> getViewField() { return fov.getViewField(world(), pos(), 5); } }
Add quotes around date and time for python 2
from django.db.backends.mysql.schema import DatabaseSchemaEditor \ as BaseDatabaseSchemaEditor import datetime import sys class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def execute(self, sql, params=()): sql = str(sql) if self.collect_sql: ending = "" if sql.endswith(";") else ";" if params is not None: self.collected_sql.append( (sql % tuple(map(self.quote_value, params))) + ending) else: self.collected_sql.append(sql + ending) # If not collecting the sql, do not execute def quote_value(self, value): if isinstance(value, bool): return str(int(value)) if isinstance(value, int): return value if isinstance(value, float): if value % 1 == .0: return int(value) return value if self._is_date_or_time(value) and sys.version_info.major == 2: return value if sys.version_info.major == 3: return "b\"'{0}'\"".format(value) return "'{0}'".format(value) def _is_date_or_time(self, value): try: datetime.datetime.strptime(value, '%H:%M:%S') return True except Exception: try: datetime.datetime.strptime(value, '%Y-%m-%d') return True except Exception: return False def _field_should_be_indexed(self, model, field): create_index = super( DatabaseSchemaEditor, self)._field_should_be_indexed(model, field) if (create_index and field.get_internal_type() == 'ForeignKey' and field.db_constraint): return False return create_index
from django.db.backends.mysql.schema import DatabaseSchemaEditor \ as BaseDatabaseSchemaEditor import sys class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def execute(self, sql, params=()): sql = str(sql) if self.collect_sql: ending = "" if sql.endswith(";") else ";" if params is not None: self.collected_sql.append( (sql % tuple(map(self.quote_value, params))) + ending) else: self.collected_sql.append(sql + ending) # If not collecting the sql, do not execute def quote_value(self, value): if type(value) == bool: return str(int(value)) if type(value) == int: return value if type(value) == float: if value % 1 == .0: return int(value) return value # TODO escape correctly all values for mysql # Preferably without having the mysql client as dep if sys.version_info.major == 3: return "b\"'{0}'\"".format(value) return "'{0}'".format(value) def _field_should_be_indexed(self, model, field): create_index = super( DatabaseSchemaEditor, self)._field_should_be_indexed(model, field) if (create_index and field.get_internal_type() == 'ForeignKey' and field.db_constraint): return False return create_index
Fix some bugs in the list parser regex
package org.monospark.spongematchers.parser.element; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.monospark.spongematchers.util.PatternBuilder; import com.google.common.collect.Lists; public final class ListElementParser extends StringElementParser { @Override Pattern createPattern() { return new PatternBuilder() .appendNonCapturingPart("\\[") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .openAnonymousParantheses() .appendNonCapturingPart("\\s*,\\s*") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .closeParantheses() .zeroOrMore() .appendNonCapturingPart("\\]") .build(); } @Override void parse(Matcher matcher, StringElementContext context) { createList(matcher, context); } private void createList(Matcher matcher, StringElementContext context) { List<StringElement> elements = Lists.newArrayList(); Matcher elementMatcher = StringElementParser.REPLACE_PATTERN.matcher(matcher.group()); while (elementMatcher.find()) { StringElement element = context.getElementAt(elementMatcher.start(), elementMatcher.end()); context.removeElement(element); elements.add(element); } context.addElement(new ListElement(matcher.start(), matcher.end(), elements));; } }
package org.monospark.spongematchers.parser.element; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.monospark.spongematchers.util.PatternBuilder; import com.google.common.collect.Lists; public final class ListElementParser extends StringElementParser { @Override Pattern createPattern() { return new PatternBuilder() .openNamedParantheses("list") .appendNonCapturingPart("[") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .openAnonymousParantheses() .appendNonCapturingPart("\\s*,\\s*") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .closeParantheses() .zeroOrMore() .appendNonCapturingPart("]") .closeParantheses() .or() .build(); } @Override void parse(Matcher matcher, StringElementContext context) { createList(matcher, context); } private void createList(Matcher matcher, StringElementContext context) { List<StringElement> elements = Lists.newArrayList(); Matcher elementMatcher = StringElementParser.REPLACE_PATTERN.matcher(matcher.group()); while (elementMatcher.find()) { StringElement element = context.getElementAt(elementMatcher.start(), elementMatcher.end()); context.removeElement(element); elements.add(element); } context.addElement(new ListElement(matcher.start(), matcher.end(), elements));; } }
Change .complete to .always, as .complete has been deprecated since jQuery 1.8
$(document).ready(function(){ 'use strict'; function load_new_items(){ var sign = load_path.indexOf('?') >= 0 ? '&' : '?' $.get(load_path + sign + 'page=' + (++page_num), function(data, e) { if(data.length < 5) { var page_num = 0; return false; } data_container.append(data); }).always(function() { loading_pic.hide(); }); } function loading_hidden(){ return !loading_pic.is(':visible'); } function near_bottom(){ return $(window).scrollTop() > $(document).height() - $(window).height() - bottom_px_limit; } if($('*[data-scrollinity-path]').length > 0) { var page_num = 1 var load_path = $('*[data-scrollinity-path]').data('scrollinity-path'); var loading_pic = $('*[data-scrollinity-loading-pic]'); var data_container = $('#' + $('*[data-scrollinity-data-container]').data('scrollinity-data-container')); var bottom_px_limit = $('*[data-scrollinity-bottom-px-limit]').data('scrollinity-bottom-px-limit'); $(window).on('scroll.scrollinity', function(){ if(loading_hidden() && near_bottom()) { if(page_num > 0) { loading_pic.show(); load_new_items(); } } }); } else { $(window).off('scroll.scrollinity'); } });
$(document).ready(function(){ 'use strict'; function load_new_items(){ var sign = load_path.indexOf('?') >= 0 ? '&' : '?' $.get(load_path + sign + 'page=' + (++page_num), function(data, e) { if(data.length < 5) { var page_num = 0; return false; } data_container.append(data); }).complete(function() { loading_pic.hide(); }); } function loading_hidden(){ return !loading_pic.is(':visible'); } function near_bottom(){ return $(window).scrollTop() > $(document).height() - $(window).height() - bottom_px_limit; } if($('*[data-scrollinity-path]').length > 0) { var page_num = 1 var load_path = $('*[data-scrollinity-path]').data('scrollinity-path'); var loading_pic = $('*[data-scrollinity-loading-pic]'); var data_container = $('#' + $('*[data-scrollinity-data-container]').data('scrollinity-data-container')); var bottom_px_limit = $('*[data-scrollinity-bottom-px-limit]').data('scrollinity-bottom-px-limit'); $(window).on('scroll.scrollinity', function(){ if(loading_hidden() && near_bottom()) { if(page_num > 0) { loading_pic.show(); load_new_items(); } } }); } else { $(window).off('scroll.scrollinity'); } });
Change Game form score input to select
from django import forms from django_select2.forms import ModelSelect2MultipleWidget from django_superform import ModelFormField, SuperForm from .models import Team, Game from .utils import clean_team_forms from foosball.users.models import User class MultiPlayerWidget(ModelSelect2MultipleWidget): model = User search_fields = [ 'username__icontains', 'first_name__icontains', 'last_name__icontains', 'email__icontains', ] def build_attrs(self, extra_attrs=None, **kwargs): attrs = super().build_attrs(extra_attrs=extra_attrs, **kwargs) attrs['data-maximum-selection-length'] = 2 return attrs def label_from_instance(self, obj): return " - ".join(filter(None, [obj.username, obj.name])) class TeamModelForm(forms.ModelForm): class Meta: model = Team fields = ('score', 'players') widgets = { 'players': MultiPlayerWidget, 'score': forms.Select(choices=((i, i) for i in range(11))) } class GameModelForm(forms.ModelForm): class Meta: model = Game fields = ('played_at', 'table') class GameForm(SuperForm): game = ModelFormField(GameModelForm) team1 = ModelFormField(TeamModelForm) team2 = ModelFormField(TeamModelForm) def is_valid(self): return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
from django import forms from django_select2.forms import ModelSelect2MultipleWidget from django_superform import ModelFormField, SuperForm from .models import Team, Game from .utils import clean_team_forms from foosball.users.models import User class MultiPlayerWidget(ModelSelect2MultipleWidget): model = User search_fields = [ 'username__icontains', 'first_name__icontains', 'last_name__icontains', 'email__icontains', ] def build_attrs(self, extra_attrs=None, **kwargs): attrs = super().build_attrs(extra_attrs=extra_attrs, **kwargs) attrs['data-maximum-selection-length'] = 2 return attrs def label_from_instance(self, obj): return " - ".join(filter(None, [obj.username, obj.name])) class TeamModelForm(forms.ModelForm): class Meta: model = Team fields = ('score', 'players') widgets = { 'players': MultiPlayerWidget } class GameModelForm(forms.ModelForm): class Meta: model = Game fields = ('played_at', 'table') class GameForm(SuperForm): game = ModelFormField(GameModelForm) team1 = ModelFormField(TeamModelForm) team2 = ModelFormField(TeamModelForm) def is_valid(self): return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
[LEADERBOARD/USERDATA] Add userinfo getter, fix typo in class name
const LEADERBOARD_SIZE = 10; class Leaderboard { constructor () { this.db = fbApp.database(); } refreshScores (callback) { this.db.ref('leaderboard').orderByValue().limitToLast(LEADERBOARD_SIZE).once('value', (snapshot) => { var board = []; snapshot.forEach((data) => { board.push({user: data.key, score: data.val()}); }); board.reverse(); callback(board); }); } updateScore (username, score) { this.db.ref('leaderboard/' + username).on('value', (snapshot) => { this.db.ref('leaderboard/' + username).set(Math.max(score, snapshot.val())); }); } updatePassedLevel (username, levelNumber) { this.db.ref('passedLevels/' + username + '/' + levelNumber.toString()).set(1); } getPassedLevels (username, callback) { this.db.ref('passedLevels/' + username + '/').orderByKey().once('value', (snapshot) => { var levels = []; snapshot.forEach((data) => { levels.push(data.key * 1); }); callback(levels); }); } getUserInfo (username, callback) { this.getPassedLevels(username, (levels) => { this.db.ref('leaderboard/' + username).on('value', (snapshot) => { callback({score: snapshot.val(), levels: levels}); }); }) } }
const LEADERBOARD_SIZE = 10; class leaderboard { constructor () { this.db = fbApp.database(); } refreshScores (callback) { this.db.ref('leaderboard').orderByValue().limitToLast(LEADERBOARD_SIZE).once('value', (snapshot) => { var board = []; snapshot.forEach((data) => { board.push({user: data.key, score: data.val()}); }); board.reverse(); callback(board); }); } updateScore (username, score) { this.db.ref('leaderboard/' + username).on('value', (snapshot) => { this.db.ref('leaderboard/' + username).set(Math.max(score, snapshot.val())); }); } updatePassedLevel (username, levelNumber) { this.db.ref('passedLevels/' + username + '/' + levelNumber.toString()).set(1); } getPassedLevels (username, callback) { this.db.ref('passedLevels/' + username + '/').orderByKey().once('value', (snapshot) => { var levels = []; snapshot.forEach((data) => { levels.push(data.key * 1); }); callback(levels); }); } }
Fix Load multiple JSON bug using array of promises
define([ 'base/class', 'jquery', 'underscore', 'base/utils' ], function(Class, $, _, Util) { var LocalJSONReader = Class.extend({ init: function(basepath) { this.data = []; this.basepath = basepath; }, read: function(queries, language) { var _this = this, defer = $.Deferred(), promises = []; var path = this.basepath.replace("{{LANGUAGE}}", language); _this.data = []; for (var i=0; i < queries.length; i++) { var fakeResponsePath = path.replace("response", "response_" + i); var promise = $.getJSON(fakeResponsePath, function(res) { _this.data.push(res); }) .error(function() { console.log("Error Happened While Lading File: " + fakeResponsePath); }); promises.push(promise); } $.when.apply(null, promises).done(function() { defer.resolve(); }); return defer; }, getData: function() { return this.data; } }); return LocalJSONReader; });
define([ 'base/class', 'jquery', 'underscore', 'base/utils' ], function(Class, $, _, Util) { var LocalJSONReader = Class.extend({ init: function(basepath) { this.data = []; this.basepath = basepath; }, read: function(queries, language) { var _this = this, defer = $.Deferred(); var path = this.basepath.replace("{{LANGUAGE}}", language); _this.data = []; for (var i=0; i < queries.length; i++) { var fakeResponsePath = path.replace("response", "response_" + i); var promise = $.getJSON(fakeResponsePath, function(res) { _this.data.push(res); }) .error(function() { console.log("Error Happened While Lading File: " + fakeResponsePath); }); } promise.done(function() { console.log(_this.data); defer.resolve(); }); return defer; }, getData: function() { return this.data; } }); return LocalJSONReader; });
Bump version to 0.0.3 for pip.
from setuptools import setup import os setup( name = "conduit", version = "0.0.3", author = "Steve Leibman", author_email = "[email protected]", description = ("Framework for dataflow-style python programming"), license = "MIT", keywords = "dataflow distributed pipe flow programming", url = "https://github.com/sleibman/python-conduit", packages = ['conduit', 'conduit.util', 'conduit.test'], long_description = """ python-conduit ============== Python framework for dataflow-style programs. Users of this framework structure their code into blocks with named inputs and outputs that are connected by channels. A typical application will have one or more data generator/importer blocks which then pass their data through various blocks which apply filters or tranforms to operate on the data. For other similar projects, see: http://wiki.python.org/moin/FlowBasedProgramming License ------- conduit is free software and is released under the terms of the MIT license (<http://opensource.org/licenses/mit-license.php>), as specified in the accompanying LICENSE.txt file. """, test_suite = 'conduit.test', classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Utilities", ], )
from setuptools import setup import os setup( name = "conduit", version = "0.0.2", author = "Steve Leibman", author_email = "[email protected]", description = ("Framework for dataflow-style python programming"), license = "MIT", keywords = "dataflow distributed pipe flow programming", url = "https://github.com/sleibman/python-conduit", packages = ['conduit', 'conduit.util', 'conduit.test'], long_description = """ python-conduit ============== Python framework for dataflow-style programs. Users of this framework structure their code into blocks with named inputs and outputs that are connected by channels. A typical application will have one or more data generator/importer blocks which then pass their data through various blocks which apply filters or tranforms to operate on the data. For other similar projects, see: http://wiki.python.org/moin/FlowBasedProgramming License ------- conduit is free software and is released under the terms of the MIT license (<http://opensource.org/licenses/mit-license.php>), as specified in the accompanying LICENSE.txt file. """, test_suite = 'conduit.test', classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Utilities", ], )