text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Upgrade to ew editor API
var CodeMirror = require('codemirror') , bindCodemirror = require('gulf-codemirror') module.exports = setup module.exports.consumes = ['editor'] module.exports.provides = [] function setup(plugin, imports, register) { var editor = imports.editor var cmCssLink = document.createElement('link') cmCssLink.setAttribute('rel', "stylesheet") cmCssLink.setAttribute('href', "/static/hive-editor-text-codemirror/static/codemirror.css") document.head.appendChild(cmCssLink) editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor' , function*(editorEl) { var cm = CodeMirror(function(el) { editorEl.appendChild(el) el.style['height'] = '100%' el.style['width'] = '100%' }) editorEl.style['height'] = '100%' document.body.style['position'] = 'absolute' document.body.style['bottom'] = document.body.style['top'] = document.body.style['left'] = document.body.style['right'] = '0' return bindCodemirror(cm) }) register() }
var CodeMirror = require('codemirror') , bindCodemirror = require('gulf-codemirror') module.exports = setup module.exports.consumes = ['editor'] module.exports.provides = [] function setup(plugin, imports, register) { var editor = imports.editor var cmCssLink = document.createElement('link') cmCssLink.setAttribute('rel', "stylesheet") cmCssLink.setAttribute('href', "/static/hive-editor-text-codemirror/static/codemirror.css") document.head.appendChild(cmCssLink) editor.registerEditor('text', function*() { var editor = document.querySelector('#editor') var cm = CodeMirror(function(el) { editor.appendChild(el) el.style['height'] = '100%' el.style['width'] = '100%' }) editor.style['height'] = '100%' document.body.style['position'] = 'absolute' document.body.style['bottom'] = document.body.style['top'] = document.body.style['left'] = document.body.style['right'] = '0' return bindCodemirror(cm) }) register() }
Update Accordion to respect arbitrary user-defined props.
// @flow import React, { Component, type ElementProps } from 'react'; import { Provider } from 'mobx-react'; import { createAccordionStore } from '../accordionStore/accordionStore'; type AccordionProps = ElementProps<'div'> & { accordion: boolean, onChange: Function, }; class Accordion extends Component<AccordionProps, *> { static defaultProps = { accordion: true, onChange: () => {}, className: 'accordion', children: null, }; accordionStore = createAccordionStore({ accordion: this.props.accordion, onChange: this.props.onChange, }); render() { const { accordion: accordionProp, onChange, ...rest } = this.props; const { accordion } = this.accordionStore; return ( <Provider accordionStore={this.accordionStore}> <div role={accordion ? 'tablist' : null} {...rest} /> </Provider> ); } } export default Accordion;
// @flow import React, { Component, type Node } from 'react'; import { Provider } from 'mobx-react'; import { createAccordionStore } from '../accordionStore/accordionStore'; type AccordionProps = { accordion: boolean, children: Node, className: string, onChange: Function, }; class Accordion extends Component<AccordionProps, *> { static defaultProps = { accordion: true, onChange: () => {}, className: 'accordion', children: null, }; accordionStore = createAccordionStore({ accordion: this.props.accordion, onChange: this.props.onChange, }); render() { const { className, children } = this.props; const { accordion } = this.accordionStore; return ( <Provider accordionStore={this.accordionStore}> <div role={accordion ? 'tablist' : null} className={className}> {children} </div> </Provider> ); } } export default Accordion;
Fix type error in the producers thread test, which was not a compiler error because Object. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=142185290
/* * Copyright (C) 2016 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package producerstest.monitoring; import com.google.common.util.concurrent.ListenableFuture; import dagger.producers.Producer; import dagger.producers.ProducerModule; import dagger.producers.Produces; import producerstest.monitoring.ThreadQualifiers.Deferred; import producerstest.monitoring.ThreadQualifiers.EntryPoint; import producerstest.monitoring.ThreadQualifiers.Required; @ProducerModule final class ThreadModule { @Produces @Deferred Object deferred(ThreadAccumulator acc) { acc.markThread("deferred"); return new Object(); } @Produces @Required ListenableFuture<Object> required(@Deferred Producer<Object> o, ThreadAccumulator acc) { acc.markThread("required"); return o.get(); } @Produces @EntryPoint ThreadAccumulator entryPoint(@Required Object o, ThreadAccumulator acc) { acc.markThread("entryPoint"); return acc; } }
/* * Copyright (C) 2016 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package producerstest.monitoring; import dagger.producers.Producer; import dagger.producers.ProducerModule; import dagger.producers.Produces; import producerstest.monitoring.ThreadQualifiers.Deferred; import producerstest.monitoring.ThreadQualifiers.EntryPoint; import producerstest.monitoring.ThreadQualifiers.Required; @ProducerModule final class ThreadModule { @Produces @Deferred Object deferred(ThreadAccumulator acc) { acc.markThread("deferred"); return new Object(); } @Produces @Required Object required(@Deferred Producer<Object> o, ThreadAccumulator acc) { acc.markThread("required"); return o.get(); } @Produces @EntryPoint ThreadAccumulator entryPoint(@Required Object o, ThreadAccumulator acc) { acc.markThread("entryPoint"); return acc; } }
OAK-1847: Use SegmentMK for testing where possible git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1596603 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.kernel; import org.apache.jackrabbit.oak.NodeStoreFixture; import org.apache.jackrabbit.oak.spi.state.NodeStore; class AbstractKernelTest { protected NodeStore createNodeStore() { return NodeStoreFixture.SEGMENT_MK.createNodeStore(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.kernel; import org.apache.jackrabbit.oak.NodeStoreFixture; import org.apache.jackrabbit.oak.spi.state.NodeStore; class AbstractKernelTest { protected NodeStore createNodeStore() { return NodeStoreFixture.MK_IMPL.createNodeStore(); } }
Remove mutability of callback revision
package com.balancedpayments; import com.balancedpayments.core.Resource; import com.balancedpayments.core.ResourceCollection; import com.balancedpayments.core.ResourceField; import com.balancedpayments.core.ResourceQuery; import com.balancedpayments.errors.HTTPError; import java.util.Map; public class Callback extends Resource { public static final String resource_href = "/callbacks"; @ResourceField(mutable=true) public String url; @ResourceField(mutable=true, required=false) public String method; @ResourceField(required=false) public String revision; public static class Collection extends ResourceCollection<Callback> { public Collection(String href) { super(Callback.class, href); } }; public Callback() { super(); } public Callback(String href) throws HTTPError { super(href); } public Callback(Map<String, Object> payload) throws HTTPError { super(payload); } public static ResourceQuery<Callback> query() { return new ResourceQuery<Callback>(Callback.class, resource_href); } @Override public void save() throws HTTPError { if (id == null && href == null) { href = resource_href; } super.save(); } }
package com.balancedpayments; import com.balancedpayments.core.Resource; import com.balancedpayments.core.ResourceCollection; import com.balancedpayments.core.ResourceField; import com.balancedpayments.core.ResourceQuery; import com.balancedpayments.errors.HTTPError; import java.util.Map; public class Callback extends Resource { public static final String resource_href = "/callbacks"; @ResourceField(mutable=true) public String url; @ResourceField(mutable=true, required=false) public String method; @ResourceField(mutable=true, required=false) public String revision; public static class Collection extends ResourceCollection<Callback> { public Collection(String href) { super(Callback.class, href); } }; public Callback() { super(); } public Callback(String href) throws HTTPError { super(href); } public Callback(Map<String, Object> payload) throws HTTPError { super(payload); } public static ResourceQuery<Callback> query() { return new ResourceQuery<Callback>(Callback.class, resource_href); } @Override public void save() throws HTTPError { if (id == null && href == null) { href = resource_href; } super.save(); } }
Fix pesky modal duplication issue...
Template.nav.onRendered(function() { this.$('.button-collapse').sideNav({ closeOnClick: true }); }); Template.nav.events({ 'click .logout': function(e){ e.preventDefault(); Meteor.logout(function(){ sAlert.info('Logged out succesfully'); }); } }) Template.userDropdown.onRendered(function() { this.$('.dropdown-button').dropdown({ beloworigin: true }); }); Template.userDropdown.helpers({ avatar: function(){ return Meteor.user().profile.avatarImg; } }); Template.sidenav.onRendered(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered this.$('.open-notifications').leanModal(); }); Template.sidenav.events({ 'click .open-notifications': function(){ $('#notifications_modal').openModal(); } });
Template.nav.onRendered(function() { this.$('.button-collapse').sideNav({ closeOnClick: true }); }); Template.nav.events({ 'click .logout': function(e){ e.preventDefault(); Meteor.logout(function(){ sAlert.info('Logged out succesfully'); }); } }) Template.userDropdown.onRendered(function() { this.$('.dropdown-button').dropdown({ beloworigin: true }); }); Template.userDropdown.helpers({ avatar: function(){ return Meteor.user().profile.avatarImg; } }); Template.sidenav.onRendered(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered this.$('.open-notifications').leanModal(); }); Template.sidenav.events({ 'click .open-notifications': function(){ } });
Use UMD for CLI; fix
#!/usr/bin/env node const jsf = require('../dist/main.umd.js'); // FIXME: load faker/change on startup? const sample = process.argv.slice(2)[0]; const { inspect } = require('util'); const { Transform } = require('stream'); const { readFileSync } = require('fs'); const pretty = process.argv.indexOf('--pretty') !== -1; const noColor = process.argv.indexOf('--no-color') !== -1; function generate(schema, callback) { jsf.resolve(JSON.parse(schema)).then(result => { let sample; if (pretty) { sample = inspect(result, { colors: !noColor, depth: Infinity }); } else { sample = JSON.stringify(result); } callback(null, `${sample}\n`); }); } process.stdin.pipe(new Transform({ transform(entry, enc, callback) { generate(Buffer.from(entry, enc).toString(), callback); } })).pipe(process.stdout);
#!/usr/bin/env node const jsf = require('../dist/bundle.js'); // FIXME: load faker/change on startup? const sample = process.argv.slice(2)[0]; const { inspect } = require('util'); const { Transform } = require('stream'); const { readFileSync } = require('fs'); const pretty = process.argv.indexOf('--pretty') !== -1; const noColor = process.argv.indexOf('--no-color') !== -1; function generate(schema, callback) { jsf.resolve(JSON.parse(schema)).then(result => { let sample; if (pretty) { sample = inspect(result, { colors: !noColor, depth: Infinity }); } else { sample = JSON.stringify(result); } callback(null, `${sample}\n`); }); } process.stdin.pipe(new Transform({ transform(entry, enc, callback) { generate(Buffer.from(entry, enc).toString(), callback); } })).pipe(process.stdout);
Clean error output when command is a string
import functools import subprocess from doit.exceptions import TaskFailed def capture_subprocess_error(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except subprocess.CalledProcessError as e: command_string = e.cmd if isinstance(e.cmd, str) else ' '.join(e.cmd) return TaskFailed( 'Error while executing {}:\nstdout:\n{}\n\nstderr:\n{}'.format( command_string, e.stdout.decode('utf8') if e.stdout else '', e.stderr.decode('utf8') if e.stderr else '')) return wrapper
import functools import subprocess from doit.exceptions import TaskFailed def capture_subprocess_error(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except subprocess.CalledProcessError as e: return TaskFailed( 'Error while executing {}:\nstdout:\n{}\n\nstderr:\n{}'.format( ' '.join(e.cmd), e.stdout.decode('utf8') if e.stdout else '', e.stderr.decode('utf8') if e.stderr else '')) return wrapper
Allow passing cookies instance in client This allows the client to add onSet/onRemove cookies
import { Component } from 'react'; import { instanceOf, node } from 'prop-types'; import Cookies from 'universal-cookie'; import { isNode } from 'universal-cookie/lib/utils'; export default class CookiesProvider extends Component { static propTypes = { children: node, cookies: instanceOf(Cookies) }; static childContextTypes = { cookies: instanceOf(Cookies).isRequired }; constructor(props) { super(props); if (props.cookies) { this.cookies = props.cookies; } else { this.cookies = new Cookies(); } } getChildContext() { return { cookies: this.cookies }; } render() { return this.props.children; } } if (isNode()) { CookiesProvider.propTypes.cookies = instanceOf(Cookies).isRequired; }
import { Component } from 'react'; import { instanceOf, node } from 'prop-types'; import Cookies from 'universal-cookie'; import { isNode } from 'universal-cookie/lib/utils'; export default class CookiesProvider extends Component { static propTypes = { children: node }; static childContextTypes = { cookies: instanceOf(Cookies).isRequired }; constructor(props) { super(props); if (isNode()) { this.cookies = props.cookies; } else { this.cookies = new Cookies(); } } getChildContext() { return { cookies: this.cookies }; } render() { return this.props.children; } } if (isNode()) { CookiesProvider.propTypes.cookies = instanceOf(Cookies).isRequired; }
Remove logic on update remote
var fs = require('fs'); var moment = require('moment'); var rank = require('librank').rank; // data backup path var data_path = "./data/talks/"; // read all files in the database var res = fs.readdirSync(data_path); // current timestamp var now = moment(); // calculate difference of hours between two timestamps function countHours(start, end) { var duration = moment.duration(end.diff(start)); var hours = duration.asHours(); return hours; } // calculate ranking for all elements in the database res.forEach(function(element) { /* // full fs file path var talk_path = data_path + element; // get its data var talk = require(talk_path); // points var points = talk.voteCount + 1; // hours var hours = countHours(talk.created, now); // gravity var gravity = 1.8; // ranking calculation var score = rank.rank(points, hours, gravity); console.log(score, " - ", talk.title); */ });
var fs = require('fs'); var moment = require('moment'); var rank = require('librank').rank; // data backup path var data_path = "./data/talks/"; // read all files in the database var res = fs.readdirSync(data_path); // current timestamp var now = moment(); // calculate difference of hours between two timestamps function countHours(start, end) { var duration = moment.duration(end.diff(start)); var hours = duration.asHours(); return hours; } // calculate ranking for all elements in the database res.forEach(function(element) { // full fs file path var talk_path = data_path + element; // get its data var talk = require(talk_path); // points var points = talk.voteCount + 1; // hours var hours = countHours(talk.created, now); // gravity var gravity = 1.8; // ranking calculation var score = rank.rank(points, hours, gravity); console.log(score, " - ", talk.title); });
Add a note about semantic versioning to |PEG.VERSION| comment
/* * PEG.js @VERSION * * http://pegjs.majda.cz/ * * Copyright (c) 2010-2012 David Majda * Licensend under the MIT license. */ var PEG = (function(undefined) { var PEG = { /* PEG.js version (uses semantic versioning). */ VERSION: "@VERSION", /* * Generates a parser from a specified grammar and returns it. * * The grammar must be a string in the format described by the metagramar in * the parser.pegjs file. * * Throws |PEG.parser.SyntaxError| if the grammar contains a syntax error or * |PEG.GrammarError| if it contains a semantic error. Note that not all * errors are detected during the generation and some may protrude to the * generated parser and cause its malfunction. */ buildParser: function(grammar, options) { return PEG.compiler.compile(PEG.parser.parse(grammar), options); } }; /* Thrown when the grammar contains an error. */ PEG.GrammarError = function(message) { this.name = "PEG.GrammarError"; this.message = message; }; PEG.GrammarError.prototype = Error.prototype; // @include "utils.js" // @include "parser.js" // @include "compiler.js" return PEG; })(); if (typeof module !== "undefined") { module.exports = PEG; }
/* * PEG.js @VERSION * * http://pegjs.majda.cz/ * * Copyright (c) 2010-2012 David Majda * Licensend under the MIT license. */ var PEG = (function(undefined) { var PEG = { /* PEG.js version. */ VERSION: "@VERSION", /* * Generates a parser from a specified grammar and returns it. * * The grammar must be a string in the format described by the metagramar in * the parser.pegjs file. * * Throws |PEG.parser.SyntaxError| if the grammar contains a syntax error or * |PEG.GrammarError| if it contains a semantic error. Note that not all * errors are detected during the generation and some may protrude to the * generated parser and cause its malfunction. */ buildParser: function(grammar, options) { return PEG.compiler.compile(PEG.parser.parse(grammar), options); } }; /* Thrown when the grammar contains an error. */ PEG.GrammarError = function(message) { this.name = "PEG.GrammarError"; this.message = message; }; PEG.GrammarError.prototype = Error.prototype; // @include "utils.js" // @include "parser.js" // @include "compiler.js" return PEG; })(); if (typeof module !== "undefined") { module.exports = PEG; }
Fix the problem with Chute's API not returning correct Content-Type.
import Promise from 'bluebird'; import request from 'superagent'; import assign from 'lodash/object/assign'; const API_BASE = 'https://api.getchute.com/v2'; export default { fetchAssets: (albumId, opts = {}) => { return new Promise((resolve, reject) => { const defs = { 'per_page': 20, 'page': 1, }; const query = assign({}, defs, opts); request .get(`${API_BASE}/albums/${albumId}/assets`) .query(query) .withCredentials() .accept('json') .end((err, res) => { if (err || !res.ok) { reject(err); } else { // Despite providing "Accept: application/json" header // Chute's API returns "Content-Type: text/html" therefore // superagent is unable to automatically parse res.text // into res.body. resolve(JSON.parse(res.text)); } }); }); }, };
import Promise from 'bluebird'; import request from 'superagent'; import assign from 'lodash/object/assign'; const API_BASE = 'https://api.getchute.com/v2'; export default { fetchAssets: (albumId, opts = {}) => { return new Promise((resolve, reject) => { const defs = { 'per_page': 20, 'page': 1, }; const query = assign({}, defs, opts); request .get(`${API_BASE}/albums/${albumId}/assets`) .query(query) .withCredentials() .accept('json') .end((err, res) => { if (err || !res.ok) reject(err); else resolve(res.body); }); }); }, };
Use a diamond operator where possible
package org.realityforge.replicant.client; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; /** * Representation of a subscriptions that impact entity. */ public class EntitySubscriptionEntry { private final Map<GraphDescriptor, GraphSubscriptionEntry> _graphSubscriptions = new HashMap<>(); private final Map<GraphDescriptor, GraphSubscriptionEntry> _roGraphSubscriptions = Collections.unmodifiableMap( _graphSubscriptions ); private final Class<?> _type; private final Object _id; public EntitySubscriptionEntry( @Nonnull final Class<?> type, @Nonnull final Object id ) { _type = type; _id = id; } @Nonnull public Class<?> getType() { return _type; } @Nonnull public Object getID() { return _id; } public Map<GraphDescriptor, GraphSubscriptionEntry> getGraphSubscriptions() { return _roGraphSubscriptions; } final Map<GraphDescriptor, GraphSubscriptionEntry> getRwGraphSubscriptions() { return _graphSubscriptions; } }
package org.realityforge.replicant.client; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; /** * Representation of a subscriptions that impact entity. */ public class EntitySubscriptionEntry { private final Map<GraphDescriptor, GraphSubscriptionEntry> _graphSubscriptions = new HashMap<GraphDescriptor, GraphSubscriptionEntry>(); private final Map<GraphDescriptor, GraphSubscriptionEntry> _roGraphSubscriptions = Collections.unmodifiableMap( _graphSubscriptions ); private final Class<?> _type; private final Object _id; public EntitySubscriptionEntry( @Nonnull final Class<?> type, @Nonnull final Object id ) { _type = type; _id = id; } @Nonnull public Class<?> getType() { return _type; } @Nonnull public Object getID() { return _id; } public Map<GraphDescriptor, GraphSubscriptionEntry> getGraphSubscriptions() { return _roGraphSubscriptions; } final Map<GraphDescriptor, GraphSubscriptionEntry> getRwGraphSubscriptions() { return _graphSubscriptions; } }
Use es6 syntax in get average score function
const colorRanges = { 95: 'brightgreen', 90: 'green', 75: 'yellowgreen', 60: 'yellow', 40: 'orange', 0: 'red', }; const percentageToColor = (percentage) => { let key = percentage; while (!(key in colorRanges)) { key -= 1; } return colorRanges[key]; }; const getAverageScore = async metrics => Object.assign({}, ...Object.keys(metrics[0]).map( (category) => { const categoryScoreSum = metrics.map(metric => metric[category]).reduce((a, b) => a + b, 0); return { [category]: Math.round(categoryScoreSum / metrics.length) }; }, )); const getSquashedScore = async (metrics) => { const metricNames = Object.keys(metrics[0]); let count = 0; let total = 0; for (let i = 0; i < metricNames.length; i += 1) { for (let times = 0; times < metrics.length; times += 1) { count += 1; total += metrics[times][metricNames[i]]; } } return { lighthouse: Math.round(total / count) }; }; module.exports = { percentageToColor, getAverageScore, getSquashedScore, };
const colorRanges = { 95: 'brightgreen', 90: 'green', 75: 'yellowgreen', 60: 'yellow', 40: 'orange', 0: 'red', }; const percentageToColor = (percentage) => { while(!(percentage in colorRanges)) { percentage -= 1; } return colorRanges[percentage]; }; const getAverageScore = async (metrics) => { const lighthouseMetrics = {}; const metricNames = Object.keys(metrics[0]); for (let i = 0; i < metricNames.length; i += 1) { let times = 0; let total = 0; for (; times < metrics.length; times += 1) { total += metrics[times][metricNames[i]]; } lighthouseMetrics[metricNames[i]] = Math.round(total / times); } return lighthouseMetrics; }; const getSquashedScore = async (metrics) => { const metricNames = Object.keys(metrics[0]); let count = 0; let total = 0; for (let i = 0; i < metricNames.length; i += 1) { for (let times = 0; times < metrics.length; times += 1) { count += 1; total += metrics[times][metricNames[i]]; } } return { lighthouse: Math.round(total / count) }; }; module.exports = { percentageToColor, getAverageScore, getSquashedScore, };
Test commit from JKP Info
<?php /** * Created by PhpStorm. * User: stevan * Date: 29.9.17. * Time: 09.07 */ namespace SalexUserBundle\EventListener; // ... use Avanzu\AdminThemeBundle\Event\MessageListEvent; use FOS\UserBundle\Model\UserInterface; use SalexUserBundle\Entity\User; use SalexUserBundle\Model\MessageModel; use Symfony\Component\DependencyInjection\ContainerInterface; class MessageListener { private $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function onListMessages(MessageListEvent $event) { foreach($this->getMessages() as $message) { $event->addMessage($message); } } protected function getMessages() { $userManager = $this->container->get('fos_user.user_manager'); $from = $userManager->findUserBy(array('id'=>1)); // retrieve your message models/entities here $items = array( new MessageModel($from, 'Created reservation', new \DateTime(), $from), new MessageModel($userManager->findUserBy(array('id'=>1)), 'Created reservation', new \DateTime(), $from), new MessageModel($userManager->findUserBy(array('id'=>1)), 'Created reservation', new \DateTime(), $from), ); return $items; } }
<?php /** * Created by PhpStorm. * User: stevan * Date: 29.9.17. * Time: 09.07 */ namespace SalexUserBundle\EventListener; // ... use Avanzu\AdminThemeBundle\Event\MessageListEvent; use FOS\UserBundle\Model\UserInterface; use SalexUserBundle\Entity\User; use SalexUserBundle\Model\MessageModel; use Symfony\Component\DependencyInjection\ContainerInterface; class MessageListener { private $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function onListMessages(MessageListEvent $event) { foreach($this->getMessages() as $message) { $event->addMessage($message); } } protected function getMessages() { $userManager = $this->container->get('fos_user.user_manager'); $from = $userManager->findUserBy(array('id'=>6)); // retrieve your message models/entities here $items = array( new MessageModel($from, 'Created reservation', new \DateTime(), $from), new MessageModel($userManager->findUserBy(array('id'=>50)), 'Created reservation', new \DateTime(), $from), new MessageModel($userManager->findUserBy(array('id'=>51)), 'Created reservation', new \DateTime(), $from), ); return $items; } }
Undo BC-breaking change, restore 'import onnx' providing submodules. Signed-off-by: Edward Z. Yang <dbd597f5635f432486c5d365e9bb585b3eaa1853@fb.com>
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .onnx_ml_pb2 import * # noqa from .version import version as __version__ # noqa # Import common subpackages so they're available when you 'import onnx' import onnx.helper # noqa import onnx.checker # noqa import onnx.defs # noqa import sys def load(obj): ''' Loads a binary protobuf that stores onnx graph @params Takes a file-like object (has "read" function) or a string containing a file name @return ONNX ModelProto object ''' model = ModelProto() if hasattr(obj, 'read') and callable(obj.read): model.ParseFromString(obj.read()) else: with open(obj, 'rb') as f: model.ParseFromString(f.read()) return model
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .onnx_ml_pb2 import * # noqa from .version import version as __version__ # noqa import sys def load(obj): ''' Loads a binary protobuf that stores onnx graph @params Takes a file-like object (has "read" function) or a string containing a file name @return ONNX ModelProto object ''' model = ModelProto() if hasattr(obj, 'read') and callable(obj.read): model.ParseFromString(obj.read()) else: with open(obj, 'rb') as f: model.ParseFromString(f.read()) return model
Make search for classifying tasks case insensitive.
const {TASKS_TYPES} = require('./conf/consts') const getTaskType = (taskName) =>{ for (let task_type of TASKS_TYPES) { for (let keyword of task_type.keywords) { if(taskName..toUpperCase().includes(keyword.toUpperCase())) return task_type.name } } } module.exports.formatTasks = (rawtasks,fromDate) => { console.log('Formatting raw data.') let ftasks = rawtasks.map(el => { // map the project_id attribute of all tasks and save in 'formatted tasks' //Set task task type el.task_type = getTaskType(el.name) el.assignee = el.assignee.name // we are only interested in the Assignee's name. We don't check if this exists since one of our filters for getting the task is the assignee return el }) // Filter only tasks that have a "completed at" value and that the "completed_at" month is the same // as the month we are requesting (There seems to be no way to filter these out directly in the // request to the server) let completedTasks = [] ftasks.forEach(function(task){ if(task.completed_at !== '' && task.completed_at !== null && (new Date(task.completed_at)).getUTCMonth() === (new Date(fromDate)).getUTCMonth()){ completedTasks.push(task) } }) return completedTasks }
const {TASKS_TYPES} = require('./conf/consts') const getTaskType = (taskName) =>{ for (let task_type of TASKS_TYPES) { for (let keyword of task_type.keywords) { if(taskName.includes(keyword)) return task_type.name } } } module.exports.formatTasks = (rawtasks,fromDate) => { console.log('Formatting raw data.') let ftasks = rawtasks.map(el => { // map the project_id attribute of all tasks and save in 'formatted tasks' //Set task task type el.task_type = getTaskType(el.name) el.assignee = el.assignee.name // we are only interested in the Assignee's name. We don't check if this exists since one of our filters for getting the task is the assignee return el }) // Filter only tasks that have a "completed at" value and that the "completed_at" month is the same // as the month we are requesting (There seems to be no way to filter these out directly in the // request to the server) let completedTasks = [] ftasks.forEach(function(task){ if(task.completed_at !== '' && task.completed_at !== null && (new Date(task.completed_at)).getUTCMonth() === (new Date(fromDate)).getUTCMonth()){ completedTasks.push(task) } }) return completedTasks }
Remove bash_completition references in consumer-manager
from setuptools import setup from kafka_info import __version__ setup( name="kafka_info", version=__version__, author="Federico Giraud", author_email="fgiraud@yelp.com", description="Shows kafka cluster information and metrics", packages=["kafka_info", "kafka_info.utils", "kafka_info.commands", "kafka_consumer_manager", "kafka_consumer_manager.commands"], data_files=[("bash_completion.d", ["kafka-info"])], scripts=["kafka-info", "kafka-consumer-manager"], install_requires=[ "argparse", "argcomplete", "kazoo", "PyYAML", "yelp-kafka", ], )
from setuptools import setup from kafka_info import __version__ setup( name="kafka_info", version=__version__, author="Federico Giraud", author_email="fgiraud@yelp.com", description="Shows kafka cluster information and metrics", packages=["kafka_info", "kafka_info.utils", "kafka_info.commands", "kafka_consumer_manager", "kafka_consumer_manager.commands"], data_files=[("bash_completion.d", ["kafka-info", "kafka-consumer-manager"])], scripts=["kafka-info", "kafka-consumer-manager"], install_requires=[ "argparse", "argcomplete", "kazoo", "PyYAML", "yelp-kafka", ], )
Update alowed paths for GGJ.
const routeRegex = /^\/(global-game-jam-2021|globalgamejam2021|ggj2021|ggj21)(?:\/.*)?$/; const githubUrl = 'https://levilindsey.github.io/global-game-jam-2021'; // Attaches the route handlers for this app. exports.attachRoutes = (server, appPath, config) => { server.get(routeRegex, handleRequest); // --- --- // // Handles a request for this app. function handleRequest(req, res, next) { // Check whether this request was directed to the games subdomain. if (config.gamesDomains.indexOf(req.hostname) < 0) { next(); return; } const dirs = req.path.split('/'); if (dirs[2] === '' || dirs.length === 2) { res.redirect(githubUrl); } else { next(); } } };
const routeRegex = /^\/(global-game-jam-2021|ggj2021|ggj21)(?:\/.*)?$/; const githubUrl = 'https://levilindsey.github.io/global-game-jam-2021'; // Attaches the route handlers for this app. exports.attachRoutes = (server, appPath, config) => { server.get(routeRegex, handleRequest); // --- --- // // Handles a request for this app. function handleRequest(req, res, next) { // Check whether this request was directed to the games subdomain. if (config.gamesDomains.indexOf(req.hostname) < 0) { next(); return; } const dirs = req.path.split('/'); if (dirs[2] === '' || dirs.length === 2) { res.redirect(githubUrl); } else { next(); } } };
Clean up namespace to get rid of sphinx warnings
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Access to Fermi Gamma-ray Space Telescope data. http://fermi.gsfc.nasa.gov http://fermi.gsfc.nasa.gov/ssc/data/ """ from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'], "Fermi query URL") FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server') FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located') from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.") del ConfigurationItem # clean up namespace - prevents doc warnings
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Access to Fermi Gamma-ray Space Telescope data. http://fermi.gsfc.nasa.gov http://fermi.gsfc.nasa.gov/ssc/data/ """ from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'], "Fermi query URL") FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server') FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located') from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
fix(ExampleBuilder): Fix example runner to support __BASE_PATH__ and serve the full vtk-js repo
module.exports = function buildConfig(name, relPath, destPath, root) { return ` var loaders = require('../config/webpack.loaders.js'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var webpack = require('webpack'); module.exports = { plugins: [ new HtmlWebpackPlugin({ inject: 'body', }), new webpack.DefinePlugin({ __BASE_PATH__: "''", }), ], entry: '${relPath}', output: { path: '${destPath}', filename: '${name}.js', }, module: { preLoaders: [{ test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/, }], loaders: loaders, }, eslint: { configFile: '${root}/.eslintrc.js', }, devServer: { contentBase: '${root}', port: 9999, host: '0.0.0.0', hot: true, quiet: false, noInfo: false, stats: { colors: true, }, proxy: { '/data/**': { target: 'http://0.0.0.0:9999/Data', pathRewrite: { '^/data': '' }, }, }, }, }; `; };
module.exports = function buildConfig(name, relPath, destPath, root) { return ` var loaders = require('../config/webpack.loaders.js'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { plugins: [ new HtmlWebpackPlugin({ inject: 'body', }), ], entry: '${relPath}', output: { path: '${destPath}', filename: '${name}.js', }, module: { preLoaders: [{ test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/, }], loaders: loaders, }, eslint: { configFile: '${root}/.eslintrc.js', }, devServer: { contentBase: '${destPath}', port: 9999, host: '0.0.0.0', hot: true, quiet: false, noInfo: false, stats: { colors: true, }, }, }; `; };
Disable detailed certifications tests until bug fix Movies and TV certifications are randomly returned for each other See #1
package tmdb import ( . "gopkg.in/check.v1" ) func (s *TmdbSuite) TestGetCertificationsMovieList(c *C) { movieResult, err := s.tmdb.GetCertificationsMovieList() s.baseTest(&movieResult, err, c) usMovieCerts := movieResult.Certifications["US"] c.Assert(usMovieCerts, NotNil) // usMovieCertsOpts := "NR|G|PG|PG-13|R|NC-17" // for _, movieCert := range usMovieCerts { // c.Assert(movieCert.Certification, Matches, usMovieCertsOpts) // } } func (s *TmdbSuite) TestGetCertificationsTvList(c *C) { tvResult, err := s.tmdb.GetCertificationsTvList() s.baseTest(&tvResult, err, c) usTvCerts := tvResult.Certifications["US"] c.Assert(usTvCerts, NotNil) // usTvCertsOpts := "NR|TV-Y|TV-Y7|TV-G|TV-PG|TV-14|TV-MA" // for _, tvCert := range usTvCerts { // c.Assert(tvCert.Certification, Matches, usTvCertsOpts) // } }
package tmdb import ( . "gopkg.in/check.v1" ) func (s *TmdbSuite) TestGetCertificationsMovieList(c *C) { movieResult, err := s.tmdb.GetCertificationsMovieList() s.baseTest(&movieResult, err, c) usMovieCerts := movieResult.Certifications["US"] usMovieCertsOpts := "NR|G|PG|PG-13|R|NC-17" for _, movieCert := range usMovieCerts { c.Assert(movieCert.Certification, Matches, usMovieCertsOpts) } } func (s *TmdbSuite) TestGetCertificationsTvList(c *C) { tvResult, err := s.tmdb.GetCertificationsTvList() s.baseTest(&tvResult, err, c) usTvCerts := tvResult.Certifications["US"] usTvCertsOpts := "NR|TV-Y|TV-Y7|TV-G|TV-PG|TV-14|TV-MA" for _, tvCert := range usTvCerts { c.Assert(tvCert.Certification, Matches, usTvCertsOpts) } }
Use yaml.safe_dump rather than yaml.dump. No more "!!python/unicode".
# (c) 2012, Jeroen Hoekx <jeroen@hoekx.be> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import json import yaml class FilterModule(object): ''' Ansible core jinja2 filters ''' def filters(self): return { 'to_json': json.dumps, 'from_json': json.loads, 'to_yaml': yaml.safe_dump, 'from_yaml': yaml.load, }
# (c) 2012, Jeroen Hoekx <jeroen@hoekx.be> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import json import yaml class FilterModule(object): ''' Ansible core jinja2 filters ''' def filters(self): return { 'to_json': json.dumps, 'from_json': json.loads, 'to_yaml': yaml.dump, 'from_yaml': yaml.load, }
Fix bad indentation in a pyximport test The indentation was inadvertently broken when expanding tabs in e908c0b9262008014d0698732acb5de48dbbf950. Fixes: $ python pyximport/test/test_reload.py File "pyximport/test/test_reload.py", line 23 assert hello.x == 1 ^ IndentationError: unexpected indent
from __future__ import absolute_import, print_function import time, os, sys from . import test_pyximport if 1: from distutils import sysconfig try: sysconfig.set_python_build() except AttributeError: pass import pyxbuild print(pyxbuild.distutils.sysconfig == sysconfig) def test(): tempdir = test_pyximport.make_tempdir() sys.path.append(tempdir) hello_file = os.path.join(tempdir, "hello.pyx") open(hello_file, "w").write("x = 1; print x; before = 'before'\n") import hello assert hello.x == 1 time.sleep(1) # sleep to make sure that new "hello.pyx" has later # timestamp than object file. open(hello_file, "w").write("x = 2; print x; after = 'after'\n") reload(hello) assert hello.x == 2, "Reload should work on Python 2.3 but not 2.2" test_pyximport.remove_tempdir(tempdir) if __name__=="__main__": test()
from __future__ import absolute_import, print_function import time, os, sys from . import test_pyximport if 1: from distutils import sysconfig try: sysconfig.set_python_build() except AttributeError: pass import pyxbuild print(pyxbuild.distutils.sysconfig == sysconfig) def test(): tempdir = test_pyximport.make_tempdir() sys.path.append(tempdir) hello_file = os.path.join(tempdir, "hello.pyx") open(hello_file, "w").write("x = 1; print x; before = 'before'\n") import hello assert hello.x == 1 time.sleep(1) # sleep to make sure that new "hello.pyx" has later # timestamp than object file. open(hello_file, "w").write("x = 2; print x; after = 'after'\n") reload(hello) assert hello.x == 2, "Reload should work on Python 2.3 but not 2.2" test_pyximport.remove_tempdir(tempdir) if __name__=="__main__": test()
Remove unused _hydrating bubbling behavior (-8 B)
/** * Find the closest error boundary to a thrown error and call it * @param {object} error The thrown value * @param {import('../internal').VNode} vnode The vnode that threw * the error that was caught (except for unmounting when this parameter * is the highest parent that was being unmounted) */ export function _catchError(error, vnode) { /** @type {import('../internal').Component} */ let component, ctor, handled; for (; (vnode = vnode._parent); ) { if ((component = vnode._component) && !component._processingException) { try { ctor = component.constructor; if (ctor && ctor.getDerivedStateFromError != null) { component.setState(ctor.getDerivedStateFromError(error)); handled = component._dirty; } if (component.componentDidCatch != null) { component.componentDidCatch(error); handled = component._dirty; } // This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration. if (handled) { return (component._pendingError = component); } } catch (e) { error = e; } } } throw error; }
/** * Find the closest error boundary to a thrown error and call it * @param {object} error The thrown value * @param {import('../internal').VNode} vnode The vnode that threw * the error that was caught (except for unmounting when this parameter * is the highest parent that was being unmounted) */ export function _catchError(error, vnode) { /** @type {import('../internal').Component} */ let component, ctor, handled; const wasHydrating = vnode._hydrating; for (; (vnode = vnode._parent); ) { if ((component = vnode._component) && !component._processingException) { try { ctor = component.constructor; if (ctor && ctor.getDerivedStateFromError != null) { component.setState(ctor.getDerivedStateFromError(error)); handled = component._dirty; } if (component.componentDidCatch != null) { component.componentDidCatch(error); handled = component._dirty; } // This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration. if (handled) { vnode._hydrating = wasHydrating; return (component._pendingError = component); } } catch (e) { error = e; } } } throw error; }
Add check for invalid connection
// client start file const Display = require('./interface.js'); const network = require('./network.js'); let dis = new Display(); // TODO: placeholder nick let nick = "Kneelawk"; // TODO: placeholder server let server = "http://localhost:8080"; let session; network.login(server, nick).on('login', (body) => { if (!body) { // TODO: more error handling } session = body; }).on('error', (error) => { // TODO: error handling }); let lastTime = 0; let updateLoopId = setInterval(() => { network.update(server, lastTime).on('response', (messages) => { if (messages && messages.length > 0) { messages.sort((a, b) => { if (a.timestamp > b.timestamp) return 1; else if (a.timestamp < b.timestamp) return -1; else return 0; }); messages.forEach((element) => { dis.recieve(element.timestamp, element.nick, element.body); }); lastTime = messages[messages.length - 1].timestamp; } }).on('error', (error) => { // TODO: error handling }); }, 1000); // checking every second should be good enough // TODO: get input from user // TODO: stopping the client and disconnecting
// client start file const Display = require('./interface.js'); const network = require('./network.js'); let dis = new Display(); // TODO: placeholder nick let nick = "Kneelawk"; // TODO: placeholder server let server = "http://localhost:8080"; let session; network.login(server, nick).on('login', (body) => { session = body; }).on('error', (error) => { // TODO: error handling }); let lastTime = 0; let updateLoopId = setInterval(() => { network.update(server, lastTime).on('response', (messages) => { if (messages && messages.length > 0) { messages.sort((a, b) => { if (a.timestamp > b.timestamp) return 1; else if (a.timestamp < b.timestamp) return -1; else return 0; }); messages.forEach((element) => { dis.recieve(element.timestamp, element.nick, element.body); }); lastTime = messages[messages.length - 1].timestamp; } }).on('error', (error) => { // TODO: error handling }); }, 1000); // checking every second should be good enough // TODO: get input from user // TODO: stopping the client and disconnecting
Make scrollbar size inversely relative to chat size.
package mnm.mods.tabbychat.gui; import mnm.mods.tabbychat.core.GuiNewChatTC; import mnm.mods.util.gui.GuiComponent; import net.minecraft.client.gui.Gui; public class Scrollbar extends GuiComponent { private ChatArea chat; public Scrollbar(ChatArea chat) { this.chat = chat; } @Override public void drawComponent(int mouseX, int mouseY) { if (GuiNewChatTC.getInstance().getChatOpen()) { int scroll = chat.getScrollPos(); int max = chat.getBounds().height; int lines = max / mc.fontRendererObj.FONT_HEIGHT; int total = chat.getChat(false).size(); if (total <= lines) { return; } total -= lines; int size = Math.max(max / total, 10); float perc = Math.abs((float) scroll / (float) total - 1) * Math.abs((float) size / (float) max - 1); int pos = (int) (perc * max); Gui.drawRect(0, pos, 1, pos + size, -1); } } }
package mnm.mods.tabbychat.gui; import mnm.mods.tabbychat.core.GuiNewChatTC; import mnm.mods.util.gui.GuiComponent; import net.minecraft.client.gui.Gui; public class Scrollbar extends GuiComponent { private ChatArea chat; public Scrollbar(ChatArea chat) { this.chat = chat; } @Override public void drawComponent(int mouseX, int mouseY) { if (GuiNewChatTC.getInstance().getChatOpen()) { int scroll = chat.getScrollPos(); int max = chat.getBounds().height; int lines = max / mc.fontRendererObj.FONT_HEIGHT; int total = chat.getChat(false).size(); if (total < lines) { return; } total -= lines; int size = 25; float perc = Math.abs((float) scroll / (float) total - 1) * Math.abs((float) size / (float) max - 1); int pos = (int) (perc * max); Gui.drawRect(0, pos, 1, pos + size, -1); } } }
Return fail message if parking space do not exist
<?php namespace App\Http\Controllers; class ParkingController { public function getAll() { return Response::json('success', $this->table()->get()); } public function get($id) { $parking = $this->table()->where('id', $id)->get(); if (empty($parking)) { return Response::json('fail', [ 'message' => 'The parking space does not exist' ]); } return Response::json('success', $parking); } public function rentSpace() { // Add server side validation check if space is rented $id = input('id'); $parking = $this->getParking($id)->first(); if ($parking->rented === 'true') { return Response::json('fail', [ 'message' => 'The parking space has been rented' ]); } $this->getParking($id)->update(['rented' => 'true']); return Response::json('success'); } private function table() { return \Builder::table('parking'); } private function getParking($id) { return $this->table()->where('id', $id); } }
<?php namespace App\Http\Controllers; class ParkingController { public function getAll() { return Response::json('success', $this->table()->get()); } public function get($id) { $parking = $this->table()->where('id', $id)->get(); return Response::json('success', $parking); } public function rentSpace() { // Add server side validation check if space is rented $id = input('id'); $parking = $this->getParking($id)->first(); if ($parking->rented === 'true') { return Response::json('fail', [ 'message' => 'The parking space has been rented' ]); } $this->getParking($id)->update(['rented' => 'true']); return Response::json('success'); } private function table() { return \Builder::table('parking'); } private function getParking($id) { return $this->table()->where('id', $id); } }
Add non-promise based handling for notifications Fix #8
'use strict' exports.authorize = function () { try { return Notification.requestPermission() .then(function (permission) { if (permission === 'denied') return else if (permission === 'default') return // Do something with the granted permission, if needed. }) } catch (error) { // Safari doesn't return a promise for requestPermissions and it // throws a TypeError. It takes a callback as the first argument // instead. if (error instanceof TypeError) { Notification.requestPermission((permission) => { if (permission === 'denied') return else if (permission === 'default') return }) } else { throw error } } } exports.show = function (title, options) { const notification = new Notification( title || 'No title set on options object!', { dir: options.dir || 'auto', lang: options.lang || 'en-US', body: options.body || '', tag: options.tag || '', icon: options.icon || '' } ) if (options.closeAfter) { setTimeout(function () { notification.close() }, options.closeAfter) } } exports.isSupported = ('Notification' in window)
'use strict' exports.authorize = function () { return Notification.requestPermission() .then(function (permission) { if (permission === 'denied') return else if (permission === 'default') return // Do something with the granted permission, if needed. }) } exports.show = function (title, options) { const notification = new Notification( title || 'No title set on options object!', { dir: options.dir || 'auto', lang: options.lang || 'en-US', body: options.body || '', tag: options.tag || '', icon: options.icon || '' } ) if (options.closeAfter) { setTimeout(function () { notification.close() }, options.closeAfter) } } exports.isSupported = ('Notification' in window)
ESLint: Allow async functions in tests
module.exports = { parserOptions: { 'ecmaVersion': 2017, }, env: { 'embertest': true }, extends: [ 'eslint:recommended', 'plugin:ember-suave/recommended' ], globals: { '$': true, 'addOfflineUsersForElectron': true, 'attachCustomForm': true, 'authenticateUser': true, 'checkCustomFormIsDisplayed': true, 'checkCustomFormIsFilled': true, 'checkCustomFormIsFilledAndReadonly': true, 'createCustomFormForType': true, 'fillCustomForm': true, 'invalidateSession': true, 'require': true, 'runWithPouchDump': true, 'select': true, 'selectDate': true, 'typeAheadFillIn': true, 'wait': true, 'waitToAppear': true, 'waitToDisappear': true }, rules: { 'camelcase': 0, 'ember-suave/no-direct-property-access': 0, 'ember-suave/require-access-in-comments': 0, 'no-console': 0 } };
module.exports = { env: { 'embertest': true }, extends: [ 'eslint:recommended', 'plugin:ember-suave/recommended' ], globals: { '$': true, 'addOfflineUsersForElectron': true, 'attachCustomForm': true, 'authenticateUser': true, 'checkCustomFormIsDisplayed': true, 'checkCustomFormIsFilled': true, 'checkCustomFormIsFilledAndReadonly': true, 'createCustomFormForType': true, 'fillCustomForm': true, 'invalidateSession': true, 'require': true, 'runWithPouchDump': true, 'select': true, 'selectDate': true, 'typeAheadFillIn': true, 'wait': true, 'waitToAppear': true, 'waitToDisappear': true }, rules: { 'camelcase': 0, 'ember-suave/no-direct-property-access': 0, 'ember-suave/require-access-in-comments': 0, 'no-console': 0 } };
Raise exception in case of config load error
import os import json class JSONConfigLoader(): def __init__(self, base_path): self.sources = [ os.path.dirname(os.getcwd()), os.path.dirname(os.path.abspath(base_path)), os.path.expanduser('~'), '/etc', ] def load(self, filename): tries = [] for source in self.sources: file_path = os.path.join(source, filename) tries.append(file_path) if not os.path.exists(file_path): continue with open(file_path) as f: return json.load(f) raise Exception("Config file not found in: %s" % tries)
import os import json class JSONConfigLoader(): def __init__(self): self.sources = [ os.path.dirname(os.getcwd()), os.path.dirname(os.path.abspath(__file__)), os.path.expanduser('~'), '/etc', ] def load(self, filename): for source in self.sources: file_path = os.path.join(source, filename) if not os.path.exists(file_path): continue with open(file_path) as f: return json.load(f) return None
Use uuid.hex instead of reinventing it.
# -*- coding: utf-8 -*- # OpenFisca -- A versatile microsimulation software # By: OpenFisca Team <contact@openfisca.fr> # # Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team # https://github.com/openfisca # # This file is part of OpenFisca. # # OpenFisca is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # OpenFisca is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Helpers to handle uuid""" import uuid def generate_uuid(): return unicode(uuid.uuid4().hex)
# -*- coding: utf-8 -*- # OpenFisca -- A versatile microsimulation software # By: OpenFisca Team <contact@openfisca.fr> # # Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team # https://github.com/openfisca # # This file is part of OpenFisca. # # OpenFisca is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # OpenFisca is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Helpers to handle uuid""" import uuid def generate_uuid(): return unicode(uuid.uuid4()).replace('-', '')
Update Oslo imports to remove namespace package Change-Id: I4ec9b2a310471e4e07867073e9577731ac34027d Blueprint: drop-namespace-packages
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html . """ import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='oslo.utils') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html . """ from oslo import i18n _translators = i18n.TranslatorFactory(domain='oslo.utils') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
Add HGTDIR to store hgt files inside a directory
import os import json import numpy as np SAMPLES = 1201 # For SRTM3, use 3601 for SRTM1 HGTDIR = 'hgt' # All 'hgt' files will be kept here uncompressed def get_elevation(lat, lon): file = get_file_name(lat, lon) if file: return read_elevation_from_file(file, lat, lon) # Treat it as data void as in SRTM documentation return -32768 def read_elevation_from_file(file, lat, lon): with open(file) as hgt_data: # HGT is 16bit signed integer - big endian elevations = np.fromfile(hgt_data, np.dtype('>i2'), SAMPLES*SAMPLES) .reshape((SAMPLES, SAMPLES)) lat_row = round((lat - int(lat))* 1200, 0) lon_row = round((lon - int(lon))* 1200, 0) return elevations[1200-lat_row, lon_row].astype(int) def get_file_name(lat, lon): file = "N%(lat)dE0%(lon)d.hgt" % {'lat':lat, 'lon':lon} file = os.path.join(HGTDIR, file) if os.path.isfile(file): return file else: return None
import os import json import numpy as np SAMPLES = 1201 # For SRTM3, use 3601 for SRTM1 def get_elevation(lat, lon): file = get_file_name(lat, lon) if file: return read_elevation_from_file(file, lat, lon) # Treat it as data void as in SRTM documentation return -32768 def read_elevation_from_file(file, lat, lon): with open(file) as hgt_data: # HGT is 16bit signed integer - big endian elevations = np.fromfile(hgt_data, np.dtype('>i2'), SAMPLES*SAMPLES) .reshape((SAMPLES, SAMPLES)) lat_row = round((lat - int(lat))* 1200, 0) lon_row = round((lon - int(lon))* 1200, 0) return elevations[1200-lat_row, lon_row].astype(int) def get_file_name(lat, lon): file = "N%(lat)dE0%(lon)d.hgt" % {'lat':lat, 'lon':lon} if os.path.isfile(file): return file else: return None
Fix unecessary call to automatic delivery of badges when this is a booking which is not checked-in
'use strict'; var _ = require('lodash'); function saveApplication (args, callback) { var seneca = this; var ENTITY_NS = 'cd/applications'; var applicationsEntity = seneca.make$(ENTITY_NS); var application = args.application; delete application.emailSubject; if (_.isEmpty(application)) return callback(null, {error: 'args.application is empty'}); if (!application.id) application.created = new Date(); // TODO: separate with seneca-mesh to avoid coupling of services applicationsEntity.save$(application, function(err, result){ if (err) return callback(err); if(application.attendance && !_.isEmpty(application.attendance)){ seneca.act({role: 'cd-badges', cmd: 'assignRecurrentBadges', application : application}, function (err, approval) { if (err) return callback(err); return callback(null, result); }); }else { return callback(null, result); } }); } module.exports = saveApplication;
'use strict'; var _ = require('lodash'); function saveApplication (args, callback) { var seneca = this; var ENTITY_NS = 'cd/applications'; var applicationsEntity = seneca.make$(ENTITY_NS); var application = args.application; delete application.emailSubject; if (_.isEmpty(application)) return callback(null, {error: 'args.application is empty'}); if (!application.id) application.created = new Date(); // TODO: separate with seneca-mesh to avoid coupling of services applicationsEntity.save$(application, function(err, result){ if (err) return callback(err); seneca.act({role: 'cd-badges', cmd: 'assignRecurrentBadges', application : application}, function (err, approval) { if (err) return callback(err); return callback(null, result); }); }); } module.exports = saveApplication;
Make the internal MatcherType of the BlockType MatcherType a constant
package org.monospark.spongematchers.type; import java.util.Map; import org.monospark.spongematchers.matcher.SpongeMatcher; import org.monospark.spongematchers.matcher.sponge.BlockTypeMatcher; import org.monospark.spongematchers.parser.SpongeMatcherParseException; import org.monospark.spongematchers.parser.element.StringElement; import org.spongepowered.api.block.BlockType; public final class BlockTypeType extends MatcherType<BlockType> { private static final MatcherType<Map<String,Object>> TYPE = MatcherType.definedMap() .addEntry("id", MatcherType.STRING) .addEntry("properties", MatcherType.PROPERTY_HOLDER) .build(); BlockTypeType() { super("block type"); } @Override public boolean canMatch(Object o) { return o instanceof BlockType; } @Override protected boolean canParse(StringElement element, boolean deep) { return TYPE.canParseMatcher(element, deep); } @Override protected SpongeMatcher<BlockType> parse(StringElement element) throws SpongeMatcherParseException { return BlockTypeMatcher.create(TYPE.parseMatcher(element)); } }
package org.monospark.spongematchers.type; import java.util.Map; import org.monospark.spongematchers.matcher.SpongeMatcher; import org.monospark.spongematchers.matcher.sponge.BlockTypeMatcher; import org.monospark.spongematchers.parser.SpongeMatcherParseException; import org.monospark.spongematchers.parser.element.StringElement; import org.spongepowered.api.block.BlockType; public final class BlockTypeType extends MatcherType<BlockType> { private MatcherType<Map<String,Object>> type = MatcherType.definedMap() .addEntry("id", MatcherType.STRING) .addEntry("properties", MatcherType.PROPERTY_HOLDER) .build(); BlockTypeType() { super("block type"); } @Override public boolean canMatch(Object o) { return o instanceof BlockType; } @Override protected boolean canParse(StringElement element, boolean deep) { return type.canParseMatcher(element, deep); } @Override protected SpongeMatcher<BlockType> parse(StringElement element) throws SpongeMatcherParseException { return BlockTypeMatcher.create(type.parseMatcher(element)); } }
Improve text suffix for days
module.exports = function(date) { if(date === undefined) { throw new Error('No date provided'); } if((date instanceof Date) === false) { throw new Error('Provided date is not an instance of a Date'); } var now = new Date(); var result = ""; if(now.getFullYear() > date.getFullYear()) { result = checkIsSingle(now.getFullYear() - date.getFullYear(), 'year'); } else if(now.getMonth() > date.getMonth()) { result = checkIsSingle(now.getMonth() - date.getMonth(), 'month'); } else if(now.getDate() > date.getDate()) { result = checkIsSingle(now.getDate() - date.getDate(), 'day'); } else if(now.getHours() > date.getHours()) { result = checkIsSingle(now.getHours() - date.getHours(), 'hour'); } else if(now.getMinutes() > date.getMinutes()) { result = checkIsSingle(now.getMinutes() - date.getMinutes(), 'minute'); } else if(now.getSeconds() > date.getSeconds()) { result = checkIsSingle(now.getSeconds() - date.getSeconds(), 'second'); } else { result = 'Just now'; } return result; } function checkIsSingle(number, string) { var result = number + ' ' + string; if(number > 1) { result += 's'; } return result; }
module.exports = function(date) { if(date === undefined) { throw new Error('No date provided'); } if((date instanceof Date) === false) { throw new Error('Provided date is not an instance of a Date'); } var now = new Date(); var result = ""; if(now.getFullYear() > date.getFullYear()) { result = checkIsSingle(now.getFullYear() - date.getFullYear(), 'year'); } else if(now.getMonth() > date.getMonth()) { result = checkIsSingle(now.getMonth() - date.getMonth(), 'month'); } else if(now.getDate() > date.getDate()) { result = (now.getDate() - date.getDate()) + ' days'; } else if(now.getHours() > date.getHours()) { result = checkIsSingle(now.getHours() - date.getHours(), 'hour'); } else if(now.getMinutes() > date.getMinutes()) { result = checkIsSingle(now.getMinutes() - date.getMinutes(), 'minute'); } else if(now.getSeconds() > date.getSeconds()) { result = checkIsSingle(now.getSeconds() - date.getSeconds(), 'second'); } else { result = 'Just now'; } return result; } function checkIsSingle(number, string) { var result = number + ' ' + string; if(number > 1) { result += 's'; } return result; }
Allow null values in model collection.
<?php /** * Created by PhpStorm. * User: daedeloth * Date: 30/11/14 * Time: 18:49 */ namespace Neuron\Collections; use Neuron\Interfaces\Model; /** * Class TokenizedCollection * * @package Neuron\Collections */ class ModelCollection extends Collection { private $map = array (); public function __construct () { $this->on ('add', array ($this, 'onAdd')); $this->on ('set', array ($this, 'onAdd')); $this->on ('unset', array ($this, 'onUnset')); } /** * @param Model|null $model * @param null $offset */ protected function onAdd (Model $model = null, $offset = null) { $this->map[$model->getId ()] = $model; } /** * @param Model|null $model * @param null $offset */ protected function onUnset (Model $model = null, $offset = null) { if ($model) unset ($this->map[$model->getId ()]); } /** * Return all ids. * @return array */ public function getIds () { return array_keys ($this->map); } /** * @param $id * @return mixed|null */ public function getFromId ($id) { if (isset ($this->map[$id])) { return $this->map[$id]; } return null; } }
<?php /** * Created by PhpStorm. * User: daedeloth * Date: 30/11/14 * Time: 18:49 */ namespace Neuron\Collections; use Neuron\Interfaces\Model; /** * Class TokenizedCollection * * @package Neuron\Collections */ class ModelCollection extends Collection { private $map = array (); public function __construct () { $this->on ('add', array ($this, 'onAdd')); $this->on ('set', array ($this, 'onAdd')); $this->on ('unset', array ($this, 'onUnset')); } protected function onAdd (Model $model, $offset) { $this->map[$model->getId ()] = $model; } protected function onUnset (Model $model = null, $offset = null) { if ($model) unset ($this->map[$model->getId ()]); } /** * Return all ids. * @return array */ public function getIds () { return array_keys ($this->map); } public function getFromId ($id) { if (isset ($this->map[$id])) { return $this->map[$id]; } return null; } }
Use getParent() allows for some easier mocking
<?php namespace BeBat\PolyTree\Relations; use BeBat\PolyTree\Contracts\Node; use BeBat\PolyTree\Exceptions\Cycle as CycleException; class HasChildren extends Direct { public function __construct(Node $node) { $foreignKey = $node->getParentKeyName(); $otherKey = $node->getChildKeyName(); parent::__construct($node, $foreignKey, $otherKey); } public function attach($child, array $attributes = [], $touch = true) { if (!$child instanceof Node) { throw new \Exception("We're not quite ready to deal with this situation yet"); } $connection = $this->getBaseQuery()->getConnection(); $connection->beginTransaction(); parent::attach($child, $attributes, $touch); $descendants = $this->getParent()->hasDescendants(); $descendants->unlock(); $descendants->attach($child); $descendants->lock(); $connection->commit(); } }
<?php namespace BeBat\PolyTree\Relations; use BeBat\PolyTree\Contracts\Node; use BeBat\PolyTree\Exceptions\Cycle as CycleException; class HasChildren extends Direct { public function __construct(Node $node) { $foreignKey = $node->getParentKeyName(); $otherKey = $node->getChildKeyName(); parent::__construct($node, $foreignKey, $otherKey); } public function attach($child, array $attributes = [], $touch = true) { if (!$child instanceof Node) { throw new \Exception("We're not quite ready to deal with this situation yet"); } $connection = $this->getBaseQuery()->getConnection(); $connection->beginTransaction(); parent::attach($child, $attributes, $touch); $descendants = $this->parent->hasDescendants(); $descendants->unlock(); $descendants->attach($child); $descendants->lock(); $connection->commit(); } }
Store a timeout value on the TaskWrapper, defaulting to no timeout. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
from .job import Job from .utils import get_backend from . import app_settings class task(object): def __init__(self, queue='default', timeout=None): self.queue = queue self.timeout = timeout app_settings.WORKERS.setdefault(self.queue, 1) def __call__(self, fn): return TaskWrapper(fn, self.queue, self.timeout) class TaskWrapper(object): def __init__(self, fn, queue, timeout): self.fn = fn self.queue = queue self.timeout = timeout self.path = '%s.%s' % (fn.__module__, fn.__name__) def __repr__(self): return "<TaskWrapper: %s>" % self.path def __call__(self, *args, **kwargs): job = Job(self.path, args, kwargs) job.validate() get_backend().enqueue(job, self.queue)
from .job import Job from .utils import get_backend from . import app_settings class task(object): def __init__(self, queue='default'): self.queue = queue app_settings.WORKERS.setdefault(self.queue, 1) def __call__(self, fn): return TaskWrapper(fn, self.queue) class TaskWrapper(object): def __init__(self, fn, queue): self.fn = fn self.queue = queue self.path = '%s.%s' % (fn.__module__, fn.__name__) def __repr__(self): return "<TaskWrapper: %s>" % self.path def __call__(self, *args, **kwargs): job = Job(self.path, args, kwargs) job.validate() get_backend().enqueue(job, self.queue)
Use index name matching the current naming schema
"""Added end_date to full text index events Revision ID: 573faf4ac644 Revises: 342fa3076650 Create Date: 2015-03-06 17:26:54.718493 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '573faf4ac644' down_revision = '342fa3076650' def upgrade(): op.alter_column('event_index', 'start_date', nullable=False, schema='events') op.create_index('ix_events_event_index_start_date', 'event_index', ['start_date'], schema='events') op.add_column('event_index', sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'), schema='events') op.alter_column('event_index', 'end_date', server_default=None, schema='events') op.create_index('ix_events_event_index_end_date', 'event_index', ['end_date'], schema='events') def downgrade(): op.alter_column('event_index', 'start_date', nullable=True, schema='events') op.drop_index('ix_events_event_index_start_date', table_name='event_index', schema='events') op.drop_column('event_index', 'end_date', schema='events')
"""Added end_date to full text index events Revision ID: 573faf4ac644 Revises: 342fa3076650 Create Date: 2015-03-06 17:26:54.718493 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '573faf4ac644' down_revision = '342fa3076650' def upgrade(): op.alter_column('event_index', 'start_date', nullable=False, schema='events') op.create_index('ix_start_date', 'event_index', ['start_date'], schema='events') op.add_column('event_index', sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'), schema='events') op.alter_column('event_index', 'end_date', server_default=None, schema='events') op.create_index('ix_end_date', 'event_index', ['end_date'], schema='events') def downgrade(): op.alter_column('event_index', 'start_date', nullable=True, schema='events') op.drop_index('ix_start_date', table_name='event_index', schema='events') op.drop_column('event_index', 'end_date', schema='events')
Fix a typo in the valid message
from pyisemail.diagnosis import BaseDiagnosis class ValidDiagnosis(BaseDiagnosis): """A diagnosis indicating the address is valid for use. """ DESCRIPTION = "Address is valid." MESSAGE = ("Address is valid. Please note that this does not mean " "the address actually exists, nor even that the domain " "actually exists. This address could be issued by the " "domain owner without breaking the rules of any RFCs.") def __init__(self, diagnosis_type='VALID'): self.diagnosis_type = diagnosis_type self.description = self.DESCRIPTION self.message = self.MESSAGE self.references = None self.code = 0
from pyisemail.diagnosis import BaseDiagnosis class ValidDiagnosis(BaseDiagnosis): """A diagnosis indicating the address is valid for use. """ DESCRIPTION = "Address is valid." MESSAGE = ("Address is valid. Please note that this does not mean " "the address actually exists, nor even that the domain " "actually exists. This address could be issued by the " "domain owner without braking the rules of any RFCs.") def __init__(self, diagnosis_type='VALID'): self.diagnosis_type = diagnosis_type self.description = self.DESCRIPTION self.message = self.MESSAGE self.references = None self.code = 0
Add check to ensure that we're in the same OS thread
import guv guv.monkey_patch() from guv import gyield, patcher import threading import greenlet threading_orig = patcher.original('threading') greenlet_ids = {} def check_thread(): current = threading_orig.current_thread() assert type(current) is threading_orig._MainThread def debug(i): print('{} greenlet_ids: {}'.format(i, greenlet_ids)) def f(): check_thread() greenlet_ids[1] = greenlet.getcurrent() debug(2) print('t: 1') gyield() print('t: 2') gyield() print('t: 3') def main(): check_thread() greenlet_ids[0] = greenlet.getcurrent() debug(1) t = threading.Thread(target=f) t.start() debug(3) print('m: 1') gyield() print('m: 2') gyield() print('m: 3') if __name__ == '__main__': main()
import guv guv.monkey_patch() from guv import gyield, sleep import threading import greenlet greenlet_ids = {} def debug(i): print('{} greenlet_ids: {}'.format(i, greenlet_ids)) def f(): greenlet_ids[1] = greenlet.getcurrent() debug(2) print('t: 1') gyield() print('t: 2') gyield() print('t: 3') def main(): greenlet_ids[0] = greenlet.getcurrent() debug(1) t = threading.Thread(target=f) t.start() debug(3) print('m: 1') gyield() print('m: 2') gyield() print('m: 3') if __name__ == '__main__': main()
Add functionality for filling in checkboxes
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add("login", (email, password) => { ... }) // //mm // -- This is a child command -- // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) Cypress.Commands.add('setRadioInput', (selector, value) => { const selectorValue = value === 'Yes' ? '0' : '1' cy.get(`#${selector}-${selectorValue}`).check(); }) Cypress.Commands.add('setTextInput', (selector, value) => { cy.get(`#${selector}`).type(value); }) Cypress.Commands.add('setCheckboxInput', (selector) => { cy.get(`#${selector}`).check(); })
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add("login", (email, password) => { ... }) // //mm // -- This is a child command -- // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) Cypress.Commands.add('setRadioInput', (selector, value) => { const selectorValue = value === 'Yes' ? '0' : '1' cy.get(`#${selector}-${selectorValue}`).check(); }) Cypress.Commands.add('setTextInput', (selector, value) => { cy.get(`#${selector}`).type(value); })
Remove Google+ from Social Sharing Bundle (2) Signed-off-by: Marius Blüm <38edb439dbcce85f0f597d90d338db16e5438073@lineone.io>
<?php /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @author Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\App\AppStore\Bundles; class SocialSharingBundle extends Bundle { /** * {@inheritDoc} */ public function getName() { return (string)$this->l10n->t('Social sharing bundle'); } /** * {@inheritDoc} */ public function getAppIdentifiers() { return [ 'socialsharing_twitter', 'socialsharing_facebook', 'socialsharing_email', 'socialsharing_diaspora', ]; } }
<?php /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @author Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\App\AppStore\Bundles; class SocialSharingBundle extends Bundle { /** * {@inheritDoc} */ public function getName() { return (string)$this->l10n->t('Social sharing bundle'); } /** * {@inheritDoc} */ public function getAppIdentifiers() { return [ 'socialsharing_twitter', 'socialsharing_googleplus', 'socialsharing_facebook', 'socialsharing_email', 'socialsharing_diaspora', ]; } }
Add Injection into __all__ list of top level package
"""Dependency injector.""" from .catalog import AbstractCatalog from .catalog import override from .providers import Provider from .providers import Delegate from .providers import Factory from .providers import Singleton from .providers import ExternalDependency from .providers import Class from .providers import Object from .providers import Function from .providers import Value from .providers import Callable from .providers import Config from .injections import Injection from .injections import KwArg from .injections import Attribute from .injections import Method from .injections import inject from .utils import is_provider from .utils import ensure_is_provider from .utils import is_injection from .utils import ensure_is_injection from .utils import is_kwarg_injection from .utils import is_attribute_injection from .utils import is_method_injection from .errors import Error __all__ = ( # Catalogs 'AbstractCatalog', 'override', # Providers 'Provider', 'Delegate', 'Factory', 'Singleton', 'ExternalDependency', 'Class', 'Object', 'Function', 'Value', 'Callable', 'Config', # Injections 'Injection', 'KwArg', 'Attribute', 'Method', 'inject', # Utils 'is_provider', 'ensure_is_provider', 'is_injection', 'ensure_is_injection', 'is_kwarg_injection', 'is_attribute_injection', 'is_method_injection', # Errors 'Error', )
"""Dependency injector.""" from .catalog import AbstractCatalog from .catalog import override from .providers import Provider from .providers import Delegate from .providers import Factory from .providers import Singleton from .providers import ExternalDependency from .providers import Class from .providers import Object from .providers import Function from .providers import Value from .providers import Callable from .providers import Config from .injections import Injection from .injections import KwArg from .injections import Attribute from .injections import Method from .injections import inject from .utils import is_provider from .utils import ensure_is_provider from .utils import is_injection from .utils import ensure_is_injection from .utils import is_kwarg_injection from .utils import is_attribute_injection from .utils import is_method_injection from .errors import Error __all__ = ( # Catalogs 'AbstractCatalog', 'override', # Providers 'Provider', 'Delegate', 'Factory', 'Singleton', 'ExternalDependency', 'Class', 'Object', 'Function', 'Value', 'Callable', 'Config', # Injections 'KwArg', 'Attribute', 'Method', 'inject', # Utils 'is_provider', 'ensure_is_provider', 'is_injection', 'ensure_is_injection', 'is_kwarg_injection', 'is_attribute_injection', 'is_method_injection', # Errors 'Error', )
Replace host for testing by ->getHost()
<?php namespace SLLH\HybridAuthBundle\Security\Http\Logout; use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface, Symfony\Component\Security\Core\Authentication\Token\TokenInterface, Symfony\Component\HttpFoundation\Response, Symfony\Component\HttpFoundation\Request, Symfony\Component\HttpFoundation\Cookie; use SLLH\HybridAuthBundle\Security\Http\HybridAuthProviderMap; /** * HybridAuthLogoutHandler * * @author Sullivan SENECHAL <soullivaneuh@gmail.com> */ class HybridAuthLogoutHandler implements LogoutHandlerInterface { /** * @var HybridAuthProviderMap */ private $providerMap; public function __construct(HybridAuthProviderMap $providerMap) { $this->providerMap = $providerMap; } public function logout(Request $request, Response $response, TokenInterface $token) { $this->providerMap->getHybridAuth()->logoutAllProviders(); $response->headers->setCookie(new Cookie('sllh_hybridauth_logout', true, 0, '/', $request->getHost(), false)); } } ?>
<?php namespace SLLH\HybridAuthBundle\Security\Http\Logout; use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface, Symfony\Component\Security\Core\Authentication\Token\TokenInterface, Symfony\Component\HttpFoundation\Response, Symfony\Component\HttpFoundation\Request, Symfony\Component\HttpFoundation\Cookie; use SLLH\HybridAuthBundle\Security\Http\HybridAuthProviderMap; /** * HybridAuthLogoutHandler * * @author Sullivan SENECHAL <soullivaneuh@gmail.com> */ class HybridAuthLogoutHandler implements LogoutHandlerInterface { /** * @var HybridAuthProviderMap */ private $providerMap; public function __construct(HybridAuthProviderMap $providerMap) { $this->providerMap = $providerMap; } public function logout(Request $request, Response $response, TokenInterface $token) { $this->providerMap->getHybridAuth()->logoutAllProviders(); $response->headers->setCookie(new Cookie('sllh_hybridauth_logout', true, 0, '/', 'localsf2.dowith.fr', false)); } } ?>
Fix Nodemon + Yarn integration problem
'use strict'; const process = require('process'); const { promisify } = require('util'); const { watch, series, parallel } = require('gulp'); const FILES = require('../files'); // Returns a watch task // E.g. with `tasks` `{ FORMAT: format }`, the `format` task will be fired // everytime `FILES.FORMAT` is changed. // If specified, `initialTask` is fired first const getWatchTask = function (tasks, initialTask) { const watchTask = getWatchTasks(tasks); if (initialTask === undefined) { return watchTask; } // Runs the task before watching // Using `ignoreInitial` chokidar option does not work because the task would // be marked as complete before the initial run. return series(initialTask, watchTask); }; const getWatchTasks = tasks => function watchTasks () { const promises = Object.entries(tasks) .map(([type, task]) => watchByType({ type, task })); return Promise.all(promises); }; const watchByType = async function ({ type, task }) { const taskA = Array.isArray(task) ? parallel(task) : task; const watcher = watch(FILES[type], taskA); // Wait for watching to be setup to mark the `watch` task as complete await promisify(watcher.on.bind(watcher))('ready'); }; module.exports = { getWatchTask, };
'use strict'; const process = require('process'); const { promisify } = require('util'); const { watch, series, parallel } = require('gulp'); const FILES = require('../files'); // Returns a watch task // E.g. with `tasks` `{ FORMAT: format }`, the `format` task will be fired // everytime `FILES.FORMAT` is changed. // If specified, `initialTask` is fired first const getWatchTask = function (tasks, initialTask) { const watchTask = getWatchTasks(tasks); if (initialTask === undefined) { return watchTask; } // Runs the task before watching // Using `ignoreInitial` chokidar option does not work because the task would // be marked as complete before the initial run. return series(initialTask, watchTask); }; const getWatchTasks = tasks => function watchTasks () { const promises = Object.entries(tasks) .map(([type, task]) => watchByType({ type, task })); return Promise.all(promises); }; const watchByType = async function ({ type, task }) { const taskA = Array.isArray(task) ? parallel(task) : task; const watcher = watch(FILES[type], taskA); // Otherwise the task will hang when fired through npm scripts process.on('SIGINT', watcher.close.bind(watcher)); // Wait for watching to be setup to mark the `watch` task as complete await promisify(watcher.on.bind(watcher))('ready'); }; module.exports = { getWatchTask, };
Use inotify backend (auto detect)
<?php namespace Kwf\FileWatcher; use Kwf\FileWatcher\Backend as Backend; class Watcher { /** * Creates instance of best watcher backend for your system. */ public static function create($paths) { $backends = array( new Backend\Inotifywait($paths), new Backend\Watchmedo($paths), new Backend\Inotify($paths), new Backend\Poll($paths), ); foreach ($backends as $b) { if ($b->isAvailable()) { $backend = $b; break; } } return $backend; } }
<?php namespace Kwf\FileWatcher; use Kwf\FileWatcher\Backend as Backend; class Watcher { /** * Creates instance of best watcher backend for your system. */ public static function create($paths) { $backends = array( new Backend\Inotifywait($paths), new Backend\Watchmedo($paths), new Backend\Poll($paths), ); foreach ($backends as $b) { if ($b->isAvailable()) { $backend = $b; break; } } return $backend; } }
Set previous action after executing
""" St. George Game main.py Sage Berg, Skyler Berg Created: 5 Dec 2014 """ import places from character import Character from display import Display from actions import AskAboutAssassins, BuyADrink, LeaveInAHuff, SingASong def main(): display = Display() display.enable() character = Character() character.place = places.tavern character.actions["a"] = AskAboutAssassins() character.actions["b"] = BuyADrink() character.actions["c"] = LeaveInAHuff() character.actions["d"] = SingASong() display.write("\n---The St. George Game---\n") display.write("You are in a tavern. The local assassins hate you.") while character.alive and character.alone: action = character.choose_action() display.enable() action.execute(character) character.prev_act = action character.generate_actions() if __name__ == "__main__": while True: # the game automatically restarts main()
""" St. George Game main.py Sage Berg, Skyler Berg Created: 5 Dec 2014 """ import places from character import Character from display import Display from actions import AskAboutAssassins, BuyADrink, LeaveInAHuff, SingASong def main(): display = Display() display.enable() character = Character() character.place = places.tavern character.actions["a"] = AskAboutAssassins() character.actions["b"] = BuyADrink() character.actions["c"] = LeaveInAHuff() character.actions["d"] = SingASong() display.write("\n---The St. George Game---\n") display.write("You are in a tavern. The local assassins hate you.") while character.alive and character.alone: action = character.choose_action() display.enable() action.execute(character) character.generate_actions() if __name__ == "__main__": while True: # the game automatically restarts main()
Check if memcache persistent connection not established before adding server to pool
<?php class f_MemcachedProvider { private $memcachedInstance = null; public function __construct($config) { $this->memcachedInstance = new Memcached('memcachedConnection'); // Check if memcached instance has no servers in it's pool yet (see http://www.php.net/manual/en/memcached.construct.php#93536) if (!count($this->memcachedInstance->getServerList())) { if ($this->memcachedInstance->addServer($config["server"]["host"], $config["server"]["port"]) === false) { Framework::error("MemcachedProvider: could not obtain memcache instance"); } } } /** * @return Boolean */ public function isAvailable() { return ($this->memcachedInstance !== null); } public function close() { if ($this->isAvailable()) { $this->memcachedInstance = null; } } /** * @return Memcache */ public function getConnection() { return $this->memcachedInstance; } }
<?php class f_MemcachedProvider { private $memcachedInstance = null; public function __construct($config) { $this->memcachedInstance = new Memcached('memcachedConnection'); if ($this->memcachedInstance->addServer($config["server"]["host"], $config["server"]["port"]) === false) { Framework::error("MemcachedProvider: could not obtain memcache instance"); } } /** * @return Boolean */ public function isAvailable() { return ($this->memcachedInstance !== null); } public function close() { if ($this->isAvailable()) { $this->memcachedInstance = null; } } /** * @return Memcache */ public function getConnection() { return $this->memcachedInstance; } }
Fix wrong class in 'super()' call Oops
class CommandException(Exception): """ This custom exception can be thrown by commands when something goes wrong during execution. The parameter is a message sent to the source that called the command (a channel or a user) """ def __init__(self, displayMessage=None, shouldLogError=True): """ Create a new CommandException, to be thrown when something goes wrong during Command execution :param displayMessage: An optional message to display to the IRC chat the bot is in :param shouldLogError: Whether this exception should be logged to the program log. This is useful if it's a problem that needs to be solved, but can be set to False if it's a user input error """ self.displayMessage = displayMessage self.shouldLogError = shouldLogError def __str__(self): return self.displayMessage class CommandInputException(CommandException): """ This custom exception can be raised when the input to some module or command is invalid or can't be parsed. It is a more specific implementation of the CommandException, that doesn't log itself to the logfile """ def __init__(self, displayMessage): """ Create a new InputException. The display message will be shown to the user :param displayMessage: The message to show to the user that called the command. This message should explain how the input should be correctly formatted """ super(CommandInputException, self).__init__(displayMessage, False)
class CommandException(Exception): """ This custom exception can be thrown by commands when something goes wrong during execution. The parameter is a message sent to the source that called the command (a channel or a user) """ def __init__(self, displayMessage=None, shouldLogError=True): """ Create a new CommandException, to be thrown when something goes wrong during Command execution :param displayMessage: An optional message to display to the IRC chat the bot is in :param shouldLogError: Whether this exception should be logged to the program log. This is useful if it's a problem that needs to be solved, but can be set to False if it's a user input error """ self.displayMessage = displayMessage self.shouldLogError = shouldLogError def __str__(self): return self.displayMessage class CommandInputException(CommandException): """ This custom exception can be raised when the input to some module or command is invalid or can't be parsed. It is a more specific implementation of the CommandException, that doesn't log itself to the logfile """ def __init__(self, displayMessage): """ Create a new InputException. The display message will be shown to the user :param displayMessage: The message to show to the user that called the command. This message should explain how the input should be correctly formatted """ super(CommandException, self).__init__(displayMessage, False)
Allow error chance of 0
/** * Randomly generate a boolean based on an input probability. * @private * @param {Number} chance Value between 0 and 1 representing 0% and 100% * probabilities of a true value, respectively * @return {Boolean} Random value */ var pass = function (chance) { return Math.random() < chance; }; /** * Generate an error to return to the client. * @private * @return {Error} Error object */ var getRandomError = function () { return new Error('Server error'); }; /** * Returns middleware which will simulate server errors being generated and sent * back to the client. * @function express-simulate-errors * @param {Object=} options * @param {Number} [options.chance=1] Chance of a random error occurring * @return {Function} Middleware function */ module.exports = function (options) { if (!options) { options = {}; } var chance = options.chance; if (chance !== 0 && !(chance > 0)) { chance = 1; } return function (req, res, next) { var passed = pass(chance); if (passed) { var err = getRandomError(); next(err); } else { next(); } }; };
/** * Randomly generate a boolean based on an input probability. * @private * @param {Number} chance Value between 0 and 1 representing 0% and 100% * probabilities of a true value, respectively * @return {Boolean} Random value */ var pass = function (chance) { return Math.random() < chance; }; /** * Generate an error to return to the client. * @private * @return {Error} Error object */ var getRandomError = function () { return new Error('Server error'); }; /** * Returns middleware which will simulate server errors being generated and sent * back to the client. * @function express-simulate-errors * @param {Object=} options * @param {Number} [options.chance=1] Chance of a random error occurring * @return {Function} Middleware function */ module.exports = function (options) { if (!options) { options = {}; } var chance = options.chance || 1; return function (req, res, next) { var passed = pass(chance); if (passed) { var err = getRandomError(); next(err); } else { next(); } }; };
Fix validation of "hidden" checkbox not working
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Tags; use Flarum\Core\Validator\AbstractValidator; class TagValidator extends AbstractValidator { /** * {@inheritdoc} */ protected $rules = [ 'name' => ['required'], 'slug' => ['required', 'unique:tags'], 'is_hidden' => ['bool'], 'description' => ['string', 'max:700'], 'color' => ['regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i'], ]; }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Tags; use Flarum\Core\Validator\AbstractValidator; class TagValidator extends AbstractValidator { /** * {@inheritdoc} */ protected $rules = [ 'name' => ['required'], 'slug' => ['required', 'unique:tags'], 'isHidden' => ['bool'], 'description' => ['string', 'max:700'], 'color' => ['regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i'], ]; }
Fix gas total is empty in fee details
import React from "react" import ReactTooltip from "react-tooltip"; import { calculateGasFee } from "../../utils/converter"; const FeeDetail = (props) => { const totalGas = props.totalGas ? props.totalGas : +calculateGasFee(props.gasPrice, props.gas); return ( <div className="gas-configed theme__text-4"> <div className={"title-fee theme__text-5"}> {props.translate("transaction.transaction_fee") || 'Max Transaction Fee'} <span className="common__info-icon" data-tip={props.translate("info.max_gas_fee")} data-for="max-gas-info"> <img src={require('../../../assets/img/common/blue-indicator.svg')} alt=""/> </span> <ReactTooltip className="common__tooltip" place="top" id="max-gas-info" type="light"/> </div> <div className={"total-fee"}> <span className={"total-fee__number theme__text"}>{totalGas.toString()} ETH</span> <span className={"total-fee__formula theme__text-6"}>{props.gasPrice} Gwei (Gas Price) * {props.gas} (Gas Limit)</span> </div> {(props.reserveRoutingEnabled && props.reserveRoutingChecked) && ( <div className="fee-info">{props.translate("info.reserve_routing_used")}</div> )} </div> ) } export default FeeDetail
import React from "react" import ReactTooltip from "react-tooltip"; const FeeDetail = (props) => { return ( <div className="gas-configed theme__text-4"> <div className={"title-fee theme__text-5"}> {props.translate("transaction.transaction_fee") || 'Max Transaction Fee'} <span className="common__info-icon" data-tip={props.translate("info.max_gas_fee")} data-for="max-gas-info"> <img src={require('../../../assets/img/common/blue-indicator.svg')} alt=""/> </span> <ReactTooltip className="common__tooltip" place="top" id="max-gas-info" type="light"/> </div> <div className={"total-fee"}> <span className={"total-fee__number theme__text"}>{props.totalGas.toString()} ETH</span> <span className={"total-fee__formula theme__text-6"}>{props.gasPrice} Gwei (Gas Price) * {props.gas} (Gas Limit)</span> </div> {(props.reserveRoutingEnabled && props.reserveRoutingChecked) && ( <div className="fee-info">{props.translate("info.reserve_routing_used")}</div> )} </div> ) } export default FeeDetail
Send and Connect frame tests
import unittest from Decode import Decoder import Frames class TestDecoder(unittest.TestCase): """ """ def setUp(self): self.decoder = Decoder() def test_decoder_get_frame_class(self): command = 'SEND' self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND) def test_decoder_invalid_frame_class(self): command = '---' self.assertRaises(Exception, self.decoder.get_frame_class, command) def test_decoder_decode_connect(self): testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"}) msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00" self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__) def test_decoder_decode_send(self): testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost", "msg":"hello queue a"}) msg = "SEND\naccept-version:1.2\nhost:localhost\n\nhello queue a\x00" self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__) if __name__ == '__main__': unittest.main()
import unittest from Decode import Decoder import Frames class TestDecoder(unittest.TestCase): def setUp(self): self.decoder = Decoder() def test_decoder_get_frame_class(self): command = 'SEND' self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND) def test_decoder_invalid_frame_class(self): command = '---' self.assertRaises(Exception, self.decoder.get_frame_class, command) def test_decoder_decode_connect(self): testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"}) msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00" self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__) if __name__ == '__main__': unittest.main()
Add partial and close server responses
var Hapi = require('hapi'); var server = Hapi.createServer('localhost', 8000); server.route({ method: 'GET', path: '/partial', handler: function(request, reply) { console.log(new Date(), 'partial'); request.raw.res.writeHead(200); request.raw.res.socket.end(); reply.close(); } }); server.route({ method: 'GET', path: '/close', handler: function(request, reply) { console.log(new Date(), 'close'); request.raw.res.socket.end(); reply.close(); } }); server.route({ method: 'GET', path: '/hang', handler: function(request, reply) { console.log(new Date(), 'hang'); } }); server.route({ method: 'GET', path: '/log', handler: function(request, reply) { console.log(new Date(), 'log'); console.log(request.headers['user-agent']); console.log(request.query.log); console.log(); console.log(); reply(new Hapi.response.Empty()); } }); server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: 'static' } } }); server.start();
var Hapi = require('hapi'); var server = Hapi.createServer('localhost', 8000); server.route({ method: 'GET', path: '/hang', handler: function(request, reply) { console.log(new Date(), 'hang'); if (request.query.duration) { setTimeout(function() { reply(new Hapi.response.Empty()); }, parseInt(request.query.duration, 10)); } } }); server.route({ method: 'GET', path: '/log', handler: function(request, reply) { console.log(new Date(), 'log'); console.log(request.headers['user-agent']); console.log(request.query.log); console.log(); console.log(); reply(new Hapi.response.Empty()); } }); server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: 'static' } } }); server.start();
Fix fallback locale and fixtures
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Translation\Provider; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ class LocaleProvider implements LocaleProviderInterface { /** * @var string */ private $currentLocale; /** * @var string */ private $fallbackLocale; /** * @param string $currentLocale * @param string $fallbackLocale */ function __construct($currentLlocale, $fallbackLocale) { $this->currentLocale = $currentLlocale; $this->fallbackLocale = $fallbackLocale; } /** * {@inheritdoc} */ public function getCurrentLocale() { return $this->currentLocale; } public function getFallbackLocale() { return $this->fallbackLocale; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Translation\Provider; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ class LocaleProvider implements LocaleProviderInterface { /** * @var string */ private $locale; /** * @param string $currentLocale */ function __construct($locale) { $this->locale = $locale; } /** * {@inheritdoc} */ public function getCurrentLocale() { return $this->locale; } public function getFallbackLocale() { return $this->locale; } }
Routes: Store a common reference to the DEBT app
module.exports = function( web ) { var app = web.get( "debt" ); web.get( "/", function( request, response ) { if ( app.state === "database-setup" ) { return app.install(function( error ) { if ( error ) { return response.send( 500 ); } app.state = "user-setup"; return response.redirect( "/install" ); }); } if ( app.state === "user-setup" ) { return response.redirect( "/install" ); } response.render( "home" ); }); web.get( "/install", web.authorize, function( request, response ) { // Prevent users from granting themselves admin rights after install if ( app.state === "installed" ) { return response.redirect( "/" ); } app.permission.grantToUser( request.session.userId, "DEBT:ADMIN", function( error ) { if ( error ) { return response.send( 500 ); } app.state = "installed"; response.render( "installed" ); }); }); };
module.exports = function( web ) { web.get( "/", function( request, response ) { var app = web.get( "debt" ); if ( app.state === "database-setup" ) { return app.install(function( error ) { if ( error ) { return response.send( 500 ); } app.state = "user-setup"; return response.redirect( "/install" ); }); } if ( app.state === "user-setup" ) { return response.redirect( "/install" ); } response.render( "home" ); }); web.get( "/install", web.authorize, function( request, response ) { var app = web.get( "debt" ); // Prevent users from granting themselves admin rights after install if ( app.state === "installed" ) { return response.redirect( "/" ); } app.permission.grantToUser( request.session.userId, "DEBT:ADMIN", function( error ) { if ( error ) { return response.send( 500 ); } app.state = "installed"; response.render( "installed" ); }); }); };
Camel-file-watch: Use FileHash because HashCode has been removed
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.watch; import java.io.IOException; import java.nio.file.Path; import io.methvin.watcher.hashing.FileHash; import io.methvin.watcher.hashing.FileHasher; /** * For unit test only! */ public class TestHasher implements FileHasher { @Override public FileHash hash(Path path) throws IOException { // Always return constant // This should cause every event is triggered only once (hashcode remains the same), so we can test this. // Never use this in production code return FileHash.fromLong(1L); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.watch; import java.io.IOException; import java.nio.file.Path; import io.methvin.watcher.hashing.FileHasher; import io.methvin.watcher.hashing.HashCode; /** * For unit test only! */ public class TestHasher implements FileHasher { @Override public HashCode hash(Path path) throws IOException { // Always return constant // This should cause every event is triggered only once (hashcode remains the same), so we can test this. // Never use this in production code return HashCode.fromLong(1L); } }
Change to import gravity constant from constants file. git-svn-id: acf0ef94bfce630b1a882387fc03ab8593ec6522@23 150532fb-1d5b-0410-a8ab-efec50f980d4
#!/usr/bin/python import numpy as N def u_star(u,v,w): ''' Compute the friction velocity, u_star, from the timeseries of the velocity \ components u, v, and w (an nD array) ''' from metpy.bl.turb.fluxes import rs as R rs = R(u,v,w) uw = rs[3] vw = rs[4] us = N.power(N.power(uw,2)+N.power(vw,2),0.25) return us def theta_star(u,v,w,T): ''' Compute the friction temperature, theta_star, from the timeseries of the velocity \ components u, v, and w, and temperature (an nD array) ''' from metpy.bl.turb.fluxes import turb_covar as TC ts = -TC(w,T)/u_star(u,v,w) return ts def obu_length(u,v,w,T): ''' Compute the Obukhov Length, L, using the timeseries of the velocity \ components u, v, and w, and temperature (an nD array) ''' from metpy.constants import g L = N.power(u_star(u,v,w),2)*N.average(T)/(0.4*g*theta_star(u,v,w,T)) return L
#!/usr/bin/python import numpy as N def u_star(u,v,w): ''' Compute the friction velocity, u_star, from the timeseries of the velocity \ components u, v, and w (an nD array) ''' from metpy.bl.turb.fluxes import rs as R rs = R(u,v,w) uw = rs[3] vw = rs[4] us = N.power(N.power(uw,2)+N.power(vw,2),0.25) return us def theta_star(u,v,w,T): ''' Compute the friction temperature, theta_star, from the timeseries of the velocity \ components u, v, and w, and temperature (an nD array) ''' from metpy.bl.turb.fluxes import turb_covar as TC ts = -TC(w,T)/u_star(u,v,w) return ts def obu_length(u,v,w,T): ''' Compute the Obukhov Length, L, using the timeseries of the velocity \ components u, v, and w, and temperature (an nD array) ''' L = N.power(u_star(u,v,w),2)*N.average(T)/(0.4*9.81*theta_star(u,v,w,T)) return L
Correct for internal adjustment to block resistance in getter.
package org.pfaa.block; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; public abstract class CompositeBlock extends Block implements CompositeBlockAccessors { public CompositeBlock(int id, int textureIndex, Material material) { super(id, textureIndex, material); } public CompositeBlock(int id, Material material) { this(id, 0, material); } @Override public int damageDropped(int meta) { return meta; } @Override public int getBlockTextureFromSideAndMetadata(int side, int meta) { return blockIndexInTexture + damageDropped(meta); } /* (non-Javadoc) * @see org.pfaa.block.ICompositeBlock#getSubBlocks(int, net.minecraft.creativetab.CreativeTabs, java.util.List) */ @Override public void getSubBlocks(int id, CreativeTabs creativeTabs, List list) { for (int i = 0; i < getMetaCount(); ++i) { list.add(new ItemStack(id, 1, damageDropped(i))); } } public abstract int getMetaCount(); public float getBlockResistance() { return this.blockResistance / 3.0F; } }
package org.pfaa.block; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; public abstract class CompositeBlock extends Block implements CompositeBlockAccessors { public CompositeBlock(int id, int textureIndex, Material material) { super(id, textureIndex, material); } public CompositeBlock(int id, Material material) { this(id, 0, material); } @Override public int damageDropped(int meta) { return meta; } @Override public int getBlockTextureFromSideAndMetadata(int side, int meta) { return blockIndexInTexture + damageDropped(meta); } /* (non-Javadoc) * @see org.pfaa.block.ICompositeBlock#getSubBlocks(int, net.minecraft.creativetab.CreativeTabs, java.util.List) */ @Override public void getSubBlocks(int id, CreativeTabs creativeTabs, List list) { for (int i = 0; i < getMetaCount(); ++i) { list.add(new ItemStack(id, 1, damageDropped(i))); } } public abstract int getMetaCount(); public float getBlockResistance() { return this.blockResistance; } }
Improve http request error reporting and metadata
var Bluebird = require('bluebird'); module.exports = issueRequest; function issueRequest (request) { return Bluebird.resolve(request) .catch(normalizeResponseError) .then(function (res) { // Api compatibility res.statusCode = res.status; return res; }); } function normalizeResponseError (err) { var error; var res = err.response; if (!res) { error = new Error(err.message); } else if (res.clientError) { error = new Error('Invalid request: ' + res.body && res.body.message ? res.body.message : res.text); } else if (res.serverError) { error = new Error('Server error: ' + res.body && res.body.message ? res.body.message : res.text); } Object.defineProperty(error, 'stack', { get: function () { return err.stack; }}); error.statusCode = err.status || 500; return error; }
var Bluebird = require('bluebird'); module.exports = issueRequest; function issueRequest (request) { return Bluebird.resolve(request) .catch(function (err) { throw new Error('Error communicating with the webtask cluster: ' + err.message); }) .then(function (res) { if (res.error) throw createResponseError(res); // Api compatibility res.statusCode = res.status; return res; }); } function createResponseError (res) { if (res.clientError) return new Error('Invalid request: ' + res.body && res.body.message ? res.body.message : res.text); if (res.serverError) return new Error('Server error: ' + res.body && res.body.message ? res.body.message : res.text); }
Implement demo 'exercises' api method.
# Copyright 2016 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import requests from flask import Blueprint, render_template, jsonify from flask_login import login_required challenges = Blueprint('challenges', __name__) @challenges.route('/challenges', methods=['GET']) @login_required def challenges_view(): return render_template('challenges.html', page="Challenges") @challenges.route('/exercises', methods=['GET']) @login_required def api_exercises(): exercises = requests.get("http://localhost:8000/").json() result = { "exercises": [] } for current in exercises['exercises']: result['exercises'].append({ "name": current.get('name', 'unknown'), "category": current.get('answers')[0].split(".")[1], "solved": 0, "cost": 100 }) return jsonify(result)
# Copyright 2016 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from flask import Blueprint, render_template from flask_login import login_required challenges = Blueprint('challenges', __name__) @challenges.route('/challenges', methods=['GET']) @login_required def challenges_view(): return render_template('challenges.html', page="Challenges")
Check to see if the calendar type parameter is actually an existing class before adding it to the calendar factory.
<?php namespace Plummer\Calendarful\Calendar; class CalendarFactory implements CalendarFactoryInterface { private $calendarTypes = []; public function addCalendarType($type, $calendarType) { if(is_string($calendarType) and !class_exists($calendarType)) { throw new \InvalidArgumentException("Class {$calendarType} des not exist."); } else if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType, false))) { throw new \InvalidArgumentException('File or File path required.'); } $this->calendarTypes[$type] = is_string($calendarType) ? $calendarType : get_class($calendarType); } public function getCalendarTypes() { return $this->calendarTypes; } public function createCalendar($type) { if(!isset($this->calendarTypes[$type])) { throw new \Exception('The type passed does not exist.'); } $calendar = new $this->calendarTypes[$type](); return $calendar; } }
<?php namespace Plummer\Calendarful\Calendar; class CalendarFactory implements CalendarFactoryInterface { private $calendarTypes = []; public function addCalendarType($type, $calendarType) { if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType))) { throw new \InvalidArgumentException('File or File path required.'); } $this->calendarTypes[$type] = is_string($calendarType) ? $calendarType : get_class($calendarType); } public function getCalendarTypes() { return $this->calendarTypes; } public function createCalendar($type) { if(!isset($this->calendarTypes[$type])) { throw new \Exception('The type passed does not exist.'); } $calendar = new $this->calendarTypes[$type](); return $calendar; } }
Correct root resource link to real order_book route
package horizon import ( "net/http" "github.com/jagregory/halgo" "github.com/stellar/go-horizon/render/hal" ) // RootResource is the initial map of links into the api. type RootResource struct { halgo.Links } var globalRootResource = RootResource{ Links: halgo.Links{}. Self("/"). Link("account", "/accounts/{address}"). Link("account_transactions", "/accounts/{address}/transactions{?cursor,limit,order}"). Link("transaction", "/transactions/{hash}"). Link("transactions", "/transactions{?cursor,limit,order}"). Link("order_book", "/order_book{?selling_type,selling_code,selling_issuer,buying_type,buying_code,buying_issuer}"). Link("metrics", "/metrics"). Link("friendbot", "/friendbot{?addr}"), } func rootAction(w http.ResponseWriter, r *http.Request) { hal.Render(w, globalRootResource) }
package horizon import ( "net/http" "github.com/jagregory/halgo" "github.com/stellar/go-horizon/render/hal" ) // RootResource is the initial map of links into the api. type RootResource struct { halgo.Links } var globalRootResource = RootResource{ Links: halgo.Links{}. Self("/"). Link("account", "/accounts/{address}"). Link("account_transactions", "/accounts/{address}/transactions{?cursor,limit,order}"). Link("transaction", "/transactions/{hash}"). Link("transactions", "/transactions{?cursor,limit,order}"). Link("orderbook", "/orderbooks{?base_type,base_code,base_issuer,counter_type,counter_code,counter_issuer}"). Link("metrics", "/metrics"). Link("friendbot", "/friendbot{?addr}"), } func rootAction(w http.ResponseWriter, r *http.Request) { hal.Render(w, globalRootResource) }
Update to use signals as use_for_related_fields does not work for all cases
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .model_cache_sharing.types import ModelCacheInfo from .model_cache_sharing import model_cache_backend """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when an update or delete happens on the model. For compatibility with Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) model_cache_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .backends.sharing.types import ModelCacheInfo from .backends.sharing import sharing_backend from .cache_manager import CacheManager """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when a model does not use manager provide by django-cache-manager. For Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if type(sender.objects) == CacheManager: logger.info('Ignoring post_save/post_delete signal from sender {0} as model manager is CachingManager'.format(sender)) return model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) sharing_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
Update to the loading dependencies...load the core rendering before the text rendering.
/* globals Demo, console, require */ Demo = { input: {}, components: {}, renderer: {} }; Demo.loader = (function() { 'use strict'; function loadScripts(sources, onComplete, message) { require(sources, function() { console.log(message); onComplete(); }); } function inputsComplete() { loadScripts(['Components/Text'], componentsComplete, 'Components loaded'); } function componentsComplete() { loadScripts(['Rendering/core'], coreRenderingComplete, 'Rendering core loaded'); } function coreRenderingComplete() { loadScripts(['Rendering/Text'], renderingComplete, 'Rendering loaded'); } function renderingComplete() { loadScripts(['model'], modelComplete, 'Model loaded'); } function modelComplete() { loadScripts(['main'], mainComplete, 'Main loaded'); } function mainComplete() { console.log('it is all loaded up'); Demo.main.initialize(); } // // Start with the input scripts, the cascade from there console.log('Starting to dynamically load project scripts'); loadScripts(['Input/Keyboard'], inputsComplete, 'Inputs loaded'); }());
/* globals Demo, console, require */ Demo = { input: {}, components: {}, renderer: {} }; Demo.loader = (function() { 'use strict'; function loadScripts(sources, onComplete, message) { require(sources, function() { onComplete(message); }); } function inputsComplete() { loadScripts(['Components/Text'], componentsComplete, 'Components loaded'); } function componentsComplete() { loadScripts(['Rendering/core', 'Rendering/Text'], renderingComplete, 'Rendering loaded'); } function renderingComplete() { loadScripts(['model'], modelComplete, 'Model loaded'); } function modelComplete() { loadScripts(['main'], mainComplete, 'Main loaded'); } function mainComplete() { console.log('it is all loaded up'); Demo.main.initialize(); } // // Start with the input scripts, the cascade from there console.log('Starting to dynamically load project scripts'); loadScripts(['Input/Mouse', 'Input/Keyboard'], inputsComplete, 'Inputs loaded'); }());
Fix up following rebase, use array of strings rather than its own func
export default function(type) { let url = null; switch (type) { case 'dc': url = ['/v1/catalog/datacenters']; break; case 'service': url = ['/v1/internal/ui/services', '/v1/health/service/']; break; case 'node': url = ['/v1/internal/ui/nodes']; break; case 'kv': url = '/v1/kv/'; break; case 'acl': url = ['/v1/acl/list']; break; case 'session': url = ['/v1/session/node/']; break; } return function(actual) { if (url === null) { return false; } if (typeof url === 'string') { return url === actual; } return url.some(function(item) { return actual.indexOf(item) === 0; }); }; }
export default function(type) { let url = null; switch (type) { case 'dc': url = ['/v1/catalog/datacenters']; break; case 'service': url = ['/v1/internal/ui/services', '/v1/health/service/']; break; case 'node': url = ['/v1/internal/ui/nodes']; break; case 'kv': url = '/v1/kv/'; break; case 'acl': url = ['/v1/acl/list']; break; case 'session': url = function(url) { return url.indexOf('/v1/session/node/') === 0; }; break; } return function(actual) { if (url === null) { return false; } if (typeof url === 'string') { return url === actual; } return url.some(function(item) { return actual.indexOf(item) === 0; }); }; }
Switch from hashHistory to browserHistory
import 'babel-polyfill'; import React from 'react'; import moment from 'moment'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from 'app/utils/configureStore'; import Root from './Root'; moment.locale('nb-NO'); global.log = function log(self = this) { console.log(self); return this; }; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); const rootElement = document.getElementById('root'); render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); if (module.hot) { module.hot.accept('./Root', () => { render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); }); }
import 'babel-polyfill'; import React from 'react'; import moment from 'moment'; import { render } from 'react-dom'; import { hashHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from 'app/utils/configureStore'; import Root from './Root'; moment.locale('nb-NO'); global.log = function log(self = this) { console.log(self); return this; }; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); const rootElement = document.getElementById('root'); render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); if (module.hot) { module.hot.accept('./Root', () => { render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); }); }
Remove unnecessary ENT_HTML5 constant, which broke PHP 5.3 compatibility
<?php namespace ColinODell\CommonMark\Util; class UrlEncoder { protected static $dontEncode = array( '%21' => '!', '%23' => '#', '%24' => '$', '%26' => '&', '%27' => '\'', '%28' => '(', '%29' => ')', '%2A' => '*', '%2B' => '+', '%2C' => ',', '%2D' => '-', '%2E' => '.', '%2F' => '/', '%3A' => ':', '%3B' => ';', '%3D' => '=', '%3F' => '?', '%40' => '@', '%5F' => '_', '%7E' => '~' ); public static function unescapeAndEncode($uri) { $decoded = html_entity_decode($uri); return strtr(rawurlencode(rawurldecode($decoded)), self::$dontEncode); } }
<?php namespace ColinODell\CommonMark\Util; class UrlEncoder { protected static $dontEncode = array( '%21' => '!', '%23' => '#', '%24' => '$', '%26' => '&', '%27' => '\'', '%28' => '(', '%29' => ')', '%2A' => '*', '%2B' => '+', '%2C' => ',', '%2D' => '-', '%2E' => '.', '%2F' => '/', '%3A' => ':', '%3B' => ';', '%3D' => '=', '%3F' => '?', '%40' => '@', '%5F' => '_', '%7E' => '~' ); public static function unescapeAndEncode($uri) { $decoded = html_entity_decode($uri, ENT_HTML5); return strtr(rawurlencode(rawurldecode($decoded)), self::$dontEncode); } }
Allow any logged-in user to perform image searches.
from django.conf.urls import patterns, url from django.views.generic import TemplateView from core.auth import perm import search.views urlpatterns = patterns('', url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'), url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'), url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'), url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'), url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'), url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'), )
from django.conf.urls import patterns, url from django.views.generic import TemplateView from core.auth import perm import search.views urlpatterns = patterns('', url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'), url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'), url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'), url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'), url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'), url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'), )
Fix minor bug with parsing JSON for play mode
var WORK = 0, PLAY = 1; function createSession(start, end, tag) { var session = new Object(); session.start = start; session.end = end; session.tag = tag; return session; } Pebble.addEventListener('ready', function() { console.log('PebbleKit JS Ready!'); }); Pebble.addEventListener('appmessage', function(e) { var dict = e.payload; console.log('Got message: ' + JSON.stringify(dict)); var mode = dict['TYPE']; switch (mode) { case WORK: var work = JSON.parse(localStorage.getItem('work')); if (!work) work = []; var session = createSession(dict['TIME_START'], dict['TIME_STOP'], dict['TAG']); work.push(session); localStorage.setItem('work', JSON.stringify(work)); break; case PLAY: var play = JSON.parse(localStorage.getItem('play')); if (!play) play = []; var session = createSession(dict['TIME_START'], dict['TIME_STOP'], dict['TAG']); play.push(session); localStorage.setItem('play', JSON.stringify(play)); break; } });
var WORK = 0, PLAY = 1; function createSession(start, end, tag) { var session = new Object(); session.start = start; session.end = end; session.tag = tag; return session; } Pebble.addEventListener('ready', function() { console.log('PebbleKit JS Ready!'); }); Pebble.addEventListener('appmessage', function(e) { var dict = e.payload; console.log('Got message: ' + JSON.stringify(dict)); var mode = dict['TYPE']; switch (mode) { case WORK: var work = JSON.parse(localStorage.getItem('work')); if (!work) work = []; var session = createSession(dict['TIME_START'], dict['TIME_STOP'], dict['TAG']); work.push(session); localStorage.setItem('work', JSON.stringify(work)); break; case PLAY: var play = localStorage.getItem('play'); if (!play) play = []; var session = createSession(dict['TIME_START'], dict['TIME_STOP'], dict['TAG']); play.push(session); localStorage.setItem('play', JSON.stringify(play)); break; } });
Refactor Chip8 to use a Memory instance.
class Memory(object): def __init__(self): self._stream = [0x00] * 4096 def __len__(self): return len(self._stream) def read_byte(self, address): return self._stream[address] def write_byte(self, address, data): self._stream[address] = data def load(self, address, data): for offset, datum in enumerate(data): self._stream[address + offset] = datum class Chip8(object): def __init__(self): self.registers = [0x00] * 16 self.index_register = 0 self.program_counter = 0x200 self.memory = Memory() # 0x000-0x1FF - Chip 8 interpreter (contains font set in emu) # 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F) # 0x200-0xFFF - Program ROM and work RAM self.screen = [0x00] * 32 * 64 self.keyboard = [0x00] * 16 self.stack = [] self.delay_timer = 0 self.sound_timer = 0
class Memory(object): def __init__(self): self._stream = [0x00] * 4096 def __len__(self): return len(self._stream) def read_byte(self, address): return self._stream[address] def write_byte(self, address, data): self._stream[address] = data def load(self, address, data): for offset, datum in enumerate(data): self._stream[address + offset] = datum class Chip8(object): def __init__(self): self.registers = [0x00] * 16 self.index_register = 0 self.program_counter = 0x200 self.memory = [0x00] * 4096 # 0x000-0x1FF - Chip 8 interpreter (contains font set in emu) # 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F) # 0x200-0xFFF - Program ROM and work RAM self.screen = [0x00] * 32 * 64 self.keyboard = [0x00] * 16 self.stack = [] self.delay_timer = 0 self.sound_timer = 0
Update the maximum allowed length for file name in sanitizer test
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=254, min_size=1)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=255, min_size=1)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
Update for to be for range. It pleases the linter. Signed-off-by: Stu Pollock <f92a33a5576f99e8c458f20aa3ed76c650ba4a5c@pivotal.io>
package main import ( "fmt" "os" "strings" "time" ) func Usage() { fmt.Fprintf(os.Stderr, "Usage: %s [STOP|START] [STOPFILE]\n", os.Args[0]) os.Exit(1) } func main() { if len(os.Args) != 3 { Usage() } mode := strings.ToLower(os.Args[1]) filename := os.Args[2] switch mode { case "start": if _, err := os.Stat(filename); os.IsNotExist(err) { f, err := os.Create(filename) if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } f.Close() } tick := time.NewTicker(time.Second) for range tick.C { if _, err := os.Stat(filename); os.IsNotExist(err) { fmt.Println("Exiting now...") return } fmt.Println("Hello") } case "stop": os.Remove(filename) default: Usage() } }
package main import ( "fmt" "os" "strings" "time" ) func Usage() { fmt.Fprintf(os.Stderr, "Usage: %s [STOP|START] [STOPFILE]\n", os.Args[0]) os.Exit(1) } func main() { if len(os.Args) != 3 { Usage() } mode := strings.ToLower(os.Args[1]) filename := os.Args[2] switch mode { case "start": if _, err := os.Stat(filename); os.IsNotExist(err) { f, err := os.Create(filename) if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } f.Close() } tick := time.NewTicker(time.Second) for _ = range tick.C { if _, err := os.Stat(filename); os.IsNotExist(err) { fmt.Println("Exiting now...") return } fmt.Println("Hello") } case "stop": os.Remove(filename) default: Usage() } }
Remove use of check_output (not in Py2.6)
from __future__ import absolute_import import os.path import pytest import subprocess from django.conf import settings from raven.versioning import fetch_git_sha, fetch_package_version from raven.utils import six def has_git_requirements(): return os.path.exists(os.path.join(settings.PROJECT_ROOT, '.git', 'refs', 'heads', 'master')) # Python 2.6 does not contain subprocess.check_output def check_output(cmd, **kwargs): return subprocess.Popen( cmd, stdout=subprocess.PIPE, **kwargs ).communicate()[0] @pytest.mark.skipif('not has_git_requirements()') def test_fetch_git_sha(): result = fetch_git_sha(settings.PROJECT_ROOT) assert result is not None assert len(result) == 40 assert isinstance(result, six.string_types) assert result == check_output( 'git rev-parse --verify HEAD', shell=True, cwd=settings.PROJECT_ROOT ).decode('latin1').strip() def test_fetch_package_version(): result = fetch_package_version('raven') assert result is not None assert isinstance(result, six.string_types)
from __future__ import absolute_import import os.path import pytest import subprocess from django.conf import settings from raven.versioning import fetch_git_sha, fetch_package_version from raven.utils import six def has_git_requirements(): return os.path.exists(os.path.join(settings.PROJECT_ROOT, '.git', 'refs', 'heads', 'master')) @pytest.mark.skipif('not has_git_requirements()') def test_fetch_git_sha(): result = fetch_git_sha(settings.PROJECT_ROOT) assert result is not None assert len(result) == 40 assert isinstance(result, six.string_types) assert result == subprocess.check_output( 'git rev-parse --verify HEAD', shell=True, cwd=settings.PROJECT_ROOT ).decode('latin1').strip() def test_fetch_package_version(): result = fetch_package_version('raven') assert result is not None assert isinstance(result, six.string_types)
Fix AMD and CommonJS were mixed up
/** * Disproperty: Disposable properties. * Copyright (c) 2015 Vladislav Zarakovsky * MIT license https://github.com/vlazar/disproperty/blob/master/LICENSE */ (function(root) { function disproperty(obj, prop, value) { return Object.defineProperty(obj, prop, { configurable: true, get: function() { delete this[prop]; return value; }, set: function(newValue) { value = newValue; } }); } // Exports: AMD, CommonJS, <script> tag if (typeof define === 'function' && define.amd) { define(function() { return disproperty }); } else if (typeof exports === 'object') { module.exports = disproperty; } else { root.disproperty = disproperty; } })(this);
/** * Disproperty: Disposable properties. * Copyright (c) 2015 Vladislav Zarakovsky * MIT license https://github.com/vlazar/disproperty/blob/master/LICENSE */ (function(root) { function disproperty(obj, prop, value) { return Object.defineProperty(obj, prop, { configurable: true, get: function() { delete this[prop]; return value; }, set: function(newValue) { value = newValue; } }); } // Exports: AMD, CommonJS, <script> tag if (typeof define === 'function' && define.amd) { module.exports = disproperty; } else if (typeof exports === 'object') { define(function() { return disproperty }); } else { root.disproperty = disproperty; } })(this);
Fix mistaken usage of require(reify/lib/runtime).enable. Related fix in meteor-babel@0.24.4: https://github.com/meteor/babel/commit/786194734c693aef91dc1ee3b9e7166d8c54fff6
"use strict"; // Install ES2015-complaint polyfills for Object, Array, String, Function, // Symbol, Map, Set, and Promise, patching the native implementations when // they are available. require("./install-promise.js"); const Module = module.constructor; const Mp = Module.prototype; // Enable the module.{watch,export,...} runtime API needed by Reify. require("reify/lib/runtime").enable(Mp); const moduleLoad = Mp.load; Mp.load = function (filename) { const result = moduleLoad.apply(this, arguments); const runSetters = this.runSetters || this.runModuleSetters; if (typeof runSetters === "function") { // Make sure we call module.runSetters (or module.runModuleSetters, a // legacy synonym) whenever a module finishes loading. runSetters.call(this); } return result; }; // Installs source map support with a hook to add functions to look for // source maps in custom places. require('./source-map-retriever-stack.js');
// Install ES2015-complaint polyfills for Object, Array, String, Function, // Symbol, Map, Set, and Promise, patching the native implementations when // they are available. require("./install-promise.js"); // Enable the module.{watch,export,...} runtime API needed by Reify. require("reify/lib/runtime").enable(module.constructor); var Mp = module.constructor.prototype; var moduleLoad = Mp.load; Mp.load = function (filename) { var result = moduleLoad.apply(this, arguments); var runSetters = this.runSetters || this.runModuleSetters; if (typeof runSetters === "function") { // Make sure we call module.runSetters (or module.runModuleSetters, a // legacy synonym) whenever a module finishes loading. runSetters.call(this); } return result; }; // Installs source map support with a hook to add functions to look for // source maps in custom places. require('./source-map-retriever-stack.js');
Change url from relative to internal service endpoint
import json from datetime import datetime import requests from .model.puzzleboard import pop_puzzleboard class HuntwordsPuzzleBoardPopCommand(object): '''Command class that processes puzzleboard-pop message''' def run(self, jreq): '''Command that processes puzzleboard-pop message''' req = json.loads(jreq) pboard = pop_puzzleboard(req['puzzle']) jpboard = json.dumps(dict(pboard)) resp = { 'puzzleboard': jpboard, 'processed': { 'at': f'{datetime.now().isoformat()}', 'status': 'ok' } } send_consumed(pboard) return json.dumps(resp) def send_consumed(pboard): '''Send async request to generate a new copy''' url = 'http://puzzleboard-consumed.openfaas-fn:8080' data = f'{{"puzzle": "{pboard.puzzle.name}" }}' requests.post(url, data)
import json from datetime import datetime import requests from .model.puzzleboard import pop_puzzleboard class HuntwordsPuzzleBoardPopCommand(object): '''Command class that processes puzzleboard-pop message''' def run(self, jreq): '''Command that processes puzzleboard-pop message''' req = json.loads(jreq) pboard = pop_puzzleboard(req['puzzle']) jpboard = json.dumps(dict(pboard)) resp = { 'puzzleboard': jpboard, 'processed': { 'at': f'{datetime.now().isoformat()}', 'status': 'ok' } } send_consumed(pboard) return json.dumps(resp) def send_consumed(pboard): '''Send async request to generate a new copy''' url = '/async-function/puzzleboard-consumed' data = f'{{"puzzle": "{pboard.puzzle.name}" }}' requests.post(url, data)
Increase to 25 agents for iOS performance test.
angular.module('MyModule') .controller('circlecontroller', function ($scope, $timeout, KineticService, UtilityService, AgentService) { 'use strict'; var stage = {}; function init() { $scope.pageName = "CIRCLES"; stage = KineticService.createStage('container', 1024, 768); for (var i = 0; i < 25; i++) { var v1 = new Vec2(UtilityService.randomInt( -10, 10), UtilityService.randomInt( -10, 10)); v1.normalize(); AgentService.createAgent(stage, null, v1, UtilityService.randomInt(4, 20)); } } init(); $scope.onTimeout = function () { mytimeout = $timeout($scope.onTimeout, 40); AgentService.checkAllBoundaries(stage.getWidth(), stage.getHeight()); AgentService.moveAllAgents(); AgentService.drawAllLayers(); }; var mytimeout = $timeout($scope.onTimeout, 40); $scope.$on("$destroy", function () { $timeout.cancel(mytimeout); }); });
angular.module('MyModule') .controller('circlecontroller', function ($scope, $timeout, KineticService, UtilityService, AgentService) { 'use strict'; var stage = {}; function init() { $scope.pageName = "CIRCLES"; stage = KineticService.createStage('container', 1024, 768); for (var i = 0; i < 5; i++) { var v1 = new Vec2(UtilityService.randomInt( -10, 10), UtilityService.randomInt( -10, 10)); v1.normalize(); AgentService.createAgent(stage, null, v1, UtilityService.randomInt(4, 20)); } } init(); $scope.onTimeout = function () { mytimeout = $timeout($scope.onTimeout, 40); AgentService.checkAllBoundaries(stage.getWidth(), stage.getHeight()); AgentService.moveAllAgents(); AgentService.drawAllLayers(); }; var mytimeout = $timeout($scope.onTimeout, 40); $scope.$on("$destroy", function () { $timeout.cancel(mytimeout); }); });
Change the wrong license headers
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.transport.http.netty.util.server; import java.util.concurrent.CountDownLatch; /** * Thread that start the back-end server */ public class ServerThread extends Thread { CountDownLatch latch; HTTPServer httpServer; public ServerThread(CountDownLatch countDownLatch, HTTPServer httpServer) { this.latch = countDownLatch; this.httpServer = httpServer; } @Override public void run() { httpServer.start(); latch.countDown(); } }
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.transport.http.netty.util.server; import java.util.concurrent.CountDownLatch; /** * Thread that start the back-end server */ public class ServerThread extends Thread { CountDownLatch latch; HTTPServer httpServer; public ServerThread(CountDownLatch countDownLatch, HTTPServer httpServer) { this.latch = countDownLatch; this.httpServer = httpServer; } @Override public void run() { httpServer.start(); latch.countDown(); } }
Make logged actions collapsed by default This makes it lot easier to follow in the console what actions are fired.
import { compose, createStore, applyMiddleware } from 'redux'; import { apiMiddleware } from 'redux-api-middleware'; import rootReducer from 'reducers/index'; const isDevelopment = process.env.NODE_ENV !== 'production'; let finalCreateStore; const storeEnhancers = [applyMiddleware(apiMiddleware)]; if (isDevelopment) { const createLogger = require('redux-logger'); const loggerMiddleware = createLogger({ collapsed: true, duration: true, }); storeEnhancers.push(applyMiddleware(loggerMiddleware)); if (__DEVTOOLS__) { const { devTools, persistState } = require('redux-devtools'); storeEnhancers.push(devTools()); storeEnhancers.push(persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))); } } finalCreateStore = compose(...storeEnhancers)(createStore); function configureStore(initialState) { const store = finalCreateStore(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('reducers', () => { const nextRootReducer = require('reducers/index'); store.replaceReducer(nextRootReducer); }); } return store; } export default configureStore;
import { compose, createStore, applyMiddleware } from 'redux'; import { apiMiddleware } from 'redux-api-middleware'; import rootReducer from 'reducers/index'; const isDevelopment = process.env.NODE_ENV !== 'production'; let finalCreateStore; const storeEnhancers = [applyMiddleware(apiMiddleware)]; if (isDevelopment) { const createLogger = require('redux-logger'); const loggerMiddleware = createLogger(); storeEnhancers.push(applyMiddleware(loggerMiddleware)); if (__DEVTOOLS__) { const { devTools, persistState } = require('redux-devtools'); storeEnhancers.push(devTools()); storeEnhancers.push(persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))); } } finalCreateStore = compose(...storeEnhancers)(createStore); function configureStore(initialState) { const store = finalCreateStore(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('reducers', () => { const nextRootReducer = require('reducers/index'); store.replaceReducer(nextRootReducer); }); } return store; } export default configureStore;
Add a little under-the-hood tests.
import { assertThat, equalTo, containsString, throws, returns, } from 'hamjest'; describe('The core function, `assertThat()`', () => { it('is a function', () => { const typeOfAssertThat = typeof assertThat; assertThat(typeOfAssertThat, equalTo('function')); }); describe('requires at least two params', () => { it('1st: the actual value', () => { assertThat('actual', equalTo('actual')); }); it('2nd: a matcher for the expected value', () => { const matcher = equalTo('expected'); assertThat('expected', matcher); }); describe('the optional 3rd param', () => { it('goes first(!), and is the assertion reason', () => { const reason = 'This is the reason, the first `assertThat()` throws as part of its message.'; try { assertThat(reason, true, equalTo(false)); } catch (e) { assertThat(e.message, containsString(reason)); } }); }); }); describe('does under the hood', () => { it('nothing when actual and expected match (using the given matcher)', () => { const passingTest = () => assertThat(true, equalTo(true)); assertThat(passingTest, returns()); }); it('throws an assertion, when actual and expected don`t match', () => { const failingTest = () => assertThat(false, equalTo(true)); assertThat(failingTest, throws()); }); }); });
import { assertThat, equalTo, containsString } from 'hamjest'; describe('The core function, `assertThat()`', () => { it('is a function', () => { const typeOfAssertThat = typeof assertThat; assertThat(typeOfAssertThat, equalTo('function')); }); describe('requires at least two params', () => { it('1st: the actual value', () => { assertThat('actual', equalTo('actual')); }); it('2nd: a matcher for the expected value', () => { const matcher = equalTo('expected'); assertThat('expected', matcher); }); describe('the optional 3rd param', () => { it('goes first(!), and is the assertion reason', () => { const reason = 'This is the reason, the first `assertThat()` throws as part of its message.'; try { assertThat(reason, true, equalTo(false)); } catch (e) { assertThat(e.message, containsString(reason)); } }); }); }); });
Add function calls and check for a night success function.
/* * For reducing boilerplate on examine listeners. * * config object: * * poi : An array or object with points of interest. * It can be an array of strings or an object with strings as the keys and * functions as the values. * * action: Needed if poi is an array of strings, * It is the function to run if the POI is found. * * (optional) notFound: Function to run if the POI is * not found. A default is provided. */ var util = require('util'); module.exports.examine = (args, player, players, config) => { // Check to make sure config is valid. if (!config.poi) { util.log("Invalid config for examine event: ", config); return; } // Set defaults as needed. config.foundAtNight = config.foundAtNight || config.found; var valid = config.poi.indexOf(args.toLowerCase()) > -1; if (valid && CommandUtil.isDaytime()) { config.found(); } else if (valid) { config.foundAtNight() } else config.nothingFound() }
/* * For reducing boilerplate on examine listeners. * * config object: * * poi : An array or object with points of interest. * It can be an array of strings or an object with strings as the keys and * functions as the values. * * action: Needed if poi is an array of strings, * It is the function to run if the POI is found. * * (optional) notFound: Function to run if the POI is * not found. A default is provided. */ var util = require('util'); module.exports.examine = (args, player, players, config) => { // Check to make sure config is valid if (!config.poi) { util.log("Invalid config for examine event: ", config); return; } var valid = poi.indexOf(args.toLowerCase()) > -1; if (valid && CommandUtil.isDaytime()) { player.say(); players.eachIf(p => CommandUtil.otherPlayerInRoom(player, p), p => { p.sayL10n(l10n, 'OTHER_LOOKING', player.getName()); }); } else if (valid) { player.sayL10n(l10n, 'DARKNESS'); } else nothingFound() }
Duplicate pages before other components Is needed when components rely on pages (e.g. editableItems-Model)
<?php class Kwc_Root_Category_Admin extends Kwc_Abstract_Admin { public function getDuplicateProgressSteps($source) { $ret = parent::getDuplicateProgressSteps($source); //pages are not duplicated because they are not returned by 'inherit'=>false //so duplicate them here $s = array( 'generatorFlags' => array('pageGenerator'=>true), 'ignoreVisible'=>true ); foreach ($source->getChildComponents($s) as $c) { $ret += $c->generator->getDuplicateProgressSteps($c); } return $ret; } public function duplicate($source, $target, Zend_ProgressBar $progressBar = null) { //pages are not duplicated because they are not returned by 'inherit'=>false //so duplicate them here $s = array( 'generatorFlags' => array('pageGenerator'=>true), 'ignoreVisible'=>true ); foreach ($source->getChildComponents($s) as $c) { $c->generator->duplicateChild($c, $target, $progressBar); } parent::duplicate($source, $target, $progressBar); } }
<?php class Kwc_Root_Category_Admin extends Kwc_Abstract_Admin { public function getDuplicateProgressSteps($source) { $ret = parent::getDuplicateProgressSteps($source); //pages are not duplicated because they are not returned by 'inherit'=>false //so duplicate them here $s = array( 'generatorFlags' => array('pageGenerator'=>true), 'ignoreVisible'=>true ); foreach ($source->getChildComponents($s) as $c) { $ret += $c->generator->getDuplicateProgressSteps($c); } return $ret; } public function duplicate($source, $target, Zend_ProgressBar $progressBar = null) { parent::duplicate($source, $target, $progressBar); //pages are not duplicated because they are not returned by 'inherit'=>false //so duplicate them here $s = array( 'generatorFlags' => array('pageGenerator'=>true), 'ignoreVisible'=>true ); foreach ($source->getChildComponents($s) as $c) { $c->generator->duplicateChild($c, $target, $progressBar); } } }
Fix thread reducer -> history
import initialState from './initialState'; import { THREAD_LOADED, THREAD_REQUESTED, THREAD_DESTROYED } from '../constants' export default function (state = initialState.thread, action) { switch (action.type) { case THREAD_REQUESTED: return Object.assign({}, state, { isFetching: true, isActive: true }) case THREAD_LOADED: return Object.assign({}, state, { posts: action.payload, isFetching: false }) case THREAD_DESTROYED: const history = Object.assign({}, state.history, { [action.payload]: state.posts }) return Object.assign({}, state, { history: history, posts: [], isActive: false }) default: return state } }
import initialState from './initialState'; import { THREAD_LOADED, THREAD_REQUESTED, THREAD_DESTROYED } from '../constants' export default function (state = initialState.thread, action) { switch (action.type) { case THREAD_REQUESTED: return Object.assign({}, state, { isFetching: true, isActive: true }) case THREAD_LOADED: return Object.assign({}, state, { posts: action.payload, isFetching: false }) case THREAD_DESTROYED: console.log(state) console.log(state.history) state.history[action.payload] = state.posts; console.log(state.history) return Object.assign({}, state, { history: state.history, posts: [], isActive: false }) default: return state } }
Update array store to match.
<?php namespace Illuminate\Session; use Illuminate\Cookie\CookieJar; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class ArrayStore extends CacheDrivenStore { /** * Load the session for the request. * * @param Illuminate\CookieJar $cookies * @param string $name * @return void */ public function start(CookieJar $cookies, $name) { $this->session = $this->createFreshSession(); } /** * Finish the session handling for the request. * * @param Symfony\Component\HttpFoundation\Response $response * @param int $lifetime * @return void */ public function finish(Response $response, $lifetime) { // No storage on array sessions... } /** * Write the session cookie to the response. * * @param Illuminate\Cookie\CookieJar $cookie * @param string $name * @param int $lifetime * @param string $path * @param string $domain * @return void */ public function getCookie(CookieJar $cookie, $name, $lifetime, $path, $domain) { // } }
<?php namespace Illuminate\Session; use Illuminate\Cookie\CookieJar; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class ArrayStore extends CacheDrivenStore { /** * Load the session for the request. * * @param Illuminate\CookieJar $cookies * @param string $name * @return void */ public function start(CookieJar $cookies, $name) { $this->session = $this->createFreshSession(); } /** * Finish the session handling for the request. * * @param Symfony\Component\HttpFoundation\Response $response * @param int $lifetime * @return void */ public function finish(Response $response, $lifetime) { // No storage on array sessions... } /** * Write the session cookie to the response. * * @param Illuminate\Cookie\CookieJar $cookie * @param string $name * @param int $lifetime * @return void */ public function getCookie(CookieJar $cookie, $name, $lifetime) { // } }
Set relations for workouts table
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWorkoutsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('workouts', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users') ->onDelete('cascade'); $table->dateTime('date'); $table->string('active_cal', 15); $table->string('avg_pace', 45); $table->string('distance', 15); $table->string('weight', 15); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('workouts'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWorkoutsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('workouts', function (Blueprint $table) { $table->increments('id'); $table->dateTime('date'); $table->string('active_cal', 15); $table->string('avg_pace', 45); $table->string('distance', 15); $table->string('weight', 15); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('workouts'); } }
Remove sticky menu for widths <500px Used the built-in `min-width` setting from jQuery.pin. Chose 500px for breakpoint because that's where the menu style changes in CSS.
$(function() { var share = new Share("#share-button-top", { networks: { facebook: { app_id: "1604147083144211", } } }); // This is still buggy and just a band-aid $(window).on('resize', function(){ $('.navbar').attr('style', '').removeData('pin'); $('.navbar').pin({ minWidth: 500 }); }); var sortAscending = {title: true}; $(".projects").isotope({ layoutMode: "fitRows", getSortData: { stars: "[data-stars] parseInt", forks: "[data-forks] parseInt", issues: "[data-issues] parseInt", language: "[data-language]", title: "[data-title]" } }); $('.landing .card').matchHeight(); $("select[name='filter']").change(function(e) { console.log("Filter by: %o", $(this).val()); $(".projects").isotope({filter: $(this).val().replace(/^\.lang-\./, '.lang-')}); }); $("select[name='sort']").change(function(e) { var val = $(this).val(); $(".projects").isotope({sortBy: val, sortAscending: sortAscending[val] || false}); }); });
$(function() { var share = new Share("#share-button-top", { networks: { facebook: { app_id: "1604147083144211", } } }); var winWidth = $(window).width(); var stickyHeader = function () { winWidth = $(window).width(); if (winWidth >= 768) { $('.navbar').attr('style', '').removeData('pin'); $('.navbar').pin(); } } stickyHeader(); // This is still buggy and just a band-aid $(window).on('resize', stickyHeader()); var sortAscending = {title: true}; $(".projects").isotope({ layoutMode: "fitRows", getSortData: { stars: "[data-stars] parseInt", forks: "[data-forks] parseInt", issues: "[data-issues] parseInt", language: "[data-language]", title: "[data-title]" } }); $('.landing .card').matchHeight(); $("select[name='filter']").change(function(e) { console.log("Filter by: %o", $(this).val()); $(".projects").isotope({filter: $(this).val().replace(/^\.lang-\./, '.lang-')}); }); $("select[name='sort']").change(function(e) { var val = $(this).val(); $(".projects").isotope({sortBy: val, sortAscending: sortAscending[val] || false}); }); });
Add generic type to ArrayList
package fr.masciulli.drinks.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import fr.masciulli.drinks.R; import fr.masciulli.drinks.model.Drink; public class DrinksListAdapter extends BaseAdapter { private List<Drink> mDrinks = new ArrayList<Drink>(); private Context mContext; public DrinksListAdapter(Context context) { mContext = context; for (int i = 0; i < 100; i++) { mDrinks.add(new Drink("Amaretto Frost")); } } @Override public int getCount() { return mDrinks.size(); } @Override public Drink getItem(int i) { return mDrinks.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View root, ViewGroup parent) { root = LayoutInflater.from(mContext).inflate(R.layout.item_drink, parent, false); ((TextView) root.findViewById(R.id.name)).setText(getItem(i).getName()); return root; } }
package fr.masciulli.drinks.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import fr.masciulli.drinks.R; import fr.masciulli.drinks.model.Drink; public class DrinksListAdapter extends BaseAdapter { private List<Drink> mDrinks = new ArrayList(); private Context mContext; public DrinksListAdapter(Context context) { mContext = context; for (int i = 0; i < 100; i++) { mDrinks.add(new Drink("Amaretto Frost")); } } @Override public int getCount() { return mDrinks.size(); } @Override public Drink getItem(int i) { return mDrinks.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View root, ViewGroup parent) { root = LayoutInflater.from(mContext).inflate(R.layout.item_drink, parent, false); ((TextView) root.findViewById(R.id.name)).setText(getItem(i).getName()); return root; } }
Include `<` and `>` into BNF attributes
/* Language: Backus–Naur Form Author: Oleg Efimov <efimovov@gmail.com> */ function(hljs){ return { contains: [ // Attribute { className: 'attribute', begin: /</, end: />/ }, // Specific { begin: /::=/, starts: { end: /$/, contains: [ { begin: /</, end: />/ }, // Common hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE ] } } ] }; }
/* Language: Backus–Naur Form Author: Oleg Efimov <efimovov@gmail.com> */ function(hljs){ return { contains: [ // Attribute { className: 'attribute', begin: /</, end: />/, excludeBegin: true, excludeEnd: true }, // Specific { begin: /::=/, starts: { end: /$/, contains: [ { begin: /</, end: />/ }, // Common hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE ] } } ] }; }
Make data.labels and data.series optional
import React from 'react'; import Chartist from 'chartist'; export default class Chart extends React.Component { componentDidMount() { this.updateChart(this.props); } componentWillReceiveProps(newProps) { this.updateChart(newProps); } componentWillUnmount() { this.chartist.detach(); } render() { return <div className = {['ct-chart', this.props.ratio].join(' ').trim()}></div>; } updateChart(props) { const {type, data, options = {}, responsiveOptions = []} = props; this.chartist ? this.chartist.update(data, options, true) : data.series ? this.chartist = new Chartist[type](React.findDOMNode(this), data, options, responsiveOptions) : null; } } Chart.propTypes = { type: React.PropTypes.string.isRequired, ratio: React.PropTypes.string, data: React.PropTypes.shape({ labels: React.PropTypes.array, series: React.PropTypes.array }), options: React.PropTypes.object, responsiveOptions: React.PropTypes.array };
import React from 'react'; import Chartist from 'chartist'; export default class Chart extends React.Component { componentDidMount() { this.updateChart(this.props); } componentWillReceiveProps(newProps) { this.updateChart(newProps); } componentWillUnmount() { this.chartist.detach(); } render() { return <div className = {['ct-chart', this.props.ratio].join(' ').trim()}></div>; } updateChart(props) { const {type, data, options = {}, responsiveOptions = []} = props; this.chartist ? this.chartist.update(data, options, true) : data.series ? this.chartist = new Chartist[type](React.findDOMNode(this), data, options, responsiveOptions) : null; } } Chart.propTypes = { type: React.PropTypes.string.isRequired, ratio: React.PropTypes.string, data: React.PropTypes.shape({ labels: React.PropTypes.array.isRequired, series: React.PropTypes.array.isRequired }), options: React.PropTypes.object, responsiveOptions: React.PropTypes.array };
Add basic type equality checking to sum type
package org.hummingbirdlang.types.composite; import org.hummingbirdlang.types.CompositeType; import org.hummingbirdlang.types.Property; import org.hummingbirdlang.types.PropertyNotFoundException; import org.hummingbirdlang.types.Type; /** * Disjoint union type (aka. sum type): it is composed of members A and B. * Eventually the union is discriminated into either A or B. */ public class SumType extends CompositeType { public final Type[] subTypes; public SumType(Type[] subTypes) { this.subTypes = subTypes; } @Override public Property getProperty(String name) throws PropertyNotFoundException { throw new PropertyNotFoundException("Not yet implemented"); } /** * Other type must be equal to or smaller than this union for equality * to hold. */ @Override public boolean equals(Type otherType) { // Equality check first. if (this == otherType) { return true; } // Then check if we contain the other type. for (Type subType : this.subTypes) { if (subType.equals(otherType)) { return true; } } return false; } @Override public String toString() { StringBuilder result = new StringBuilder(); boolean bar = false; for (Type subType : this.subTypes) { if (bar) { result.append(" | "); } else { bar = true; } result.append(subType.toString()); } return result.toString(); } }
package org.hummingbirdlang.types.composite; import org.hummingbirdlang.types.CompositeType; import org.hummingbirdlang.types.Property; import org.hummingbirdlang.types.PropertyNotFoundException; import org.hummingbirdlang.types.Type; /** * Disjoint union type (aka. sum type): it is composed of members A and B. * Eventually the union is discriminated into either A or B. */ public class SumType extends CompositeType { public final Type[] subTypes; public SumType(Type[] subTypes) { this.subTypes = subTypes; } @Override public Property getProperty(String name) throws PropertyNotFoundException { throw new PropertyNotFoundException("Not yet implemented"); } @Override public String toString() { StringBuilder result = new StringBuilder(); boolean bar = false; for (Type subType : this.subTypes) { if (bar) { result.append(" | "); } else { bar = true; } result.append(subType.toString()); } return result.toString(); } }
Mark all notifications with the same subject as read
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Core\Notifications\Commands; use Flarum\Core\Notifications\Notification; use Flarum\Core\Exceptions\PermissionDeniedException; use Flarum\Core\Support\DispatchesEvents; class ReadNotificationHandler { /** * @param ReadNotification $command * @return Notification * @throws \Flarum\Core\Exceptions\PermissionDeniedException */ public function handle(ReadNotification $command) { $actor = $command->actor; if ($actor->isGuest()) { throw new PermissionDeniedException; } $notification = Notification::where('user_id', $actor->id)->findOrFail($command->notificationId); Notification::where([ 'user_id' => $actor->id, 'type' => $notification->type, 'subject_id' => $notification->subject_id ]) ->update(['is_read' => true]); return $notification; } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Core\Notifications\Commands; use Flarum\Core\Notifications\Notification; use Flarum\Core\Exceptions\PermissionDeniedException; use Flarum\Core\Support\DispatchesEvents; class ReadNotificationHandler { /** * @param ReadNotification $command * @return Notification * @throws \Flarum\Core\Exceptions\PermissionDeniedException */ public function handle(ReadNotification $command) { $actor = $command->actor; if ($actor->isGuest()) { throw new PermissionDeniedException; } $notification = Notification::where('user_id', $actor->id)->findOrFail($command->notificationId); $notification->read(); $notification->save(); return $notification; } }
Move call to parent constructor to top
<?php namespace app; class MyPhixApp extends \Phix\App { public function __construct($config = null) { parent::__construct($config); $this ->viewsDir(__DIR__ . '/views') ->layout('layout') ->reg('site_title', 'My Application') ->get('/', function($app) { $app->render('home'); }) ->get('/unreachable', function($app) { $app->redirect('/'); }) ->get('/notfound', function($app) { $app->notFound('Ooops. The URL ' . $app->escape($app->requestUri()) . ' is not there.'); }); } }
<?php namespace app; class MyPhixApp extends \Phix\App { public function __construct($config = null) { $this ->viewsDir(__DIR__ . '/views') ->layout('layout') ->reg('site_title', 'My Application') ->get('/', function($app) { $app->render('home'); }) ->get('/unreachable', function($app) { $app->redirect('/'); }) ->get('/notfound', function($app) { $app->notFound('Ooops. The URL ' . $app->escape($app->requestUri()) . ' is not there.'); }); parent::__construct($config); } }
Remove unnecessary override of getById git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1275 0d517254-b314-0410-acde-c619094fa49f
package edu.northwestern.bioinformatics.studycalendar.dao; import org.springframework.transaction.annotation.Transactional; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.StudyParticipantAssignment; import java.util.List; /** * @author Rhett Sutphin */ @Transactional(readOnly = true) public class StudyDao extends StudyCalendarGridIdentifiableDao<Study> { @Override public Class<Study> domainClass() { return Study.class; } @Transactional(readOnly = false) public void save(Study study) { getHibernateTemplate().saveOrUpdate(study); } @SuppressWarnings({ "unchecked" }) public List<Study> getAll() { return getHibernateTemplate().find("from Study"); } @SuppressWarnings({ "unchecked" }) public List<StudyParticipantAssignment> getAssignmentsForStudy(Integer studyId) { return getHibernateTemplate().find( "select a from StudyParticipantAssignment a inner join a.studySite ss inner join a.participant p where ss.study.id = ? order by p.lastName, p.firstName", studyId); } }
package edu.northwestern.bioinformatics.studycalendar.dao; import org.springframework.transaction.annotation.Transactional; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.StudyParticipantAssignment; import java.util.List; /** * @author Rhett Sutphin */ @Transactional(readOnly = true) public class StudyDao extends StudyCalendarGridIdentifiableDao<Study> { public Class<Study> domainClass() { return Study.class; } @Transactional(readOnly = false) public void save(Study study) { getHibernateTemplate().saveOrUpdate(study); } public List<Study> getAll() { return getHibernateTemplate().find("from Study"); } public List<StudyParticipantAssignment> getAssignmentsForStudy(Integer studyId) { return getHibernateTemplate().find( "select a from StudyParticipantAssignment a inner join a.studySite ss inner join a.participant p where ss.study.id = ? order by p.lastName, p.firstName", studyId); } public Study getById(int id) { return (Study) getHibernateTemplate().get(Study.class, new Integer(id)); } }
Call onSelect event when a game is clicked.
import React from 'react'; import '../styles/games.css'; export default class GameList extends React.Component { constructor(props) { super(props); this.state = {games: []}; } componentWillReceiveProps(nextProps) { let games = []; nextProps.games.forEach(game => { games.push(<li key={game.id} data-id={game.id} onClick={this.handleClick.bind(this)}>{game.title}</li>); }); this.setState({games: games}); } handleClick(event) { this.props.onSelect(this.props.games.find(game => game.id === Number(event.target.dataset.id))); } render() { if (this.props.games.length > 0) { return ( <ul className='games'>{this.state.games}</ul> ); } else { return ( <div className='games empty'>No games found.</div> ); } } }
import React from 'react'; import '../styles/games.css'; export default class GameList extends React.Component { constructor(props) { super(props); this.state = {games: []}; } componentWillReceiveProps(nextProps) { let games = []; nextProps.games.forEach(game => { games.push(<li key={game.id}>{game.title}</li>); }); this.setState({games: games}); } render() { if (this.props.games.length > 0) { return ( <ul className='games'>{this.state.games}</ul> ); } else { return ( <div className='games empty'>No games found.</div> ); } } }
Simplify config helpers, add overwriteConfig option
'use strict'; var fs = require('fs'), _ = require('lodash'); //rsvp = require('rsvp'); var _save, saveConfig, overwriteConfig, loadConfig, deleteConfigKey; _save = function(config, fileLocation) { // TODO: convert _save to a promise fs.writeFileSync(fileLocation, JSON.stringify(config, null, 2)); return config; }; saveConfig = function(newConfig, oldConfig, fileLocation) { var config = _.merge(oldConfig, newConfig, function(prev, next) { return next ? next : prev; }); return _save(config, fileLocation); }; overwriteConfig = function(config, fileLocation) { return _save(config, fileLocation); }; loadConfig = function(fileLocation) { // TODO: convert loadConfig to a promise var config = null; try { config = JSON.parse(fs.readFileSync(fileLocation)); } catch (err) { // we don't want to break on bad config files, just don't load them // TODO: tell someone that a config file is not parseable console.log(err); } return config; }; deleteConfigKey = function(configKey, fileLocation) { // TODO: convert deleteConfigKey to a promise var config = loadConfig(fileLocation); delete config[configKey]; return _save(config, fileLocation); }; module.exports = { saveConfig: saveConfig, overwriteConfig: overwriteConfig, loadConfig: loadConfig, deleteConfigKey: deleteConfigKey };
'use strict'; var fs = require('fs'), path = require('path'), _ = require('lodash'); //rsvp = require('rsvp'); var _save, saveConfig, loadConfig, deleteConfigKey; _save = function(config, filePath, fileName) { // TODO: convert _save to a promise var fileName = path.join(filePath, fileName); fs.writeFileSync(fileName, JSON.stringify(config, null, 2)); return config; }; saveConfig = function(newConfig, oldConfig, filePath, fileName) { config = _.merge(oldConfig, newConfig, function(prev, next) { return next ? next : prev; }); return _save(config, filePath, fileName); }; loadConfig = function(filePath, fileName) { // TODO: convert loadConfig to a promise var config = null; try { config = JSON.parse(fs.readFileSync(path.join(configFolder, useCaseFileName))); } catch (err) { // we don't want to break on bad config files, just don't load them // TODO: tell someone that a config file is not parseable console.log(err); } return config; }; deleteConfigKey = function(configKey, filePath, fileName) { // TODO: convert deleteConfigKey to a promise var config = loadConfig(filePath, fileName); delete config[configKey]; return _save(config, filePath, fileName); }; module.exports = { saveConfig: saveConfig, loadConfig: loadConfig, deleteConfigKey: deleteConfigKey };
Fix updating nodes: Use new $http API.
'use strict'; angular.module('ffffng') .controller('UpdateNodeCtrl', function ($scope, Navigator, NodeService, config) { $scope.config = config; $scope.node = undefined; $scope.token = undefined; $scope.saved = false; $scope.hasData = function () { return $scope.node !== undefined; }; $scope.onSubmitToken = function (token) { $scope.token = token; return NodeService.getNode(token) .then(function (response) { $scope.node = response.data; }); }; $scope.save = function (node) { return NodeService.updateNode(node, $scope.token) .then(function (response) { $scope.node = response.data.node; $scope.token = response.data.token; $scope.saved = true; }); }; $scope.cancel = function () { Navigator.home(); }; if (window.__nodeToken) { var token = window.__nodeToken; window.__nodeToken = undefined; $scope.onSubmitToken(token); } });
'use strict'; angular.module('ffffng') .controller('UpdateNodeCtrl', function ($scope, Navigator, NodeService, config) { $scope.config = config; $scope.node = undefined; $scope.token = undefined; $scope.saved = false; $scope.hasData = function () { return $scope.node !== undefined; }; $scope.onSubmitToken = function (token) { $scope.token = token; return NodeService.getNode(token) .success(function (node) { $scope.node = node; }); }; $scope.save = function (node) { return NodeService.updateNode(node, $scope.token) .then(function (response) { $scope.node = response.data.node; $scope.token = response.data.token; $scope.saved = true; }); }; $scope.cancel = function () { Navigator.home(); }; if (window.__nodeToken) { var token = window.__nodeToken; window.__nodeToken = undefined; $scope.onSubmitToken(token); } });