text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Speed up python parsing a bit
/* * Copyright (c) 2005, Your Corporation. All Rights Reserved. */ package com.jetbrains.python.psi; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.jetbrains.python.PythonFileType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Constructor; public class PyElementType extends IElementType { protected Class<? extends PsiElement> _psiElementClass; private static final Class[] PARAMETER_TYPES = new Class[]{ASTNode.class}; private Constructor<? extends PsiElement> myConstructor; public PyElementType(@NotNull @NonNls String debugName) { super(debugName, PythonFileType.INSTANCE.getLanguage()); } public PyElementType(@NonNls String debugName, Class<? extends PsiElement> psiElementClass) { this(debugName); _psiElementClass = psiElementClass; } @Nullable public PsiElement createElement(ASTNode node) { if (_psiElementClass == null) { return null; } try { if (myConstructor == null) { myConstructor = _psiElementClass.getConstructor(PARAMETER_TYPES); } return myConstructor.newInstance(node); } catch (Exception e) { throw new IllegalStateException("No necessary constructor for " + node.getElementType(), e); } } @Override public String toString() { return "Py:" + super.toString(); } }
/* * Copyright (c) 2005, Your Corporation. All Rights Reserved. */ package com.jetbrains.python.psi; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.jetbrains.python.PythonFileType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class PyElementType extends IElementType { protected Class<? extends PsiElement> _psiElementClass; private static final Class[] PARAMETER_TYPES = new Class[]{ASTNode.class}; public PyElementType(@NotNull @NonNls String debugName) { super(debugName, PythonFileType.INSTANCE.getLanguage()); } public PyElementType(@NonNls String debugName, Class<? extends PsiElement> psiElementClass) { this(debugName); _psiElementClass = psiElementClass; } @Nullable public PsiElement createElement(ASTNode node) { if (_psiElementClass == null) { return null; } try { return _psiElementClass.getConstructor(PARAMETER_TYPES).newInstance(node); } catch (Exception e) { throw new IllegalStateException("No necessary constructor for " + node.getElementType(), e); } } @Override public String toString() { return "Py:" + super.toString(); } }
Add Channel deletion side-effect that updates affected lessons
from django.db.models import F from django.db.models.signals import pre_delete from django.dispatch import receiver from .models import ChannelMetadata from .models import ContentNode from kolibri.core.notifications.models import LearnerProgressNotification from kolibri.core.lessons.models import Lesson @receiver(pre_delete, sender=ContentNode) def cascade_delete_node(sender, instance=None, *args, **kwargs): """ For a given node, we delete all notifications objects whose contentnode is the instance's node.. """ LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete() @receiver(pre_delete, sender=ChannelMetadata) def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs): """ For a given channel, decrement the order of all channels that come after this channel. """ ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1) @receiver(pre_delete, sender=ChannelMetadata) def update_lesson_resources_before_delete(sender, instance=None, *args, **kwargs): # Update the resources array of all lessons to ensure they don't have # any deleted content lessons = Lesson.objects.all() for lesson in lessons: updated_resources = [r for r in lesson.resources if r['channel_id'] != instance.id] if len(updated_resources) < len(lesson.resources): lesson.resources = updated_resources lesson.save()
from django.db.models import F from django.db.models.signals import pre_delete from django.dispatch import receiver from .models import ChannelMetadata from .models import ContentNode from kolibri.core.notifications.models import LearnerProgressNotification @receiver(pre_delete, sender=ContentNode) def cascade_delete_node(sender, instance=None, *args, **kwargs): """ For a given node, we delete all notifications objects whose contentnode is the instance's node.. """ LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete() @receiver(pre_delete, sender=ChannelMetadata) def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs): """ For a given channel, decrement the order of all channels that come after this channel. """ ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
Add a test to verify that the controller calls the calculator service properly.
'use strict'; var expect = require('chai').expect; var angular = require('angular'); var helloWorldModule = require('./helloWorld.controller'); var calculatorModule = require('../services/calculator/calculator.service'); describe('helloWorld', function() { var $controller; var mockCalculator; beforeEach(function() { angular.mock.module(helloWorldModule.moduleName); mockCalculator = { calculateResult: null, calculate: sinon.spy(function() { return mockCalculator.calculateResult; }), }; angular.mock.module(function ($provide) { $provide.value(calculatorModule.factoryName, mockCalculator); }); angular.mock.inject(['$controller', function(_$controller_) { $controller = _$controller_; }]); }); it('should have a message', function() { var controller = buildController(); expect(controller.message).to.equal('Hello Angular explorers!') }); it('should calculate the result of the operands and operator', function() { var controller = buildController(); controller.operand1 = 5; controller.operand2 = 10; controller.operator = '*'; mockCalculator.calculateResult = 'mocked result'; controller.equals(); expect(controller.result).to.equal('mocked result'); expect(controller.error).to.be.null; sinon.assert.calledOnce(mockCalculator.calculate); sinon.assert.calledWith(mockCalculator.calculate, '*', 5, 10); }); function buildController() { return $controller(helloWorldModule.controllerName); } });
'use strict'; var expect = require('chai').expect; var angular = require('angular'); var helloWorldModule = require('./helloWorld.controller'); var calculatorModule = require('../services/calculator/calculator.service'); describe('helloWorld', function() { var $controller; var mockCalculator; beforeEach(function() { angular.mock.module(helloWorldModule.moduleName); mockCalculator = { calculateResult: null, calculate: sinon.spy(function() { return mockCalculator.calculateResult; }), }; angular.mock.module(function ($provide) { $provide.value(calculatorModule.factoryName, mockCalculator); }); angular.mock.inject(['$controller', function(_$controller_) { $controller = _$controller_; }]); }); it ('should have a message', function() { var controller = buildController(); expect(controller.message).to.equal('Hello Angular explorers!') }); function buildController() { return $controller(helloWorldModule.controllerName); } });
Remove infinite loop if user is neither native nor verified
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not request.path == DETACH_PATH: return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not request.path.startswith(ACTIVATE_PATH): return HttpResponseRedirect(ACTIVATE_PATH)
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api'): if not request.user.is_anonymous \ and not request.user.is_native \ and not request.path == DETACH_PATH: return HttpResponseRedirect(DETACH_PATH) if not request.user.is_anonymous \ and not request.user.is_mail_verified \ and not request.path.startswith(ACTIVATE_PATH): return HttpResponseRedirect(ACTIVATE_PATH)
Fix SSHOpener to use the new ClosingSubFS
from ._base import Opener from ._registry import registry from ..subfs import ClosingSubFS @registry.install class SSHOpener(Opener): protocols = ['ssh'] @staticmethod def open_fs(fs_url, parse_result, writeable, create, cwd): from ..sshfs import SSHFS ssh_host, _, dir_path = parse_result.resource.partition('/') ssh_host, _, ssh_port = ssh_host.partition(':') ssh_port = int(ssh_port) if ssh_port.isdigit() else 22 ssh_fs = SSHFS( ssh_host, port=ssh_port, user=parse_result.username, passwd=parse_result.password, ) if dir_path: return ssh_fs.opendir(dir_path, factory=ClosingSubFS) else: return ssh_fs
from ._base import Opener from ._registry import registry @registry.install class SSHOpener(Opener): protocols = ['ssh'] @staticmethod def open_fs(fs_url, parse_result, writeable, create, cwd): from ..sshfs import SSHFS ssh_host, _, dir_path = parse_result.resource.partition('/') ssh_host, _, ssh_port = ssh_host.partition(':') ssh_port = int(ssh_port) if ssh_port.isdigit() else 22 ssh_fs = SSHFS( ssh_host, port=ssh_port, user=parse_result.username, passwd=parse_result.password, ) return ssh_fs.opendir(dir_path) if dir_path else ssh_fs
Fix usage of java 11 API
/** * */ package at.porscheinformatik.seleniumcomponents; import java.util.Locale; /** * @author Daniel Furtlehner */ public final class LocaleUtils { private LocaleUtils() { super(); } /** * Parses the locale from the specified string. Expects the locale in the form of: language [SEPARATOR country * [SEPARATOR variant]]. The SEPARATOR may be '-' or '_'. If the string is empty or null it returns null. * * @param value the string * @return the locale */ public static Locale toLocale(String value) { if (value == null || value.trim().length() == 0) { return Locale.ROOT; } String[] values = value.split("[_-]"); if (values.length >= 3) { return new Locale(values[0], values[1], values[2]); } if (values.length == 2) { return new Locale(values[0], values[1]); } return new Locale(values[0]); } }
/** * */ package at.porscheinformatik.seleniumcomponents; import java.util.Locale; /** * @author Daniel Furtlehner */ public final class LocaleUtils { private LocaleUtils() { super(); } /** * Parses the locale from the specified string. Expects the locale in the form of: language [SEPARATOR country * [SEPARATOR variant]]. The SEPARATOR may be '-' or '_'. If the string is empty or null it returns null. * * @param value the string * @return the locale */ public static Locale toLocale(String value) { if (value == null || value.isBlank()) { return Locale.ROOT; } String[] values = value.split("[_-]"); if (values.length >= 3) { return new Locale(values[0], values[1], values[2]); } if (values.length == 2) { return new Locale(values[0], values[1]); } return new Locale(values[0]); } }
Fix deprecation tag to link to service instead of context.
/* /* * Copyright © 2014 Cask Data, 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. */ package co.cask.cdap.api.procedure; import co.cask.cdap.api.RuntimeContext; import co.cask.cdap.api.ServiceDiscoverer; import co.cask.cdap.api.data.DataSetContext; /** * This interface represents the Procedure context. * * @deprecated As of version 2.6.0, with no direct replacement, see {@link co.cask.cdap.api.service.Service} */ @Deprecated public interface ProcedureContext extends RuntimeContext, DataSetContext, ServiceDiscoverer { /** * @return The specification used to configure this {@link Procedure} instance. */ ProcedureSpecification getSpecification(); /** * @return number of instances for the procedure. */ int getInstanceCount(); }
/* /* * Copyright © 2014 Cask Data, 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. */ package co.cask.cdap.api.procedure; import co.cask.cdap.api.RuntimeContext; import co.cask.cdap.api.ServiceDiscoverer; import co.cask.cdap.api.data.DataSetContext; /** * This interface represents the Procedure context. * * @deprecated As of version 2.6.0, replaced by {@link co.cask.cdap.api.service.ServiceWorkerContext} */ @Deprecated public interface ProcedureContext extends RuntimeContext, DataSetContext, ServiceDiscoverer { /** * @return The specification used to configure this {@link Procedure} instance. */ ProcedureSpecification getSpecification(); /** * @return number of instances for the procedure. */ int getInstanceCount(); }
Make small change in panel size
package de.tudresden.inf.lat.born.main; import java.awt.Dimension; import java.util.Objects; import javax.swing.JFrame; import org.semanticweb.owlapi.apibinding.OWLManager; /** * This is used to start the graphical user interface. * * @author Julian Mendez */ public class BornStandalone { /** * Starts the application from the command line. The parameters are ignored. * * @param args * parameters (which are ignored) */ public static void main(String[] args) { Objects.requireNonNull(args); (new BornStandalone()).run(); } /** * Starts the graphical user interface. */ public void run() { BornStarter starter = new BornStarter(OWLManager.createOWLOntologyManager()); JFrame frame = new JFrame(); frame.add(starter.getPanel().getView().getPanel()); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setSize(new Dimension(1024, 800)); frame.setVisible(true); } }
package de.tudresden.inf.lat.born.main; import java.awt.Dimension; import java.util.Objects; import javax.swing.JFrame; import org.semanticweb.owlapi.apibinding.OWLManager; /** * This is used to start the graphical user interface. * * @author Julian Mendez */ public class BornStandalone { /** * Starts the application from the command line. The parameters are ignored. * * @param args * parameters (which are ignored) */ public static void main(String[] args) { Objects.requireNonNull(args); (new BornStandalone()).run(); } /** * Starts the graphical user interface. */ public void run() { BornStarter starter = new BornStarter(OWLManager.createOWLOntologyManager()); JFrame frame = new JFrame(); frame.add(starter.getPanel().getView().getPanel()); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setSize(new Dimension(1024, 720)); frame.setVisible(true); } }
Add registration button to landing page
// Landing page for AAF. import React from 'react'; import { Link } from 'react-router-dom'; const Landing = (props) => { return ( <div> <h1>Landing page</h1> <ul> <li> <Link to="/dashboard">Click me for dashboard</Link> </li> <li> <Link to="/secure/pairing">Click me for secure/pairing</Link> </li> <li> <Link to="/secure/messaging">Click me for messaging</Link> </li> <li> <Link to="/wishlist">Click me for wishlistPublic</Link> </li> <li> <Link to="/secure/wishlist">Click me for secure/wishlistPrivate</Link> </li> <li> <Link to="/secure/org">Click me for secure/org</Link> </li> <li> <Link to="/aboutus">Click me for about us</Link> </li> <li> <Link to="/registration"><button>Register</button></Link> </li> </ul> </div> ); }; export default Landing;
// Landing page for AAF. import React from 'react'; import { Link } from 'react-router-dom'; const Landing = (props) => { return ( <div> <h1>Landing page</h1> <ul> <li> <Link to="/dashboard">Click me for dashboard</Link> </li> <li> <Link to="/secure/pairing">Click me for secure/pairing</Link> </li> <li> <Link to="/secure/messaging">Click me for messaging</Link> </li> <li> <Link to="/wishlist">Click me for wishlistPublic</Link> </li> <li> <Link to="/secure/wishlist">Click me for secure/wishlistPrivate</Link> </li> <li> <Link to="/secure/org">Click me for secure/org</Link> </li> <li> <Link to="/aboutus">Click me for about us</Link> </li> </ul> </div> ); }; export default Landing;
Use list to store functions for type safety.
package com.legendzero.lzlib.database; import com.legendzero.lzlib.data.SQLData; import java.util.Iterator; import java.util.List; import java.util.function.Function; public class SQLBatch<T> extends SQLStatement { private final List<Function<? super T, Object>> mappingFunctions; public SQLBatch(String update, List<Function<? super T, Object>> mappingFunctions) { super(update); this.mappingFunctions = mappingFunctions; } public SQLBatch(SQLStatement sqlStatement, List<Function<? super T, Object>> mappingFunctions) { super(sqlStatement); this.mappingFunctions = mappingFunctions; } public List<Function<? super T, Object>> getMappingFunctions() { return this.mappingFunctions; } public final int[] batch(SQLData<?> data, Iterable<T> iterable) { return data.batch(this, iterable); } public final int[] batch(SQLData<?> data, Iterator<T> iterator) { return data.batch(this, iterator); } public final int[] batch(SQLData<?> data, T... values) { return data.batch(this, values); } }
package com.legendzero.lzlib.database; import com.legendzero.lzlib.data.SQLData; import java.util.Iterator; import java.util.function.Function; public class SQLBatch<T> extends SQLStatement { private final Function<? super T, Object>[] mappingFunctions; public SQLBatch(String update, Function<? super T, Object>... mappingFunctions) { super(update); this.mappingFunctions = mappingFunctions; } public SQLBatch(SQLStatement sqlStatement, Function<? super T, Object>... mappingFunctions) { super(sqlStatement); this.mappingFunctions = mappingFunctions; } public Function<? super T, Object>[] getMappingFunctions() { return this.mappingFunctions; } public final int[] batch(SQLData<?> data, Iterable<T> iterable) { return data.batch(this, iterable); } public final int[] batch(SQLData<?> data, Iterator<T> iterator) { return data.batch(this, iterator); } public final int[] batch(SQLData<?> data, T... values) { return data.batch(this, values); } }
Add --admin option for connecting in admin mode
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option('--endpoint', type=str) @click.option('--admin', is_flag=True) @click.pass_context def cli(ctx, endpoint, admin): ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'], admin=admin, ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
Move Type Mapping To Export Default In Index.JS Move the Type Mapping to export default, in Index.js because to allow the developer to develop components of a theme for each of the types that Frig allows to be rendered.
import Form from './components/form.js' import Input from './components/input.js' import UnboundInput from './components/unbound_input.js' import Submit from './components/submit.js' import FormErrorList from './components/form_error_list.js' import Fieldset from './components/fieldset.js' import FieldsetText from './components/fieldset_text.js' import ValueLinkedSelect from './components/value_linked_select.js' import util from './util.js' import typeMapping from './type_mapping.js' import * as factories from './factories.js' const HigherOrderComponents = { Boolean: require('./higher_order_components/boolean.js'), Focusable: require('./higher_order_components/focusable.js'), } // Setter and getter for the Frig default theme function defaultTheme(theme) { if (theme === null) return Form.defaultProps.theme if (typeof theme !== 'object') { throw new Error('Invalid Frig theme. Expected an object') } Form.originalClass.defaultProps.theme = theme UnboundInput.originalClass.defaultProps.theme = theme return true } // This is so consumers can call `Frig.defaultTheme()`. // All other exports are named and must be imported/destructured. export default { defaultTheme, typeMapping, } export { Form, Input, UnboundInput, Submit, FormErrorList, Fieldset, FieldsetText, ValueLinkedSelect, HigherOrderComponents, util, factories, }
import Form from './components/form.js' import Input from './components/input.js' import UnboundInput from './components/unbound_input.js' import Submit from './components/submit.js' import FormErrorList from './components/form_error_list.js' import Fieldset from './components/fieldset.js' import FieldsetText from './components/fieldset_text.js' import ValueLinkedSelect from './components/value_linked_select.js' import util from './util.js' import typeMapping from './type_mapping.js' import * as factories from './factories.js' const HigherOrderComponents = { Boolean: require('./higher_order_components/boolean.js'), Focusable: require('./higher_order_components/focusable.js'), } // Setter and getter for the Frig default theme function defaultTheme(theme) { if (theme === null) return Form.defaultProps.theme if (typeof theme !== 'object') { throw new Error('Invalid Frig theme. Expected an object') } Form.originalClass.defaultProps.theme = theme UnboundInput.originalClass.defaultProps.theme = theme return true } // This is so consumers can call `Frig.defaultTheme()`. // All other exports are named and must be imported/destructured. export default { defaultTheme, } export { Form, Input, UnboundInput, Submit, FormErrorList, Fieldset, FieldsetText, ValueLinkedSelect, HigherOrderComponents, util, typeMapping, factories, }
Clear badge text and set it when enabling or disabling badge text option
import backgroundStore from './store'; import { startCountingBadgeTextAndAddListeners, stopCountingBadgeTextAndRemoveListeners, } from './badge-text-listeners'; // Init background // First check if we even want to check for badge text, if true then start a // timeout to wait for the browser to start up and add call startCounting... backgroundStore.subscribe(subscribeToBadgeTextState(backgroundStore)); function subscribeToBadgeTextState(store) { let prevValue = store.getState().general.showTabCountBadgeText; const LOADING_TEXT = '...'; if (prevValue) { // Show loading indicator browser.browserAction.setBadgeText({ text: LOADING_TEXT, }); setTimeout(() => startCountingBadgeTextAndAddListeners(), 1000); } return () => { const nextValue = store.getState().general.showTabCountBadgeText; // These should only run if the setting actually changed // If the initial prevValue is already true we dont need to add these // listeners if (nextValue && !prevValue) { browser.browserAction.setBadgeText({ text: LOADING_TEXT }); startCountingBadgeTextAndAddListeners(); } else if (!nextValue && prevValue) { browser.browserAction.setBadgeText({ text: '' }); stopCountingBadgeTextAndRemoveListeners(); } prevValue = nextValue; }; }
import backgroundStore from './store'; import { startCountingBadgeTextAndAddListeners, stopCountingBadgeTextAndRemoveListeners, } from './badge-text-listeners'; // Init background // First check if we even want to check for badge text, if true then start a // timeout to wait for the browser to start up and add call startCounting... backgroundStore.subscribe(subscribeToBadgeTextState(backgroundStore)); function subscribeToBadgeTextState(store) { let prevValue = store.getState().general.showTabCountBadgeText; if (prevValue) { const LOADING_TEXT = '...'; // Show loading indicator browser.browserAction.setBadgeText({ text: LOADING_TEXT, }); setTimeout(() => startCountingBadgeTextAndAddListeners(), 1000); } return () => { const nextValue = store.getState().general.showTabCountBadgeText; // These should only run if the setting actually changed // If the initial prevValue is already true we dont need to add these // listeners if (nextValue && !prevValue) { startCountingBadgeTextAndAddListeners(); } else if (!nextValue && prevValue) { stopCountingBadgeTextAndRemoveListeners(); } prevValue = nextValue; }; }
NetworkFeeder: Set default delay to 5 seconds (because of my slow laptop).
import time import threading import socket class NetworkFeeder: """ A class that feeds data to a socket port """ def __init__(self, proto, host, port, data, is_client=True, delay=5, timeout=2): if not is_client: raise NotImplementedError("Server mode is not implemented.") if proto != "tcp": raise NotImplementedError("Only TCP mode is supported for now.") self._proto = proto self._is_client = is_client self._delay = delay self._data = data self._host = host self._port = port self._timeout = timeout t = threading.Thread(target=self.worker) t.start() def worker(self): if self._delay: time.sleep(self._delay) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM if self._proto == "tcp" else socket.SOCK_DGRAM) sock.settimeout(self._timeout) sock.connect((self._host, self._port)) sock.send(self._data) sock.close()
import time import threading import socket class NetworkFeeder: """ A class that feeds data to a socket port """ def __init__(self, proto, host, port, data, is_client=True, delay=3, timeout=2): if not is_client: raise NotImplementedError("Server mode is not implemented.") if proto != "tcp": raise NotImplementedError("Only TCP mode is supported for now.") self._proto = proto self._is_client = is_client self._delay = delay self._data = data self._host = host self._port = port self._timeout = timeout t = threading.Thread(target=self.worker) t.start() def worker(self): if self._delay: time.sleep(self._delay) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM if self._proto == "tcp" else socket.SOCK_DGRAM) sock.settimeout(self._timeout) sock.connect((self._host, self._port)) sock.send(self._data) sock.close()
Add challenge to basic auth for staging server
const express = require('express'), basicAuth = require('express-basic-auth'), app = express(); // Add authentication only if the ENV variable is present // The format must be user1=password1,user2=password2... if (process.env.BASIC_AUTH_USERS) { let users = {}; process.env.BASIC_AUTH_USERS.split(',').forEach(userString => { let user = userString.split(':'); users[user[0]] = user[1]; }, this); // Apply the middleware app.use(basicAuth({ users: users, challenge: true, realm: process.env.BASIC_AUTH_REALM })); } // Port const port = process.env.PORT || 3001; // Static files app.use(express.static('build')); app.get('/', (req, res) => { res.send('hello world'); }); app.get('/status.json', (req, res) => { res.json({ status: 'ok' }); }); app.get('*', (req, res) => { res.sendfile(__dirname + '/build/index.html'); }); // Create the server app.listen(port, () => { console.log('Our app is running on http://localhost:' + port); });
const express = require('express'), basicAuth = require('express-basic-auth'), app = express(); // Add authentication only if the ENV variable is present // The format must be user1=password1,user2=password2... if (process.env.BASIC_AUTH_USERS) { let users = {}; process.env.BASIC_AUTH_USERS.split(',').forEach(userString => { let user = userString.split(':'); users[user[0]] = user[1]; }, this); // Apply the middleware app.use(basicAuth({ users: users })); } // Port const port = process.env.PORT || 3001; // Static files app.use(express.static('build')); app.get('/', (req, res) => { res.send('hello world'); }); app.get('/status.json', (req, res) => { res.json({ status: 'ok' }); }); app.get('*', (req, res) => { res.sendfile(__dirname + '/build/index.html'); }); // Create the server app.listen(port, () => { console.log('Our app is running on http://localhost:' + port); });
Add some other famous streaming websites
var targetPages = [ "*://*.youtube.com/watch*", "*://*.vimeo.com/*", "*://*.streamable.com/*", "*://*.liveleak.com/view*", "*://*.vid.me/*", "*://*.funnyordie.com/videos/*", "*://*.dailymotion.com/video/*" ]; var settings = {}; function openOriginal(info, tab) { browser.tabs.create({ url: info.linkUrl }); } function restoreSettings() { function setSettings(data) { settings = data; } var getting = browser.storage.local.get(); getting.then(setSettings); } function openInMpv(requestDetails) { function closeTab(data) { if (!data.active) { browser.tabs.remove(data.id); } } if (requestDetails.type === "main_frame" && requestDetails.originUrl != undefined) { var command = `${requestDetails.url} --force-window=immediate ${settings.args}`; browser.runtime.sendNativeMessage("mpv", command); var querying = browser.tabs.get(requestDetails.tabId); querying.then(closeTab); return { cancel: true }; } } chrome.contextMenus.create({ id: "open_original", title: "Open without MPV", onclick: openOriginal, contexts: ["link"] }); browser.storage.onChanged.addListener(restoreSettings); browser.webRequest.onBeforeRequest.addListener(openInMpv, { urls: targetPages }, ["blocking"]); restoreSettings();
var targetPages = ["https://www.youtube.com/watch*"]; var settings = {}; function openOriginal(info, tab) { browser.tabs.create({ url: info.linkUrl }); } function restoreSettings() { function setSettings(data) { settings = data; } var getting = browser.storage.local.get(); getting.then(setSettings); } function openInMpv(requestDetails) { function closeTab(data) { if (!data.active) { browser.tabs.remove(data.id); } } if (requestDetails.type === "main_frame" && requestDetails.originUrl != undefined) { var command = `${requestDetails.url} --force-window=immediate ${settings.args}`; browser.runtime.sendNativeMessage("mpv", command); var querying = browser.tabs.get(requestDetails.tabId); querying.then(closeTab); return { cancel: true }; } } chrome.contextMenus.create({ id: "open_original", title: "Open without MPV", onclick: openOriginal, contexts: ["link"] }); browser.storage.onChanged.addListener(restoreSettings); browser.webRequest.onBeforeRequest.addListener(openInMpv, { urls: targetPages }, ["blocking"]); restoreSettings();
Return filled model after saving
<?php namespace Picqer\Financials\Exact\Persistance; trait Storable { public function save() { if ($this->exists()) { $result = $this->update(); } else { $result = $this->insert(); } return $this->find($result[$this->primaryKey]); } public function insert() { return $this->connection()->post($this->url, $this->json()); } public function update() { return $this->connection()->put($this->url . "(guid'$this->primaryKey')", $this->json()); } public function delete() { return $this->connection()->delete($this->url . "(guid'$this->primaryKey')"); } }
<?php namespace Picqer\Financials\Exact\Persistance; trait Storable { public function save() { if ($this->exists()) $this->fill($this->update()); $this->fill($this->insert()); return $this; } public function insert() { return $this->connection()->post($this->url, $this->json()); } public function update() { return $this->connection()->put($this->url . "(guid'$this->primaryKey')", $this->json()); } public function delete() { return $this->connection()->delete($this->url . "(guid'$this->primaryKey')"); } }
Update comment for auto generated files
"""This subpackage contains all data dictionaries.""" # The Python source code in this package other than this file has been auto-generated. from enum import Enum class OrderedEnum(Enum): """An Enum whose members are ordered by their value.""" def __ge__(self, other): if self.__class__ is other.__class__: return self.value >= other.value return NotImplemented def __gt__(self, other): if self.__class__ is other.__class__: return self.value > other.value return NotImplemented def __le__(self, other): if self.__class__ is other.__class__: return self.value <= other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: return self.value < other.value return NotImplemented class VariableEnum(OrderedEnum): """Contains all variables in a datadict. Parameters: * position: the position in the datadict (int) * label: the string describing the variable """ def __init__(self, position, label): self.position = position self.label = label
"""This subpackage contains all data dictionaries.""" # The Python source code gets auto-generated and this package is intentially empty. from enum import Enum class OrderedEnum(Enum): """An Enum whose members are ordered by their value.""" def __ge__(self, other): if self.__class__ is other.__class__: return self.value >= other.value return NotImplemented def __gt__(self, other): if self.__class__ is other.__class__: return self.value > other.value return NotImplemented def __le__(self, other): if self.__class__ is other.__class__: return self.value <= other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: return self.value < other.value return NotImplemented class VariableEnum(OrderedEnum): """Contains all variables in a datadict. Parameters: * position: the position in the datadict (int) * label: the string describing the variable """ def __init__(self, position, label): self.position = position self.label = label
Fix namespace to use DoctrineORMAdminBundle
<?php namespace Sonata\MediaBundle\Admin\Manager; use Sonata\DoctrineORMAdminBundle\Model\ModelManager; use Sonata\AdminBundle\Datagrid\ProxyQueryInterface; /** * this method overwrite the default AdminModelManager to call * the custom methods from the dedicated media manager */ class DoctrineORMManager extends ModelManager { protected $manager; public function __construct($entityManager, $manager) { parent::__construct($entityManager); $this->manager = $manager; } public function create($object) { $this->manager->save($object); } public function update($object) { $this->manager->save($object); } public function delete($object) { $this->manager->delete($object); } /** * Deletes a set of $class identified by the provided $idx array * * @param $class * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy * @return void */ public function batchDelete($class, ProxyQueryInterface $queryProxy) { foreach ($queryProxy->getQuery()->iterate() as $pos => $object) { $this->delete($object[0]); } } }
<?php namespace Sonata\MediaBundle\Admin\Manager; use Sonata\AdminBundle\Model\ORM\ModelManager; use Sonata\AdminBundle\Datagrid\ProxyQueryInterface; /** * this method overwrite the default AdminModelManager to call * the custom methods from the dedicated media manager */ class DoctrineORMManager extends ModelManager { protected $manager; public function __construct($entityManager, $manager) { parent::__construct($entityManager); $this->manager = $manager; } public function create($object) { $this->manager->save($object); } public function update($object) { $this->manager->save($object); } public function delete($object) { $this->manager->delete($object); } /** * Deletes a set of $class identified by the provided $idx array * * @param $class * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy * @return void */ public function batchDelete($class, ProxyQueryInterface $queryProxy) { foreach ($queryProxy->getQuery()->iterate() as $pos => $object) { $this->delete($object[0]); } } }
Update random number generator test
import os import mxnet as mx import numpy as np def same(a, b): return np.sum(a != b) == 0 def check_with_device(device): with mx.Context(device): a, b = -10, 10 mu, sigma = 10, 2 for i in range(5): shape = (100 + i, 100 + i) mx.random.seed(128) ret1 = mx.random.normal(mu, sigma, shape) un1 = mx.random.uniform(a, b, shape) mx.random.seed(128) ret2 = mx.random.normal(mu, sigma, shape) un2 = mx.random.uniform(a, b, shape) assert same(ret1.asnumpy(), ret2.asnumpy()) assert same(un1.asnumpy(), un2.asnumpy()) assert abs(np.mean(ret1.asnumpy()) - mu) < 0.1 assert abs(np.std(ret1.asnumpy()) - sigma) < 0.1 assert abs(np.mean(un1.asnumpy()) - (a+b)/2) < 0.1 def test_random(): check_with_device(mx.cpu()) if __name__ == '__main__': test_random()
import os import mxnet as mx import numpy as np def same(a, b): return np.sum(a != b) == 0 def check_with_device(device): with mx.Context(device): a, b = -10, 10 mu, sigma = 10, 2 shape = (100, 100) mx.random.seed(128) ret1 = mx.random.normal(mu, sigma, shape) un1 = mx.random.uniform(a, b, shape) mx.random.seed(128) ret2 = mx.random.normal(mu, sigma, shape) un2 = mx.random.uniform(a, b, shape) assert same(ret1.asnumpy(), ret2.asnumpy()) assert same(un1.asnumpy(), un2.asnumpy()) assert abs(np.mean(ret1.asnumpy()) - mu) < 0.1 assert abs(np.std(ret1.asnumpy()) - sigma) < 0.1 assert abs(np.mean(un1.asnumpy()) - (a+b)/2) < 0.1 def test_random(): check_with_device(mx.cpu()) if __name__ == '__main__': test_random()
Convert HMAC-SHA1 signatures to lower case
package xyz.pushpad; import javax.crypto.spec.SecretKeySpec; import javax.crypto.Mac; import java.security.SignatureException; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import javax.xml.bind.DatatypeConverter; public class Pushpad { public String authToken; public String projectId; public Pushpad(String authToken, String projectId) { this.authToken = authToken; this.projectId = projectId; } public String signatureFor(String data) { SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); String encoded = null; try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(data.getBytes()); encoded = DatatypeConverter.printHexBinary(rawHmac).toLowerCase(); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } return encoded; } public String path() { return "https://pushpad.xyz/projects/" + this.projectId + "/subscription/edit"; } public String pathFor(String uid) { String uidSignature = this.signatureFor(uid); return this.path() + "?uid=" + uid + "&uid_signature=" + uidSignature; } public Notification buildNotification(String title, String body, String targetUrl) { return new Notification(this, title, body, targetUrl); } }
package xyz.pushpad; import javax.crypto.spec.SecretKeySpec; import javax.crypto.Mac; import java.security.SignatureException; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import javax.xml.bind.DatatypeConverter; public class Pushpad { public String authToken; public String projectId; public Pushpad(String authToken, String projectId) { this.authToken = authToken; this.projectId = projectId; } public String signatureFor(String data) { SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); String encoded = null; try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(data.getBytes()); encoded = DatatypeConverter.printHexBinary(rawHmac); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } return encoded; } public String path() { return "https://pushpad.xyz/projects/" + this.projectId + "/subscription/edit"; } public String pathFor(String uid) { String uidSignature = this.signatureFor(uid); return this.path() + "?uid=" + uid + "&uid_signature=" + uidSignature; } public Notification buildNotification(String title, String body, String targetUrl) { return new Notification(this, title, body, targetUrl); } }
Check for fb on click and not on load
'use strict'; var $ = require('jquery'), React = require('react'); if (typeof window !== 'undefined') { var _gaq = window._gaq || undefined; } module.exports = React.createClass({ click: function () { if (_gaq !== undefined) { _gaq.push(['_trackEvent', 'LoginModal', 'fblogin', window.location.pathname]); } if (!window.FB) { throw 'FB is not defined! Please load the Facebook SDK'; } var FB = window.FB; this.props.toggleLoader(); FB.init({ appId : '251682631638868', status : true, cookie : true, fileUpload : true, version : 'v2.1' }); FB.login(function(resp){ this.props.callback(resp); }.bind(this), {scope: this.props.scope}); }, render: function () { return ( <button className='cd-button cd-button-fb btn-block' onClick={this.click}>{this.props.text}</button> ); } });
'use strict'; var $ = require('jquery'), React = require('react'); if (typeof window !== 'undefined') { var _gaq = window._gaq || undefined; var FB = window.FB || undefined; } module.exports = React.createClass({ click: function () { if (_gaq !== undefined) { _gaq.push(['_trackEvent', 'LoginModal', 'fblogin', window.location.pathname]); } if (!FB) { throw 'FB is not defined! Please load the Facebook SDK'; } this.props.toggleLoader(); FB.init({ appId : '251682631638868', status : true, cookie : true, fileUpload : true, version : 'v2.1' }); FB.login(function(resp){ this.props.callback(resp); }.bind(this), {scope: this.props.scope}); }, render: function () { return ( <button className='cd-button cd-button-fb btn-block' onClick={this.click}>{this.props.text}</button> ); } });
Add search to Topic List screen Add search by topic in the navigation of the Topic List screen
/* @flow */ import React, { PureComponent } from 'react'; import type { Actions, Stream, Topic } from '../types'; import connectWithActions from '../connectWithActions'; import { Screen } from '../common'; import { topicNarrow } from '../utils/narrow'; import { getTopicsInScreen } from '../selectors'; import { getStreamEditInitialValues } from '../subscriptions/subscriptionSelectors'; import TopicList from './TopicList'; type Props = { actions: Actions, stream: Stream, topics: Topic[], }; type State = { filter: string, }; class TopicListScreen extends PureComponent<Props, State> { props: Props; state: State = { filter: '', }; componentDidMount() { const { actions, stream } = this.props; actions.fetchTopics(stream.stream_id); } handlePress = (streamObj: string, topic: string) => { const { actions, stream } = this.props; actions.doNarrow(topicNarrow(stream.name, topic)); }; handleFilterChange = (filter: string) => this.setState({ filter }); render() { const { topics } = this.props; const { filter } = this.state; const filteredTopics = topics && topics.filter(topic => topic.name.toLowerCase().includes(filter.toLowerCase())); return ( <Screen title="Topics" padding search searchBarOnChange={this.handleFilterChange}> <TopicList topics={filteredTopics} onPress={this.handlePress} /> </Screen> ); } } export default connectWithActions(state => ({ stream: getStreamEditInitialValues(state), topics: getTopicsInScreen(state), }))(TopicListScreen);
/* @flow */ import React, { PureComponent } from 'react'; import type { Actions, Stream, Topic } from '../types'; import connectWithActions from '../connectWithActions'; import { Screen } from '../common'; import { topicNarrow } from '../utils/narrow'; import { getTopicsInScreen } from '../selectors'; import { getStreamEditInitialValues } from '../subscriptions/subscriptionSelectors'; import TopicList from './TopicList'; type Props = { actions: Actions, stream: Stream, topics: Topic[], }; class TopicListScreen extends PureComponent<Props> { props: Props; componentDidMount() { const { actions, stream } = this.props; actions.fetchTopics(stream.stream_id); } handlePress = (streamObj: string, topic: string) => { const { actions, stream } = this.props; actions.doNarrow(topicNarrow(stream.name, topic)); }; render() { const { topics } = this.props; return ( <Screen title="Topics" padding> <TopicList topics={topics} onPress={this.handlePress} /> </Screen> ); } } export default connectWithActions(state => ({ stream: getStreamEditInitialValues(state), topics: getTopicsInScreen(state), }))(TopicListScreen);
Add a few PyPI classifiers.
import os.path from setuptools import setup, find_packages import stun def main(): src = os.path.realpath(os.path.dirname(__file__)) README = open(os.path.join(src, 'README.rst')).read() setup( name='pystun', version=stun.__version__, packages=find_packages(), scripts=['bin/pystun'], zip_safe=False, license='MIT', author='Justin Riley (original author: gaohawk)', author_email='justin.t.riley@gmail.com', url="http://github.com/jtriley/pystun", description="A Python STUN client for getting NAT type and external IP (RFC 3489)", long_description=README, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Topic :: Internet", "Topic :: System :: Networking :: Firewalls", "Programming Language :: Python", ], ) if __name__ == '__main__': main()
import os.path from setuptools import setup, find_packages import stun def main(): src = os.path.realpath(os.path.dirname(__file__)) README = open(os.path.join(src, 'README.rst')).read() setup( name='pystun', version=stun.__version__, packages=find_packages(), scripts=['bin/pystun'], zip_safe=False, license='MIT', author='Justin Riley (original author: gaohawk)', author_email='justin.t.riley@gmail.com', url="http://github.com/jtriley/pystun", description="A Python STUN client for getting NAT type and external IP (RFC 3489)", long_description=README, classifiers=[ "License :: OSI Approved :: MIT License", "Topic :: Internet", "Topic :: System :: Networking :: Firewalls", "Programming Language :: Python", ], ) if __name__ == '__main__': main()
Fix show last element from list
import React from 'react'; export default class List extends React.Component { static propTypes = { items: React.PropTypes.array.isRequired, } render() { const items = this.props.items; const and = 'og'; if (!items || items.length === 0) { return <span />; } if (items.length === 1) { return <span>{items[0]}</span>; } if (items.length === 2) { return <span>{items[0]} {and} {items[1]}</span>; } return <span>{items.slice(0, -1).join(', ')} {and} {items[items.length - 1]}</span>; } }
import React from 'react'; export default class List extends React.Component { static propTypes = { items: React.PropTypes.array.isRequired, } render() { const items = this.props.items; const and = 'og'; if (!items || items.length === 0) { return <span />; } if (items.length === 1) { return <span>{items[0]}</span>; } if (items.length === 2) { return <span>{items[0]} {and} {items[1]}</span>; } return <span>{items.slice(0, -1).join(', ')} {and} {items[-1]}</span>; } }
Update url for OSU harvester
''' Harvester for the ScholarsArchive@OSU for the SHARE project Example API call: http://ir.library.oregonstate.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals from scrapi.base import helpers from scrapi.base import OAIHarvester class ScholarsarchiveosuHarvester(OAIHarvester): short_name = 'scholarsarchiveosu' long_name = 'ScholarsArchive@OSU' url = 'http://ir.library.oregonstate.edu/' base_url = 'http://ir.library.oregonstate.edu/oai/request' @property def schema(self): return helpers.updated_schema(self._schema, { "uris": { "objectUris": [('//dc:identifier/node()', helpers.extract_doi_from_text)] } }) # TODO - return date once we figure out es parsing errors property_list = ['relation', 'identifier', 'type', 'setSpec'] timezone_granularity = True
''' Harvester for the ScholarsArchive@OSU for the SHARE project Example API call: http://ir.library.oregonstate.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals from scrapi.base import helpers from scrapi.base import OAIHarvester class ScholarsarchiveosuHarvester(OAIHarvester): short_name = 'scholarsarchiveosu' long_name = 'ScholarsArchive@OSU' url = 'http://ir.library.oregonstate.edu/oai/request' base_url = 'http://ir.library.oregonstate.edu/oai/request' @property def schema(self): return helpers.updated_schema(self._schema, { "uris": { "objectUris": [('//dc:identifier/node()', helpers.extract_doi_from_text)] } }) # TODO - return date once we figure out es parsing errors property_list = ['relation', 'identifier', 'type', 'setSpec'] timezone_granularity = True
Change key of logging property
package au.com.outware.cavemansample; import android.content.Context; import android.support.annotation.VisibleForTesting; import au.com.outware.caveman.data.repository.EnvironmentContentProviderRepository; import au.com.outware.caveman.domain.repository.EnvironmentRepository; /** * @author Tim Mutton * Copyright © 2015 Outware Mobile. All rights reserved. */ public class GetEnvironmentProperty { private static final String PROVIDER_AUTHORITY = "au.com.outware.caveman.contentprovider"; private static final String BASE_URL_KEY = "BaseURL"; private static final String LOGS_ENABLED_KEY = "LoggingEnabled"; private static final String TIMEOUT_KEY = "Timeout"; private static final String DEFAULT_BASE_URL = "http://base.url"; private static final boolean DEFAULT_LOGS_ENABLED = false; private static final int DEFAULT_TIMEOUT = 2000; @VisibleForTesting EnvironmentRepository environmentRepository; public GetEnvironmentProperty(Context context) { environmentRepository = new EnvironmentContentProviderRepository(context, PROVIDER_AUTHORITY); } public String getBaseUrl() { return environmentRepository.getProperty(BASE_URL_KEY, DEFAULT_BASE_URL); } public boolean isLoggingEnabled() { return environmentRepository.getProperty(LOGS_ENABLED_KEY, DEFAULT_LOGS_ENABLED); } public int getTimeout() { return environmentRepository.getProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); } }
package au.com.outware.cavemansample; import android.content.Context; import au.com.outware.caveman.data.repository.EnvironmentContentProviderRepository; import au.com.outware.caveman.domain.repository.EnvironmentRepository; /** * @author Tim Mutton * Copyright © 2015 Outware Mobile. All rights reserved. */ public class GetEnvironmentProperty { private static final String PROVIDER_AUTHORITY = "au.com.outware.caveman.contentprovider"; private static final String BASE_URL_KEY = "BaseURL"; private static final String LOGS_ENABLED_KEY = "LogEnabled"; private static final String TIMEOUT_KEY = "Timeout"; private static final String DEFAULT_BASE_URL = "http://base.url"; private static final boolean DEFAULT_LOGS_ENABLED = false; private static final int DEFAULT_TIMEOUT = 2000; EnvironmentRepository environmentRepository; public GetEnvironmentProperty(Context context) { environmentRepository = new EnvironmentContentProviderRepository(context, PROVIDER_AUTHORITY); } public String getBaseUrl() { return environmentRepository.getProperty(BASE_URL_KEY, DEFAULT_BASE_URL); } public boolean isLoggingEnabled() { return environmentRepository.getProperty(LOGS_ENABLED_KEY, DEFAULT_LOGS_ENABLED); } public int getTimeout() { return environmentRepository.getProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); } }
Add error handling for http request
"use strict"; /** * TODO: make this ingest steam IDs as an event stream, and * cache them and then poll the steam API in batches * every now and again. Or not, depending on options :) */ var steam = require('steam-api'), events = require('events'); class SteamApiWrapper extends events { constructor(apiKey) { super(); if (!apiKey) { throw "no api key provided to SteamApiWrapper constructor"; } this.steamClient = new steam.User(apiKey); } /** * callback - called once for each steamID provided */ getPlayerInfo(steamIds, callback) { if (typeof callback !== "function") { throw "no callback given"; } var client = this.steamClient.GetPlayerSummaries(steamIds); client.done(function(playersInfo,r) { playersInfo = Array.isArray(playersInfo) ? playersInfo : [playersInfo]; playersInfo.forEach(function(p) { callback(null, p); }); }); client.fail(function(e) { console.error("Failed to fetch user list: ", e); }); } } module.exports = { create: function(apiKey) { return new SteamApiWrapper(apiKey); } }
"use strict"; /** * TODO: make this ingest steam IDs as an event stream, and * cache them and then poll the steam API in batches * every now and again. Or not, depending on options :) */ var steam = require('steam-api'), events = require('events'); class SteamApiWrapper extends events { constructor(apiKey) { super(); if (!apiKey) { throw "no api key provided to SteamApiWrapper constructor"; } this.steamClient = new steam.User(apiKey); } /** * callback - called once for each steamID provided */ getPlayerInfo(steamIds, callback) { if (typeof callback !== "function") { throw "no callback given"; } this.steamClient.GetPlayerSummaries(steamIds).done(function(playersInfo,r) { playersInfo = Array.isArray(playersInfo) ? playersInfo : [playersInfo]; playersInfo.forEach(function(p) { callback(null, p); }); }); } } module.exports = { create: function(apiKey) { return new SteamApiWrapper(apiKey); } }
Add some comments to Aurora_Profiler class
<?php defined('SYSPATH') or die('No direct script access.'); /** * Helper class to work with Kohana Profiler * * @package Aurora * @author Samuel Demirdjian * @copyright (c) 2013, Samuel Demirdjian * @license http://license.enov.ws/mit MIT * */ class Aurora_Aurora_Profiler { /** * @var string The profiling category under which benchmarks will appear */ protected static $category = 'Aurora'; /** * Add a profiling mark and start counter * * @param Aurora $aurora * @param string $function * @return string benchmark id in Profiler */ public static function start($aurora, $function) { $name = Aurora_Type::cname($aurora) . '::' . $function; $benchmark = (Kohana::$profiling === TRUE) ? Profiler::start(static::$category, $name) : FALSE; return $benchmark; } /** * Stop a profiling mark * * @param string $benchmark */ public static function stop($benchmark) { if (!empty($benchmark)) { // Stop the benchmark Profiler::stop($benchmark); } } /** * Delete a profiling mark * * @param string $benchmark */ public static function delete($benchmark) { if (!empty($benchmark)) { // Delete the benchmark Profiler::delete($benchmark); } } }
<?php defined('SYSPATH') or die('No direct script access.'); /** * Helper class to work with Kohana Profiler * * @package Aurora * @author Samuel Demirdjian * @copyright (c) 2013, Samuel Demirdjian * @license http://license.enov.ws/mit MIT * */ class Aurora_Aurora_Profiler { protected static $category = 'Aurora'; public static function start($aurora, $function) { $name = Aurora_Type::cname($aurora) . '::' . $function; $benchmark = (Kohana::$profiling === TRUE) ? Profiler::start(static::$category, $name) : FALSE; return $benchmark; } public static function stop($benchmark) { if (!empty($benchmark)) { // Stop the benchmark Profiler::stop($benchmark); } } public static function delete($benchmark) { if (!empty($benchmark)) { // Delete the benchmark Profiler::delete($benchmark); } } }
Put back hard-coded cell heights for better Chrome layout
package org.fedorahosted.flies.webtrans.client; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.Widget; public class AppView extends DockPanel implements AppPresenter.Display { public AppView() { setSpacing(3); // setBorderWidth(1); } @Override public Widget asWidget() { return this; } @Override public void startProcessing() { } @Override public void stopProcessing() { } @Override public void setMain(Widget main) { add(main, DockPanel.CENTER ); setCellWidth(main, "100%"); } @Override public void setWest(Widget west) { add(west, DockPanel.WEST ); // setCellWidth(west, "220px"); } @Override public void setNorth(Widget north) { add(north, DockPanel.NORTH ); // just for Chrome's benefit: setCellHeight(north, "20px"); } @Override public void setSouth(Widget south) { add(south, DockPanel.SOUTH ); // just for Chrome's benefit: setCellHeight(south, "20px"); } }
package org.fedorahosted.flies.webtrans.client; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.Widget; public class AppView extends DockPanel implements AppPresenter.Display { public AppView() { setSpacing(3); // setBorderWidth(1); } @Override public Widget asWidget() { return this; } @Override public void startProcessing() { } @Override public void stopProcessing() { } @Override public void setMain(Widget main) { add(main, DockPanel.CENTER ); setCellWidth(main, "100%"); } @Override public void setWest(Widget west) { add(west, DockPanel.WEST ); // setCellWidth(west, "220px"); } @Override public void setNorth(Widget north) { add(north, DockPanel.NORTH ); // setCellHeight(north, "20px"); } @Override public void setSouth(Widget south) { add(south, DockPanel.SOUTH ); // setCellHeight(south, "20px"); } }
Fix a bug where the user wouldn't be able to log in
import { connect } from 'react-redux'; import { Component } from 'react'; import PropTypes from 'prop-types'; import { setConfig } from 'widget-editor'; import { browserHistory } from 'react-router'; import actions from './auth-actions'; import initialState from './auth-reducer-initial-state'; import * as reducers from './auth-reducer'; const mapStateToProps = state => ({ session: state.auth.session }); class AuthContainer extends Component { componentWillMount() { const { location } = this.props; const { query } = location; const { token } = query; if (token) { this.handleAuthenticationAction(); localStorage.setItem('token', token); } else { browserHistory.push('/'); } // We update the widget editor's config setConfig({ userToken: token || null }); } handleAuthenticationAction() { const { logInSuccess } = this.props; logInSuccess(true); } render() { return false; } } AuthContainer.propTypes = { location: PropTypes.object.isRequired, logInSuccess: PropTypes.func.isRequired }; export { actions, reducers, initialState }; export default connect(mapStateToProps, actions)(AuthContainer);
import { connect } from 'react-redux'; import { Component } from 'react'; import PropTypes from 'prop-types'; import { setConfig } from 'widget-editor'; import { browserHistory } from 'react-router'; import actions from './auth-actions'; import initialState from './auth-reducer-initial-state'; import * as reducers from './auth-reducer'; const mapStateToProps = state => ({ session: state.auth.session }); class AuthContainer extends Component { componentWillMount() { const { location } = this.props; const { token } = location; if (token) { this.handleAuthenticationAction(); localStorage.setItem('token', token); } else { browserHistory.push('/'); } // We update the widget editor's config setConfig({ userToken: token || null }); } handleAuthenticationAction() { const { logInSuccess } = this.props; logInSuccess(true); } render() { return false; } } AuthContainer.propTypes = { location: PropTypes.object.isRequired, logInSuccess: PropTypes.func.isRequired }; export { actions, reducers, initialState }; export default connect(mapStateToProps, actions)(AuthContainer);
Replace string concatenation with .format function
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) return "You've entered an incorrect query. Please check and try again. Input : {}".format(query) @url.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @url.errorhandler(403) def page_forbidden(error): return render_template('403.html', title='Page Forbidden'), 403 @url.errorhandler(500) def page_server_error(error): return render_template('500.html', title='Server Error'), 500
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) return "You've entered an incorrect query. Please check and try again. Input : "+query @url.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @url.errorhandler(403) def page_forbidden(error): return render_template('403.html', title='Page Forbidden'), 403 @url.errorhandler(500) def page_server_error(error): return render_template('500.html', title='Server Error'), 500
Fix url for screenshot test
from marionette_driver import By from marionette_driver.errors import MarionetteException from marionette_harness import MarionetteTestCase import testsuite class Test(MarionetteTestCase): def setUp(self): MarionetteTestCase.setUp(self) ts = testsuite.TestSuite() self.ts = ts self.URLs = [ 'chrome://torlauncher/content/network-settings-wizard.xhtml', ]; def test_check_tpo(self): marionette = self.marionette with marionette.using_context('content'): marionette.navigate("http://check.torproject.org") self.ts.screenshot(marionette, full=True) with marionette.using_context('content'): for url in self.URLs: marionette.navigate(url) self.ts.screenshot(marionette)
from marionette_driver import By from marionette_driver.errors import MarionetteException from marionette_harness import MarionetteTestCase import testsuite class Test(MarionetteTestCase): def setUp(self): MarionetteTestCase.setUp(self) ts = testsuite.TestSuite() self.ts = ts self.URLs = [ 'chrome://torlauncher/content/network-settings-wizard.xul', ]; def test_check_tpo(self): marionette = self.marionette with marionette.using_context('content'): marionette.navigate("http://check.torproject.org") self.ts.screenshot(marionette, full=True) with marionette.using_context('content'): for url in self.URLs: marionette.navigate(url) self.ts.screenshot(marionette)
Disable Android, not supported by Sauce Labs.
module.exports = function(session, options) { function testBrowser(name, version) { var config = { 'browserName': name, 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER || 'test', 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': session }; if (version) { config.version = version; } return config; } // Disabled: Android, seems broken on Sauce Labs. var browsers = [ //testBrowser('android', '4.3'), testBrowser('chrome'), testBrowser('firefox'), testBrowser('internet explorer', 11), testBrowser('iphone', '7.1'), testBrowser('safari', 7), ]; if (options && options.legacy) { //browsers.push(testBrowser('android', '4.0')); browsers.push(testBrowser('internet explorer', 10)); browsers.push(testBrowser('internet explorer', 8)); browsers.push(testBrowser('internet explorer', 9)); browsers.push(testBrowser('iphone', '6.1')); browsers.push(testBrowser('safari', 5)); browsers.push(testBrowser('safari', 6)); } return browsers; };
module.exports = function(session, options) { function testBrowser(name, version) { var config = { 'browserName': name, 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER || 'test', 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': session }; if (version) { config.version = version; } return config; } var browsers = [ testBrowser('android', '4.3'), testBrowser('chrome'), testBrowser('firefox'), testBrowser('internet explorer', 11), testBrowser('iphone', '7.1'), testBrowser('safari', 7), ]; if (options && options.legacy) { browsers.push(testBrowser('android', '4.0')); browsers.push(testBrowser('internet explorer', 10)); browsers.push(testBrowser('internet explorer', 8)); browsers.push(testBrowser('internet explorer', 9)); browsers.push(testBrowser('iphone', '6.1')); browsers.push(testBrowser('safari', 5)); browsers.push(testBrowser('safari', 6)); } return browsers; };
Correct the default image template value.
<?php namespace HeyUpdate\EmojiBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('hey_update_emoji'); $rootNode ->children() ->scalarNode('image_html_template') ->defaultValue('<img alt=":{{name}}:" class="emoji" src="https://twemoji.maxcdn.com/36x36/{{unicode}}.png">') ->end() ->end(); return $treeBuilder; } }
<?php namespace HeyUpdate\EmojiBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('hey_update_emoji'); $rootNode ->children() ->scalarNode('image_html_template') ->defaultValue('https://twemoji.maxcdn.com/36x36/%s.png') ->end() ->end(); return $treeBuilder; } }
Add SurfaceView and TextureView to the special classes list
package com.avast.android.butterknifezelezny.common; import java.util.ArrayList; import java.util.HashMap; public class Definitions { public static final HashMap<String, String> paths = new HashMap<String, String>(); public static final ArrayList<String> adapters = new ArrayList<String>(); static { // special classes; default package is android.widget.* paths.put("WebView", "android.webkit.WebView"); paths.put("View", "android.view.View"); paths.put("ViewStub", "android.view.ViewStub"); paths.put("SurfaceView", "android.view.SurfaceView"); paths.put("TextureView", "android.view.TextureView"); // adapters adapters.add("android.widget.ListAdapter"); adapters.add("android.widget.ArrayAdapter"); adapters.add("android.widget.BaseAdapter"); adapters.add("android.widget.HeaderViewListAdapter"); adapters.add("android.widget.SimpleAdapter"); adapters.add("android.support.v4.widget.CursorAdapter"); adapters.add("android.support.v4.widget.SimpleCursorAdapter"); adapters.add("android.support.v4.widget.ResourceCursorAdapter"); } }
package com.avast.android.butterknifezelezny.common; import java.util.ArrayList; import java.util.HashMap; public class Definitions { public static final HashMap<String, String> paths = new HashMap<String, String>(); public static final ArrayList<String> adapters = new ArrayList<String>(); static { // special classes; default package is android.widget.* paths.put("WebView", "android.webkit.WebView"); paths.put("View", "android.view.View"); paths.put("ViewStub", "android.view.ViewStub"); // adapters adapters.add("android.widget.ListAdapter"); adapters.add("android.widget.ArrayAdapter"); adapters.add("android.widget.BaseAdapter"); adapters.add("android.widget.HeaderViewListAdapter"); adapters.add("android.widget.SimpleAdapter"); adapters.add("android.support.v4.widget.CursorAdapter"); adapters.add("android.support.v4.widget.SimpleCursorAdapter"); adapters.add("android.support.v4.widget.ResourceCursorAdapter"); } }
Add explanation why we need to cast float to string in decimal type only starting from PHP 8.1
<?php namespace Doctrine\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; use function is_float; use const PHP_VERSION_ID; /** * Type that maps an SQL DECIMAL to a PHP string. */ class DecimalType extends Type { /** * {@inheritdoc} */ public function getName() { return Types::DECIMAL; } /** * {@inheritdoc} */ public function getSQLDeclaration(array $column, AbstractPlatform $platform) { return $platform->getDecimalTypeDeclarationSQL($column); } /** * {@inheritdoc} */ public function convertToPHPValue($value, AbstractPlatform $platform) { // Some drivers starting from PHP 8.1 can represent decimals as float // See also: https://github.com/doctrine/dbal/pull/4818 if (PHP_VERSION_ID >= 80100 && is_float($value)) { return (string) $value; } return $value; } }
<?php namespace Doctrine\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; use function is_float; use const PHP_VERSION_ID; /** * Type that maps an SQL DECIMAL to a PHP string. */ class DecimalType extends Type { /** * {@inheritdoc} */ public function getName() { return Types::DECIMAL; } /** * {@inheritdoc} */ public function getSQLDeclaration(array $column, AbstractPlatform $platform) { return $platform->getDecimalTypeDeclarationSQL($column); } /** * {@inheritdoc} */ public function convertToPHPValue($value, AbstractPlatform $platform) { if (PHP_VERSION_ID >= 80100 && is_float($value)) { return (string) $value; } return $value; } }
Fix range issue with travis
from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in xrange(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
Add a CSS parameter for JSON blocks
<?php class JSONLoader extends Element { public function output($args) { $id = rand(0,100000); echo(" <style> #json-".$id." { font-weight: bold; font-size: ".$args["font_size"]."em; vertical-align: middle; margin-top: ".$args["margin_top"]."; } ".$args["css"]." </style> <script> $().ready(function() { $.getJSON('".$args["url"]."', function(data) { var html = ''; ".$args["callback"]." $('#json-".$id."').html(html); }); setInterval(function () { $.getJSON('".$args["url"]."', function(data) { var html = ''; ".$args["callback"]." $('#json-".$id."').html(html); }); }, 5000); }); </script> <div id=\"json-".$id."\"></div> "); } } ?>
<?php class JSONLoader extends Element { public function output($args) { $id = rand(0,100000); echo(" <style> #json-".$id." { font-weight: bold; font-size: ".$args["font_size"]."em; vertical-align: middle; margin-top: ".$args["margin_top"]."; } </style> <script> $().ready(function() { $.getJSON('".$args["url"]."', function(data) { var html = ''; ".$args["callback"]." $('#json-".$id."').html(html); }); setInterval(function () { $.getJSON('".$args["url"]."', function(data) { var html = ''; ".$args["callback"]." $('#json-".$id."').html(html); }); }, 5000); }); </script> <div id=\"json-".$id."\"></div> "); } } ?>
Remove second Semaphore.wrap and pass in this.
(function (context) { var _SEMAPOHRES = {}; var Semaphore = function (key) { this.key = key; if (_SEMAPOHRES[this.key] == undefined) _SEMAPOHRES[this.key] = false; return this; }; Semaphore.prototype.isLocked = function() { return _SEMAPOHRES[this.key]; }; Semaphore.prototype.lock = function() { _SEMAPOHRES[this.key] = true; return this; }; Semaphore.prototype.unlock = function() { _SEMAPOHRES[this.key] = false; return this; }; Semaphore.wrap = function (key, callback) { var semaphore = new this(key); if (!semaphore.isLocked()) { semaphore.lock() callback(semaphore); } }; var conflictingSemaphore = context.Semaphore; Semaphore.noConflict = function () { context.Semaphore = conflictingSemaphore; return Semaphore; }; context.Semaphore = Semaphore; })(this);
(function (context) { var _SEMAPOHRES = {}; var Semaphore = function (key) { this.key = key; if (_SEMAPOHRES[this.key] == undefined) _SEMAPOHRES[this.key] = false; return this; }; Semaphore.prototype.isLocked = function() { return _SEMAPOHRES[this.key]; }; Semaphore.prototype.lock = function() { _SEMAPOHRES[this.key] = true; return this; }; Semaphore.prototype.unlock = function() { _SEMAPOHRES[this.key] = false; return this; }; Semaphore.wrap = function (key, callback) { var semaphore = new this(key); if (!semaphore.isLocked()) { semaphore.lock() callback(semaphore); } }; Semaphore.wrap = function (key, callback) { var semaphore = new this(key); if (!semaphore.isLocked()) { semaphore.lock() callback(semaphore); } }; var conflictingSemaphore = context.Semaphore; Semaphore.noConflict = function () { context.Semaphore = conflictingSemaphore; return Semaphore; }; context.Semaphore = Semaphore; });
Increase test timeout further because bcrypt's entire purpose in life is to be slow
const Passwords = require('../passwords'); describe('Passwords', () => { let originalTimeout; beforeEach(() => { // Increase timeout because bcrypt is slow originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; }); it('should be able to generate and compare hashes', async () => { const pass = 'apple'; const passFake = 'orange'; const passHash = await Passwords.hash(pass); const passHashSync = Passwords.hashSync(pass); const passFakeHashSync = Passwords.hashSync(passFake); expect(Passwords.compareSync(pass, passHash)).toBeTruthy(); const compareAsync = await Passwords.compare(pass, passHash); expect(compareAsync).toBeTruthy(); expect(Passwords.compareSync(pass, passHashSync)).toBeTruthy(); expect(Passwords.compareSync(passFake, passHash)).toBeFalsy(); expect(Passwords.compareSync(pass, passFakeHashSync)).toBeFalsy(); }); afterEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); })
const Passwords = require('../passwords'); describe('Passwords', () => { let originalTimeout; beforeEach(() => { // Increase timeout because bcrypt is slow originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; }); it('should be able to generate and compare hashes', async () => { const pass = 'apple'; const passFake = 'orange'; const passHash = await Passwords.hash(pass); const passHashSync = Passwords.hashSync(pass); const passFakeHashSync = Passwords.hashSync(passFake); expect(Passwords.compareSync(pass, passHash)).toBeTruthy(); const compareAsync = await Passwords.compare(pass, passHash); expect(compareAsync).toBeTruthy(); expect(Passwords.compareSync(pass, passHashSync)).toBeTruthy(); expect(Passwords.compareSync(passFake, passHash)).toBeFalsy(); expect(Passwords.compareSync(pass, passFakeHashSync)).toBeFalsy(); }); afterEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); })
Update scatter chart default config to hide lines
'use strict'; module.exports = function(Chart) { var defaultConfig = { hover: { mode: 'single' }, scales: { xAxes: [{ type: 'linear', // scatter should not use a category axis position: 'bottom', id: 'x-axis-1' // need an ID so datasets can reference the scale }], yAxes: [{ type: 'linear', position: 'left', id: 'y-axis-1' }] }, showLines: false, tooltips: { callbacks: { title: function() { // Title doesn't make sense for scatter since we format the data as a point return ''; }, label: function(tooltipItem) { return '(' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')'; } } } }; // Register the default config for this type Chart.defaults.scatter = defaultConfig; // Scatter charts use line controllers Chart.controllers.scatter = Chart.controllers.line; Chart.Scatter = function(context, config) { config.type = 'scatter'; return new Chart(context, config); }; };
'use strict'; module.exports = function(Chart) { var defaultConfig = { hover: { mode: 'single' }, scales: { xAxes: [{ type: 'linear', // scatter should not use a category axis position: 'bottom', id: 'x-axis-1' // need an ID so datasets can reference the scale }], yAxes: [{ type: 'linear', position: 'left', id: 'y-axis-1' }] }, tooltips: { callbacks: { title: function() { // Title doesn't make sense for scatter since we format the data as a point return ''; }, label: function(tooltipItem) { return '(' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')'; } } } }; // Register the default config for this type Chart.defaults.scatter = defaultConfig; // Scatter charts use line controllers Chart.controllers.scatter = Chart.controllers.line; Chart.Scatter = function(context, config) { config.type = 'scatter'; return new Chart(context, config); }; };
Add annotation for service extension
/* * RESTHeart - the Web API for MongoDB * Copyright (C) SoftInstigate Srl * * 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/>. */ package org.restheart.extensions; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * * @author Andrea Di Cesare <andrea@softinstigate.com> */ @Retention(RetentionPolicy.RUNTIME) public @interface Service { /** * Defines the name of the service that can be used in the configuration * file to define the confArgs to pass to it or to disable it */ String name(); /** * Describes the service */ String description(); /** * Defines the service uri */ String uri(); }
/* * RESTHeart - the Web API for MongoDB * Copyright (C) SoftInstigate Srl * * 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/>. */ package org.restheart.extensions; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * * @author Andrea Di Cesare <andrea@softinstigate.com> */ @Retention(RetentionPolicy.RUNTIME) public @interface Initializer { /** * Defines the name of the initializer that can be used in the configuration * file to pass arguments */ String name(); /** * Describes the initializer */ String description(); /** * Defines the order of execution (less is higher priority) */ int priority() default 10; }
Refactor the save js to be smarter about how it tries to save drafts and export..etc.
// Save and Export the file // This function returns a file.. // #TODO why aren't we using .ajax call? function saveAndExport(str, fileType){ var date = new Date(); var form_action = location.protocol + '//' + location.host + "/tagger/save_export/"; $('<form></form>', { action: form_action, method: 'POST'}).append( $('<input></input>', { name: 'filename', type: 'hidden', value: fileType + "_" + ISODateString(date)+ fileType }) ).append( $('<input></input>', { name: 'data', type: 'hidden', value: str }) ).submit(); } // Save the draft string (Items object stringified) to the server using a post xhr // The successful response will be the items coming back and reloaded. function saveDraft(str){ $.ajax({ type : "POST", dataType : 'json', url : "/tagger/save_draft", data : { content : str }, // On success update our items list to be what the server sends back // Really nothing should change other than now the items have a UUID success : function(xhr) { items = xhr }, error : function(xhr, txtStatus, errThrown) { console.log(arguments); } }) } function saveRemote(str) { }
function saveLocal(str, fileType){ var date = new Date(); var form_action = location.protocol + '//' + location.host + "/tagger/save_local/"; $('<form></form>', { action: form_action, method: 'POST'}).append( $('<input></input>', { name: 'filename', type: 'hidden', value: fileType + "_" + ISODateString(date)+ fileType }) ).append( $('<input></input>', { name: 'data', type: 'hidden', value: str }) ).submit(); } function saveServer(str){ var form_action = location.protocol + '//' + location.host + "/tagger/save_lri/"; $('<form></form>', { action: form_action, method: 'POST'}).append( $('<input></input>', { name: 'content', type: 'hidden', value: str }) ).submit(); }
Fix missing paren, imports, spelling.
"""Retrieves the friendly model name for machines that don't have one yet.""" from django.core.management.base import BaseCommand, CommandError from django.db.models import Q import server.utils as utils from server.models import Machine class Command(BaseCommand): help = 'Retrieves friendly model names for machines without one' def handle(self, *args, **options): # Get all the machines without a friendly model name and have a model no_friendly = Machine.objects.filter( Q(machine_model_friendly__isnull=True) | Q(machine_model_friendly='') ).exclude(machine_model__isnull=True).exclude(machine_model='').filter(os_family='Darwin') for machine in no_friendly[:100]: print(f'Processing {machine}') machine.machine_model_friendly = utils.friendly_machine_model(machine) machine.save()
''' Retrieves the firendly model name for machines that don't have one yet. ''' from django.core.management.base import BaseCommand, CommandError from server.models import Machine from django.db.models import Q import server.utils as utils class Command(BaseCommand): help = 'Retrieves friendly model names for machines without one' def handle(self, *args, **options): # Get all the machines without a friendly model name and have a model no_friendly = Machine.objects.filter( Q(machine_model_friendly__isnull=True) | Q(machine_model_friendly='') ).exclude(machine_model__isnull=True).exclude(machine_model='').filter(os_family='Darwin') for machine in no_friendly[:100]: print(f'Processing {machine}' machine.machine_model_friendly = utils.friendly_machine_model(machine) machine.save()
Prepare version number for upcoming beta release
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.09.19-RC"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.08.21"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ "2022.09.04" }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
Use paint() instead of setPosition() here. setPosition() doesn't work nicely with nested movies. Should probably fix that.
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.flump; import tripleplay.anim.Animation; /** Plays a movie until it ends. */ public class PlayMovie extends Animation { public PlayMovie (Movie movie) { _movie = movie; } @Override protected void init (float time) { super.init(time); _lastTime = time; } @Override protected float apply (float time) { float dt = time - _lastTime; _lastTime = time; float remaining = _movie.symbol().duration - _movie.position() - dt*_movie.speed(); if (remaining < 0) { dt = (_movie.symbol().duration-_movie.position()) / _movie.speed(); } _movie.paint(dt); return remaining; } protected Movie _movie; protected float _lastTime; }
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.flump; import tripleplay.anim.Animation; /** Plays through an entire movie once. */ public class PlayMovie extends Animation { public PlayMovie (Movie movie) { _movie = movie; } @Override protected void init (float time) { super.init(time); _movie.setPosition(0); } @Override protected float apply (float time) { float elapsed = _movie.speed() * (time - _start); _movie.setPosition(elapsed); return _movie.symbol().duration - elapsed; } protected Movie _movie; }
Format results as robot files
from __future__ import print_function import argparse from robot.errors import DataError from robot.tidy import Tidy def main(argv=None): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to run') parser.add_argument('--use-pipes', action='store_true', dest='use_pipes', default=False) parser.add_argument('--space-count', type=int, dest='space_count', default=4) args = parser.parse_args(argv) tidier = Tidy(use_pipes=args.use_pipes, space_count=args.space_count, format='robot') for filename in args.filenames: try: tidier.inplace(filename) except DataError: pass return 0 if __name__ == '__main__': exit(main())
from __future__ import print_function import argparse from robot.errors import DataError from robot.tidy import Tidy def main(argv=None): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to run') parser.add_argument('--use-pipes', action='store_true', dest='use_pipes', default=False) parser.add_argument('--space-count', type=int, dest='space_count', default=4) args = parser.parse_args(argv) tidier = Tidy(use_pipes=args.use_pipes, space_count=args.space_count) for filename in args.filenames: try: tidier.inplace(filename) except DataError: pass return 0 if __name__ == '__main__': exit(main())
Correct py_modules as a list
#! /usr/bin/env python # -*- coding:utf-8 -*- """ Install the `arte_plus7` script """ from setuptools import setup NAME = 'arte_plus7' def get_version(module): """ Extract package version without importing file Importing cause issues with coverage, (modules can be removed from sys.modules to prevent this) Inspired from pep8 setup.py """ with open('%s.py' % module) as module_fd: for line in module_fd: if line.startswith('__version__'): return eval(line.split('=')[-1]) # pylint:disable=eval-used setup( name=NAME, version=get_version(NAME), description='CLI script to get videos from Arte plus 7 using their URL', author='cladmi', download_url='https://github.com/cladmi/arte_plus7', py_modules=[NAME], entry_points={ 'console_scripts': ['{name} = {name}:main'.format(name=NAME)], }, classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Intended Audience :: End Users/Desktop', 'Topic :: utilities', ], install_requires=['argparse', 'beautifulsoup4'], )
#! /usr/bin/env python # -*- coding:utf-8 -*- """ Install the `arte_plus7` script """ from setuptools import setup NAME = 'arte_plus7' def get_version(module): """ Extract package version without importing file Importing cause issues with coverage, (modules can be removed from sys.modules to prevent this) Inspired from pep8 setup.py """ with open('%s.py' % module) as module_fd: for line in module_fd: if line.startswith('__version__'): return eval(line.split('=')[-1]) # pylint:disable=eval-used setup( name=NAME, version=get_version(NAME), description='CLI script to get videos from Arte plus 7 using their URL', author='cladmi', download_url='https://github.com/cladmi/arte_plus7', py_modules=NAME, entry_points={ 'console_scripts': ['{name} = {name}:main'.format(name=NAME)], }, classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Intended Audience :: End Users/Desktop', 'Topic :: utilities', ], install_requires=['argparse', 'beautifulsoup4'], )
Change the name of the class
// You are given a phone book that consists of people's names and their phone number. After that // you will be given some person's name as query. For each query, print the phone number of that // person. import java.util.*; import java.io.*; public class q1 { public static void main(String []argh) { Map<String, Integer> phonebook = new HashMap<String, Integer>(); Scanner in = new Scanner(System.in); int n=in.nextInt(); in.nextLine(); for(int i=0;i<n;i++) { String name=in.nextLine(); int phone=in.nextInt(); phonebook.put(name, phone); in.nextLine(); } while(in.hasNext()) { String s=in.nextLine(); if(phonebook.containsKey(s)) { System.out.println(s + "=" + phonebook.get(s)); } else { System.out.println("Not found"); } } } }
// You are given a phone book that consists of people's names and their phone number. After that // you will be given some person's name as query. For each query, print the phone number of that // person. import java.util.*; import java.io.*; public class Solution { public static void main(String []argh) { Map<String, Integer> phonebook = new HashMap<String, Integer>(); Scanner in = new Scanner(System.in); int n=in.nextInt(); in.nextLine(); for(int i=0;i<n;i++) { String name=in.nextLine(); int phone=in.nextInt(); phonebook.put(name, phone); in.nextLine(); } while(in.hasNext()) { String s=in.nextLine(); if(phonebook.containsKey(s)) { System.out.println(s + "=" + phonebook.get(s)); } else { System.out.println("Not found"); } } } }
Remove .py extension from py_module.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='flask-appconfig', version='0.9.1.dev1', description=('Configures Flask applications in a canonical way. Also auto-' 'configures Heroku. Aims to standardize configuration.'), long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/flask-appconfig', license='MIT', packages=find_packages(exclude=['tests']), py_modules=['flaskdev'], install_requires=['flask', 'six'], entry_points={ 'console_scripts': [ 'flaskdev = flask_appconfig.cmd:main_flaskdev', ], } )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='flask-appconfig', version='0.9.1.dev1', description=('Configures Flask applications in a canonical way. Also auto-' 'configures Heroku. Aims to standardize configuration.'), long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/flask-appconfig', license='MIT', packages=find_packages(exclude=['tests']), py_modules=['flaskdev.py'], install_requires=['flask', 'six'], entry_points={ 'console_scripts': [ 'flaskdev = flask_appconfig.cmd:main_flaskdev', ], } )
Add rudimentary implementation of assignment node
package org.hummingbirdlang.nodes; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.realize.InferenceVisitor; public class HBAssignmentNode extends HBExpressionNode { @Child private HBExpressionNode targetNode; @Child private HBExpressionNode valueNode; public HBAssignmentNode(HBExpressionNode targetNode, HBExpressionNode valueNode) { this.targetNode = targetNode; this.valueNode = valueNode; } public void accept(InferenceVisitor visitor) { return; } @Override public Object executeGeneric(VirtualFrame frame) { if (!(this.targetNode instanceof HBIdentifierNode)) { throw new RuntimeException("Cannot yet handle assignment of non-identifier node: " + this.targetNode.toString()); } HBIdentifierNode identifierNode = (HBIdentifierNode)this.targetNode; Object value = this.valueNode.executeGeneric(frame); FrameSlot frameSlot = frame.getFrameDescriptor().findFrameSlot(identifierNode.getName()); frame.setObject(frameSlot, value); return value; } @Override public String toString() { StringBuilder result = new StringBuilder("HBAssignmentNode"); result.append("("); result.append(this.targetNode.toString()); result.append(" = "); result.append(this.valueNode.toString()); result.append(")"); return result.toString(); } }
package org.hummingbirdlang.nodes; import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.realize.InferenceVisitor; public class HBAssignmentNode extends HBExpressionNode { @Child private HBExpressionNode targetNode; @Child private HBExpressionNode valueNode; public HBAssignmentNode(HBExpressionNode targetNode, HBExpressionNode valueNode) { this.targetNode = targetNode; this.valueNode = valueNode; } public void accept(InferenceVisitor visitor) { return; } @Override public Object executeGeneric(VirtualFrame frame) { return null; } @Override public String toString() { StringBuilder result = new StringBuilder("HBAssignmentNode"); result.append("("); result.append(this.targetNode.toString()); result.append(" = "); result.append(this.valueNode.toString()); result.append(")"); return result.toString(); } }
Modify cappy dependency to work with Python 3.8
############################################################################### # Copyright 2015-2020 University of Florida. All rights reserved. # This file is part of UF CTS-IT's NACCulator project. # Use of this source code is governed by the license found in the LICENSE file. ############################################################################### from setuptools import setup, find_packages VERSION = "1.2.0" setup( name="nacculator", version=VERSION, author="Taeber Rapczak", author_email="taeber@ufl.edu", maintainer="UF CTS-IT", maintainer_email="ctsit@ctsi.ufl.edu", url="https://github.com/ctsit/nacculator", license="BSD 2-Clause", description="CSV to NACC's UDS3 format converter", keywords=["REDCap", "NACC", "UDS", "Clinical data"], download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION, package_dir={'nacc': 'nacc'}, packages=find_packages(), entry_points={ "console_scripts": [ "redcap2nacc = nacc.redcap2nacc:main", "nacculator_filters = nacc.run_filters:main" ] }, dependency_links=[ "git+https://github.com/ctsit/cappy.git@2.0.0#egg=cappy-2.0.0" ], install_requires=[ "cappy==2.0.0" ], python_requires=">=3.6.0", )
############################################################################### # Copyright 2015-2020 University of Florida. All rights reserved. # This file is part of UF CTS-IT's NACCulator project. # Use of this source code is governed by the license found in the LICENSE file. ############################################################################### from setuptools import setup, find_packages VERSION = "1.2.0" setup( name="nacculator", version=VERSION, author="Taeber Rapczak", author_email="taeber@ufl.edu", maintainer="UF CTS-IT", maintainer_email="ctsit@ctsi.ufl.edu", url="https://github.com/ctsit/nacculator", license="BSD 2-Clause", description="CSV to NACC's UDS3 format converter", keywords=["REDCap", "NACC", "UDS", "Clinical data"], download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION, package_dir={'nacc': 'nacc'}, packages=find_packages(), entry_points={ "console_scripts": [ "redcap2nacc = nacc.redcap2nacc:main", "nacculator_filters = nacc.run_filters:main" ] }, install_requires=[ "cappy @ git+https://github.com/ctsit/cappy.git@2.0.0" ], python_requires=">=3.6.0", )
Fix a lint error in start-a-project
var shop = require('../../') var reg = require('../../lib/registry.js') var fs = require('fs') var path = require('path') exports.init = function (workshopper) { this.__ = workshopper.i18n.__ this.lang = workshopper.i18n.lang reg.run('start-a-project') } exports.problem = { file: path.join(__dirname, 'problem.{lang}.txt') } exports.verify = function (args, cb) { var cwd = shop.cwd() var __ = this.__ try { require(cwd + '/package.json') } catch (er) { console.log(__('start-a-project.no_package')) return cb(false) } if (/^extracredit$/i.test(args[0] + args[1])) { try { fs.readFileSync(path.resolve(cwd, '.git', 'config')) console.log(__('start-a-project.extra_credit')) } catch (er) { console.log(fs.readFileSync(path.join(__dirname, 'suggestion.' + this.lang() + '.txt'), 'utf8') + cwd) return cb(false) } } else { console.log(fs.readFileSync(path.join(__dirname, 'continue.' + this.lang() + '.txt'), 'utf8')) } console.log(__('start-a-project.success')) return cb(true) }
var shop = require('../../') var reg = require('../../lib/registry.js') var fs = require('fs') var path = require('path') exports.init = function (workshopper) { this.__ = workshopper.i18n.__ this.lang = workshopper.i18n.lang reg.run('start-a-project') } exports.problem = { file: path.join(__dirname, 'problem.{lang}.txt') } exports.verify = function (args, cb) { var cwd = shop.cwd() var __ = this.__ try { require(cwd + '/package.json') } catch (er) { console.log(__('start-a-project.no_package')) return cb(false) } if (/^extracredit$/i.test(args[0] + args[1])) { try { fs.readFileSync(path.resolve(cwd, '.git', 'config')) console.log(__('start-a-project.extra_credit')) } catch (er) { console.log(fs.readFileSync(path.join(__dirname, 'suggestion.' + this.lang() + '.txt'), 'utf8') + cwd) return cb(false) } } else { console.log(fs.readFileSync(path.join(__dirname, 'continue.' + this.lang() + '.txt'), 'utf8')) } console.log(__('start-a-project.success')) return cb(true) }
Correct the module name in the header comment
/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // // Dalliance Genome Explorer // (c) Thomas Down 2006-2014 // // numformats.js // function formatLongInt(n) { return (n|0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') } function formatQuantLabel(v) { var t = '' + v; var dot = t.indexOf('.'); if (dot < 0) { return t; } else { var dotThreshold = 2; if (t.substring(0, 1) == '-') { ++dotThreshold; } if (dot >= dotThreshold) { return t.substring(0, dot); } else { return t.substring(0, dot + 2); } } } if (typeof(module) !== 'undefined') { module.exports = { formatLongInt: formatLongInt, formatQuantLabel: formatQuantLabel }; }
/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // // Dalliance Genome Explorer // (c) Thomas Down 2006-2014 // // memstore.js // function formatLongInt(n) { return (n|0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') } function formatQuantLabel(v) { var t = '' + v; var dot = t.indexOf('.'); if (dot < 0) { return t; } else { var dotThreshold = 2; if (t.substring(0, 1) == '-') { ++dotThreshold; } if (dot >= dotThreshold) { return t.substring(0, dot); } else { return t.substring(0, dot + 2); } } } if (typeof(module) !== 'undefined') { module.exports = { formatLongInt: formatLongInt, formatQuantLabel: formatQuantLabel }; }
Move the compress middleware to the top.
/* * Melodycoder, an personal webside. * http://botobe.net/ * * Copyright (c) 2013 Kai.XU * Licensed under the MIT license. */ var express = require('express'), map = require('./map'), http = require('http'), path = require('path'), db = require('./model/db'), config = require('./config').config; var app = express(); // 开发环境 app.configure('development', function() { app.use(express.logger('dev')); app.use(express.errorHandler()); }); // 生产环境 app.configure('production', function() { app.use(express.compress()); }); app.configure(function() { app.use(express.cookieParser()); app.use(express.session({ secret : config.SESSION_SECRET })); app.use(db.initialize()); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(require('stylus').middleware(__dirname + '/public')); app.use(express.static(path.join(__dirname, 'public'))); }); map(app); http.createServer(app).listen(app.get('port'));
/* * Melodycoder, an personal webside. * http://botobe.net/ * * Copyright (c) 2013 Kai.XU * Licensed under the MIT license. */ var express = require('express'), map = require('./map'), http = require('http'), path = require('path'), db = require('./model/db'), config = require('./config').config; var app = express(); app.configure(function() { app.use(express.cookieParser()); app.use(express.session({ secret : config.SESSION_SECRET })); app.use(db.initialize()); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(require('stylus').middleware(__dirname + '/public')); app.use(express.static(path.join(__dirname, 'public'))); }); // 开发环境 app.configure('development', function() { app.use(express.logger('dev')); app.use(express.errorHandler()); }); // 生产环境 app.configure('production', function() { app.use(express.compress()); }); map(app); http.createServer(app).listen(app.get('port'));
Fix PyPi version to be compliant see https://github.com/agrover/rtslib-fb/issues/22 We can't use fb* in the name I guess, so change the name of the package to rtslib-fb and use a more normal version. Signed-off-by: Andy Grover <b7d524d2f5cc5aebadb6b92b08d3ab26911cde33@redhat.com>
#! /usr/bin/env python ''' This file is part of RTSLib Community Edition. Copyright (c) 2011 by RisingTide Systems LLC 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, version 3 (AGPLv3). 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/>. ''' import re from distutils.core import setup import rtslib setup ( name = 'rtslib-fb', version = '2.1.31', description = 'API for Linux kernel SCSI target (aka LIO)', license='AGPLv3', maintainer='Andy Grover', maintainer_email='agrover@redhat.com', url='http://github.com/agrover/rtslib-fb', packages=['rtslib'], )
#! /usr/bin/env python ''' This file is part of RTSLib Community Edition. Copyright (c) 2011 by RisingTide Systems LLC 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, version 3 (AGPLv3). 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/>. ''' import re from distutils.core import setup import rtslib setup ( name = 'rtslib', version = '2.1.fb30', description = 'API for Linux kernel SCSI target (aka LIO)', license='AGPLv3', maintainer='Andy Grover', maintainer_email='agrover@redhat.com', url='http://github.com/agrover/rtslib-fb', packages=['rtslib'], )
Add assertion that no options are passed to LCTD Attempting to pass options to the current version of LCTD would cause it to crash.
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer All rights reserved. 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 benchexec.util as util import benchexec.tools.template import benchexec.result as result class Tool(benchexec.tools.template.BaseTool): def executable(self): return util.find_executable('lctdsvcomp') def name(self): return 'LCTD' def cmdline(self, executable, options, tasks, propertyfile, rlimits): assert len(tasks) == 1 assert len(options) == 0 return [executable] + tasks def determine_result(self, returncode, returnsignal, output, isTimeout): if "TRUE\n" in output: status = result.RESULT_TRUE_PROP elif "FALSE\n" in output: status = result.RESULT_FALSE_REACH else: status = "UNKNOWN" return status
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer All rights reserved. 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 benchexec.util as util import benchexec.tools.template import benchexec.result as result class Tool(benchexec.tools.template.BaseTool): def executable(self): return util.find_executable('lctdsvcomp') def name(self): return 'LCTD' def cmdline(self, executable, options, tasks, propertyfile, rlimits): assert len(tasks) == 1 return [executable] + tasks def determine_result(self, returncode, returnsignal, output, isTimeout): if "TRUE\n" in output: status = result.RESULT_TRUE_PROP elif "FALSE\n" in output: status = result.RESULT_FALSE_REACH else: status = "UNKNOWN" return status
Fix fatal error when a dependency needs to be installed ``` PHP Catchable fatal error: Argument 1 passed to Composer\DependencyResolver\Rule::getPrettyString() must be an instance of Composer\DependencyResolver\Pool, none given, called in /home/vagrant/.wp-cli/php/WP_CLI/PackageManagerEventSubscriber.php on line 40 and defined in /home/vagrant/.wp-cli/vendor/composer/composer/src/Composer/DependencyResolver/Rule.php on line 161 ```
<?php namespace WP_CLI; use \Composer\DependencyResolver\Rule; use \Composer\EventDispatcher\Event; use \Composer\EventDispatcher\EventSubscriberInterface; use \Composer\Script\PackageEvent; use \Composer\Script\ScriptEvents; use \WP_CLI; /** * A Composer Event subscriber so we can keep track of what's happening inside Composer */ class PackageManagerEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install', ScriptEvents::POST_PACKAGE_INSTALL => 'post_install', ); } public static function pre_install( PackageEvent $event ) { WP_CLI::log( ' - Installing package' ); } public static function post_install( PackageEvent $event ) { $operation = $event->getOperation(); $reason = $operation->getReason(); if ( $reason instanceof Rule ) { switch ( $reason->getReason() ) { case Rule::RULE_PACKAGE_CONFLICT; case Rule::RULE_PACKAGE_SAME_NAME: case Rule::RULE_PACKAGE_REQUIRES: $composer_error = $reason->getPrettyString( $event->getPool() ); break; } if ( ! empty( $composer_error ) ) { WP_CLI::log( sprintf( " - Error: %s", $composer_error ) ); } } } }
<?php namespace WP_CLI; use \Composer\DependencyResolver\Rule; use \Composer\EventDispatcher\Event; use \Composer\EventDispatcher\EventSubscriberInterface; use \Composer\Script\PackageEvent; use \Composer\Script\ScriptEvents; use \WP_CLI; /** * A Composer Event subscriber so we can keep track of what's happening inside Composer */ class PackageManagerEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install', ScriptEvents::POST_PACKAGE_INSTALL => 'post_install', ); } public static function pre_install( PackageEvent $event ) { WP_CLI::log( ' - Installing package' ); } public static function post_install( PackageEvent $event ) { $operation = $event->getOperation(); $reason = $operation->getReason(); if ( $reason instanceof Rule ) { switch ( $reason->getReason() ) { case Rule::RULE_PACKAGE_CONFLICT; case Rule::RULE_PACKAGE_SAME_NAME: case Rule::RULE_PACKAGE_REQUIRES: $composer_error = $reason->getPrettyString(); break; } if ( ! empty( $composer_error ) ) { WP_CLI::log( sprintf( " - Error: %s", $composer_error ) ); } } } }
Remove tag, remove unneeded variable
<?php //SHTracker, Copyright Josh Fradley (http://github.com/joshf/SHTracker) //Connect to database require_once("config.php"); //Connect to database $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if (!$con) { die("Error: Could not connect to database (" . mysql_error() . "). Check your database settings are correct."); } //Check database exists $does_db_exist = mysql_select_db(DB_NAME, $con); if (!$does_db_exist) { die("Error: Database does not exist (" . mysql_error() . "). Check your database settings are correct."); } mysql_select_db(DB_NAME, $con); if (isset($_GET["id"])) { $id = mysql_real_escape_string($_GET["id"]); } else { die("Error: ID cannot be blank."); } //If ID exists, show count or else die $showinfo = mysql_query("SELECT count FROM Data WHERE id = \"$id\""); $showresult = mysql_fetch_assoc($showinfo); if ($showresult != 0) { echo $showresult["count"]; } else { die("Error: ID does not exist."); } mysql_close($con); ?>
<?php //SHTracker, Copyright Josh Fradley (http://github.com/joshf/SHTracker) //Connect to database require_once("config.php"); //Connect to database $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if (!$con) { die("Error: Could not connect to database (" . mysql_error() . "). Check your database settings are correct."); } //Check database exists $does_db_exist = mysql_select_db(DB_NAME, $con); if (!$does_db_exist) { die("Error:</b> Database does not exist (" . mysql_error() . "). Check your database settings are correct."); } mysql_select_db(DB_NAME, $con); if (isset($_GET["id"])) { $id = mysql_real_escape_string($_GET["id"]); } else { die("Error: ID cannot be blank."); } //If ID exists, show count or else die $showinfo = mysql_query("SELECT name, count FROM Data WHERE id = \"$id\""); $showresult = mysql_fetch_assoc($showinfo); if ($showresult != 0) { echo $showresult["count"]; } else { die("Error: ID does not exist."); } mysql_close($con); ?>
Make sure the cursor is properly closed after usage
import uuid from django.core.cache import cache from django.db import connection def check_database(): """Check if the application can perform a dummy sql query""" with connection.cursor() as cursor: cursor.execute('SELECT 1; -- Healthcheck') row = cursor.fetchone() return row[0] == 1 def check_cache_default(): """Check if the application can connect to the default cached and read/write some dummy data. """ dummy = str(uuid.uuid4()) key = 'healthcheck:%s' % dummy cache.set(key, dummy, timeout=5) cached_value = cache.get(key) return cached_value == dummy def check_dummy_true(): return True def check_dummy_false(): return False def check_remote_addr(request): return request.META['REMOTE_ADDR']
import uuid from django.core.cache import cache from django.db import connection def check_database(): """Check if the application can perform a dummy sql query""" cursor = connection.cursor() cursor.execute('SELECT 1; -- Healthcheck') row = cursor.fetchone() return row[0] == 1 def check_cache_default(): """Check if the application can connect to the default cached and read/write some dummy data. """ dummy = str(uuid.uuid4()) key = 'healthcheck:%s' % dummy cache.set(key, dummy, timeout=5) cached_value = cache.get(key) return cached_value == dummy def check_dummy_true(): return True def check_dummy_false(): return False def check_remote_addr(request): return request.META['REMOTE_ADDR']
Add export of Experiment Example to use in tests
var example = { name : 'Paper chaser', hypothesis : '5g is the best weight for planes', kind : 'ad_hoc', dependentVariable: { name : 'Flight length', measures : [{ name : 'Distance', kind : 'numeric', scale : null, list : null, samples : [{ value: 3.2 }, { value: 2.5 }], request : { freq : null, question : 'how far did it fly?' } }] }, independentVars : [{ name: 'Weight', actionStart : null, actionWarning : null, //should likely be some datetime thing.... consecutiveActions : 1, options : ['3.4','6.0'], remind : { freq : null, // whatever datetime thing we decide on reminder: 'Put this amount of weight in your plane' } }] }; module.exports = example;
var example = { name : 'Paper chaser', hypothesis : '5g is the best weight for planes', kind : 'ad_hoc', dependentVariable: { name : 'Flight length', measures : [{ name : 'Distance', kind : 'numeric', scale : null, list : null, samples : [{ value: 3.2 }, { value: 2.5 }], request : { freq : null, question : 'how far did it fly?' } }] }, independentVars : [{ name: 'Weight', actionStart : null, actionWarning : null, //should likely be some datetime thing.... consecutiveActions : 1, options : ['3.4','6.0'], remind : { freq : null, // whatever datetime thing we decide on reminder: 'Put this amount of weight in your plane' } }] };
Call version comparison method to create constraint
<?php if ( ! function_exists( 'CheckVersions' ) ) { /** * Facade to quickly check if version requirements are met. * * @param array $requirements The requirements to check. */ function CheckVersions( $requirements ) { // Only show for admin users. if ( ! current_user_can( 'manage_options' ) || ! is_array( $requirements ) ) { return; } $config = include_once dirname( __FILE__ ) . '/../configs/default.php'; $checker = new Whip_RequirementsChecker( $config ); foreach ( $requirements as $component => $versionComparison ) { $checker->addRequirement( Whip_VersionRequirement::fromCompareString( $component, $versionComparison ) ); } $checker->check(); if ( ! $checker->hasMessages() ) { return; } $presenter = new Whip_WPMessagePresenter( $checker->getMostRecentMessage() ); $presenter->register_hooks(); } }
<?php if ( ! function_exists( 'CheckVersions' ) ) { /** * Facade to quickly check if version requirements are met. * * @param array $requirements The requirements to check. */ function CheckVersions( $requirements ) { // Only show for admin users. if ( ! current_user_can( 'manage_options' ) || ! is_array( $requirements ) ) { return; } $config = include_once dirname( __FILE__ ) . '/../configs/default.php'; $checker = new Whip_RequirementsChecker( $config ); foreach ( $requirements as $component => $version ) { $checker->addRequirement( new Whip_VersionRequirement( $component, $version ) ); } $checker->check(); if ( ! $checker->hasMessages() ) { return; } $presenter = new Whip_WPMessagePresenter( $checker->getMostRecentMessage() ); $presenter->register_hooks(); } }
Add particle count parameter to Smoke effect
package de.slikey.effectlib.effect; import de.slikey.effectlib.Effect; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import org.bukkit.Particle; import de.slikey.effectlib.util.RandomUtils; import org.bukkit.Location; public class SmokeEffect extends Effect { /** * ParticleType of spawned particle */ public Particle particle = Particle.SMOKE_NORMAL; /** * Number of particles to display */ public int particles = 20; public SmokeEffect(EffectManager effectManager) { super(effectManager); type = EffectType.REPEATING; period = 1; iterations = 300; } @Override public void onRun() { Location location = getLocation(); for (int i = 0; i < particles; i++) { location.add(RandomUtils.getRandomCircleVector().multiply(RandomUtils.random.nextDouble() * 0.6d)); location.add(0, RandomUtils.random.nextFloat() * 2, 0); display(particle, location); } } }
package de.slikey.effectlib.effect; import de.slikey.effectlib.Effect; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import org.bukkit.Particle; import de.slikey.effectlib.util.RandomUtils; import org.bukkit.Location; public class SmokeEffect extends Effect { /** * ParticleType of spawned particle */ public Particle particle = Particle.SMOKE_NORMAL; public SmokeEffect(EffectManager effectManager) { super(effectManager); type = EffectType.REPEATING; period = 1; iterations = 300; } @Override public void onRun() { Location location = getLocation(); for (int i = 0; i < 20; i++) { location.add(RandomUtils.getRandomCircleVector().multiply(RandomUtils.random.nextDouble() * 0.6d)); location.add(0, RandomUtils.random.nextFloat() * 2, 0); display(particle, location); } } }
Fix 'is ore' check not handling multiple oredict registrations properly
package squeek.wailaharvestability.helpers; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; public class OreHelper { public static boolean isBlockAnOre(Block block) { return isBlockAnOre(block, 0); } public static boolean isBlockAnOre(Block block, int metadata) { return isItemAnOre(new ItemStack(block, 1, metadata)); } public static boolean isItemAnOre(ItemStack itemStack) { // check the ore dictionary to see if it starts with "ore" int[] oreIDs = OreDictionary.getOreIDs(itemStack); for (int oreID : oreIDs) { if (OreDictionary.getOreName(oreID).startsWith("ore")) return true; } // ore in the display name (but not part of another word) if (itemStack.getDisplayName().matches(".*(^|\\s)([oO]re)($|\\s).*")) return true; // ore as the start of the unlocalized name if (itemStack.getUnlocalizedName().startsWith("ore")) return true; return false; } }
package squeek.wailaharvestability.helpers; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; public class OreHelper { public static boolean isBlockAnOre(Block block) { return isBlockAnOre(block, 0); } public static boolean isBlockAnOre(Block block, int metadata) { return isItemAnOre(new ItemStack(block, 1, metadata)); } public static boolean isItemAnOre(ItemStack itemStack) { // check the ore dictionary to see if it starts with "ore" int oreID = -1; if ((oreID = OreDictionary.getOreID(itemStack)) != -1 && OreDictionary.getOreName(oreID).startsWith("ore")) return true; // ore in the display name (but not part of another word) if (itemStack.getDisplayName().matches(".*(^|\\s)([oO]re)($|\\s).*")) return true; // ore as the start of the unlocalized name if (itemStack.getUnlocalizedName().startsWith("ore")) return true; return false; } }
Reduce duplication in acceptance tests
import { expect } from 'chai'; import { addTodo } from './common.js'; describe('App', function() { beforeEach(function() { addTodo('buy cheddar'); addTodo('buy chorizo'); addTodo('buy bacon'); }); describe('todos', function() { it('should not be marked as completed after being added', function() { expect(allTodosChecked()).to.be.false; }); it('should be marked as completed when checking them', function() { $$('.todo .toggle').forEach(toggle => toggle.click()); expect(allTodosChecked()).to.be.true; }); function allTodosChecked() { // We can use getAttribute without map after // https://github.com/webdriverio/wdio-sync/issues/43 is fixed. const states = $$('.todo .toggle').map( toggle => toggle.getAttribute('checked')); expect(states).to.have.length(3); return states.every(state => state === 'true'); } }); });
import { expect } from 'chai'; import { addTodo } from './common.js'; describe('App', function() { beforeEach(function() { addTodo('buy cheddar'); addTodo('buy chorizo'); addTodo('buy bacon'); }); describe('todos', function() { it('should not be marked as completed after being added', function() { // We can use getAttribute without map after // https://github.com/webdriverio/wdio-sync/issues/43 is fixed. const states = $$('.todo .toggle').map(c => c.getAttribute('checked')); expect(states).to.have.length(3); expect(states.every(state => state === 'true')).to.be.false; }); it('should be marked as completed when checking them', function() { $$('.todo .toggle').forEach(toggle => toggle.click()); const states = browser.elements('input[type=checkbox]').getAttribute('checked'); expect(states).to.have.length(3); expect(states.every(state => state === 'true')).to.be.true; }); }); });
Use sql.query instead of sql.open/conn.query This is a bit of a shortcut, but the readability of the code is greatly improved.
var sql = require('msnodesql'); // Change the connectionString. Example // "Driver={SQL Server Native Client 11.0};Server=tcp:?????.database.windows.net,1433;Database=????;Uid=?????@?????;Pwd=?????"; var connectionString = ""; var testQuery = "SELECT 1"; if(connectionString == "") { console.log("This script cannot run without a connection string"); return; } var http = require('http'); var port = process.env.PORT || 1337; var httpServer = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); sql.query(connectionString, testQuery, function(err, result) { if(err) res.end("Query Failed \n"); else res.end("Query result: " + result[0]['Column0'] + " \n"); }); }); httpServer.listen(port); console.log('Server running at localhost:'+port);
var sql = require('msnodesql'); // Change the connectionString. Example // "Driver={SQL Server Native Client 11.0};Server=tcp:?????.database.windows.net,1433;Database=????;Uid=?????@?????;Pwd=?????"; var connectionString = ""; var testQuery = "SELECT 1"; if(connectionString == "") { console.log("This script cannot run without a connection string"); return; } var http = require('http'); var port = process.env.PORT || 1337; var httpServer = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); sql.open(connectionString, function(err, conn) { if(err) res.end("Connection Failed \n"); conn.query(testQuery, [], function(err, result) { if(err) res.end("Query Failed \n"); else res.end("Query result - " + result[0]['Column0'] + " \n"); }); }); }); httpServer.listen(port); console.log('Server running at localhost:'+port);
Fix test that depended on previous high school name in demo data set
<?php class CleverQueryParamTest extends PHPUnit_Framework_TestCase { public function testWhere() { authorizeFromEnv(); $validQueries = array( array('where' => json_encode(array('name' => 'City High School'))), array('where' => '{"name": {"$regex": "High"}}'), array('where' => array('name' => 'City High School')) ); foreach ($validQueries as $query) { $schools = CleverSchool::all($query); $this->assertEquals(count($schools), 1); $this->assertEquals($schools[0]->name, 'City High School'); } } public function testCount() { authorizeFromEnv(); $validQueries = array( array('count' => 'true'), array('count' => true), ); foreach ($validQueries as $query) { $resp = CleverStudent::all($query); $this->assertEquals($resp['count'] > 0, true); } } }
<?php class CleverQueryParamTest extends PHPUnit_Framework_TestCase { public function testWhere() { authorizeFromEnv(); $validQueries = array( array('where' => json_encode(array('name' => 'Clever High School'))), array('where' => '{"name": {"$regex": "High"}}'), array('where' => array('name' => 'Clever High School')) ); foreach ($validQueries as $query) { $schools = CleverSchool::all($query); $this->assertEquals(count($schools), 1); $this->assertEquals($schools[0]->name, 'Clever High School'); } } public function testCount() { authorizeFromEnv(); $validQueries = array( array('count' => 'true'), array('count' => true), ); foreach ($validQueries as $query) { $resp = CleverStudent::all($query); $this->assertEquals($resp['count'] > 0, true); } } }
Add control-panel asset & initial specs
/*global window*/ /*global angular*/ /*global ___socket___*/ (function (window, socket) { "use strict"; var app = angular.module("BrowserSync", []); /** * Socket Factory */ app.service("Socket", function () { return { addEvent: function (name, callback) { socket.on(name, callback); }, removeEvent: function (name, callback) { socket.removeListener(name, callback); } }; }); /** * Options Factory */ app.service("Options", function () { return { }; }); app.controller("MainCtrl", function ($scope, Socket) { $scope.options = {}; $scope.socketEvents = { connection: function (options) { $scope.$apply(function () { $scope.options = options; }); } }; Socket.addEvent("connection", $scope.socketEvents.connection); }); }(window, (typeof ___socket___ === "undefined") ? {} : ___socket___));
/*global window*/ /*global angular*/ /*global ___socket___*/ (function (window, socket) { "use strict"; var app = angular.module("BrowserSync", []); /** * Socket Factory */ app.service("Socket", function () { return { addEvent: function (name, callback) { socket.on(name, callback); }, removeEvent: function (name, callback) { socket.removeListener(name, callback); } }; }); /** * Options Factory */ app.service("Options", function () { return { } }); app.controller("MainCtrl", function ($scope, Socket) { $scope.options = {}; $scope.socketEvents = { connection: function (options) { $scope.$apply(function () { $scope.options = options; }); } }; Socket.addEvent("connection", $scope.socketEvents.connection); }); }(window, (typeof ___socket___ === "undefined") ? {} : ___socket___));
Fix code style issues with Black
# -*- coding: utf-8 -*- import os from scout.demo import cnv_report_path from scout.commands import cli def test_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(cnv_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"], ) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"], ) assert 'Path "invalid-path" does not exist.' in result.output assert result.exit_code == 2
# -*- coding: utf-8 -*- import os from scout.demo import cnv_report_path from scout.commands import cli def test_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(cnv_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_cnv_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],) assert 'Path "invalid-path" does not exist.' in result.output assert result.exit_code == 2
Fix test backspace (this test has to be changed since the parent implementation is now called when there is no space to eat)
from pyqode.qt import QtCore from pyqode.qt.QtTest import QTest from pyqode.core.api import TextHelper from pyqode.core import modes from test.helpers import editor_open def get_mode(editor): return editor.modes.get(modes.SmartBackSpaceMode) def test_enabled(editor): mode = get_mode(editor) assert mode.enabled mode.enabled = False mode.enabled = True @editor_open(__file__) def test_key_pressed(editor): QTest.qWait(1000) TextHelper(editor).goto_line(21, 4) QTest.qWait(2000) assert editor.textCursor().positionInBlock() == 4 QTest.keyPress(editor, QtCore.Qt.Key_Backspace) QTest.qWait(2000) assert editor.textCursor().positionInBlock() == 0 TextHelper(editor).goto_line(19, 5) QTest.qWait(2000) assert editor.textCursor().positionInBlock() == 5 QTest.keyPress(editor, QtCore.Qt.Key_Backspace) QTest.qWait(2000) assert editor.textCursor().positionInBlock() == 4 TextHelper(editor).goto_line(20, 0) QTest.qWait(2000) assert editor.textCursor().positionInBlock() == 0 QTest.keyPress(editor, QtCore.Qt.Key_Backspace) QTest.qWait(2000) assert editor.textCursor().positionInBlock() == 28
from pyqode.qt import QtCore from pyqode.qt.QtTest import QTest from pyqode.core.api import TextHelper from pyqode.core import modes from test.helpers import editor_open def get_mode(editor): return editor.modes.get(modes.SmartBackSpaceMode) def test_enabled(editor): mode = get_mode(editor) assert mode.enabled mode.enabled = False mode.enabled = True @editor_open(__file__) def test_key_pressed(editor): QTest.qWait(1000) TextHelper(editor).goto_line(20, 4) assert editor.textCursor().positionInBlock() == 4 QTest.keyPress(editor, QtCore.Qt.Key_Backspace) assert editor.textCursor().positionInBlock() == 0 TextHelper(editor).goto_line(19, 5) assert editor.textCursor().positionInBlock() == 5 QTest.keyPress(editor, QtCore.Qt.Key_Backspace) assert editor.textCursor().positionInBlock() == 4 TextHelper(editor).goto_line(20, 0) assert editor.textCursor().positionInBlock() == 0 QTest.keyPress(editor, QtCore.Qt.Key_Backspace) assert editor.textCursor().positionInBlock() == 0
Fix Grunt task relative path.
var path = require('path'); var testee = require('../lib/testee'); module.exports = function (grunt) { grunt.registerMultiTask('testee', 'Run tests', function () { var done = this.async(); var options = this.options(); var browsers = options.browsers || ['phantom']; var files = grunt.file.expand(grunt.util._.flatten(this.files.map(function (file) { // Test file path need to be absolute to the root so that grunt.file.expand can glob them return path.join(options.root || '', file.orig.src.toString()); }))); if(options.root) { // Each file in the globbed list needs to be converted back to their relative paths files = files.map(function (file) { return path.relative(options.root, file); }); } if(!files.length) { return done(new Error('No file passed to Testee task.')); } testee.test(files, browsers, options).then(function () { done(); }, function (error) { done(error); }); }); };
var path = require('path'); var testee = require('../lib/testee'); module.exports = function (grunt) { grunt.registerMultiTask('testee', 'Run tests', function () { var done = this.async(); var options = this.options(); var browsers = options.browsers || ['phantom']; var files = grunt.file.expand(grunt.util._.flatten(this.files.map(function (file) { // Test file path need to be absolute to the root so that grunt.file.expand can glob them return path.join(options.root || '.', file.orig.src.toString()); }))); if(options.root) { // Each file in the globbed list needs to be converted back to their relative paths files = files.map(function (file) { return path.relative(options.root, file); }); } if(!files.length) { return done(new Error('No file passed to Testee task.')); } testee.test(files, browsers, options).then(function () { done(); }, function (error) { done(error); }); }); };
Select only customers that have one or more projects
<?php namespace Ixudra\Portfolio\Repositories\Eloquent; use Ixudra\Core\Repositories\Eloquent\BaseEloquentRepository; use Ixudra\Portfolio\Models\Customer; class EloquentCustomerRepository extends BaseEloquentRepository { protected function getModel() { return new Customer; } protected function getTable() { return 'customers'; } public function search($filters, $resultsPerPage) { $results = $this->getModel(); $results = $results ->join('projects', 'customers.id', '=', 'projects.customer_id'); foreach( $filters as $key => $value ) { if( !$this->hasString( $filters, $key ) ) { continue; } $results = $results->where( $key, 'like', $value ); } return $results ->select($this->getTable() .'.*') ->paginate($resultsPerPage) ->appends($filters) ->appends('results_per_page', $resultsPerPage); } }
<?php namespace Ixudra\Portfolio\Repositories\Eloquent; use Ixudra\Core\Repositories\Eloquent\BaseEloquentRepository; use Ixudra\Portfolio\Models\Customer; class EloquentCustomerRepository extends BaseEloquentRepository { protected function getModel() { return new Customer; } protected function getTable() { return 'customers'; } public function search($filters, $resultsPerPage) { $results = $this->getModel(); foreach( $filters as $key => $value ) { if( !$this->hasString( $filters, $key ) ) { continue; } $results = $results->where( $key, 'like', $value ); } return $results ->select($this->getTable() .'.*') ->paginate($resultsPerPage) ->appends($filters) ->appends('results_per_page', $resultsPerPage); } }
Fix implicit dependency on pypandoc
from setuptools import setup, find_packages import os from osuapi import __version__ as version, __title__ as name, __author__ as author, __license__ as license def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() try: import pypandoc except ImportError: readme = None else: with open('README.md') as readme_md: readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown') setup( name=name, version=version, author=author, url="https://github.com/khazhyk/osuapi", license="MIT", long_description=readme, keywords="osu", packages=find_packages(), description="osu! api wrapper.", classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Utilities" ] )
from setuptools import setup, find_packages import os from osuapi import __version__ as version, __title__ as name, __author__ as author, __license__ as license import pypandoc def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() with open('README.md') as readme_md: readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown') setup( name=name, version=version, author=author, url="https://github.com/khazhyk/osuapi", license="MIT", long_description=readme, keywords="osu", packages=find_packages(), description="osu! api wrapper.", classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Utilities" ] )
Fix issue with path variable
import os from setuptools import setup PACKAGE_VERSION = '0.3' def version(): def version_file(mode='r'): return open(os.path.join(os.path.dirname(os.path.abspath(__file__), 'version.txt')), mode) if os.getenv('TRAVIS'): with version_file('w') as verfile: verfile.write('{0}.{1}'.format(PACKAGE_VERSION, os.getenv('TRAVIS_BUILD_NUMBER'))) with version_file() as verfile: data = verfile.readlines() return data[0].strip() setup( name='osaapi', version=version(), author='apsliteteam, oznu', author_email='aps@odin.com', packages=['osaapi'], url='https://aps.odin.com', license='Apache License', description='A python client for the Odin Service Automation (OSA) and billing APIs.', long_description=open('README.md').read(), )
import os from setuptools import setup PACKAGE_VERSION = '0.3' def version(): def version_file(mode='r'): return open(os.path.dirname(os.path.abspath(__file__), 'version.txt'), mode) if os.getenv('TRAVIS'): with version_file('w') as verfile: verfile.write('{0}.{1}'.format(PACKAGE_VERSION, os.getenv('TRAVIS_BUILD_NUMBER'))) with version_file() as verfile: data = verfile.readlines() return data[0].strip() setup( name='osaapi', version=version(), author='apsliteteam, oznu', author_email='aps@odin.com', packages=['osaapi'], url='https://aps.odin.com', license='Apache License', description='A python client for the Odin Service Automation (OSA) and billing APIs.', long_description=open('README.md').read(), )
Remove unneeded disabled class for slider
/** * @class CM_FormField_Integer * @extends CM_FormField_Abstract */ var CM_FormField_Integer = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Integer', ready: function() { var field = this; var $slider = this.$(".slider"); var $input = this.$("input"); $slider.slider({ value: $input.val(), min: field.getOption("min"), max: field.getOption("max"), step: field.getOption("step"), slide: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); }, change: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); } }); $slider.children(".ui-slider-handle").text($input.val()); $input.watch("disabled", function (propName, oldVal, newVal) { $slider.slider("option", "disabled", newVal); }); $input.changetext(function() { $slider.slider("option", "value", $(this).val()); field.trigger('change'); }); } });
/** * @class CM_FormField_Integer * @extends CM_FormField_Abstract */ var CM_FormField_Integer = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Integer', ready: function() { var field = this; var $slider = this.$(".slider"); var $input = this.$("input"); $slider.slider({ value: $input.val(), min: field.getOption("min"), max: field.getOption("max"), step: field.getOption("step"), slide: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); }, change: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); } }); $slider.children(".ui-slider-handle").text($input.val()); $input.watch("disabled", function (propName, oldVal, newVal) { $slider.slider("option", "disabled", newVal); $slider.toggleClass("disabled", newVal); }); $input.changetext(function() { $slider.slider("option", "value", $(this).val()); field.trigger('change'); }); } });
Update command to use nlppln utils - fixes the double extension of output files
#!/usr/bin/env python import click import os import codecs import json from xtas.tasks._frog import parse_frog, frog_to_saf from nlppln.utils import create_dirs, out_file_name @click.command() @click.argument('input_files', nargs=-1, type=click.Path(exists=True)) @click.argument('output_dir', nargs=1, type=click.Path()) def frog2saf(input_files, output_dir): create_dirs(output_dir) for fi in input_files: with codecs.open(fi) as f: lines = f.readlines() lines = [line.strip() for line in lines] saf_data = frog_to_saf(parse_frog(lines)) head, tail = os.path.split(fi) fname = tail.replace(os.path.splitext(tail)[1], '') out_file = os.path.join(output_dir, out_file_name(output_dir, fname, 'json')) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4) if __name__ == '__main__': frog2saf()
#!/usr/bin/env python import click import os import codecs import json from xtas.tasks._frog import parse_frog, frog_to_saf @click.command() @click.argument('input_files', nargs=-1, type=click.Path(exists=True)) @click.argument('output_dir', nargs=1, type=click.Path()) def frog2saf(input_files, output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir) for fi in input_files: with codecs.open(fi) as f: lines = f.readlines() lines = [line.strip() for line in lines] saf_data = frog_to_saf(parse_frog(lines)) head, tail = os.path.split(fi) fname = tail.replace(os.path.splitext(tail)[1], '') out_file = os.path.join(output_dir, '{}.json'.format(fname)) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4) if __name__ == '__main__': frog2saf()
Use a .md long_description for PyPI
import os from setuptools import setup from mdtoc import __version__ setup( name="mdtoc", version=__version__, description="Adds table of contents to Markdown files", long_description=open( os.path.join(os.path.abspath(os.path.dirname(__file__)), "README.md") ).read(), author="Scott Frazer", author_email="scott.d.frazer@gmail.com", packages=["mdtoc"], install_requires=["xtermcolor", "requests<3.0.0"], scripts={"scripts/mdtoc"}, license="MIT", keywords="Markdown, table of contents, toc", url="http://github.com/scottfrazer/mdtoc", classifiers=[ "License :: OSI Approved :: MIT License", "Environment :: Console", "Topic :: Utilities", "Topic :: Text Processing", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", ], )
from setuptools import setup from mdtoc import __version__ long_description = "Adds table of contents to Markdown files" setup( name="mdtoc", version=__version__, description=long_description, author="Scott Frazer", author_email="scott.d.frazer@gmail.com", packages=["mdtoc"], install_requires=["xtermcolor", "requests<3.0.0"], scripts={"scripts/mdtoc"}, license="MIT", keywords="Markdown, table of contents, toc", url="http://github.com/scottfrazer/mdtoc", classifiers=[ "License :: OSI Approved :: MIT License", "Environment :: Console", "Topic :: Utilities", "Topic :: Text Processing", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", ], )
Allow start and end arguments to take inputs of multiple words such as 'New York'
from argparse import ArgumentParser from matplotlib import pyplot as plt from graph import Greengraph def process(): parser = ArgumentParser( description="Produce graph quantifying the amount of green land between two locations") parser.add_argument("--start", required=True, nargs="+", help="The starting location ") parser.add_argument("--end", required=True, nargs="+", help="The ending location") parser.add_argument("--steps", help="The number of steps between the starting and ending locations, defaults to 10") parser.add_argument("--out", help="The output filename, defaults to graph.png") arguments = parser.parse_args() #mygraph = Greengraph(arguments.start, arguments.end) if arguments.steps: data = mygraph.green_between(arguments.steps) else: data = mygraph.green_between(10) plt.plot(data) # TODO add a title and axis labels to this graph if arguments.out: plt.savefig(arguments.out) else: plt.savefig("graph.png") print arguments.start print arguments.end if __name__ == "__main__": process()
from argparse import ArgumentParser from matplotlib import pyplot as plt from graph import Greengraph def process(): parser = ArgumentParser( description="Produce graph quantifying the amount of green land between two locations") parser.add_argument("--start", required=True, help="The starting location ") parser.add_argument("--end", required=True, help="The ending location") parser.add_argument("--steps", help="The number of steps between the starting and ending locations, defaults to 10") parser.add_argument("--out", help="The output filename, defaults to graph.png") arguments = parser.parse_args() mygraph = Greengraph(arguments.start, arguments.end) if arguments.steps: data = mygraph.green_between(arguments.steps) else: data = mygraph.green_between(10) plt.plot(data) # TODO add a title and axis labels to this graph if arguments.out: plt.savefig(arguments.out) else: plt.savefig("graph.png") if __name__ == "__main__": process()
Add documentation for lib/mdb package.
/* Package mdb implements a simple in-memory Machine DataBase. */ package mdb import ( "io" ) // Machine describes a single machine with a unique Hostname and optional // metadata about the machine. type Machine struct { Hostname string RequiredImage string `json:",omitempty"` PlannedImage string `json:",omitempty"` DisableUpdates bool `json:",omitempty"` OwnerGroup string `json:",omitempty"` } // UpdateFrom updates dest with data from source. func (dest *Machine) UpdateFrom(source Machine) { dest.updateFrom(source) } // Mdb describes a list of Machines. It implements sort.Interface. type Mdb struct { Machines []Machine } // DebugWrite writes the JSON representation to w. func (mdb *Mdb) DebugWrite(w io.Writer) error { return mdb.debugWrite(w) } // Len returns the number of machines. func (mdb *Mdb) Len() int { return len(mdb.Machines) } // Less compares the hostnames of left and right. func (mdb *Mdb) Less(left, right int) bool { if mdb.Machines[left].Hostname < mdb.Machines[right].Hostname { return true } return false } // Swap swaps two entries in mdb. func (mdb *Mdb) Swap(left, right int) { tmp := mdb.Machines[left] mdb.Machines[left] = mdb.Machines[right] mdb.Machines[right] = tmp }
package mdb import ( "io" ) type Machine struct { Hostname string RequiredImage string `json:",omitempty"` PlannedImage string `json:",omitempty"` DisableUpdates bool `json:",omitempty"` OwnerGroup string `json:",omitempty"` } func (dest *Machine) UpdateFrom(source Machine) { dest.updateFrom(source) } type Mdb struct { Machines []Machine } func (mdb *Mdb) DebugWrite(w io.Writer) error { return mdb.debugWrite(w) } func (mdb *Mdb) Len() int { return len(mdb.Machines) } func (mdb *Mdb) Less(left, right int) bool { if mdb.Machines[left].Hostname < mdb.Machines[right].Hostname { return true } return false } func (mdb *Mdb) Swap(left, right int) { tmp := mdb.Machines[left] mdb.Machines[left] = mdb.Machines[right] mdb.Machines[right] = tmp }
Make `stdio` a global, point `runtime.stdio` to it
// Copyright 2014-2015 runtime.js project 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. 'use strict'; /* global isolate, runtime */ console.log = isolate.log; var resources = require('./resources'); require('./polyfill'); var tty = require('./tty'); var keyboard = require('./keyboard'); var ps2 = require('./ps2'); var pci = require('./pci'); var net = require('./net'); var StdIO = require('./stdio'); global.stdio = new StdIO(); function Runtime() { this.tty = tty; this.keyboard = keyboard; this.pci = pci; this.ps2 = ps2; this.allocator = resources.allocator; this.net = net; this.bufferAddress = runtime.bufferAddress; // fixme this.debug = runtime.debug; // fixme this.machine = { reboot: resources.natives.reboot, shutdown: function() { resources.acpi.enterSleepState(5); } }; this.stdio = global.stdio; } global.runtime = module.exports = new Runtime();
// Copyright 2014-2015 runtime.js project 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. 'use strict'; /* global isolate, runtime */ console.log = isolate.log; var resources = require('./resources'); require('./polyfill'); var tty = require('./tty'); var keyboard = require('./keyboard'); var ps2 = require('./ps2'); var pci = require('./pci'); var net = require('./net'); var StdIO = require('./stdio'); function Runtime() { this.tty = tty; this.keyboard = keyboard; this.pci = pci; this.ps2 = ps2; this.allocator = resources.allocator; this.net = net; this.bufferAddress = runtime.bufferAddress; // fixme this.debug = runtime.debug; // fixme this.machine = { reboot: resources.natives.reboot, shutdown: function() { resources.acpi.enterSleepState(5); } }; this.stdio = new StdIO(); } global.runtime = module.exports = new Runtime();
Attach the URL to the event. Signed-off-by: François de Metz <5187da0b934cc25eb2201a3ec9206c24b13cb23b@stormz.me>
var icalendar = require('icalendar'); exports.generateIcal = function(boards) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; var event = new icalendar.VEvent(); event.setSummary(card.get('name')); event.setDescription(card.get('description')); event.setDate(card.get('badges').due); event.addProperty('ATTACH', card.get('url')); ical.addComponent(event); }); }); return ical; }
var icalendar = require('icalendar'); exports.generateIcal = function(boards) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; var event = new icalendar.VEvent(); event.setSummary(card.get('name')); event.setDescription(card.get('description')); event.setDate(card.get('badges').due); ical.addComponent(event); }); }); return ical; }
Add test for administrative area collection shortcuts
<?php use Galahad\LaravelAddressing\Country; /** * Class AdministrativeAreaTest * * @author Junior Grossi <juniorgro@gmail.com> */ class AdministrativeAreaTest extends PHPUnit_Framework_TestCase { public function testMinasGeraisStateInBrazil() { $country = new Country; $brazil = $country->getByCode('BR'); $minasGerais = $brazil->getAdministrativeAreas()->getByCode('MG'); $this->assertEquals($minasGerais->getName(), 'Minas Gerais'); } public function testAlabamaCodeByName() { $country = new Country; $us = $country->getByCode('US'); $alabama = $us->getAdministrativeAreas()->getByName('Alabama'); $alabama2 = $us->states()->name('Alabama'); $this->assertEquals($alabama->getCode(), 'AL'); $this->assertEquals($alabama2->getCode(), 'AL'); } }
<?php use Galahad\LaravelAddressing\Country; /** * Class AdministrativeAreaTest * * @author Junior Grossi <juniorgro@gmail.com> */ class AdministrativeAreaTest extends PHPUnit_Framework_TestCase { public function testMinasGeraisStateInBrazil() { $country = new Country; $brazil = $country->getByCode('BR'); $minasGerais = $brazil->getAdministrativeAreas()->getByCode('MG'); $this->assertEquals($minasGerais->getName(), 'Minas Gerais'); } public function testAlabamaCodeByName() { $country = new Country; $us = $country->getByCode('US'); $alabama = $us->getAdministrativeAreas()->getByName('Alabama'); $this->assertEquals($alabama->getCode(), 'AL'); } }
Use this instead of $scope. Use of plugin with multiple editors.
angular.module('ngWig') .config(['ngWigToolbarProvider', function(ngWigToolbarProvider) { ngWigToolbarProvider.addCustomButton('clear-styles', 'nw-clear-styles-button'); }]) .component('nwClearStylesButton', { template: '<button ng-click="$ctrl.clearStyles($event)" ng-disabled="editMode" class="nw-button clear-styles" title="Clear Styles" ng-disabled="isDisabled">Clear Styles</button>', controller: function() { this.clearStyles = function(e){ // find the ngWig element that hosts the plugin var ngWigElement = e.target.parentElement.parentElement.parentElement.parentElement.parentElement; if(ngWigElement){ var container = angular.element(ngWigElement.querySelector('#ng-wig-editable')); container.text(container[0].textContent); container[0].focus(); } } } });
angular.module('ngWig') .config(['ngWigToolbarProvider', function(ngWigToolbarProvider) { ngWigToolbarProvider.addCustomButton('clear-styles', 'nw-clear-styles-button'); }]) .component('nwClearStylesButton', { template: '<button ng-click="clearStyles()" ng-disabled="editMode" class="nw-button clear-styles" title="Clear Styles" ng-disabled="isDisabled">Clear Styles</button>', controller: function($scope) { $scope.clearStyles = function(){ var container = angular.element(document.querySelector('#ng-wig-editable')); if(container){ container.text(container[0].textContent); container[0].focus(); } } } });
Fix a bug where fetch v3 wasn't used
// For normal consumers, use -1 const REPLICA_ID = -1 const versions = { 0: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, topics }) => { const request = require('./v0/request') const response = require('./v0/response') return { request: request({ replicaId, maxWaitTime, minBytes, topics }), response } }, 1: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, topics }) => { const request = require('./v1/request') const response = require('./v1/response') return { request: request({ replicaId, maxWaitTime, minBytes, topics }), response } }, 2: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, topics }) => { const request = require('./v2/request') const response = require('./v2/response') return { request: request({ replicaId, maxWaitTime, minBytes, topics }), response } }, 3: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, maxBytes, topics }) => { const request = require('./v3/request') const response = require('./v3/response') return { request: request({ replicaId, maxWaitTime, minBytes, maxBytes, topics }), response } }, } module.exports = { versions: Object.keys(versions), protocol: ({ version }) => versions[version], }
// For normal consumers, use -1 const REPLICA_ID = -1 const versions = { 0: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, topics }) => { const request = require('./v0/request') const response = require('./v0/response') return { request: request({ replicaId, maxWaitTime, minBytes, topics }), response } }, 1: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, topics }) => { const request = require('./v1/request') const response = require('./v1/response') return { request: request({ replicaId, maxWaitTime, minBytes, topics }), response } }, 2: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, topics }) => { const request = require('./v2/request') const response = require('./v2/response') return { request: request({ replicaId, maxWaitTime, minBytes, topics }), response } }, 3: ({ replicaId = REPLICA_ID, maxWaitTime, minBytes, maxBytes, topics }) => { const request = require('./v2/request') const response = require('./v2/response') return { request: request({ replicaId, maxWaitTime, minBytes, maxBytes, topics }), response } }, } module.exports = { versions: Object.keys(versions), protocol: ({ version }) => versions[version], }
refactor: Merge request now exports its desired collection name
const mongoose = require('mongoose'); const Schema = mongoose.Schema; module.exports = { name: 'MergeRequest', schema: new Schema({ merge_request: { id: Number, url: String, target_branch: String, source_branch: String, created_at: String, updated_at: String, title: String, description: String, status: String, work_in_progress: Boolean }, last_commit: { id: Number, message: String, timestamp: String, url: String, author: { name: String, email: String } }, project: { name: String, namespace: String }, author: { name: String, username: String }, assignee: { claimed_on_slack: Boolean, name: String, username: String } }) }
const mongoose = require('mongoose'); const Schema = mongoose.Schema; module.exports = new Schema({ merge_request: { id: Number, url: String, target_branch: String, source_branch: String, created_at: String, updated_at: String, title: String, description: String, status: String, work_in_progress: Boolean }, last_commit: { id: Number, message: String, timestamp: String, url: String, author: { name: String, email: String } }, project: { name: String, namespace: String }, author: { name: String, username: String }, assignee: { claimed_on_slack: Boolean, name: String, username: String } });
Fix require path for NoHostServer.js
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, browser: true */ /*global define, brackets */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"), ExtensionUtils = brackets.getModule("utils/ExtensionUtils"), LiveDevServerManager = brackets.getModule("LiveDevelopment/LiveDevServerManager"), ProjectManager = brackets.getModule("project/ProjectManager"), NoHostServer = require("nohost/src/NoHostServer").NoHostServer; function _createServer() { var config = { pathResolver : ProjectManager.makeProjectRelativeIfPossible, root : ProjectManager.getProjectRoot().fullPath }; return new NoHostServer(config); } AppInit.appReady(function () { LiveDevServerManager.registerServer({ create: _createServer }, 9001); }); });
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, browser: true */ /*global define, brackets */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"), ExtensionUtils = brackets.getModule("utils/ExtensionUtils"), LiveDevServerManager = brackets.getModule("LiveDevelopment/LiveDevServerManager"), ProjectManager = brackets.getModule("project/ProjectManager"), NoHostServer = require("nohost/NoHostServer").NoHostServer; function _createServer() { var config = { pathResolver : ProjectManager.makeProjectRelativeIfPossible, root : ProjectManager.getProjectRoot().fullPath }; return new NoHostServer(config); } AppInit.appReady(function () { LiveDevServerManager.registerServer({ create: _createServer }, 9001); }); });
Make the destination directory if it does not exist
from subprocess import check_call import urllib import json import os import os.path def install(): with open('.bowerrc') as f: bowerrc = json.load(f) with open('bower.json') as f: bower_json = json.load(f) registry = 'https://bower.herokuapp.com' topdir = os.path.abspath(os.curdir) for pkg in bower_json['dependencies'].keys(): req = urllib.urlopen('%s/packages/%s' % (registry, pkg)) info = json.load(req) if not os.path.isdir(bowerrc['directory']): os.makedirs(bowerrc['directory']) os.chdir(bowerrc['directory']) check_call(['git', 'clone', info['url']]) os.chdir(pkg) install() os.chdir(topdir)
from subprocess import check_call import urllib import json import os import os.path def install(): with open('.bowerrc') as f: bowerrc = json.load(f) with open('bower.json') as f: bower_json = json.load(f) registry = 'https://bower.herokuapp.com' topdir = os.path.abspath(os.curdir) for pkg in bower_json['dependencies'].keys(): req = urllib.urlopen('%s/packages/%s' % (registry, pkg)) info = json.load(req) os.chdir(bowerrc['directory']) check_call(['git', 'clone', info['url']]) os.chdir(pkg) install() os.chdir(topdir)
Fix redis lock, use SETNX
# -*- coding: utf-8 -*- from kvs import CacheKvs class Locker(object): """ locker for move the locker """ LOCKER_KEY = 'locker' EXPIRES = 5 # 5 sec def __init__(self, key=None): self.key = self.LOCKER_KEY if key: self.key += '.{}'.format(key) self.locker = CacheKvs(self.key) def lock(self): self.locker.set('locked', expires=self.EXPIRES, nx=True) def unlock(self): self.locker.delete() def is_lock(self): return self.locker.get() == 'locked' def on_lock(self, func): def wrapper(*args, **kwargs): if self.lock(): try: return func(*args, **kwargs) except Exception as e: raise e finally: self.unlock() return wrapper
# -*- coding: utf-8 -*- from kvs import CacheKvs class Locker(object): """ locker for move the locker """ LOCKER_KEY = 'locker' EXPIRES = 5 # 5 sec def __init__(self, key=None): self.key = self.LOCKER_KEY if key: self.key += '.{}'.format(key) self.locker = CacheKvs(self.key) def lock(self): self.locker.set('locked', expires=self.EXPIRES, nx=True) def unlock(self): self.locker.delete() def is_lock(self): return self.locker.get() == 'locked' def on_lock(self, func): def wrapper(*args, **kwargs): if self.is_lock(): return self.lock() try: return func(*args, **kwargs) except Exception as e: raise e finally: self.unlock() return wrapper
Remove syncdb signal - will move to migration shortly
from accounts import models, names def ensure_core_accounts_exists(sender, **kwargs): # We only create core accounts the first time syncdb is run if models.Account.objects.all().count() > 0: return # Create asset accounts assets = models.AccountType.add_root(name='Assets') assets.accounts.create(name=names.REDEMPTIONS) assets.accounts.create(name=names.LAPSED) # Create liability accounts liabilities = models.AccountType.add_root(name='Liabilities') liabilities.accounts.create(name=names.MERCHANT_SOURCE, credit_limit=None) liabilities.add_child(name="Giftcards") liabilities.add_child(name="User accounts") #post_syncdb.connect(ensure_core_accounts_exists, sender=models)
from django.db.models.signals import post_syncdb from accounts import models, names def ensure_core_accounts_exists(sender, **kwargs): # We only create core accounts the first time syncdb is run if models.Account.objects.all().count() > 0: return # Create asset accounts assets = models.AccountType.add_root(name='Assets') assets.accounts.create(name=names.REDEMPTIONS) assets.accounts.create(name=names.LAPSED) # Create liability accounts liabilities = models.AccountType.add_root(name='Liabilities') liabilities.accounts.create(name=names.MERCHANT_SOURCE, credit_limit=None) liabilities.add_child(name="Giftcards") liabilities.add_child(name="User accounts") post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Remove old Python pypi classifiers.
# -*- coding: utf-8 -*- import os from setuptools import setup VERSION = '3.1.1' setup( name='conllu', packages=["conllu"], version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/conllu/', install_requires=[], keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], )
# -*- coding: utf-8 -*- import os from setuptools import setup VERSION = '3.1.1' setup( name='conllu', packages=["conllu"], version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/conllu/', install_requires=[], keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], )
Save the image to png
#! /usr/bin/env python from theora import Ogg from numpy import concatenate, zeros_like from scipy.misc import toimage f = open("video.ogv") o = Ogg(f) Y, Cb, Cr = o.test() Cb2 = zeros_like(Y) for i in range(Cb2.shape[0]): for j in range(Cb2.shape[1]): Cb2[i, j] = Cb[i/2, j/2] Cr2 = zeros_like(Y) for i in range(Cr2.shape[0]): for j in range(Cr2.shape[1]): Cr2[i, j] = Cr[i/2, j/2] w, h = Y.shape Y = Y.reshape((1, w, h)) Cb = Cb2.reshape((1, w, h)) Cr = Cr2.reshape((1, w, h)) A = concatenate((Y, Cb, Cr)) img = toimage(A, mode="YCbCr", channel_axis=0) img.convert("RGB").save("frame.png") from pylab import imshow, show from matplotlib import cm imshow(img, origin="lower") show()
#! /usr/bin/env python from theora import Ogg from numpy import concatenate, zeros_like from scipy.misc import toimage f = open("video.ogv") o = Ogg(f) Y, Cb, Cr = o.test() Cb2 = zeros_like(Y) for i in range(Cb2.shape[0]): for j in range(Cb2.shape[1]): Cb2[i, j] = Cb[i/2, j/2] Cr2 = zeros_like(Y) for i in range(Cr2.shape[0]): for j in range(Cr2.shape[1]): Cr2[i, j] = Cr[i/2, j/2] w, h = Y.shape Y = Y.reshape((1, w, h)) Cb = Cb2.reshape((1, w, h)) Cr = Cr2.reshape((1, w, h)) A = concatenate((Y, Cb, Cr)) img = toimage(A, mode="YCbCr", channel_axis=0) print img from pylab import imshow, show from matplotlib import cm imshow(img, origin="lower") show()
Fix fetching files from directory record.
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Models\File; /** * A directory record. */ class DirectoryRecord extends FileRecord { /** * {@inheritdoc} */ public function __get($field) { if ($field == 'type') return 'directory'; return parent::__get($field); } /** * {@inheritdoc} */ public function getData() { $data = parent::getData(); $data['type'] = 'directory'; return $data; } /** * Get content of directory. * @return FileRecord[] List of file records. */ public function getContent() { $files = scandir($this->path); if ($files === false) return array(); $records = array(); foreach ($files as $file) { if ($file[0] != '.') { $path = $this->path . '/' . $file; if (is_dir($path)) $records[] = new DirectoryRecord($path); else $records[] = new FileRecord($path); } } return $records; } }
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Models\File; /** * A directory record. */ class DirectoryRecord extends FileRecord { /** * {@inheritdoc} */ public function __get($field) { if ($field == 'type') return 'directory'; return parent::__get($field); } /** * {@inheritdoc} */ public function getData() { $data = parent::getData(); $data['type'] = 'directory'; return $data; } /** * Get content of directory. * @return FileRecord[] List of file records. */ public function getContent() { $files = scandir($this->path); if ($files === false) return array(); $records = array(); foreach ($files as $file) { if ($file[0] != '.') { $path = $this->path . '/' . $file; if (is_dir($path)) $records[] = new DirectoryRecord($this->getModel(), $path); else $records[] = new FileRecord($this->getModel(), $path); } } return $records; } }
Add missing assertion in demo dir test
package exercism import ( "github.com/stretchr/testify/assert" "io/ioutil" "os" "path/filepath" "testing" ) func TestReadingWritingConfig(t *testing.T) { tmpDir, err := ioutil.TempDir("", "") assert.NoError(t, err) writtenConfig := Config{ GithubUsername: "user", ApiKey: "MyKey", ExercismDirectory: "/exercism/directory", } ConfigToFile(tmpDir, writtenConfig) loadedConfig, err := ConfigFromFile(tmpDir) assert.NoError(t, err) assert.Equal(t, writtenConfig, loadedConfig) } func TestDemoDir(t *testing.T) { path, err := ioutil.TempDir("", "") assert.NoError(t, err) os.Chdir(path) path, err = filepath.EvalSymlinks(path) assert.NoError(t, err) path = filepath.Join(path, "exercism-demo") demoDir, err := DemoDirectory() assert.NoError(t, err) assert.Equal(t, demoDir, path) }
package exercism import ( "github.com/stretchr/testify/assert" "io/ioutil" "os" "path/filepath" "testing" ) func TestReadingWritingConfig(t *testing.T) { tmpDir, err := ioutil.TempDir("", "") assert.NoError(t, err) writtenConfig := Config{ GithubUsername: "user", ApiKey: "MyKey", ExercismDirectory: "/exercism/directory", } ConfigToFile(tmpDir, writtenConfig) loadedConfig, err := ConfigFromFile(tmpDir) assert.NoError(t, err) assert.Equal(t, writtenConfig, loadedConfig) } func TestDemoDir(t *testing.T) { path, err := ioutil.TempDir("", "") assert.NoError(t, err) os.Chdir(path) path, err = filepath.EvalSymlinks(path) assert.NoError(t, err) path = filepath.Join(path, "exercism-demo") demoDir, err := DemoDirectory() assert.Equal(t, demoDir, path) }
states/statemgr: Fix the Filesystem state manager tests Now that we're verifying the Terraform version during state loading, we need to force a particular Terraform version to use during these tests.
// The version package provides a location to set the release versions for all // packages to consume, without creating import cycles. // // This package should not import any other terraform packages. package version import ( "fmt" version "github.com/hashicorp/go-version" ) // The main version number that is being run at the moment. var Version = "0.12.0" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release // such as "dev" (in development), "beta", "rc1", etc. var Prerelease = "dev" // SemVer is an instance of version.Version. This has the secondary // benefit of verifying during tests and init time that our version is a // proper semantic version, which should always be the case. var SemVer *version.Version func init() { SemVer = version.Must(version.NewVersion(Version)) } // Header is the header name used to send the current terraform version // in http requests. const Header = "Terraform-Version" // String returns the complete version string, including prerelease func String() string { if Prerelease != "" { return fmt.Sprintf("%s-%s", Version, Prerelease) } return Version }
// The version package provides a location to set the release versions for all // packages to consume, without creating import cycles. // // This package should not import any other terraform packages. package version import ( "fmt" version "github.com/hashicorp/go-version" ) // The main version number that is being run at the moment. const Version = "0.12.0" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release // such as "dev" (in development), "beta", "rc1", etc. var Prerelease = "dev" // SemVer is an instance of version.Version. This has the secondary // benefit of verifying during tests and init time that our version is a // proper semantic version, which should always be the case. var SemVer = version.Must(version.NewVersion(Version)) // Header is the header name used to send the current terraform version // in http requests. const Header = "Terraform-Version" // String returns the complete version string, including prerelease func String() string { if Prerelease != "" { return fmt.Sprintf("%s-%s", Version, Prerelease) } return Version }
Fix warning when generating javadoc ; Add class description
package com.boundary.sdk.event; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities used for java script execution * * @author davidg * */ public class ScriptUtils { private static Logger LOG = LoggerFactory.getLogger(ScriptUtils.class); public ScriptUtils() { } /** * Finds a script to be tested from * @param scriptPath * @return {@link File} */ static public FileReader getFile(String scriptPath) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(scriptPath); assert(url == null); File f = new File(url.getFile()); FileReader reader = null; try { reader = new FileReader(f); } catch (FileNotFoundException e) { e.printStackTrace(); LOG.error(e.getMessage()); } return reader; } }
package com.boundary.sdk.event; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ScriptUtils { private static Logger LOG = LoggerFactory.getLogger(ScriptUtils.class); public ScriptUtils() { } /** * Finds a script to be tested from * @param scriptName * @return {@link File} */ static public FileReader getFile(String scriptPath) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(scriptPath); assert(url == null); File f = new File(url.getFile()); FileReader reader = null; try { reader = new FileReader(f); } catch (FileNotFoundException e) { e.printStackTrace(); LOG.error(e.getMessage()); } return reader; } }
Fix class name in javadoc Closes gh-1530
/* * Copyright 2002-2012 the original author or 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 org.springframework.web.client; import java.io.IOException; /** * Exception thrown when an I/O error occurs. * * @author Arjen Poutsma * @since 3.0 */ public class ResourceAccessException extends RestClientException { private static final long serialVersionUID = -8513182514355844870L; /** * Construct a new {@code ResourceAccessException} with the given message. * @param msg the message */ public ResourceAccessException(String msg) { super(msg); } /** * Construct a new {@code ResourceAccessException} with the given message and {@link IOException}. * @param msg the message * @param ex the {@code IOException} */ public ResourceAccessException(String msg, IOException ex) { super(msg, ex); } }
/* * Copyright 2002-2012 the original author or 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 org.springframework.web.client; import java.io.IOException; /** * Exception thrown when an I/O error occurs. * * @author Arjen Poutsma * @since 3.0 */ public class ResourceAccessException extends RestClientException { private static final long serialVersionUID = -8513182514355844870L; /** * Construct a new {@code HttpIOException} with the given message. * @param msg the message */ public ResourceAccessException(String msg) { super(msg); } /** * Construct a new {@code HttpIOException} with the given message and {@link IOException}. * @param msg the message * @param ex the {@code IOException} */ public ResourceAccessException(String msg, IOException ex) { super(msg, ex); } }
Fix var name, is plural in site map
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib.sitemaps import GenericSitemap as DjangoGenericSitemap from django.contrib.sitemaps import Sitemap as DjangoSitemap from django.utils import timezone from opps.containers.models import Container def InfoDisct(googlenews=False): containers = Container.objects.filter(date_available__lte=timezone.now(), published=True) if googlenews: containers = containers[:1000] return { 'queryset': containers, 'date_field': 'date_available', } class BaseSitemap(DjangoSitemap): priority = 0.6 def items(self): return Container.objects.filter(date_available__lte=timezone.now(), published=True) def lastmod(self, obj): return obj.date_available class GenericSitemap(DjangoGenericSitemap): limit = 1000 priority = 0.6
# -*- coding: utf-8 -*- from django.contrib.sitemaps import GenericSitemap as DjangoGenericSitemap from django.contrib.sitemaps import Sitemap as DjangoSitemap from django.utils import timezone from opps.containers.models import Container def InfoDisct(googlenews=False): container = Container.objects.filter(date_available__lte=timezone.now(), published=True) if googlenews: container = container[:1000] return { 'queryset': container, 'date_field': 'date_available', } class BaseSitemap(DjangoSitemap): priority = 0.6 def items(self): return Container.objects.filter(date_available__lte=timezone.now(), published=True) def lastmod(self, obj): return obj.date_available class GenericSitemap(DjangoGenericSitemap): limit = 1000 priority = 0.6
Support for initializing io.Socket after the page has been loaded
/** * Socket.IO client * * @author Guillermo Rauch <guillermo@learnboost.com> * @license The MIT license. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com> */ (function(){ var _pageLoaded = false; io.util = { ios: false, load: function(fn){ if (document.readyState == 'complete' || _pageLoaded) return fn(); if ('attachEvent' in window){ window.attachEvent('onload', fn); } else { window.addEventListener('load', fn, false); } }, inherit: function(ctor, superCtor){ // no support for `instanceof` for now for (var i in superCtor.prototype){ ctor.prototype[i] = superCtor.prototype[i]; } }, indexOf: function(arr, item, from){ for (var l = arr.length, i = (from < 0) ? Math.max(0, l + from) : from || 0; i < l; i++){ if (arr[i] === item) return i; } return -1; }, isArray: function(obj){ return Object.prototype.toString.call(obj) === '[object Array]'; } }; io.util.ios = /iphone|ipad/i.test(navigator.userAgent); io.util.load(function(){ _pageLoaded = true; }); })();
/** * Socket.IO client * * @author Guillermo Rauch <guillermo@learnboost.com> * @license The MIT license. * @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com> */ (function(){ var _pageLoaded = false; io.util = { ios: false, load: function(fn){ if (_pageLoaded) return fn(); if ('attachEvent' in window){ window.attachEvent('onload', fn); } else { window.addEventListener('load', fn, false); } }, inherit: function(ctor, superCtor){ // no support for `instanceof` for now for (var i in superCtor.prototype){ ctor.prototype[i] = superCtor.prototype[i]; } }, indexOf: function(arr, item, from){ for (var l = arr.length, i = (from < 0) ? Math.max(0, l + from) : from || 0; i < l; i++){ if (arr[i] === item) return i; } return -1; }, isArray: function(obj){ return Object.prototype.toString.call(obj) === '[object Array]'; } }; io.util.ios = /iphone|ipad/i.test(navigator.userAgent); io.util.load(function(){ _pageLoaded = true; }); })();
[turbofan] Fix test of %_MathClz32 intrinsic. This test will fail once we optimize top-level code, because the aforementioned intrinsic doesn't perform a NumberToUint32 conversion. R=titzer@chromium.org TEST=mjsunit/asm/math-clz32 Review URL: https://codereview.chromium.org/1041173002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#27524}
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax var stdlib = { Math: Math }; var f = (function Module(stdlib) { "use asm"; var clz32 = stdlib.Math.clz32; function f(a) { a = a >>> 0; return clz32(a)|0; } return f; })(stdlib); assertEquals(32, f(0)); assertEquals(32, f(NaN)); assertEquals(32, f(undefined)); for (var i = 0; i < 32; ++i) { assertEquals(i, f((-1) >>> i)); } for (var i = -2147483648; i < 2147483648; i += 3999773) { assertEquals(%MathClz32(i), f(i)); assertEquals(%MathClz32(i), %_MathClz32(i >>> 0)); }
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax var stdlib = { Math: Math }; var f = (function Module(stdlib) { "use asm"; var clz32 = stdlib.Math.clz32; function f(a) { a = a >>> 0; return clz32(a)|0; } return f; })(stdlib); assertEquals(32, f(0)); assertEquals(32, f(NaN)); assertEquals(32, f(undefined)); for (var i = 0; i < 32; ++i) { assertEquals(i, f((-1) >>> i)); } for (var i = -2147483648; i < 2147483648; i += 3999773) { assertEquals(%MathClz32(i), f(i)); assertEquals(%_MathClz32(i), f(i)); }